Compare commits

..
Author SHA1 Message Date
Julius MarmingeandClaude Opus 5 bb0492d294 fix(web): address UI-consistency findings on the browser defaults row
Three findings from the UI-consistency check, all in the new panel:

The viewport cluster forced a hard minimum width — `min-w-36` on the select
plus a non-shrinking group of two `w-24` fields and the rotate button — so the
row overflowed at narrow widths once a non-fill default was set. The cluster
now wraps and the fields are narrower.

Control heights were mixed in one `items-center` row: a default-size select
beside `sm` number fields and an `icon-sm` button. The select is now `sm` too,
so all three measure 28px.

The wrapper's `opacity-64` compounded with each primitive's own
`disabled:opacity-64`, dimming the controls to roughly 0.41 alpha — dimmer
than disabled controls anywhere else in Settings. The wrapper now dims only
the row text, leaving each control at the standard disabled opacity.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 16:34:09 +02:00
Julius MarmingeandClaude Opus 5 cca9dc8330 test(web): update preview tests for the new open and createTab shapes
`preview.open` now carries the configured default viewport and `createTab`
carries the zoom/appearance defaults, so the call-shape assertions had to move
with them.

PreviewView's test stubs `browserDefaults` directly rather than deepening the
`state/session` mock: the component now reaches `useSettings`, which pulls in
`state/server`, and a test about browser chrome shouldn't drag the settings and
connection graph along with it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 16:26:16 +02:00
Julius MarmingeandClaude Opus 5 b4777dad6d fix(web): tighten the desktop-only browser notice copy
Two sentences explaining where the browser runs, when one clause says it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 16:26:16 +02:00
Julius MarmingeandClaude Opus 5 f4c628c757 fix(web): frame the desktop-only browser defaults as one disabled block
Disabling each control on its own left labels and descriptions at full
strength, so the group still read as editable. The defaults now sit in a
bordered, dimmed block with the reason at its top.

The explanation stays outside the dimmed area: the one part that must remain
readable is the part saying why the rest isn't.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 16:26:16 +02:00
Julius MarmingeandClaude Opus 5 839966a4f4 fix(web): disable desktop-only browser defaults on web clients
The preview browser is a Chromium guest the desktop app hosts, so its defaults
mean nothing in a web client. They are also client-local, which is why these
are disabled rather than hidden: editing them from a browser tab would write
preferences belonging to a different client, reading as though the desktop app
had been configured when it hadn't.

Follows the pattern Keybindings already uses for a desktop-only concern — an
inline notice above the affected controls. Reset affordances are withheld too,
since there is nothing to reset from here.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 16:26:16 +02:00
Julius MarmingeandClaude Opus 5 86975b87a7 feat(web): proper number fields, orientation, and floating-preview toggle
Three follow-ups to the browser defaults:

The dimension inputs were bare `Input type=number` at w-16, which clipped
4-digit values ("1280" rendered as "128("). They are now `NumberField`, the
repo's real numeric control, widened to fit and with grouping switched off so
a height reads "1024" rather than "1,024".

They commit on blur via `onValueCommitted` instead of per keystroke. Typing
"2560" passes through "256", which is itself a legal dimension, so a
change-handler would persist that intermediate size and rewrite settings on
every key.

Adds an orientation control next to the dimensions, reusing the device
toolbar's rotate affordance — its icon moves to a shared module rather than
being duplicated. Rotating a preset keeps the preset: `resolvePreviewViewport`
already stores rotated presets as the id plus swapped dimensions, so a rotated
iPad Mini stays an iPad Mini instead of decaying into a custom size.

Adds `browserAutoShowFloatingPreview` (on by default) for whether an
agent-opened preview pops the floating player into view. An explicit
`open`/`show` on `preview_open` still wins: that is the agent deliberately
surfacing or hiding its work, which shouldn't be overridden by a default.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 16:26:16 +02:00
Julius MarmingeandClaude Opus 5 de4c1ee1e1 feat(web): configurable browser defaults in Settings → Integrations
The preview browser always opened in fill mode, at 100% zoom, following the
system appearance. That is rarely what you want if you work in responsive mode
against a handful of known viewports, and there was no way to say otherwise.

Adds a Settings → Integrations page whose first section is Browser, holding the
defaults a preview tab opens at: viewport (fill, responsive, or a device
preset), zoom, and appearance. They apply to every entry point that opens a tab
without stating its own size — a hand-opened browser panel and an agent calling
`preview_open` alike.

The viewport travels with `preview.open` and zoom/appearance with `createTab`,
so a tab is born configured rather than reflowing a frame later.

Agents keep their 1280x800 fallback, but only when no default is configured:
a fill-mode tab would otherwise be sized by whatever the panel happens to be,
and agents assert against what they open.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 16:26:16 +02:00
ad117235b5 feat(desktop): add signal macOS DMG installer background (#6201)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 16:13:01 +02:00
Julius Marmingeandcodex 20a70420a8 fix(web): keep timestamp date and time in the same locale (#7081)
Co-authored-by: codex <[email protected]>
2026-08-15 14:59:33 +02:00
ec141c1257 fix(clients): default clone destination to folder plus repo name (#5989)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:37:47 +00:00
Ngo Quoc Viet 2fc6762395 fix: restore CLAUDE.md symlink target (#3929) 2026-08-15 12:37:30 +00:00
Aditya Garud 664499c92e Limit physical key fallback to non-Latin layout output (#4469) 2026-08-15 12:33:52 +00:00
Aditya Garud 931e91527c Keep the server alive when a response write hits a dead socket (#4470) 2026-08-15 12:31:32 +00:00
04f23098e1 fix(marketing): detect Mac chip on homepage download button (#4197)
Co-authored-by: Claude Opus 4.8 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:29:36 +00:00
61b2e744df fix(server): respect inherited OPENCODE_CONFIG_CONTENT (#4242)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 14:27:58 +02:00
El-Hussein Abdelraouf e17f244e0d feat(web): make right panel maximize bindable (#5091) 2026-08-15 12:27:49 +00:00
CursedApple 62bb97428a fix(web): contain long approval commands (#6503) 2026-08-15 12:27:42 +00:00
f8bb92b51b fix(mobile): local-checkout threads record their branch so PR badges show (#4986)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 14:27:29 +02:00
shubhu 277a7cb445 fix(mobile): prevent crash on sign out in settings (#4899) 2026-08-15 14:27:26 +02:00
Kevin Bravo 07e668dc48 fix(server): settle snoozed threads immediately (#5379) 2026-08-15 14:27:23 +02:00
Ostap 4fc80fcbdc fix(server): stop replaying a command receipt for a different aggregate (#5246) 2026-08-15 14:27:19 +02:00
3b54a2a574 fix(server): settle pending user-input requests when a Claude session stops (#5127)
Co-authored-by: Capxul Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:27:04 +00:00
delltrak 39167eb1a5 fix(web): describe what Ultracode does in the Reasoning picker (#6092) 2026-08-15 12:27:01 +00:00
JackatDJL 7ce4194707 fix: detect SSH remotes with non-git user prefixes (e.g. gitlab@) (#3649) 2026-08-15 12:26:45 +00:00
JJ dc0ff8f13e fix(server): allow install scripts in npm-global provider updates (#5646) 2026-08-15 12:26:32 +00:00
Luis Gustavo Couto Wacker 160c76c6d1 fix(desktop): keep probing backend readiness while the process is alive (#5526) 2026-08-15 12:26:29 +00:00
Dev Talan 86fb47afd7 fix(server): allow long-running git pushes (#6499) 2026-08-15 12:26:27 +00:00
Mark GriffinandCursor d550b829bd fix(web): stop clipping the changed-files expand hover on Windows (#6545)
Co-authored-by: Cursor <[email protected]>
2026-08-15 12:26:10 +00:00
RaitP1 1a5ff424ce fix(web): keep multi-select questions open after the first click (#6646) 2026-08-15 12:25:57 +00:00
Paul b72d5d7988 fix(desktop): timestamps follow the OS locale instead of en-US (#6190) 2026-08-15 12:25:54 +00:00
Harshith Goka 31d0fb6ca7 fix(mobile): use Android monospace font family (#4609) 2026-08-15 12:25:14 +00:00
Aditya Garud db02c6b9c9 Skip user hooks during Claude capability probes (#4466) 2026-08-15 12:16:44 +00:00
Alex Brodsky 21b6fb528d fix(web): add web app manifest so installed app keeps its scope (#4306) 2026-08-15 12:12:42 +00:00
Aditya Garud 7083bce26a Keep block code plain when copying from rendered markdown (#4468) 2026-08-15 12:12:15 +00:00
jorvareaandjorvarea f915320914 fix(web): keep the final segment of directory paths with a trailing separator (#5460)
Co-authored-by: jorvarea <[email protected]>
2026-08-15 12:10:32 +00:00
Akos BaloghandClaude Opus 4.8 7c8848ebb0 fix(desktop): route mouse thumb buttons to the in-app browser (#4459)
Co-authored-by: Claude Opus 4.8 <[email protected]>
2026-08-15 12:10:21 +00:00
cf7bfd1c93 fix(web): preserve XML-like tags in user messages (#4133)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-15 12:08:29 +00:00
CursedApple 5e14737152 fix(web): scale command details with code font (#6510) 2026-08-15 12:08:10 +00:00
ca37b19cf8 fix(web): show selected model in context window tooltip (#4772)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:07:53 +00:00
d5465aebf2 fix(web): retain terminal PR badges after checkout switch (#4755)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:07:51 +00:00
Carlos JimenezandJulius Marminge d715c2e56b fix(server): let slow provider CLIs raise their discovery probe budget (#6223)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-15 12:07:38 +00:00
Roshan Mhatre ad47d2347c fix(claude): discover repo-local .agents/skills in skill discovery (#5488) 2026-08-15 12:07:31 +00:00
Rishet11 684d703b0a fix(shared): degrade an unknown system time zone to UTC in usage windows (#6670) 2026-08-15 12:07:24 +00:00
Jaroslav BrtisandClaude Opus 5 40ab7bf32a feat(web): collapse the question prompt from its header (#6773)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-15 12:07:09 +00:00
Naveed Iqbal 7c55e86320 fix(web): reject oversized prompts before provider turn start (#6602) 2026-08-15 12:07:07 +00:00
Ostap c0f9d917c1 fix(server): wait for concurrent SQLite writers instead of failing with SQLITE_BUSY (#5134) 2026-08-15 12:06:53 +00:00
Vitaly IegorovandClaude Fable 5 a5d35321bd fix(web): show provider account accent badge in sidebar rows and hover card (#5980)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 12:06:50 +00:00
Tai Nguyen efe1773e9c fix(web): hide T3 Connect toggle in web app settings (#5068) 2026-08-15 12:06:25 +00:00
Tai Nguyen c4556ab237 fix(web): stop wrapping partial code block selections in markdown fences (#5069) 2026-08-15 12:06:22 +00:00
f075a58119 perf(server): persist the wire projection for streaming tool.updated data (#6675)
Co-authored-by: mInrOz <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 12:05:48 +00:00
Torben Wetter 9d0f2fc212 fix(ssh): surface a failed remote t3 install instead of a silent 0-byte server.log (#5132) 2026-08-15 12:05:45 +00:00
Joaquin NavarroandClaude Fable 5 e9e46972fb fix(claude): make "Always allow for session" stick, and only for the session (#5041)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 12:05:21 +00:00
duncan-vcandduncan-vc 551f4c99c1 fix(server): return valid preview action results (#5966)
Co-authored-by: duncan-vc <[email protected]>
2026-08-15 12:04:21 +00:00
402c9e0748 docs: mention Bitbucket user read scope needed by auth probe (#6291)
Co-authored-by: Gerwin Bisschop <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 12:04:02 +00:00
Naveed Iqbal 474cc5fb01 fix(server): ignore Claude command lifecycle messages (#6606) 2026-08-15 12:03:43 +00:00
Linus Boehm e204f5a5d3 fix(desktop): agent shells inherit a UTF-8 locale on macOS (#6236) 2026-08-15 12:03:28 +00:00
Mark GriffinandCursor 3cde99b259 fix(web): hide provider Update toast action while an update is running (#6544)
Co-authored-by: Cursor <[email protected]>
2026-08-15 14:03:14 +02:00
Rishet11 51c6daa3bd fix(server): treat a missing Codex rollout as a recoverable resume error (#6671) 2026-08-15 14:02:55 +02:00
Akshar Patel 135dc156e3 fix(codex): keep background memory out of chats (#5468) 2026-08-15 12:02:44 +00:00
WilliawarandClaude Fable 5 d79f975d0b fix(web): keep the composer glass aligned with the context strip at any interface font size (#5703)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-15 12:02:41 +00:00
aoright b0de385777 fix(web): support Shift+Insert terminal paste (#5982) 2026-08-15 12:02:24 +00:00
abhwshek c7b14a8666 fix(client-runtime): branch list no longer resets while paging through refs (#5858) 2026-08-15 12:02:21 +00:00
Jorge Pineda 9e61d0f127 fix(web): replace whitespace in new ref names with dashes (#6270) 2026-08-15 12:02:03 +00:00
Vividh Mahajan 06dd9993b6 fix(web): reserve sibling column width when resizing the right panel (#6279) 2026-08-15 12:01:47 +00:00
143f713c79 fix(web): show command output in work log (#4083)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:01:45 +00:00
5ffbf3ce4a Make ClaudeTextGeneration tests hermetic on Windows (#4508)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:01:29 +00:00
mohammed shazeb 34a12bc33f fix(web): reject unsupported composer image types at attach time (#6574) 2026-08-15 12:01:26 +00:00
7afa184a99 fix(web): keep send reachable while a turn is running on mobile (#4781)
Co-authored-by: AMohamedAakhil <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 12:01:11 +00:00
Torben Wetter a7c5ad5db1 fix(web): unstick /connect after in-modal sign-in by redirecting to the authorize endpoint (#5133) 2026-08-15 12:01:08 +00:00
Akshar Patel 6e6d1b4941 fix(web): keep floating preview anchored after panel closes (#6547) 2026-08-15 12:00:53 +00:00
Rishet11 9bdd912933 fix(web): stop counting a workflow coordinator as a working agent (#6672) 2026-08-15 12:00:51 +00:00
Daniel Vernon 4db50757c0 fix(mobile): explain iOS-only settings on Android (#4981) 2026-08-15 12:00:18 +00:00
Wout Stiens 270489b887 fix(terminal): right-click paste works in the terminal (#5240) 2026-08-15 11:44:37 +00:00
a38cac81d8 fix(web): keep a long path from running under the folder picker button (#4823)
Co-authored-by: Sy-D <[email protected]>
Co-authored-by: Claude Opus 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-15 11:42:08 +00:00
JJ 3bc4fdf05b fix(mobile): recover the QR pairing scanner when camera access is denied (#6487) 2026-08-15 11:41:51 +00:00
Nicolas Layne db3278f977 fix(marketing): keep Grok mark clear of mobile hero copy (#4542) 2026-08-15 11:39:05 +00:00
Taras d94fbda344 fix(gitlab): submit review comments on context lines (#6348) 2026-08-15 13:37:02 +02:00
Bilal Bakr b7dbbbaf6c feat(desktop): Chrome-style hold-to-quit (#5508) 2026-08-15 13:33:29 +02:00
Guilherme Barros 178da6bc32 fix(shared): match source-control providers by DNS label (#6175) 2026-08-15 13:31:56 +02:00
Ulises Britos ddee418a8d fix(server): stop the provider title mirror from overwriting real thread titles (#5941) 2026-08-15 13:31:36 +02:00
2cb1a26f06 fix(web): open the file a bare filename reference names (#6297)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 12:44:51 +02:00
b277cc65e0 fix(mobile): use tryOpenExternalUrl for markdown links in ThreadFeed (#5872)
Co-authored-by: codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-15 12:44:30 +02:00
Guilherme Barros 9f26656cb9 fix(web): open diff files from nested projects (#6174) 2026-08-15 12:44:22 +02:00
Lars Nieuwenhuis 48cba7d93c fix(web): restore the Archive action in the default sidebar thread menu (#6526) 2026-08-15 12:44:19 +02:00
t3-code[bot] 71c6f82487 fix(server): bound thread activity hydration (#6153)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-15 12:44:03 +02:00
Lars Nieuwenhuis eaa6c4712f fix(web): widen ordered-list marker gutter for 3+ digit item numbers (#6527) 2026-08-15 12:44:01 +02:00
David Balderston a6ac27e7fd feat(web): accept file drops across the chat workspace (#6636) 2026-08-15 12:43:58 +02:00
Yukun Shan 1e87029261 fix(web): preserve Claude insight line breaks (#4344) 2026-08-15 12:43:50 +02:00
Guilherme Barros 672216d7e1 fix(ssh): let cold remote servers finish starting (#6168) 2026-08-15 12:43:42 +02:00
Lars Nieuwenhuis 75472802bc fix(server): treat removed Bitbucket permissions endpoint as unknown, not blocking (#6525) 2026-08-15 12:43:20 +02:00
Tylerandtsouth89 afca73d368 fix(server): keep provider notification consumers alive past startSession (#6538)
Co-authored-by: tsouth89 <[email protected]>
2026-08-15 12:43:13 +02:00
Julius MarmingeandClaude Opus 5 d8a6dfd315 fix(desktop): app zoom no longer zooms the preview browser (#6649)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-15 12:29:26 +02:00
Julius Marminge e9ae134c59 docs: route feature requests to Discussions
- Disable feature-request issue templates
- Direct contributors to Ideas discussions for proposals
2026-08-15 11:30:08 +02:00
Wout Stiens f0ebc628c6 fix(web): improve Codex usage graph contrast (#6669) 2026-08-15 04:42:35 -04:00
Wout Stiens 6ae9662d8e fix(web): restore selected themes in dark mode (#6665) 2026-08-15 07:33:08 +00:00
8c628f1499 fix(web): align pull request action menu rows (#6534)
Co-authored-by: Nickolas Kyryliuk <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-14 22:48:54 -04:00
Theo BrowneandClaude Fable 5 48ddb3d469 feat(web): older chat timestamps show the date, not just the time (#6654)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 22:48:08 -04:00
maria 804cba4305 revert: refresh workspace layouts and tool activity (#6657) 2026-08-15 02:00:02 +00:00
maria d7abd7f3bb feat(web): refresh workspace layouts and tool activity 2026-08-14 21:54:04 -04:00
Theo BrowneandClaude Fable 5 57a299a785 feat(web): open remote environments in your local editor over SSH (#6572)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 17:35:34 -07:00
SimoneandSimone 74f7b43486 fix(web): bound OKLCH gamut mapping (#6485)
Co-authored-by: Simone <[email protected]>
2026-08-14 19:32:33 -04:00
maria e25021af76 feat(packaging): maintain AUR packages in-repo (#4128) 2026-08-15 00:32:12 +02:00
SimoneandSimone f0719072a1 fix(server): handle files named HEAD in git status (#6397)
Co-authored-by: Simone <[email protected]>
2026-08-14 17:56:12 -04:00
9885a845c9 refactor(web): simplify global styling (#6381)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-14 23:30:13 +02:00
t3-code[bot]andUtkarsh Patil 196c8ea0d6 fix(web): style sidebar action tooltips (#6371)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-14 19:43:33 +00:00
Wout Stiens c9063f03ea perf(desktop): speed up Windows update installation (#6169) 2026-08-15 00:42:39 +05:30
Utkarsh Patil 1add47b322 fix(web): add copying terminal selection with ctrl+c in the web app (#5638) 2026-08-14 23:22:57 +05:30
Dara Adedeji 80991402dc fix(server): terminal subprocess polling no longer floods the PID space (#6377) 2026-08-14 23:02:25 +05:30
Wout Stiens 1a6599437b fix(web): clarify desktop update status (#6504) 2026-08-14 17:58:49 +02:00
Chris Deeming 184d8ef33b fix(mobile): steer active turns by default (#6543) 2026-08-14 13:35:10 +02:00
Julius MarmingeandClaude Fable 5 038560e580 fix(web): align every titlebar control cluster on one shared inset (#6592)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 11:22:05 +02:00
Julius MarmingeandClaude Fable 5 21a3669cee fix(mobile): prevent OTA update restart crashes (#6324)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:46:33 +02:00
Julius MarmingeandClaude Fable 5 b3b4b57794 fix(mobile): preserve keyboard suggestions while typing (#6323)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:45:43 +02:00
6ae44b418a refactor(mobile): name the iOS nav bar height fallback (#6589)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-14 08:29:09 +00:00
Michael Charles Aubrey 4a2f8b04bb fix(web): keep thread rename open during IME composition (#6281) 2026-08-14 08:27:29 +00:00
Pavlo TrinkoandClaude Fable 5 8f9ab0845d fix(mobile): add breathing room between the git progress overlay and the app bar (#6587)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:25:05 +02:00
Julius MarmingeandClaude Fable 5 baaeda305c fix: avoid stale Live Activities when publishing is disabled (#6325)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-14 10:00:25 +02:00
7e01d33f0e perf(build): stop unpacking node_modules wholesale from the Windows asar (#5877)
Co-authored-by: tsouth89 <[email protected]>
Co-authored-by: t3-code[bot] <t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
Co-authored-by: Shivam Sharma <[email protected]>
2026-08-14 08:37:57 +05:30
Chris Deeming 9fd788b5a9 fix(preview): only show browser-ready local servers (#6021) 2026-08-13 22:10:41 -04:00
Chris Deeming 710fd0eeb3 feat(desktop): add favicons to the Browser panel (#5644) 2026-08-13 22:02:09 -04:00
David Hu e15f655ba4 fix(web): show background policy tooltips sooner (#6506) 2026-08-13 22:01:11 -04:00
Theo BrowneandClaude Fable 5 59be6f7846 fix(web): simplify the desktop-managed server update banner copy (#6549)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-13 21:45:51 -04:00
t3-code[bot]andcodex 5304f3e9d4 chore(mobile): bump app version to 1.0.4
Co-authored-by: codex <[email protected]>
2026-08-14 00:01:09 +00:00
85389b9883 Nest mobile task settings in bottom sheets (#6224)
Co-authored-by: codex <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-13 23:59:27 +00:00
Theo Browne db1507e986 feat: allow disabling auto-settle on merge (#5880) 2026-08-13 16:18:15 -07:00
Rakshith Bhat 96bfa67b3d fix(web): align the snoozed thread wake icon (#6215) 2026-08-13 18:14:24 -04:00
Taylor Bombay 5ff3a03ada fix(web): align sidebar wordmark label (#6086) 2026-08-13 18:14:13 -04:00
t3-code[bot]andmaria 23d45d914e fix(web): restore default stage artwork colors (#6535)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-13 18:04:24 -04:00
Paul van DykandClaude Opus 5 bad1143b02 fix(mobile): show a real settings cog in the Android sidebar header (#6520)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-13 20:41:17 +00:00
Adamulek123andJulius Marminge 92d4a2e996 fix(web): scope pull request errors to their environment (#6490)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 20:40:21 +00:00
Utkarsh Patil 2fab18e289 fix(web): show unlinked icon when viewport aspect ratio is unlocked (#6509) 2026-08-13 16:03:48 -04:00
1b16ed663f fix(web): avoid Clerk close button overlap (#6442)
Co-authored-by: t3-code[bot] <236186684+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-13 15:08:28 -04:00
SimoneandSimone 83ad26c3a3 fix(mobile): prevent invalid HTML entities from crashing markdown (#6495)
Co-authored-by: Simone <[email protected]>
2026-08-13 15:08:13 -04:00
Chris Deeming fd51561b4e fix(mobile): extend blockquotes across wrapped lines (#6482) 2026-08-13 20:00:03 +02:00
Julius Marminge 9e201941aa Remove rebase requirement before opening PR (#6479) 2026-08-13 15:04:42 +00:00
t3-code[bot]andJulius Marminge 2ab188f1c0 fix: ignore pull request actions in latency tracker (#6476)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 14:51:31 +00:00
maria 9513e62e24 Add bil0000 to VOUCHED contributors list (#6462) 2026-08-13 14:26:36 +00:00
Bilal Bakr 97db94c9bf fix(web): keep pull request panel within viewport (#6451) 2026-08-13 08:45:33 -04:00
Exotic 5015d7cf9f fix(web): keep turn minimap stable as composer grows (#6414) 2026-08-13 15:30:37 +05:30
Nick Anisimov df19f6cfe3 fix(server): align Codex collaboration prompts (#6432) 2026-08-13 10:31:53 +02:00
Dominic RoyandClaude Fable 5 6bc6cb6be4 fix(web): keep diff file lists scrollable past expanded files (#6423)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 20:11:53 -07:00
Theo BrowneandClaude Fable 5 1e59b4c400 fix(web): keep the typed prompt when a draft changes repo (#6393)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 16:26:27 -07:00
t3-code[bot]andUtkarsh Patil 33f9705926 fix(web): make reset zoom hover visible (#6385)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 19:13:35 -04:00
Dominic Roy da6253b3dd web/settings: fix source control scan on relay environments (#6230) 2026-08-12 16:13:06 -07:00
GianmarcoandCursor ac1264e2ca feat(web): project favicon and workspace icons in command subtitles (#6330)
Co-authored-by: Cursor <[email protected]>
2026-08-12 17:32:58 -04:00
Theo Browne 2eb099fdc8 fix(web): cmd+click sidebar PR numbers open in the browser (#6378) 2026-08-12 14:28:37 -07:00
Bilal BakrandJulius Marminge b28f9bf0a1 feat(web): pull request surfaces — filters & qualifiers, all-server listing, update branch, reactions, in-place editing, smarter diffs (#6039)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-12 22:58:36 +02:00
d0b8d6306b feat(connect): deregister account environments from any client (#4844)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-12 22:46:23 +02:00
Exotic 9666b87516 fix(web): preserve appearance mode when changing themes (#6343) 2026-08-12 16:43:40 -04:00
Alex e3a9c2518d test(mobile): seed snoozed showcase threads (#5155) 2026-08-12 16:43:18 -04:00
Julius Marminge 18918d1c4d Fix mobile command popover glass rendering (#6370) 2026-08-12 22:21:45 +02:00
t3-code[bot]andmaria 8d24b5131f fix(web): open modified PR clicks in browser (#6278)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-12 14:32:44 -04:00
Exotic 770946d026 fix(web): render tooltips above dropdowns (#6241) 2026-08-12 14:32:20 -04:00
8601797233 fix(web): align update toast release notes link (#6322)
Co-authored-by: t3-code[bot] <219304759+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
Co-authored-by: Exotic <[email protected]>
2026-08-12 14:32:10 -04:00
Exotic b73232bdd3 feat(web): reset sidebar width on double click (#6320) 2026-08-12 10:07:39 -04:00
Wout Stiens f131228a59 fix(web): theme Clerk surfaces (#6300) 2026-08-12 19:36:04 +05:30
t3-code[bot]andWout Stiens e321667b10 fix(web): prevent changed files header overlap (#6314)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-12 08:56:13 -04:00
Julius Marminge 849bac8946 fix(connect): preserve CLI OAuth parameters through browser sign-in (#6285) 2026-08-12 12:58:34 +02:00
t3-code[bot]andUtkarsh Patil 6fd088af9f fix(web): align mobile onboarding header (#6293)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 16:07:44 +05:30
Wout Stiens b54bfc9312 feat(web): a better right panel empty state (#6258) 2026-08-12 15:28:46 +05:30
Nick Anisimovandshivam e1378a1f4d fix(mobile): keep ordered lists inside user bubbles (#6154)
Co-authored-by: shivam <[email protected]>
2026-08-12 14:39:51 +05:30
t3-code[bot]andmaria 5a84614809 fix(web): align the composer model picker (#6252)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-11 22:38:45 -04:00
maria 63e6faef62 chore: add dara to vouched (#6259) 2026-08-11 21:51:00 -04:00
Chris Deeming d37a9b09b8 feat(mobile): add thread title regeneration (#6253) 2026-08-11 21:43:05 -04:00
Exotic 560d4a4560 fix(web): keep sidebar wordmark visible at minimum width (#6246) 2026-08-11 19:57:10 -04:00
maria 52e5a75a87 feat(web): compact sidebar footer actions (#6210) 2026-08-11 18:53:40 -04:00
Exotic c196f422ed fix(web): clean up composer resize animation (#6209) 2026-08-11 23:21:44 +02:00
f0b57ca231 feat(web): add Open VSX theme search (#5654)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-11 20:06:05 +00:00
t3-code[bot] 2db08457f2 fix(web): use upload icon for disabled push action (#6207) 2026-08-11 20:25:24 +02:00
Wout Stiens 083fa4ab24 feat(web): use OKLCH for theme palettes (#6036) 2026-08-11 20:00:17 +02:00
Exotic 35172010b1 fix(web): use a clearer pull action icon (#6194) 2026-08-11 16:39:59 +00:00
Mina Yacoub 57b1052679 fix(web): thread error banner dismiss survives reconnect and rerenders (#6123) 2026-08-11 12:27:55 -04:00
1e355a2a34 fix(web): render dropdowns above toasts (#6165)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-11 12:27:02 -04:00
Utkarsh Patilandshivam 44621c345f feat(web): add back buttons for the pull requests and usage pages in the sidebar footer (#6031)
Co-authored-by: shivam <[email protected]>
2026-08-11 12:26:24 -04:00
Arham AminandClaude Opus 4.8 220e573b14 fix(shared): detect Azure DevOps SSH remotes (ssh.dev.azure.com) (#6187)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 16:14:02 +00:00
Arham AminandClaude Opus 4.8 6befe42eb0 fix(shared): normalize a bare Windows drive root the same as C:\ / C:/ (#6189)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 15:52:23 +00:00
Julius Marmingeandcodex b30a9bc414 feat(web): make environment artwork theme aware (#6183)
Co-authored-by: codex <[email protected]>
2026-08-11 17:46:52 +02:00
Wout Stiens ac4780f451 fix(web): restore typography font sizes to defaults (#6172) 2026-08-11 17:21:58 +02:00
Julius Marmingeandcodex 3da7f9c5c3 fix(mobile): guard App Store release versions (#6177)
Co-authored-by: codex <[email protected]>
2026-08-11 15:06:54 +00:00
Julius Marminge c842c6f5b9 Add hourly past-24-hour usage view (#6170) 2026-08-11 16:47:13 +02:00
6676f9c83b fix(mobile): stabilize thread composer and interactions (#5986)
Co-authored-by: codex <[email protected]>
Co-authored-by: Thuong Tin <[email protected]>
Co-authored-by: Kapish14 <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-11 14:05:03 +00:00
Utkarsh Patilandshivam 65b005f1e4 feat(web): add Copy Thread ID to the sidebar and chat header thread context menu (#5574)
Co-authored-by: shivam <[email protected]>
2026-08-11 18:32:02 +05:30
Utkarsh Patilandshivam 752acbf654 feat: add ability to create a new thread in the current project with shift+click and show shortcut in tooltip (#5994)
Co-authored-by: shivam <[email protected]>
2026-08-11 18:26:53 +05:30
Guilherme Vieira f5fce74169 fix(pull-requests): route self-hosted GitLab remotes (#6061) 2026-08-11 13:11:19 +02:00
t3-code[bot] 9c7622dac3 fix(server): handle unborn HEAD in VCS status (#5944)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-10 23:34:18 -04:00
yassiEmp c14bcca103 fix(server): advertise 256-color TERM on Windows terminals (#5693) 2026-08-10 23:33:58 -04:00
bkntr 1fa315ea93 fix(server): skip Linux libc detection on Windows/macOS (#5354) 2026-08-10 23:33:18 -04:00
Taras f9730979c1 perf(web): skip base64 for oversized image candidates (#5220) 2026-08-10 23:33:08 -04:00
AlexandIllia Panasenko 59d0c922e9 fix(web): persist sidebar shelf collapse state (#5136)
Co-authored-by: Illia Panasenko <[email protected]>
2026-08-10 23:32:22 -04:00
Arham AminandClaude Opus 4.8 2ea51bd31f fix(server): OpenCode model parsing drops models with a slash in the JSON body (#5072)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-10 23:31:31 -04:00
Pavlo TrinkoandClaude Fable 5 e5c82d79a0 fix(mobile): keep chat composer above the Android gesture bar (#5988)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-10 20:31:00 -04:00
Jono Kemball 9afef94a61 feat: add three-hour snooze option (#5914) 2026-08-11 00:03:26 +02:00
Utkarsh Patil a7b0366cbe fix(web): account for Windows window controls in PR page header (#6049) 2026-08-10 22:10:00 +02:00
Julius Marminge 428d9f9f67 Allow Android tablets to rotate (#5613) 2026-08-10 21:18:13 +02:00
t3-code[bot] 1b120f352f fix(ci): extend release publish timeout (#6034) 2026-08-10 21:01:09 +02:00
Chris Deeming 0a7c662d39 fix(web): improve built-in theme contrast (#6000) 2026-08-10 12:06:55 -04:00
Utkarsh Patil b91a000a17 feat(web): add duplicate action to the T3 Code default theme (#6013) 2026-08-10 18:02:27 +02:00
Tylerandtsouth89 8de0aa24d9 perf(desktop): probe the Windows shell environment concurrently (#5878)
Co-authored-by: tsouth89 <[email protected]>
2026-08-10 11:53:10 -04:00
cad2c93616 feat: multi-provider pull requests page with in-app reviews (#4849)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: maria <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-10 17:47:02 +02:00
t3-code[bot] 78f462c4e1 chore(release): prepare v0.0.33 2026-08-10 12:00:11 +00:00
Julius Marmingeandcodex 3b72d17cbc fix(mobile): parse EAS fingerprint JSON (#5991)
Co-authored-by: codex <[email protected]>
2026-08-10 11:35:40 +00:00
d440442db6 fix(mobile): stop Android user bubbles with code blocks from overlapping (#5659)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-10 12:36:08 +02:00
Mina Yacoub 67ef189d8b fix(mobile): detect PowerShell cmdlet errors in work log rows (#5726) 2026-08-10 12:34:28 +02:00
Utkarsh Patil fbcae59ef5 fix(web): use import/export-appropriate icons for theme buttons (#5964) 2026-08-10 15:48:54 +05:30
Wout Stiens 9821bca1ce fix(web): use themed confirmation dialogs (#5624) 2026-08-10 02:23:27 -04:00
Chris Deeming 3d74474f6c fix(web): update pills use readable theme foregrounds (#5938) 2026-08-09 23:26:45 -04:00
Carter Smith f0e2975180 fix(web): align project name with headline (#5864) 2026-08-09 23:22:48 -04:00
Theo BrowneandClaude Opus 5 d43210050b fix(web): trait menu closes after you pick a level (#5879)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-09 23:22:28 -04:00
SimoneandSimone ef051bdb87 fix(web): enable restore defaults after theme mix changes (#5928)
Co-authored-by: Simone <[email protected]>
2026-08-09 23:21:56 -04:00
Tristan Knight 0ca9fb3fb5 fix(web): show worktree icon in sidebar v2 (#5909) 2026-08-09 23:21:39 -04:00
Ellie Gummere cbd55d6374 fix(web): correct model picker trigger padding (#5935) 2026-08-10 04:32:13 +02:00
Julius Marminge 96906805f1 Add settings and usage breadcrumbs (#5929) 2026-08-10 02:12:19 +00:00
Julius Marminge 73b2e8fdd4 Automate production mobile EAS releases (#5609) 2026-08-10 04:11:22 +02:00
Julius Marmingeandcodex 5da45337f7 Preserve back navigation when opening settings (#5930)
Co-authored-by: codex <[email protected]>
2026-08-10 01:55:32 +00:00
Julius Marminge f21d5e444e Move project settings to contextual project routes (#5923) 2026-08-10 02:57:39 +02:00
t3-code[bot] 9a1472d955 fix(web): match usage titlebar text styling (#5897)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-09 20:14:15 -04:00
Theo Browne 2abe66800c fix(server): sandbox user-provided SVGs (#5916) 2026-08-09 16:51:43 -07:00
Theo BrowneandClaude Fable 5 0d38866dcf fix(server): usage no longer double-counts forked Codex sessions (#5887)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-09 15:56:17 -07:00
Julius MarmingeandClaude Fable 5 f993fa1c5f fix(mobile): long-pressing a thread row no longer navigates into the thread (#5901)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-10 00:29:31 +02:00
Utkarsh Patil 83d769f02d fix(web): match settings search shortcut styling to command palette's (#5841) 2026-08-09 17:48:10 -04:00
Arham AminandClaude Opus 4.8 c8ad4b8135 fix(shell): add ~/.local/bin to the Windows CLI resolver so native-installed providers are found (#5074)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-09 14:45:08 -07:00
t3-code[bot] bd18d8d6d1 fix(web): unify usage page chrome (#5823) 2026-08-09 23:26:26 +02:00
nathangerday 659986ce38 fix(web): thread title button no longer eats the drag area (#5857) 2026-08-09 17:22:52 -04:00
062b4618c2 fix(shared): bound the file-link label so bracket runs stop rescanning (#5782)
Co-authored-by: tsouth89 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-09 14:16:12 -07:00
Matt Urenovich deb901d638 fix(server): favicon resolution no longer pins the event loop (#5538) 2026-08-09 21:10:49 +00:00
Utkarsh Patil 02f4ce5667 fix(web): match create theme and import theme buttons to the standard outline style (#5860) 2026-08-09 14:04:34 -04:00
Robert Soriano 285cf5947b fix(web): preserve desktop route during Clerk auth (#5770) 2026-08-09 17:33:03 +00:00
Julius Marminge 1a003e383a Add cross-platform mobile usage dashboard (#5743) 2026-08-09 12:10:27 +02:00
Theo BrowneandClaude Fable 5 963ebf5bd7 ci: label-gated hosted-web preview deploys (#5465)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-09 00:30:27 -07:00
Theo BrowneandClaude Opus 5 ba9c9ae81d fix(server): one greedy agent process no longer takes down the whole server (#5788)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 22:13:26 -07:00
Theo Browne 076e9048dc feat(web): project icons can be chosen manually (#5775) 2026-08-08 22:13:16 -07:00
Theo BrowneandClaude Fable 5 05eb051184 feat(web): keep unsent drafts one click away in the sidebar (#5777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 20:29:21 -07:00
Theo BrowneandClaude Fable 5 ddaa6afef5 feat(server): vp run migrate-dev-db seeds worktree dev dbs with real data (#5773)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:51:18 -07:00
Theo BrowneandClaude Opus 5 6f69b4407f fix(web): sidebar rows show the branch again, not a truncated plan step (#5776)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 19:45:21 -07:00
Theo BrowneandClaude Fable 5 6dbffa022d feat: pick worktree or current checkout per project (#5766)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:44:58 -07:00
Theo BrowneandClaude Fable 5 5bb8c03664 fix(server): settle no longer leaves monitors and dev servers running (#5774)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:44:15 -07:00
Theo BrowneandClaude Fable 5 886195ec1e fix(web): usage totals no longer jump while devices report in (#5772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:05:16 -07:00
Theo BrowneandClaude Fable 5 288d8e3457 feat(web): overhaul project settings into a real settings page (#5768)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:50:03 -07:00
Theo BrowneandClaude Fable 5 5208bdeb0d fix(web): pinned reorder no longer reshuffles while writes land (#5767)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:46:27 -07:00
Theo BrowneandClaude Fable 5 a6c9b41f90 feat(server): agents can now open the images you paste into chat (#5757)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:43:53 -07:00
Theo BrowneandClaude Fable 5 70c423a5e4 fix(web): usage page loses the cost quality panel, gains a back button (#5756)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 21:31:20 -04:00
Theo Browne 89c320df0b fix(server): stop Codex threads with queued follow-ups (#5762) 2026-08-08 17:52:06 -07:00
Theo Browne 7b2cf4374f chore: vouch saphid (#5763) 2026-08-08 20:44:28 -04:00
Theo Browne 49964e38c0 chore: vouch gfsaaser24 (#5761) 2026-08-09 00:32:10 +00:00
e70cdb478d fix(server): stop Claude resume handshakes from completing turns that never ran (#5710)
Co-authored-by: t3-turbo-simulation <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 17:24:42 -07:00
naMqe be01b287b9 fix(web): add missing cursor-pointer styling to dropdowns and interactive buttons (#5716) 2026-08-08 20:02:57 -04:00
Theo BrowneandClaude Fable 5 c2f8cb7ca1 feat(web): show how many subagents are running at a glance (#5745)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 16:20:06 -07:00
Leonel Rivas 89ee692bf0 fix(web): persist diff view mode (#5731) 2026-08-08 17:02:51 -04:00
Theo BrowneandClaude Opus 5 a20923ce46 fix(web): usage chart no longer makes Claude look like the bigger spender (#5697)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 05:43:03 -07:00
Theo BrowneandClaude Opus 5 8101cd0449 feat(usage): usage page reading provider transcripts across environments (#5684)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 03:59:04 -07:00
Theo BrowneandClaude Fable 5 30164cb1ba feat(mobile): one sheet for model and thread settings (#5625)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 03:51:20 -07:00
Theo BrowneandClaude Fable 5 0640410726 fix(desktop): zoom shortcuts no longer die when the preview browser has focus (#5691)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 02:24:38 -07:00
Theo BrowneandClaude Fable 5 2c7267ad43 fix(server): stop the reaper from silently killing live background subagents (#5677)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 21:42:14 -07:00
Chris Deeming daf8ee0b2f fix(web): inherit terminal size in simple typography (#5628) 2026-08-07 23:31:47 -04:00
t3-code[bot] ed886fe181 fix(web): delay transient reconnect warnings (#5670)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 23:17:18 -04:00
Theo BrowneandClaude Opus 5 4eaf5ef8bb fix(server): stop PR status lookups amplifying GitHub rate limits (#5673)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 18:09:46 -07:00
Theo BrowneandClaude Fable 5 0de9540739 feat: sidebar v2 is now the default sidebar (#5672)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 18:06:10 -07:00
Theo BrowneandClaude Fable 5 31891a1a0c feat(web): fold plan mode and token-by-token output into Legacy features (#5664)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 17:17:44 -07:00
Illia Panasenko 45d9aa90ba fix(web): show Stop button while input is pending (#5554) 2026-08-07 17:03:52 -04:00
Henry Zhang 7a84f6cf10 fix(web): reconnect the composer seam for remote non-Git projects (#5633) 2026-08-07 17:03:31 -04:00
maria f0fb406acf feat(web): make sidebar artwork theme-aware (#5636) 2026-08-07 15:41:59 -04:00
t3-code[bot] 82406bce99 chore: vouch chrisdeeming (#5641)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 15:01:39 -04:00
Chris Deeming 72d673a855 feat(desktop): remember recently used sites in the Browser panel (#5270) 2026-08-07 14:45:56 -04:00
t3-code[bot] e2cd2383ce chore(ci): vouch StiensWout (#5637)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 14:29:50 -04:00
Theo BrowneandClaude Fable 5 5661c6116c feat(web): drag pinned threads into your own order (#5581)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 06:57:22 -07:00
Theo BrowneandClaude Opus 5 6d70e6d778 fix(mobile): reconnects no longer shift the thread list (#5372)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 06:21:04 -07:00
t3-code[bot] be1a836745 chore(release): prepare v0.0.32 2026-08-07 11:50:54 +00:00
Utkarsh Patil 239ef1c54d fix(web): show the correctly matching shortcut in new thread button's tooltip (#5594) 2026-08-07 12:54:36 +02:00
Utkarsh Patil 61b51ae0e3 feat(web): click the pin icon to unpin a thread (#5578) 2026-08-07 12:54:11 +02:00
Julius Marminge bfc69e4b4d Bump mobile app version to 1.0.2 (#5588) 2026-08-07 12:35:07 +02:00
Gabriel De Andradeandcodex af281c9fc4 fix(mobile): repair Clerk auth navigation headers (#5140)
Co-authored-by: codex <[email protected]>
2026-08-07 12:29:06 +02:00
Pavlo Trinko bd422fd8d1 fix(mobile): keep Android chat text from showing through the composer (#5582) 2026-08-07 10:22:49 +00:00
Tyler Saari 33a03c8a7b fix(mobile): pad scroll views above Android nav bar (#5415) 2026-08-07 10:21:31 +00:00
Justyn Leung a17459e8a9 fix(mobile): avoid iOS terminal reset on clear (#5440) 2026-08-07 10:20:15 +00:00
Theo BrowneandClaude Fable 5 b2ee17d7c1 feat(web): thread actions from the chat header title (#5592)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 10:18:12 +00:00
Theo BrowneandClaude Opus 5 7963cc70f3 feat(server): record runtime mode per turn and on mode changes (#5593)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 03:16:11 -07:00
Jay Meistrichandcodex b792ed9f7b fix(web): stabilize chat timeline positioning (#5449)
Co-authored-by: codex <[email protected]>
2026-08-07 12:12:19 +02:00
Theo BrowneandClaude Fable 5 2e66b1fdfc fix(web): live background-work banner no longer hides behind the update notice (#5595)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 10:10:36 +00:00
Jay Meistrich 8100062a78 fix(mobile): improve keyboard avoiding (#5451) 2026-08-07 09:40:06 +00:00
Theo BrowneandClaude Fable 5 a1762fdd74 fix(dev): Improve instructions for --share (#5586)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 09:28:51 +00:00
Theo BrowneandClaude Fable 5 388b43a27c perf(dev): faster cold-start for dev web serving (#5584)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 02:28:00 -07:00
Theo BrowneandClaude Fable 5 23f0a1ae38 fix(web): reading a thread clears Done; Woke is dismissible (#5579)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 02:09:16 -07:00
85b1734d4d feat(web): add modular theme library (#5226)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-07 10:37:43 +02:00
Theo BrowneandClaude Opus 5 3ffe84f968 fix(web): stop the sidebar "Working" label from pulsing (#5580)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 01:27:31 -07:00
Mateleo 220efad62b fix: add missing space before 'GitHub releases page' link on download page (#4511) 2026-08-07 01:21:18 -07:00
Theo BrowneandClaude Fable 5 b98a0f0d22 fix(mobile): invisible T3 Connect devices can now be seen and removed (#5563)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 00:58:26 -07:00
Theo BrowneandClaude Opus 5 95305c36fa feat(web): per-device provider settings (#4479)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 00:57:22 -07:00
Theo BrowneandClaude Fable 5 48aa875c0e feat(web): remove Build/Plan toggle from the composer (#5551)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 00:42:50 -07:00
Theo BrowneandClaude Fable 5 a8cd2ad2eb fix(web): plans stop hijacking the UI, fold into chat instead (#5558)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 00:16:14 -07:00
Theo BrowneandClaude Fable 5 4a07c1ca9d docs: ship production T3 Connect public config in .env.example (#5573)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 23:53:19 -07:00
Theo Browne cf5c9948c8 fix(web): keep agent panel rows stable (#5569) 2026-08-06 23:19:20 -07:00
Theo BrowneandClaude Opus 5 2288d416aa fix(web): stop the "requests are slow" warning from firing on every provider update (#5570)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-06 23:18:34 -07:00
Theo Browne ddfe45c66e test(server): catch client transfer regressions in CI (#5350) 2026-08-06 23:17:49 -07:00
Theo BrowneandClaude 9547cf2463 fix(server): one disconnecting client no longer blocks every reconnect (#5572)
Co-authored-by: Claude <[email protected]>
2026-08-06 23:15:40 -07:00
Theo BrowneandClaude Fable 5 1c7d059f55 fix: scrolling up during a running thread no longer snaps back to the bottom (#5566)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 21:32:01 -07:00
Theo Browne 6fa4576078 fix(server): settle stopped Claude subagents (#5568) 2026-08-06 21:15:59 -07:00
ae7b27de82 fix: prevent reconnect loops during server stalls (#5561)
Co-authored-by: t3-turbo-simulation <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-08-06 21:14:50 -07:00
Theo BrowneandClaude Fable 5 6b73b3defe feat: paginate thread loading with user-anchored turn windows (#5493)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 19:33:49 -07:00
Theo Browne 7aad7911f6 fix(server): let stopped threads settle immediately (#5553) 2026-08-06 18:43:13 -07:00
Theo Browne 6da92244cc fix(web): show one toast when snoozing threads in bulk (#5560) 2026-08-06 18:16:36 -07:00
Theo BrowneandClaude Fable 5 c471145e96 fix(server): stopping a Claude thread no longer shows an ede_diagnostic error (#5557)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:55:20 -07:00
Theo Browne 64a991ad45 fix(web): show remote environment for non-Git projects (#5555) 2026-08-06 17:55:00 -07:00
Theo BrowneandClaude Fable 5 0ec4fbc4a3 fix(server): stop showing commit/push/PR notices as errors in the work log (#5559)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:52:29 -07:00
Theo BrowneandClaude Fable 5 ea50b695a7 fix(web): update tooltip no longer dismisses when scrolling release notes (#5547)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:31:12 -07:00
Theo BrowneandClaude Fable 5 331c6dce7f fix(server): skip origin fetch when creating worktrees in repos without an origin remote (#5556)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 20:13:10 -04:00
Wout Stiens 4f5834ba72 fix(web): clear woke state on explicit thread actions (#5486) 2026-08-06 14:08:35 -04:00
Wout Stiens aa16c180e5 fix(web): align composer inline chips with prompt text (#5495) 2026-08-06 12:57:02 -04:00
Carlos Rico-OspinaandClaude Opus 5 470d4eb993 fix(mobile): stop thread messages reading through pending cards (#5450)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-06 12:56:01 -04:00
t3-code[bot] 99d91ddaa4 fix(acp): keep unknown approvals actionable (#5430)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:31 -04:00
t3-code[bot] ab3b55e29a fix(web): clarify auto permission fallback (#5431)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:00 -04:00
Theo BrowneandClaude Fable 5 e4abc31f1e docs(server): pin interleaved-collapse divergence as intentional with test
Bugbot flagged that clients collapse only adjacent lifecycle rows, so
dropping a superseded update separated by an interleaved parallel call
diverges from full-history rendering. Measured on a real database: 1.5%
of dropped rows (553/36,581), all pure in-flight state whose final result
the retained completion still shows, and zero dropped rows carry a
client-merged payload field their completion lacks (verified across all
49,515 update rows). Documents the tradeoff and adds a test pinning it.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:24:08 -04:00
Theo BrowneandClaude Fable 5 b7d1981b57 fix(server): drop superseded tool updates from snapshots
A tool.updated row is the in-flight snapshot of a call; once the call
completes, the tool.completed row carries the final state and both
clients fold every matching update into it. Shipping the updates buys
nothing: 47k such rows exist in one real database, and a single thread
carries 3,291 of them.

Filter them out of thread snapshots, mirroring the existing
context-window dedup. Matching is per turn and only against a LATER
completion, so a revert that discards the completing turn cannot leave
a call unrepresented, and a later update under the same identity (the
next call, still in flight) survives. Live events are untouched.

Rows are matched on the same identity the clients collapse by: an
explicit data.toolCallId when the adapter emits one, otherwise the
itemType/title/detail triple. No tool lifecycle row in the real db
carries a toolCallId, so the fallback does the work.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:24:08 -04:00
Theo Browne 64a3cd6d7d fix(server): separate trial cleanup from handoff retention 2026-08-06 08:09:51 -04:00
Theo Browne 48e2c27f2f fix(web): make update version tooltips accessible 2026-08-06 08:09:51 -04:00
Theo Browne 8b2ea5721a fix(server): order explicit service shutdown 2026-08-06 08:09:51 -04:00
Theo Browne df2f1273e9 fix(server): clean up interrupted update trials 2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 f9e8236899 fix(server): release the tunnel when an explicit stop interrupts an update
A pending update in the launcher state is not proof a replacement
server is coming: `t3 service uninstall` or `systemctl stop` during
the pending window also tears the server down, permanently. The
launcher now writes a stop marker before signalling its child on an
explicit stop and clears it on the next start; the shutdown tunnel
release keeps the tunnel only for pending updates without the marker.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 8f341f20c9 test(server): use the launcher state writer in release tests
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 808d685355 fix(server): keep the managed tunnel across remote update restarts
Measured on a live update: the server was back in ~9s but stayed
unreachable for ~96s, because releasing the tunnel on shutdown forces
the replacement tunnel's hostname route through 1-2 minutes of edge
propagation. An update handoff always brings a server right back
(new version or rollback), so the tunnel is never orphaned; skip the
release when the launcher state file records a pending update. The
next boot respawns the connector from the stored config against the
same tunnel and is reachable as soon as it connects.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Theo BrowneandClaude Fable 5 80720ad592 fix(web): calm one-row server update status and banner
The version-skew banner is no longer an amber warning: it reads
"Server update available" with the raw versions (unreadable for
nightlies) moved to a tooltip. The in-flight rail (Download/Install/
Resume) becomes a single status row, "Downloading…" then
"Restarting…", since the wire installing stage is a sub-second
launcher handoff and "resuming" meant nothing to most people.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Hugo Blom a483337a02 fix: respect time format for sidebar snooze (#4438) 2026-08-06 11:40:58 +02:00
Theo BrowneandClaude Fable 5 1ffba7093a fix(web): closed plan sidebar stays closed when returning to a thread (#5484)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:37:27 -07:00
Theo BrowneandClaude Fable 5 3da315e7b5 perf(server): stop shipping full MCP tool results in thread payloads (#5482)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:34:27 -07:00
Theo BrowneandClaude Fable 5 a2ca89aa10 feat: native subagent & workflow observability (#5219)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 00:32:28 -04:00
Theo BrowneandClaude Fable 5 990bb0b689 fix: reconnect faster after remote server updates (#5404)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-05 19:12:52 -07:00
Julius Marminge 7251f1a1f1 Prevent terminal loading flash (#5432) 2026-08-05 23:09:23 +02:00
t3-code[bot] 30e471530b fix(web): preserve terminal font size when splitting (#5444)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-05 17:02:53 -04:00
Julius Marminge de592a00e8 Enrich terminal font previews (#5428) 2026-08-05 16:03:10 +00:00
Wout Stiens 2a04db134c fix(web): keep terminal font settings reliable (#5397) 2026-08-05 13:42:56 +02:00
Theo Browne 37d3667de4 fix(web): keep model picker shortcuts in sync (#5400) 2026-08-05 04:23:18 -07:00
Theo Browne 9697b765e5 fix(ci): isolate releases from shared API rate limits (#5394) 2026-08-05 02:36:10 -07:00
Wout Stiens 9d9a872bcc fix(web): restore terminal link hover styles (#5382) 2026-08-05 11:20:17 +02:00
Wout Stiens 9235c83eb7 fix(web): keep the composer command menu anchored to the composer (#5336) 2026-08-05 11:19:58 +02:00
shivamandT3 Code Test e0c85a20ef fix(mobile): avoid double dividers between thread sections (#5391)
Co-authored-by: T3 Code Test <[email protected]>
2026-08-05 13:28:10 +05:30
Fllip 3c5bdb84a9 fix(web): truncate long project switcher names (#5348) 2026-08-05 02:03:56 -04:00
shivam 70de6e1786 fix(mobile): prevent Android thread search crash (#5386) 2026-08-05 11:30:10 +05:30
shivamandT3 Code Test 47dfc65265 fix(mobile): preserve grouped project workspaces (#4642)
Co-authored-by: T3 Code Test <[email protected]>
2026-08-05 10:51:35 +05:30
Theo Browne 41ebf22eea fix(web): clear main branch lint warnings (#5384) 2026-08-04 21:31:39 -07:00
Hwanseo Choi 3d429662c9 fix(mcp): unblock Kimi models in OpenCode with preview tools (#5128) 2026-08-04 23:03:15 -04:00
Theo Browne 7b38fb5c6b fix(server): allow remote updates with database migrations (#5374) 2026-08-04 18:41:56 -07:00
Fllip 7537adc30f fix(web): prevent legacy model picker layout shift (#5349) 2026-08-04 20:05:44 -04:00
Theo Browne 94696b0f54 fix(desktop,web): improve in-app browser shortcuts and URL behavior (#4703) 2026-08-04 17:01:34 -07:00
Theo BrowneandClaude Fable 5 fff6a5b028 feat(web): make pairing QR codes actually scannable, with endpoint choice (#5360)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 16:53:54 -07:00
Theo BrowneandClaude Fable 5 da6e1a9678 feat(sidebar-v2): thread pinning for sidebar v2 (#5312)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 16:35:51 -07:00
8eca20005b feat(web): configurable fonts and sizes under Settings → Appearance (#5103)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-05 00:55:06 +02:00
Theo Browne 2fa1fec8d8 refactor(server): make title prompts plaintext (#5368) 2026-08-04 15:51:56 -07:00
Theo Browne 9bd2a4c688 fix(server): keep regenerated titles on topic (#5365) 2026-08-04 15:32:05 -07:00
maria 4fb03aff0b fix(web): better right panel (new diffs styling) (#5260) 2026-08-05 00:00:24 +02:00
Theo Browne d7950ac153 fix(server): generate durable thread titles (#5357) 2026-08-04 14:02:33 -07:00
Theo BrowneandClaude Fable 5 36caf34c68 fix(desktop,web): contain renderer memory growth and recover from renderer OOM crashes (#5148)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-04 13:37:03 -07:00
Bilal Bakr 90e3778660 fix(web): stop the chat timeline reading through the provider status banner (#5353) 2026-08-04 15:41:07 -04:00
Rushikesh Gaikwad 94331c58ec fix(mobile): show correct provider icons for Grok, Cursor, and OpenCode (#4586) 2026-08-04 11:04:37 -07:00
Arham AminandClaude Opus 4.8 c30a6d9b99 fix(server): scrub AppImage XDG_DATA_DIRS and GSETTINGS_SCHEMA_DIR from terminals (#5075)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:35:10 -04:00
Yukun Shan 37ae1abbe9 fix(ssh): isolate managed tunnel processes (#4347) 2026-08-04 09:34:23 -04:00
Arham AminandClaude Opus 4.8 82b76e2138 fix(server): use a Cursor todo's title when its content is blank (#5073)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-04 09:19:12 -04:00
naMqe 8a16cadbaf fix(web): increase tooltip z-index to overlay popovers and menus (#5326) 2026-08-04 09:18:34 -04:00
Julius Marminge 2b1d4fecb8 Upgrade Effect to beta.103 (#5331) 2026-08-04 13:56:50 +02:00
t3-code[bot] cec1bb9de3 fix(web): align multiline error alert controls (#5304) 2026-08-04 13:34:22 +02:00
t3-code[bot] 25ec0b9d13 fix(web): simplify chat code blocks (#5301) 2026-08-04 13:34:10 +02:00
Rodrigo BrechardandRodrigo Brechard 966cc05a90 fix(contracts): decode ServerProviders forward-compatibly (#5327)
Co-authored-by: Rodrigo Brechard <[email protected]>
2026-08-04 13:07:22 +02:00
Wout Stiens 1cbd88aba0 fix(server): strip replayable terminal queries from history (#5319) 2026-08-04 12:52:05 +02:00
Wout Stiens 553867262c fix(terminal): protect held Ctrl/Cmd+W close shortcut (#5322) 2026-08-04 12:51:36 +02:00
Wout StiensandClaude Opus 5 11639bf439 fix(web): blink the terminal cursor again (#5314)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-04 12:50:19 +02:00
t3-code[bot] a261a6440a fix(web): match loading screen to dark theme (#5303) 2026-08-04 00:50:56 +02:00
Mike OlsonandJulius Marminge 6f04a5cffb fix(desktop): Niri/Hyprland - Linux secret storage backend (#2916)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-03 22:02:47 +02:00
maria 30c9622806 fix(web): polish interface spacing (#5252) 2026-08-02 23:35:04 -04:00
Julius Marminge 69dfb7f09a fix(desktop): claim the t3code:// scheme default on Linux at startup (#5054) 2026-08-02 21:53:37 +00:00
Theo Browne e60821f0e0 feat: fold legacy models into separate menus (#5190) 2026-08-02 00:45:05 -07:00
Theo BrowneandClaude 64bf016191 fix(server): stop npx service updates from silently leaving the old server running (#5217)
Co-authored-by: Claude <[email protected]>
2026-08-01 22:42:39 -07:00
Arham AminandClaude Opus 4.8 5192f777fe fix(server): surface cloudflared FTL/PNC relay logs as warnings, not debug (#5076)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-01 16:10:25 -04:00
t3-code[bot] 283c7ac4ba fix: normalize app icon glyph sizing (#5202)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-01 15:21:40 -04:00
Illia Panasenko 78eb3ecae9 fix(web): stop settle controls overlapping the status label (#4574) 2026-08-01 15:06:31 -04:00
Theo Browne d3037064e6 fix(server): make remote updates rollback-safe (#5181) 2026-08-01 05:48:03 -07:00
Theo BrowneandClaude Fable 5 0ad91b6e7f fix(server): follow branch drift in dedicated worktrees so PRs link to their thread (#5159)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 20:18:58 -07:00
Theo BrowneandClaude Fable 5 ca72e381c6 fix(server): bound thread catch-up replay and stop full-DB snapshot hydration (#5147)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 16:14:15 -07:00
Theo Browne 491219bf1f fix: threads with open PRs no longer auto-settle (#5151) 2026-07-31 15:46:15 -07:00
shivamandClaude Fable 5 e5c7547067 feat(web): add settings sidebar search (#4682)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 18:11:27 -04:00
shivamandClaude Fable 5 bfc31507f8 feat(web): search threads from the sidebar (#4769)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 16:52:20 -04:00
shivamandT3 Code Test 03adf215ce follow-up normalization after #4700. (#4498)
Co-authored-by: T3 Code Test <[email protected]>
2026-07-31 16:11:28 -04:00
Alex 916cff733c feat(mobile): make settled threads collapsible (#5056) 2026-07-31 14:55:29 -04:00
Gabriel De Andrade a041981276 feat(mobile): add thread snoozing (#5053) 2026-07-31 10:22:52 -04:00
Wout StiensandClaude Fable 5 964cc27901 refactor: move the canonical libghostty-vt vendor to the repository root (#5102)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 14:20:27 +02:00
Wout StiensandClaude Fable 5 acf761b2f5 feat(web): render terminals with libghostty-vt (#4860)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 13:15:25 +02:00
Julius MarmingeandClaude Fable 5 ab8182cb4e fix(ci): rotate iPad showcase captures without Simulator UI scripting (#5094)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 13:11:56 +02:00
Theo BrowneandClaude Fable 5 ef4ec2ad4b fix(server): self-update no longer rolls itself back on restart (#5095)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 03:46:47 -07:00
Theo BrowneandClaude Fable 5 61514c1294 feat(cli): npx t3 pair - generate QR code from a running server (#4955)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 03:18:55 -07:00
Mike Olson 894d6d68f5 fix(oxlint-plugin): Resolve the oxlint bin without assuming a pnpm layout (#5066) 2026-07-31 11:45:00 +02:00
Alex fccec9f097 fix(ci): capture iPad App Store screenshots in landscape (#5065) 2026-07-31 10:12:23 +02:00
Julius Marminge 50a3d6b872 fix(ci): repair the mobile showcase screenshots workflow (#5057) 2026-07-31 10:11:12 +02:00
Theo BrowneandClaude Fable 5 e259dd23c7 fix(mobile): server model, worktree, and origin preferences now apply to new tasks (#5064)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-30 21:21:39 -07:00
Julius MarmingeandClaude Fable 5 df78cda8bf fix(contracts): decode growing config unions forward-compatibly (#5055)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 01:11:46 +02:00
Alex 605c2bb734 fix(mobile): show the correct build channel in Android's Threads page header (#4861) 2026-07-30 22:30:46 +00:00
Aditya Vardhan Sharma cb11a71d63 fix(mobile): accept Android clipboard images in composer (#4836) 2026-07-31 00:20:33 +02:00
Simon DobaandClaude Opus 5 41124c7260 fix(desktop): link release notes from the update downloaded toast (#4771)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-07-31 00:19:34 +02:00
Max Anderson b0b275227b chore: add mobile issue template area (#4895) 2026-07-31 00:19:00 +02:00
Alex cb293fe790 fix(mobile): restore iOS Threads branding (#4862) 2026-07-31 00:17:47 +02:00
Simone 1d694dcbd8 fix(mobile): default bare IP pairing to HTTP (#4990) 2026-07-30 22:17:38 +00:00
Arham AminandClaude Opus 4.8 32407df9c5 fix(shared): lenient JSON parser deletes commas inside string values (#5025)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-30 22:16:22 +00:00
Elaine Lyons 162e774294 fix(mobile): remove unnecessary photo library permission (#4929) 2026-07-31 00:15:38 +02:00
Arham AminandClaude Opus 4.8 063ed7120a feat(shared): support shorthand (major-only) versions in the semver helpers (#5027)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-07-30 22:13:46 +00:00
Utkarsh Patil 34b15a9ace perf(server): cache default branch name and origin existence across status refreshes (#5008) 2026-07-31 00:08:59 +02:00
Julius MarmingeandClaude Fable 5 fbecb7365e fix(desktop): bump Clerk Electron SDK to 0.0.24 and register t3code:// scheme on Linux (#5015)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-07-31 00:06:49 +02:00
Julius MarmingeandClaude Fable 5 4029b858ea fix(ci): drop sparse-checkout from EAS workflows
actions/checkout implements sparse-checkout with --filter=blob:none, so
the runner repo is a partial clone missing the .repos/ blobs. eas-cli
archives the project via `git clone --depth 1 file://<workspace>`,
which upload-pack cannot serve from a partial clone and exits 128
(#4802 broke both EAS build workflows this way).

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 13:15:03 -07:00
maria 5b2577f6a9 style(web): make scroll-to-end pill translucent (#5036) 2026-07-30 20:08:05 +00:00
Julius MarmingeandClaude Fable 5 bc142f84a2 chore(mobile): bump app version to 1.0.1
Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-30 13:07:10 -07:00
1192 changed files with 152378 additions and 20985 deletions

No files matched your search

+4 -15
View File
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Include a pairing token only when the user still needs to pair (see below).
## Authenticate the browser on the first navigation
@@ -50,24 +50,13 @@ Treat the overall testing or implementation loop—not an assistant turn or one
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
5. Continue in the same browser context so its stored bearer session remains available.
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
Keep pairing URLs out of screenshots, committed files, and durable logs. When the user asked for a shared environment, the deliverable IS the full pairing URL — paste it in your reply, token and all; a bare origin is useless to them. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it, so never open a URL you handed to the user.
## Recover a consumed or expired pairing token
Create another token against the same database and web URL as the running dev server:
Run `node apps/server/src/bin.ts pair` from the repository root. It discovers the running dev server (worktree `.t3` first, same precedence as the dev runner) and prints a fresh `Pair URL` against the server's current web origin, including a `--share` tailnet origin. Pass `--base-dir <base-dir>` only when the server was started with `--home-dir`, using the identical path.
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
```
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
Tokens from `pair` carry standard client scopes. The startup pairing URL carries admin scopes; if the user needs Settings → Connections management (`access:write`), restart the server and hand over the new startup URL instead.
## Inspect or seed SQLite state
+17 -17
View File
@@ -66,7 +66,7 @@ Use these client origins:
- Android Emulator: `http://10.0.2.2:<server-port>`
- Physical device: bind the backend to `0.0.0.0` and use the host's reachable LAN origin
Always enter the complete `http://` origin; the mobile host field otherwise assumes HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
Enter the complete `http://` origin to make the test transport explicit. Bare IP addresses default to HTTP, while bare hostnames default to HTTPS. When testing web and mobile together, run `vp run dev --home-dir <base-dir> --host 127.0.0.1` instead and do not launch a second backend over the same base directory.
## Start or reuse Metro safely
@@ -125,31 +125,29 @@ Do not start, stop, erase, or reconfigure an emulator owned by another task. Tra
## Pair each client once
Issue a fresh credential against the running backend's exact base directory:
Use the bundled helper from the repository root. It issues a fresh credential against the running backend's exact base directory, opens the existing Add Environment route with the credential in an encoded query parameter, and asks that route to connect once:
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--base-url <mobile-origin> \
--ttl 15m \
--label agent-mobile-<short-device-id>
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
ios <simulator-udid> <server-port> <base-dir>
.agents/skills/test-t3-mobile/scripts/pair-client.sh \
android <emulator-serial> <server-port> <base-dir>
```
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
Run only the command for the selected platform. The helper uses `http://127.0.0.1:<server-port>` for iOS and `http://10.0.2.2:<server-port>` for Android. Pass a fifth argument only when testing a non-development URL scheme.
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
The helper opens this registered route:
```bash
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
adb -s <emulator-serial> shell am start -W \
-a android.intent.action.VIEW \
-d 't3code-dev://connections/new' \
com.t3tools.t3code.dev
```text
t3code-dev://connections/new?pairingUrl=<encoded-pairing-url>&autoConnect=1
```
Run only the command for the selected platform.
The Add Environment route owns the behavior: `pairingUrl` prefills its normal host and token inputs, while `autoConnect=1` submits once in development builds and returns to Home after success. Without `autoConnect`, the same route only prefills the form for manual inspection.
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
Do not enter pairing hosts or tokens through simulator keyboard automation. Xcode's semantic typer sends HID-style key events through the simulator's active keyboard state, which can corrupt uppercase tokens and punctuation even when the host Mac uses a U.S. input source. The one-shot route is the deterministic pairing path. Use the visible form only as a fallback, and paste credentials rather than typing them character by character.
Verify the expected seeded projects appear before exercising the affected flow.
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
@@ -183,6 +181,8 @@ Keep local verification focused. Do not turn this workflow into a full repositor
- **Old UI or an old error appears:** verify Metro's worktree, variant, URL, and port before diagnosing the app.
- **The environment remains empty:** verify the platform-specific HTTP origin, use a fresh token, and confirm project seeding used the identical base directory.
- **A second client cannot pair:** pairing tokens are single-use; issue another token.
- **The pairing form opens but does not connect:** confirm the deep link uses the existing `connections/new` route, includes `autoConnect=1`, and carries a freshly minted encoded `pairingUrl`.
- **Pairing text changes case or punctuation:** do not retry semantic typing. Use `scripts/pair-client.sh`; the simulator keyboard layout and HID input path are not reliable for credentials.
- **iOS semantic actions fail:** set explicit XcodeBuildMCP defaults and refresh with `snapshot_ui`.
- **Android cannot reach Metro:** verify `adb reverse` for the exact Metro port and relaunch the development-client URL.
- **Android cannot reach the backend:** use `10.0.2.2`, not `127.0.0.1`, for the Android Emulator.
+72
View File
@@ -0,0 +1,72 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 <ios|android> <device-id> <server-port> <base-dir> [url-scheme]" >&2
exit 2
}
[[ $# -ge 4 && $# -le 5 ]] || usage
platform="$1"
device_id="$2"
server_port="$3"
base_dir="$4"
url_scheme="${5:-t3code-dev}"
case "$platform" in
ios)
mobile_origin="http://127.0.0.1:${server_port}"
;;
android)
mobile_origin="http://10.0.2.2:${server_port}"
;;
*)
usage
;;
esac
repo_root="$(git rev-parse --show-toplevel)"
cd "$repo_root"
if ! pairing_output="$({
T3CODE_PORT="$server_port" node apps/server/src/bin.ts auth pairing create \
--base-dir "$base_dir" \
--base-url "$mobile_origin" \
--ttl 15m \
--label "agent-mobile-${device_id:0:8}"
} 2>&1)"; then
echo "Could not mint a mobile pairing credential." >&2
exit 1
fi
pairing_url="$(printf '%s\n' "$pairing_output" | sed -n 's/^Pair URL: //p' | tail -n 1)"
if [[ -z "$pairing_url" ]]; then
echo "Could not parse the mobile pairing URL." >&2
exit 1
fi
deep_link="$(PAIRING_URL="$pairing_url" URL_SCHEME="$url_scheme" node - <<'NODE'
const query = new URLSearchParams({
pairingUrl: process.env.PAIRING_URL,
autoConnect: "1",
});
process.stdout.write(`${process.env.URL_SCHEME}://connections/new?${query}`);
NODE
)"
case "$platform" in
ios)
xcrun simctl openurl "$device_id" "$deep_link"
;;
android)
# adb shell re-joins its arguments and evaluates them through the device
# shell, so the deep link's `?`/`&` must be quoted once more for that shell.
adb -s "$device_id" shell \
"am start -W -a android.intent.action.VIEW -d '$deep_link' com.t3tools.t3code.dev" \
>/dev/null
;;
esac
echo "Opened the existing Add Environment route with a fresh pairing credential."
+12 -9
View File
@@ -1,12 +1,14 @@
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# `cp .env.example .env` enables T3 Connect against the production deployment.
# These are the same public identifiers baked into official release builds, not
# secrets. Remove or comment them out to build with cloud features disabled.
# Do not add server-side secrets to this file.
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Production Clerk instance. To use your own, get these from the Clerk Dashboard
# under API keys, JWT templates, and OAuth applications.
T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk
T3CODE_CLERK_JWT_TEMPLATE=t3-relay
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
@@ -15,8 +17,9 @@
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
# automatically.
T3CODE_RELAY_URL=https://relay.t3.codes
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
# Defaults to https://app.t3.codes; override to test against a staging deployment.
+2
View File
@@ -9,6 +9,7 @@ body:
attributes:
value: |
Use this form for broken behavior, regressions, crashes, or reliability problems.
Feature requests belong in [Discussions](https://github.com/pingdotgg/t3code/discussions/categories/ideas).
Search existing issues first and keep the report focused on one problem.
- type: checkboxes
@@ -30,6 +31,7 @@ body:
- apps/web
- apps/server
- apps/desktop
- apps/mobile
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Feature request
url: https://github.com/pingdotgg/t3code/discussions/categories/ideas
about: Suggest an improvement or new capability in Discussions.
-101
View File
@@ -1,101 +0,0 @@
name: Feature request
description: Propose a scoped improvement or new capability.
title: "[Feature]: "
labels:
- enhancement
- needs-triage
body:
- type: markdown
attributes:
value: |
Use this form for new capabilities or meaningful improvements to existing behavior.
This repo is still early. Small, concrete requests that clearly explain the problem and scope are much easier to evaluate.
- type: checkboxes
id: checks
attributes:
label: Before submitting
options:
- label: I searched existing issues and did not find a duplicate.
required: true
- label: I am describing a concrete problem or use case, not just a vague idea.
required: true
- type: dropdown
id: area
attributes:
label: Area
description: Which part of the project would this change affect?
options:
- apps/web
- apps/server
- apps/desktop
- packages/contracts or packages/shared
- Build, CI, or release tooling
- Docs
- Not sure
validations:
required: true
- type: textarea
id: problem
attributes:
label: Problem or use case
description: What are you trying to do? What is hard, slow, or impossible today?
placeholder: I want to reconnect to an existing provider session after a browser refresh without losing the current thread state.
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed solution
description: Describe the behavior, API, or UX you want.
placeholder: Persist enough session metadata so the client can discover and reattach to the active provider session on load.
validations:
required: true
- type: textarea
id: value
attributes:
label: Why this matters
description: Who benefits, and what outcome does this unlock?
placeholder: This would make reconnects predictable during network drops and reduce accidental duplicate sessions.
validations:
required: true
- type: textarea
id: scope
attributes:
label: Smallest useful scope
description: What is the narrowest version of this request that would still solve your problem?
placeholder: A first pass only needs to support restoring the active session for the current thread.
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives considered
description: Workarounds, prior art, or other approaches you considered.
placeholder: I currently work around this by manually restarting the provider session, but that loses in-flight context.
- type: textarea
id: tradeoffs
attributes:
label: Risks or tradeoffs
description: What costs, complexity, or edge cases should be considered?
placeholder: This may require careful handling when the underlying provider session has already exited.
- type: textarea
id: references
attributes:
label: Examples or references
description: Links, screenshots, mockups, or comparable tools.
- type: checkboxes
id: contribution
attributes:
label: Contribution
options:
- label: I would be open to helping implement this.
+6
View File
@@ -11,9 +11,11 @@
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chrisdeeming
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:gfsaaser24
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
@@ -25,7 +27,9 @@ github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:saphid
github:shiroyasha9
github:StiensWout
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
@@ -33,3 +37,5 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
github:bil0000
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="800"><image width="1280" height="800" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAMgCAIAAADz+lisAAAQAElEQVR4nOzdB3gU5drG8YGEBAiEFnrvvQsISBUERUGxIBYsR1EsR0X0oCj2jl3xU8FCUVABUXrvHQzSIXRCJ4RAIJV8d/aVcd1AsoGokPf/u/baazIzO/tOWZh7nimBSUlJDgAAAAAA2V1OBwAAAAAACxCAAQAAAABWIAADAAAAAKxAAAYAAAAAWIEADAAAAACwAgEYAAAAAGAFAjAAAAAAwAoEYAAAAACAFQjAAAAAAAArEIABAAAAAFYgAAMAAAAArEAABgAAAABYgQAMAAAAALACARgAAAAAYAUCMAAAAADACgRgAAAAAIAVCMAAAAAAACsQgAEAAAAAViAAAwAAAACsQAAGAAAAAFiBAAwAAAAAsAIBGAAAAABgBQIwAAAAAMAKBGAAAAAAgBUIwAAAAAAAKxCAAQAAAABWIAADAAAAAKxAAAYAAAAAWIEADAAAAACwAgEYAAAAAGAFAjAAAAAAwAoEYAAAAACAFQjAAAAAAAArEIABAAAAAFYgAAMAAAAArEAABgAAAABYgQAMAAAAALACARgAAAAAYAUCMAAAAADACgRgAAAAAIAVCMAAAAAAACsQgAEAAAAAViAAAwAAAACsQAAGAAAAAFiBAAwAAAAAsEKgA8APKSkpDgAAwMUqR44cDoCMEICBszBx1/sdAADg4mdisPc7AG8EYOAvUs5ISkpKTNRbsuidGAwAAC5miruBgQE5c+bMlStQL8lxhgPgjBzawXcAeEXfhITE2NhTKSmnc+XKFRSUyyMwICDAAQAAuFjpkL2O3ScmJmpPRpR7Q0Lyak+GGAx4IwADqZR7T3ucPHkqPj6xSJFC+g/DAQAAuDQpBh85cjQ4OFfevHlyepCBAYcADDhn0q9+C8ePxwYHBxcsGOoAAABc+qKjY+Lj4/PnDwkMDCQDAw4BGDDpNzEx8cSJkwULFggODnIAAACyi/j4hOjoY/ny5c2VKxcZGOA5wLCaueg3OTmZ9AsAALIl7d4ULBiqXR3t8Jg9HwewGAEYVjPp9+TJU8GpSL8AACAb8uznBGuHx2RgB7AYARj2OnPP54TExCSu+wUAANmYdnUSEpK020MRGJYjAMNepvx76lR84cKFHAAAgGytSJGCp07FUQSG5QjAsJT7yF+988QjAACQ7QUFBZ0+7SQmJlIEhs0IwLCXuflzrlykXwAAYAUd9NfRf+0COYCtCMCw1Jn7P5+m/AsAACyh3R7t/FABhs0IwLCXDn/qX38qwAAAwBLa7dHODxVg2CzQAaxkjn0qAufKxa8AAABYQbs9p/8oAFMBhqXY9YfV9K9/QECAAwAAYAHt9hB9YTlOgYaNzD/9/AcAAAAsxI4QbEYABgAAAABYgQAMAAAAALACARgAAAAAYAUCMAAAAADACgRgAAAAAIAVCMAAAAAAACsQgAEAAAAAViAAAwAAAACsQAAGAAAAAFiBAAwAAAAAsAIBGAAAAABgBQIwAAAAAMAKBGAAAAAAgBUIwAAAAAAAKxCAAQAAAABWCBg4cKAD2CclJSU5OTk+PjE0NJ+T1U6fPr1nz56tW7eePp0SGprfyb6io4+9//6HOXLkKFeunGM9rfEffvipQIECRYoUdi5iO3bsHD/+l8mTpxQpUiRXrqCLZw1GRKQuwIIFCxYu7LsAZ8yYOWbM2IYNG+TKlcv5R3gvpaJFizr/qs8//3LDho3169dzAOCCHT9+Ijg4KDAwMIeHA1gm0AGQpebNm//6629o79n8GRKSt1evXg8/3Ef/0ziXvr1790VFHalatWpwcLD+XLRo0bffDgsPD7/iipZOltq8ecvp08k1atRwLoxPgzPl2LFju3fvLlWqVNo8dtZGbtkS8cEHH5YtW6Zq1SrOxWrXrl033nhTbOxJbZnNmjXZsWPH37QGz0NEROoCrFChfJUqlX0Gvfnm2zqo1Lx58wzbmZSUtHHjRh2GKFu2rHO+fJZSrVo1nX/PgQMH3n//A3V07359SEiIAwAALgABGMhKq1b91rv3g+rQbrpeOsg6ceLEzz77v9WrVw8e/Enu3LmdS9xXX309YsTIiRN/qVw5NaK0adP6iSceb9LkMier/fe/jx06dGjlyuXOhfFpcKYsWbL0sceeePnlF2+55Wbn72zkP2nhwsXKdX37Pn7fff/JmTNnbGzs37QGs9arr760du16f9p59Gj0TTf1uPbaLoMGve2cL5+l5Pyrihcv/sorL+kIDukXAIALRwAGskxk5N777++tjiFDvnDrVPfdd++TTz49a9asKVOmXn99Nyd70R75Aw/c7+DSERkZqff27dubXHeprMHLPZx/is9S+tfdfPNNDgAAyArcBAvIMnPmzFHV6OGHH/I+SzNPnjzPPfesOoYNG+72nDRpct++/Ro3btK16w3vvDNo585dpr86une/adSoH0aO/E5VrBo1aut9zpy5GrRnzx4NGjToPe9v/OWXX9Vz3rz56k5MTPzmm2/vuuteTbZPn4d/+mmMO5o+pdHWrl33wAN9NE0zaP36DQ899GiLFq300vgbN250x58/f/69996n6WjQI4/81wyKiYnRRMaNG6fuhx9+VN2bN2/Zv3+/OvyZNbn99jsHDHh+8eIl993XW83o3PmaoUO/TkpK8lmMS5cu0zR37NiphakOLQHT/1wz+NRT/9Noa9asMX+mpKSoAeqzYcOGtA120tAXPf543zZt2muymmsdpzD91fP1199UxwcffKTPjh//iz+NdDxXgL///geaO01QS2/z5s3eH9T0NWUNuu22Oz777P9UgHXOQXP00kuvdOjQyayFFStWuoO0KLTotBg1nV697v7ss8/VDDMonU3o8OHDGvT999+r+5FHUhdIePhqnzWoxuuDWg7uB7/44kuNEBUVpaFafVqJ3o389tthGnrgwAHnHJuZBn344UfaGDQXzzwzYMmSJd4f15ZmthYtrq+++ibtxuD6+ONPNXEzm+aLtm/fbpakpvziiy8dO3bMSS34f3P33feqY/bs2Rrn1VdfNx9Ppxlms5w6dVqPHj3V7OXLV6RdSs65txN/Vta5fpg+NPuDB3+mb1Qz9K7NQ581g7Su+/V7Wh2zZqXOV9qXO6b/GxgAAHaiAgxkGUVKvXfqdJVP/1KlSq5fv8b9U3vAzz2XevM51Zf279+nJDNhwqQffxxVrFixuLhTmoh2W7W/3q5d2woVyq9du/bBBx8aO/anmjVrnDx5Uvvl//3vI0FBQe6kNH7dunXU/eKLL48ZM7Z48eItW7bU/vfs2XNiYo7fe+/djic8a7TevR+Mj49r1apV4cKFNm3apJ1mDerZ89bjx49PmDBR40+a9GulSpXMDnRISN7mzZvv339gxoyZek2ePEHNq1y5sqapEFK2bLmCBQsEBwfHxydoyi1aNM9w1tRTQXr79h1qZKNGDZs2bbJs2XIl5ODgoDvuuN17cemr9UVmYarDvT/HuWZQH1d0GTBg4NixPwYGBiqpKoTfffdd5cqVS9tgn1WjJaPopQ7NQkBAoPLYokWL3333nS5drilbtuy+ffu0IkqUKK7pFChQwJ9Gyocffnz0aJSWnr5ai27Vqt/Gjx9XtGiY4zlg8fTT/c2yjYiI0Jhr1qz7+OMPAgICfBqmFXTzzbeqo3HjRhpq1sLgwR9rwSrhK7BpUoULF9ba/O23cC3J8PDwTz/9WLOfziZUqlQpd4GUL18+NDQ0T57cPmtQOVOfVQs7dLhy167d+mCZMmW0lEw0VeZUw7zbefDgQX08Li7+rJuZ0tf99z+oQwB16tTRVjpu3M96fffdCG0AGn/lylUaqg5tDHp/++131FrnHFSS1cSTkhLdL9JnAwMDmjW7fNasWQr8hw8f+eSTj8LCimjWtm7dGhycWzNbokQJjZ9+MzZ6aNPSnKrZKomnXUrpbCfpr6z0f5g++vd/Vr9Etequu3rpOJE2D62CN954zfH826LtUB358+f3Ppn/xIkTmqDWl9kC/d/AAACwFgEYyDJr1qzV+1l34t0TKXft2qWIqOjyyy/jwsJSQ5EJjS+88NJnn31qxlF0UVwx9935v//74oMPPlSo05/du9/w3nsfLF26VLvpGnTo0GElHwWVQoUKKfJpJ7tz507vvTfIc2HnyZ49b1eiaNu2tTKtmaz23bUzbW6iq2qYk1ouG2KSj5my9s41sopj9evXe/vtt8qXT70t8IgRI1VGmz9/Qa9ed77zzlvqVp/+/Z8ye+HeBV5/Zk2FxFdeecmcz6mvu+OOXt9/P9onACul6ItUUjt06JA6TM90ZlCt7dPnAVVB1bBu3bq+8sqrWgWPPfaoau9pG+xDMUNf98AD93fs2MHxxAwdF5g4cbKCzZNPPqGq4GOPPXHrrT3SXgN81kYaqsVNnjxRmV+hUbP/88/jV65cqZYrwimcKGX99NPoggULasznn3/hxx9/0gg33tjdZ/q9e/fxXkGmYR98kJqpfv11gnKOtoH/+79PTbDRZNVHs6nYn84m9Mwz/1NTVT4dMmToM8/0Nxuq9xo0ydnTwh90vMDxnLZgyuD+897MXnrpZcXO55571qziLVsirruumwqkCxfO05+PPvqY5yu+MQFYG7Oq2f5/kYLim2++ro1Btd/27Tsocx49erRr1+uU/RSJ1Qx3vQwa9O65mmFyozan558fcPvtt5nx0y4lraZzbSfpr6xJfvwwDXMcSjM1cuRwtUobj0q+27Zti4uL8753QJMml3lfCK3M7KT+nD/QsY9MbWAAAFiLU6CBLKOdbMU/tzx7ViYkP/10PxMR5aabblRQURnn9OnTpo8yrXvX2auuSt3h3r17j97NLine truncated

After

Width:  |  Height:  |  Size: 42 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="800"><image width="1280" height="800" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAMgCAIAAADz+lisAAAQAElEQVR4nOzdB5gV5dkG4AEWkCoKKopiw96wx15jD3YNaogaC5bEgmJHrDFW7LH3KNgrVuwFKypWmgVUivS2u5T/3Z14/s02V8VE9rvva69zzc6ZM/PNN3N255n3zJyiWbNmZQAAAFDfNcwAAAAgAQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJJQlAF1MHfu3AwA4LeqQYMGGfBjBGCoRh53Kz4CAPz25TG44iNQkQAM/2HuD2bNmlVaGg+zQzyKwQDAb1nE3aKiRg0bNmzcuCh+QoMfZMAPGsQBfgZUiL4lJaXTps2YO3dO48aNmzRpXK6oUaNGGQDAb1Wcso9z96WlpXEkEyL3tmjRPI5kxGCoSACGMpF755SbPn1GcXFp27YLxT+MDABg/hQx+PvvJzRt2rh582YNy8nAkAnAkP2QfuO9MGXKtKZNm7Zp0zoDAJj/TZw4ubi4uFWrFkVFRTIwZAIw5Om3tLR06tTpbdos2LRpkwwAoL4oLi6ZOHFSy5bNGzduLAOD7wEmaflFv7Nnz5Z+AYB6KQ5v2rRpHYc6ccCTH/lkkDABmKTl6Xf69BlNy0i/AEA9VH6c0zQOePIMnEHCBGDS9cM9n0tKS2e57hcAqMfiUKekZFYc9igCkzgBmHTl5d8ZM4oXXnihDACgXmvbts2MGTMVgUmcAEyiCl/5G4++8QgAqPeaNGkyZ05WWlqqCEzKBGDSld/8uXFj6RcASEKc9I+z/3EIlEGqBGAS9cP9n+co/wIAiYjDnjj4UQEmZQIw6YrTn/HXXwUYAEhEHPbEwY8KMCkryiBJ+bnPiMCNG3sXAABJiMOeOf8uAKsAkyiH/iQt/vo3atQoAwBIQBz2iL4kzkegSVH+p98/AAAgQQ6ESJkADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASRCAAQAASIIADAAAQBIEYAAAAJIgAAMAAJAEARgAAIAkCMAAAAAkQQAGAAAgCQIwAAAASWjUq1evDNIzd+7c2bNnFxeXtm7dMpvX5syZM3LkyGHDhs2ZM7d161ZZ/TVx4qTLLru8QYMGHTt2zJIXW7xfv/sWXHDBtm0Xzn7Dvvjiy4cffqR//yfbtm3buHGT384WHDq0rAPbtGmz8MKVO/DZZ5+7//4H1l67c+PGjbP/ioq9tMgii2T/U9ddd8Mnn3y61lprZgC/2JQpU5s2bVJUVNSgXAaJKcqAeeqll14+//y/x9Fz/muLFs27det21FFHxH+abP73zTffjh///QorrNC0adP49bXXXrvtttsHDRq06aabZPPU558PmTNn9sorr5z9MpUa/JNMmjTp66+/XmKJJarmsWobOWTI0D59Ll9qqSVXWKFT9lv11Vdf7bnnXtOmTY89c8MN1//iiy9+pS34MwwdWtaByyyzdKdOy1d66oILLoyTShtttNGPtnPWrFmffvppnIZYaqmlsp+rUi+tuuoq2f/O6NGjL7usTwzsscduLVq0yACAX0AAhnnp3XffO+yw7jEQh+nxEydZH3/88Wuv/ef7779/zTVXLbDAAtl87uabb7nzzrsef/yR5ZcviyhbbLH5cccdu/7662Xz2t/+dszYsWPfeeet7Jep1OCf5I03Bh5zzHFnn917n332zn7NRv43vfrq65Hrjj/+2EMO+UvDhg2nTZv2K23Beevcc88aPPjjurRzwoSJe+217y677HzxxRdmP1elXsr+pxZbbLFzzjkrzuBIvwDwywnAMM+MGvXNoYceFgM33nh9oU51yCEH9+jRc8CAAU8++dRuu+2a1S9xRH744YdmzD9GjRoVj1tvvXWe6+aXLfi7ctl/S6Ve+p/be++9MgBgXnATLJhnXnjhhagaHXXUkRU/pdmsWbPTTz81Bm6//Y7CyCee6H/88Sesu+76XbrsftFFF3/55Vf5+BjYY4+97rmn3113/SuqWCuvvFo8vvDCi/HUyJEj46mLL7604hIfeeTRGPnSSy/HcGlp6a233vbnPx8csz3iiKPuu+/+wmTxqphs8OCPDj/8iJhn/tTHH39y5JF/3XjjzeInpv/0008L07/88ssHH3xIzCeeOvrov+VPTZ48OWby4IMPxvBRR/01hj//fMh3330XA3VZtbD//n867bQzXn/9jUMOOSyascMOO9100y2zZs2q1I0DB74Z8/ziiy+jM2MgeiAfX9MKnnjiSTHZhx9+mP86d+7caECM+eSTT6o2OKsiFnTsscdvscXWMdtY6zhPkY+Pkeeff0EM9OlzRbz24YcfqUsjs/IrwC+7rE+sXcwweu/zzz+v+MKYf8w5ntpvvwOuvfafUYDNahBrdNZZ52y77fb5Vnj77XcKT0VXRNdFN8Z8unU78Nprr4tm5E/VsguNGzcunrr77rtj+Oijyzpk0KD3K23BaHy8MPqh8MLrr78hJhg/fnw8G5svNmLFRt522+3x7OjRo7MadrN46vLLr4idIdbilFNOe+ONNyq+PPa0fG+J7rr55lur7gwFV155dcw8X818QSNGjMh7Mubcu/dZkyZNysoK/rceeODBMfD888/HNOeee37+8lqake+WTz319L77do1mv/XW21V7Kat5P6nLxqrpjVlJrP4111wbS4xmxGPsHvHa/KnY1iec0DMGBgwoW6+qP4Up676DAUCaVIBhnolIGY/bb79dpfFLLLH4xx9/WPg1joBPP73s5nNRX/ruu28jyTz22BP33nvPoosuOnPmjJhJHLbG8fpWW225zDJLDx48uHv3Ix944L5VVll5+vTpcVz+t78d3aRJk8KsYvo11lg9hnv3Pvv++x9YbLHFNtlkkzj+fv75FyZPnnLwwQdm5eE5JjvssO7FxTM322yzhRde6LPPPouD5niqa9c/Tpky5bHHHo/pn3ji0eWWWy4/gG7RovlGG2303Xejn332ufjp3/+xaN7yyy8f84wQstRSHdu0WbBp06bFxSUx54033uhHVy1GRpAeMeKLaOQ666y9wQbrv/nmW5GQmzZtcsAB+1fsrlh0LCjvzBgo3J+jphWMl0d0Oe20Xg88cG9RUVEk1QjhBx74544dO1ZtcKVNEz0T0SsGYhUaNSqKPPbaa69fcslFO++801JLLfXtt9/GhmjffrGYz4ILLliXRobLL79ywoTx0Xux6Oi6d9997+GHH1xkkXZZ+QmLnj1Pzvt26NChMeWHH3505ZV9GjVqVKlhsYH23vuPMbDuuuvEs/lWuOaaK6NjI+FHYItZLbzwwrE133tvUPTkoEGDrr76ylj9WnahJZZYotAhSy+9dOvWrZs1W6DSFoycGa+NFm677TZfffV1vHDJJZeMXsqjaWTOaFjFdo4ZMyZePnNmcbW7WaSvQw/tHqcAVl999dhLH3zwofj517/ujB0gpn/nnXfj2RiInSEeL7zwomhtVoMoycbMZ80qLSwoXltU1GjDDX83YMCACPzjxn1/1VVXtGvXNlZt2LBhTZsuECvbvn37mL72ZnxaLnatWNNodpTEq/ZSLftJ7Rur9jdmJSeffGq8E6NVf/5ztzhPFLtHbIK///28rPxvS+yHMdCqVauKH+afOnVqzDC2V74H1n0HA4BkCcAwz3z44eB4rPYgvvBByq+++ioiYkSXRx55sF27slCUh8Yzzzzr2muvzqeJ6BJxJb/vzj//eX2fPpdHqItf99hj90sv7TNw4MA4TI+nxo4dF8kngspCCy0UkS8OsnfYYftLL724/MLO6V277h+JYsstN49Mm882jt3jYDq/iW5Uw7KyctmNefLJ5xxH5zFxFMfWWmvNCy/8x9JLl90W+M4774oy2ssvv9Kt258uuugfMRxjTj75xPwovGKBty6rFoXEc845K/88ZyzugAO63X1330oBOFJKLChKamPHjo2BfGQtKxitPeKIw6MKGg3bddcu55xzbmyCY475a9Teqza4kogZsbjDDz/097/fNiuPGXFe4PHH+0ew6dHjuKgKHnPMcX/8475VrwGutpG5qMX17/94ZP4IjbH6Dz308DvvvBMtjwgX4SRS1n339W3Tpk1MecYZZ957730xwZ577lFp/ocddkTFDZQ3rE+fskz16KOPRc6JfeCf/7w6DzYx2xgTqxmxv5Zd6JRTToqmRvn0xhtvOuWUk/MdteIWzJNzeQv7xfmCrPxjC3kZvO4q7mZnnXV2xM7TTz8138RDhgz9wx92jQLpq6++FL/+9a/HlC/i1jwAx84c1ey6LyiC4gUXnB87Q9R+t95628icEyZM6NLlD5H9IhJHMwrb5eKLL6mpGXlujN3pjDNO23///fLpq/ZSbKaa9pPaN9YTdXhj5vLzULFSd911R7Qqdp4o+Q4fPnzmzJkV7x2w/vrrVbwQOjJzVvZ27hPnPn7SDgYAyfIRaJhn4iA74l+hPFutPCT37HlCHhHDXnvtGUElyjhz5szJx0SmLdx1drvtyg64v/56ZDzmR9tPLine truncated

After

Width:  |  Height:  |  Size: 30 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1280" height="1000" viewBox="0 0 1280 1000"><image width="1280" height="1000" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABQAAAAPkCAIAAAB5gwQOAAABLGlDQ1BfAAB4nJWQPUsDQRCGH0NA1DSiooXFlWnUJGI+UAsTNWiZKES7y+UIYhKPy4n2af0R1naCjQipbawEKxEbe0Gwje/dFReQFJlhdp59d9jdGYgtIYunoN3x3Eq5aNROTo3JTybkgZlW12G0qer3Lax9XWF8m2rYXUv5W+G5elxXNsTzzZCvfa6HfOPzled44luf3aNKSfwgTjaHuD7EluP69e/irXbr0or+TcLuHFeVa4plylzIm7SwWaPKOWeYohR7FMizrrwj31CkyUgpkNUuRYkiOa059qXkdZZmN2BV+PMMn+x9wHZ/MBg8RdphH+6zMP0YaclNmE3A80ukRTN2TNcMpLgiZhfhZ0Gt3MHcF8z0pC76xyN6Nf71anBAB4tVUUbdpMn+AQyUTdocuQPoAAAQAElEQVR4nOz9B3hUV7rvCe9SFgiRQWSJnDMGTLIBY4NtbGMbnAPO3T7dfbrPmZl7n5nnztz7PTPfnXtudzvnhHMAY3LOOeeco8hBOdb8ai3VZqtKEgIjLKz/73HTpaq9V3hX2O9/vXuvHVVQUOAIIYQQQgghhBC/d6IcIYQQQgghhBCiCiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLIQQQgghhBCiSiABLEQofr/f5/PxryOEEEIIcWtinRn+dYQQHiSAhQjFXip0wRBCCCHELY2cGSHCkQAWVRHFeIUQQghRlVF8WFRZJIBFlcOrfkuc9wsLCyMiIvhXFwYhhBBC3HJYB8Y6M/xb4gGuOyRXR1Q1JIBFVcE70bvTvftnyAWgDHkshBBCCFGZcZ0c918n6POU6AVJCYsqha+goMAR4vdIyH3O3inePcD9vsQUdJu0EEIIIW45yuPbuHI33EGSHha/bxQBFr9bQvayCgn2lnhhCJnqzZGOEEIIIcQtRLgDE+71hDwRFqJ4pX7F7xgJYPF7ozR9W/xGoCti2DEP/Zonfu2v/KdJXwghhBC/D/xGzwYkbYTBvRfa/BR6p7QXhYLF7xLdAi1+t9iNH5i4+WDmbl9Q3BZN9HkB8vPzC+x+V8GpP3CsbnwWQgghxK1O0KUpCvPanbGioiKjo6Oio6ODyvaKgwQcwPel7Z4lxO8ACWDx+6HE2K8ra82cHrgMoHhzcnLz8nLp/OZCEBkVFfjXTPg+RYCFEEII8TvCb70gVvsLCwvy89G2BfwVGYkMjomNjUEP4/4UFjpuTDgk5Ks4sPidIQEsbnlC9mywH5jdQ44yX/qzs3Oys3PtvB8bGx2J+I2KNIudEUV3AwkhhBBC/L6wz3mZu+IKiQQUFOTn5OTZSEBcXExcXCyukHGiinlC9k46p/iuWvKWxK2OBLD4/WCXJ630dVcrzf3PgS/y8vKzkb85udHR0fHxcfxrljx9V90LWgghhBDiVifE50EG5+XlZWVl8y9x4Lg4XKMoG1ZwnxO2x7t/OkL8LpAAFrcwJd7tHK5p+ZdlTqZ4PjLFx8fHe+72cRypXyGEEEJUATyukeM+F5aVlUV4gB8JD8TGRrsv0Qh3q0KScoS4NZEAFrcq7mJk2GZXTkgcmGk9IyMzIiKyRo3qMTHR4bv8a11TCCGEEL97XIfHu+7P59zcvLS0jMLCgurVqxEqCIn92mNCNseS7yRuXSSAxa2NO4N7lye903p2dk5mZmZkZGRCQoJVv1Yne1/7rhlcCCGEEFUBr/NjX4FhVS4aOD09HV1QrVq1uLhY93ivZ+X6S3KcxC2N9jcXtx7+IO5OV954r7tUyZ95eXmZmdnM7DVqJLCiaX8NEcmaxIUQQghRRXDdHu8dzoCbhLOEy4TjhPvkfY7Me8+dPdd9f6SeIBO3IhLA4tbDG791glrXu5xpj2EVk/Avv1evXj06Otr93osjhBBCCFHFCHeHcJNwlnCZ+Ij7ZDaIvuJleX0tx7PVqFwpcSsiASxuJfwevIuR4fcz84HpOzc3r1q1+Li4WLtA6Q0RCyGEEEJUcYrfHOfgMuE44T7hRIVo3RJdL8WBxa2IBLC4lShP7NdiXnqUEx0dFRcXF1ygVOBXCCGEEOIKHtco8A//s+9DwonClXIPUxxY/J6QABa3Eu46pbvcGK5+7U9m1g5M4pGR7jvctUIphBBCCBGKcaWKnvjFccJ9wm/ClfJGd8NvtQtxyYS4VZAAFrcM3uk1/M5n9xim5YKCwLvdo6IiY2KineAcbVc5HSGEEEII4cFGgF0pi/uEE4UrZZ4EdkrTwO6eWE5xJ02ISo4EsLhl8HnezF7inc+u0GXNkkk5NjYmMjJSN+cIIYQQQlwV17nCfcKJwpWy99OVFgf2imE5WuIWQgJY3Bp4d1nwFX/dkfcAX+A1v4H7n/kQGRlln2bx602/QgghhBBl4lG2jnGibEQh9D5nf9jrkbxOmhCVHwlgcQvgD3tpu7tnQ8iGWI65IaegoIDFy+joSHt6yP5YQgghhBAiBG/AACcKcKi8D505xW/E83pl/rDtSIWotEgAi1uAEKHreILA4RtiFRQEViuZtSMiIty3HykCLIQQQghRBq6/hPuEE4UrhUOFW1XaxlfhjpncLXFLIAEsbgHC73MO+dLxSGKWKvkYGVm0nYOjjRmEEEIIIcqBx3Hy4UrhUOFWlcf78n4pRCVHAlhUdkLurnG/DFl3dIrdKW2/0cYMQgghhBDlxeM4FT0M7L23OTzk657l1yuRxK2DBLCo1HhFb+nbPhf7YP716aVHQgghhBDXR/DFSFcUb7jT5YS9GMnRxiviVkACWFRqwtcUvd+E7MHgXAkXK+orhBBCCHH9uBHg4i5WsV1I/SU9HiwfTFRyJIBFpcY7n4ZMqe4SY8itOBylO3CEEEIIIX4N/iKKvWvDdb3CXTLdBS1uFaIcISo3ERERdgt+Pjiem22806t3Ojarlbr/WQghhBDi+jHuls/eVed93Nd+CLkvz7x6I7Bjlv3gCFGJUQRYVGr8YW9dD/m+lPfROUIIIYQQ4tfg3gIdcuez/fWqTpoQlRMJYFF58RffeLDEu2v8xTfEMn9K/gohhBBC3BB8HhcrgD/s5ZTe59T8xfcrFaISIgEsKin+4jtdlfbBPdizQqk5VwghhBDiBoBb5UrcEu+/K+2DNLCotOgZYFFJCdlaMOTtR07xd697dyDUhFtJCGk1n3aG9OAPe5F11TFOuGMU7idVkEFKnBzUMysP/rCXi3r/VBuFUKLGUH8WNxyvrxVy5XKKX85Ki1IIUdmQABaVFPeibnfAcr+0Eytfhlz4/Vf26HcqgnIuZ4a8GKCcx4d/DvmmjJ+ccrxzLzxgfq0JXrUkxZ8I4nOxx4Gc4g8IXcel8VpyvzaDlKfHhLjg5Wnc8DqGHO8vZRc3f9jrvkIS5sASyx/eRuVxjsuQo9fhu5Sz25eHivCcfGHPrYV8L35bTOcp+XtHhFGaWWQucWNhVPrD3m/kfuPdoNT+ZD00J2ynaCEqDxLAojJilxvt/s/u9GqnVKt+7WG+sDcAmy8rRAGHa4YSj3F/cv8tjwYuz68lihmnHHjLE1LOciYYkkLZJwYve1d+9Ye9LMG5dhetNIOXmLsna6e0fHye6jjFnmgq+RSf53LuK7flvXX3lay+ij21XuLxIWWwj2P5SupaZZzrlGL5Mo68Dnzl6/bhI+i6c7w+wvqJvLTKgpnAfWqO8iNbiYrGulUhq9jeK5qrgV1vzfG8wkNdVFRCJIBFZcQXFnBzP3vn0xC1EFQFFTLVepVP+Gzukd/XdtNvSOTNc0UpSrWMpLy/lpaL37yToEQpVf4EyxBa7gHhmse9FvqKP6pddlKl4S2bN7XSukqwpUpOx1/KrbAlnYIB/SHHlC2DvdX0lbTWUPz0kvfSdE8Pa4hiEeASg8y+sIiuN19/8ehuiXXx/+oI8FXPzcrK2rfvQFra5fbt29epUzs7O/vUqTP01rp161SvXt2+ReM6CnDV4tkPly9fvnDhQlRUVN26dePj4x1RObBDh2kjLS0tNfVUXFxcUlLD6Ojo6+6QlRB/8a0c3WnHLL1dWwVtUrm5uefPn2dA1axZs1atWhU0dkRVxl4lQrwg759ufCJcHqsrisqJBLCojPjDHh+1b5Line truncated

After

Width:  |  Height:  |  Size: 231 KiB

+429
View File
@@ -0,0 +1,429 @@
const fs = require("node:fs");
const path = require("node:path");
const ARTIFACT_NAME = "thread-transfer-results";
const RESULT_FILE = "thread-transfer-result.json";
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
const PROVIDERS = ["codex", "claudeAgent"];
const OBSERVED_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"threadSnapshotDecodedBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const CEILING_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const SCENARIO_KEYS = [
"id",
"historyTurns",
"historyCommandToolsPerTurn",
"historyMcpResultBytes",
"measuredCommandTools",
"measuredMcpResultBytes",
];
function resultShaMarker(sha) {
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
}
function assertObject(value, label) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
}
function assertExactKeys(value, expected, label) {
assertObject(value, label);
const actual = Object.keys(value).sort();
const wanted = [...expected].sort();
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
throw new Error(`${label} has unexpected fields`);
}
}
function assertMetric(value, label) {
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
}
}
function validateResult(value) {
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
if (value.schemaVersion !== 1) {
throw new Error("result.schemaVersion must be 1");
}
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
if (value.scenario.id !== "thread-transfer-v1") {
throw new Error("result.scenario.id is not supported");
}
for (const key of SCENARIO_KEYS.slice(1)) {
assertMetric(value.scenario[key], `result.scenario.${key}`);
}
assertExactKeys(value.providers, PROVIDERS, "result.providers");
for (const provider of PROVIDERS) {
const entry = value.providers[provider];
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
for (const key of OBSERVED_KEYS) {
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
}
for (const key of CEILING_KEYS) {
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
}
}
return value;
}
function readResult(directory) {
if (!directory) return undefined;
const file = path.join(directory, RESULT_FILE);
if (!fs.existsSync(file)) return undefined;
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.size > 64 * 1_024) {
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
}
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
}
function formatBytes(bytes) {
if (bytes < 1_024) return `${bytes} B`;
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
return `${(bytes / 1_024).toFixed(1)} KiB`;
}
function formatValue(value, kind) {
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
}
function formatImpact(current, baseline, kind) {
if (baseline === undefined) return "—";
const delta = current - baseline;
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
const magnitude = formatValue(Math.abs(delta), kind);
const percent =
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
return `${prefix}${magnitude}${percent}`;
}
function sameScenario(left, right) {
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
}
const METRICS = [
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
{
key: "measuredTurnWebSocketWireBytes",
label: "Live turn WebSocket wire",
kind: "bytes",
},
{
key: "measuredTurnWebSocketDecodedBytes",
label: "Live turn WebSocket decoded",
kind: "bytes",
},
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
];
function renderComment(input) {
const current = input.current;
const baseline = input.baseline;
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
const rows = [];
const ceilingChanges = [];
let failed = false;
for (const provider of PROVIDERS) {
for (const metric of METRICS) {
const observed = current.providers[provider].observed[metric.key];
const ceiling = current.providers[provider].ceiling[metric.key];
const baselineObserved = comparable
? baseline.providers[provider].observed[metric.key]
: undefined;
const pass = observed <= ceiling;
failed ||= !pass;
rows.push(
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
);
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
ceilingChanges.push(
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
);
}
}
}
const baselineLink = input.baselineRun
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
: "unavailable";
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
const notices = [];
if (!baseline) {
notices.push(
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
);
} else if (!comparable) {
notices.push(
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
);
} else if (!input.baselineRun.matchesBase) {
notices.push(
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
);
}
if (ceilingChanges.length > 0) {
notices.push(
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
);
}
return [
COMMENT_MARKER,
resultShaMarker(input.currentRun.sha),
"## Thread transfer impact",
"",
failed
? "❌ One or more thread transfer ceilings were exceeded."
: "✅ Thread transfer remains within every enforced ceiling.",
...(notices.length > 0 ? ["", ...notices] : []),
"",
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
...rows,
"",
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
"",
"<details>",
"<summary>Scenario and decoded snapshot size</summary>",
"",
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
"",
...PROVIDERS.map(
(provider) =>
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
),
"",
"</details>",
"",
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
].join("\n");
}
async function artifactsForRun(github, owner, repo, runId) {
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
owner,
repo,
run_id: runId,
per_page: 100,
});
}
function findResultArtifact(artifacts) {
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
}
async function resolve({ github, context, core }) {
const source = context.payload.workflow_run;
const { owner, repo } = context.repo;
if (source.event !== "pull_request") {
core.setOutput("publish", "false");
return;
}
let pullNumber = source.pull_requests?.[0]?.number;
if (!pullNumber) {
const associated = await github.paginate(
github.rest.repos.listPullRequestsAssociatedWithCommit,
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
);
const matchingPulls = associated.filter(
(pull) =>
pull.state === "open" &&
pull.head.sha === source.head_sha &&
pull.head.ref === source.head_branch,
);
if (matchingPulls.length !== 1) {
core.info(
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
);
core.setOutput("publish", "false");
return;
}
pullNumber = matchingPulls[0].number;
}
if (!pullNumber) {
core.info("No open pull request is associated with the completed CI run.");
core.setOutput("publish", "false");
return;
}
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
if (pull.head.sha !== source.head_sha) {
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
core.setOutput("publish", "false");
return;
}
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
const sourceArtifact = findResultArtifact(sourceArtifacts);
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
owner,
repo,
workflow_id: source.workflow_id,
branch: pull.base.ref,
event: "push",
status: "success",
per_page: 100,
});
const orderedRuns = [
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
].slice(0, 20);
let baselineRun;
for (const run of orderedRuns) {
const artifacts = await artifactsForRun(github, owner, repo, run.id);
if (findResultArtifact(artifacts)) {
baselineRun = run;
break;
}
}
core.setOutput("publish", "true");
core.setOutput("pull_number", String(pullNumber));
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
core.setOutput("pr_run_id", String(source.id));
core.setOutput("pr_sha", source.head_sha);
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
core.setOutput(
"baseline_matches_base",
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
);
}
async function upsertComment(github, context, pullNumber, body, options = {}) {
const { owner, repo } = context.repo;
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: pullNumber,
per_page: 100,
});
const existing = comments.find(
(comment) =>
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
);
if (
options.preserveResultSha &&
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
) {
return;
}
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
}
}
async function upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
expectedSha,
body,
options,
) {
const { owner, repo } = context.repo;
const { data: pull } = await github.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
if (pull.head.sha !== expectedSha) {
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
return false;
}
await upsertComment(github, context, pullNumber, body, options);
return true;
}
async function publish({ github, context, core }) {
const pullNumber = Number(process.env.PR_NUMBER);
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
throw new Error("PR_NUMBER is invalid");
}
const current = readResult(process.env.PR_RESULT_DIR);
const currentRun = {
sha: process.env.PR_SHA,
conclusion: process.env.PR_CONCLUSION,
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
};
if (!current) {
await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
[
COMMENT_MARKER,
"## Thread transfer impact",
"",
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
"",
"_This comment will update automatically after the next completed run._",
].join("\n"),
{ preserveResultSha: currentRun.sha },
);
return;
}
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
const baselineRun = baseline
? {
sha: process.env.BASELINE_SHA,
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
}
: undefined;
const body = renderComment({ current, baseline, currentRun, baselineRun });
const published = await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
body,
);
if (published) {
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
}
}
module.exports = {
publish,
readResult,
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
};
@@ -0,0 +1,292 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const {
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
} = require("./thread-transfer-report.cjs");
function result(overrides = {}) {
const observed = {
totalWireBytes: 2_200_000,
threadSnapshotWireBytes: 1_950_000,
threadSnapshotDecodedBytes: 9_100_000,
measuredTurnWebSocketWireBytes: 250_000,
measuredTurnWebSocketDecodedBytes: 1_150_000,
measuredTurnWebSocketMessages: 15,
};
const ceiling = {
totalWireBytes: 2_900_000,
threadSnapshotWireBytes: 2_600_000,
measuredTurnWebSocketWireBytes: 320_000,
measuredTurnWebSocketDecodedBytes: 1_550_000,
measuredTurnWebSocketMessages: 20,
};
return {
schemaVersion: 1,
scenario: {
id: "thread-transfer-v1",
historyTurns: 10,
historyCommandToolsPerTurn: 5,
historyMcpResultBytes: 900_000,
measuredCommandTools: 20,
measuredMcpResultBytes: 1_100_000,
},
providers: {
codex: { observed: { ...observed, ...overrides }, ceiling },
claudeAgent: { observed, ceiling },
},
};
}
test("validates the fixed artifact schema", () => {
assert.equal(validateResult(result()).schemaVersion, 1);
assert.throws(
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
/unexpected fields/,
);
assert.throws(
() => validateResult(result({ totalWireBytes: "lots" })),
/non-negative safe integer/,
);
});
test("renders baseline, impact, ceiling, and ceiling changes", () => {
const baseline = result();
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
current.providers.codex.ceiling = {
...current.providers.codex.ceiling,
measuredTurnWebSocketWireBytes: 330_000,
};
const comment = renderComment({
current,
baseline,
currentRun: {
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
conclusion: "success",
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
},
baselineRun: {
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
matchesBase: true,
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
},
});
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
assert.match(comment, /This PR changes transfer ceilings/);
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
assert.match(
comment,
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
);
});
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
const outputs = {};
const listWorkflowRunArtifacts = () => {};
const listWorkflowRuns = () => {};
const listPullRequestsAssociatedWithCommit = () => {};
const github = {
paginate: async (method, input) => {
if (method === listPullRequestsAssociatedWithCommit) {
return [
{
number: 5350,
state: "open",
head: { sha: "head-sha", ref: "feature-branch", repo: null },
},
];
}
if (method === listWorkflowRunArtifacts) {
return [
{
name: "thread-transfer-results",
expired: false,
runId: input.run_id,
},
];
}
if (method === listWorkflowRuns) {
return [{ id: 1, head_sha: "base-sha" }];
}
throw new Error("unexpected pagination call");
},
rest: {
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
pulls: {
get: async () => ({
data: {
head: { sha: "head-sha" },
base: { sha: "base-sha", ref: "main" },
},
}),
},
repos: { listPullRequestsAssociatedWithCommit },
},
};
await resolve({
github,
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "true");
assert.equal(outputs.pull_number, "5350");
assert.equal(outputs.pr_artifact, "true");
assert.equal(outputs.baseline_run_id, "1");
assert.equal(outputs.baseline_matches_base, "true");
});
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
const outputs = {};
const listPullRequestsAssociatedWithCommit = () => {};
let fetchedPull = false;
await resolve({
github: {
paginate: async (method) => {
assert.equal(method, listPullRequestsAssociatedWithCommit);
return [5350, 5351].map((number) => ({
number,
state: "open",
head: {
sha: "head-sha",
ref: "feature-branch",
repo: { full_name: "pingdotgg/t3code" },
},
}));
},
rest: {
actions: {},
pulls: {
get: async () => {
fetchedPull = true;
},
},
repos: { listPullRequestsAssociatedWithCommit },
},
},
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "false");
assert.equal(fetchedPull, false);
});
test("does not publish a stale result after the PR head advances", async () => {
let listedComments = false;
const info = [];
const published = await upsertCommentForCurrentHead(
{
paginate: async () => {
listedComments = true;
return [];
},
rest: {
issues: {
listComments: () => {},
createComment: () => {
throw new Error("must not create a stale comment");
},
updateComment: () => {
throw new Error("must not update a stale comment");
},
},
pulls: {
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: (message) => info.push(message) },
5350,
"old-head-sha",
"stale body",
);
assert.equal(published, false);
assert.equal(listedComments, false);
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
});
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
let updatedComment = false;
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const published = await upsertCommentForCurrentHead(
{
paginate: async () => [
{
id: 1,
user: { login: "github-actions[bot]" },
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
},
],
rest: {
issues: {
listComments: () => {},
createComment: () => {
updatedComment = true;
},
updateComment: () => {
updatedComment = true;
},
},
pulls: {
get: async () => ({ data: { head: { sha } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: () => {} },
5350,
sha,
"missing artifact warning",
{ preserveResultSha: sha },
);
assert.equal(published, true);
assert.equal(updatedComment, false);
});
+21
View File
@@ -84,8 +84,29 @@ jobs:
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
env:
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
run: vp run test
- name: Publish transfer budget report
if: always()
run: |
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
else
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
fi
- name: Upload thread transfer result
if: always()
uses: actions/upload-artifact@v7
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer-result.json
if-no-files-found: ignore
retention-days: 30
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
+4 -4
View File
@@ -39,10 +39,10 @@ jobs:
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
+180 -9
View File
@@ -5,6 +5,25 @@ name: Mobile EAS Production
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
#
# Every merge to main that touches the mobile app reconciles, per platform:
# 1. Store builds: if the latest production build's version differs from
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
# track). Bumping `version` is therefore all it takes to
# start the next release train — the first build of a version enters
# external-TestFlight beta review immediately, and later builds of the
# same version auto-approve until that version is released. After App
# Store approval, Apple closes the release train and `version` must be
# bumped before another iOS build can be submitted. Releasing to the App
# Store stays a manual App Store Connect step.
# 2. OTA: publish a production-channel update for each platform where at
# least one finished production build matches the current native
# fingerprint. Old-version binaries with a matching fingerprint receive
# it too. When native drift means no binary could install the update,
# it is skipped and flagged in the job summary instead of published
# into the void.
# workflow_dispatch remains as a manual override for both modes (e.g. to
# retry an errored build or force an OTA).
on:
workflow_dispatch:
inputs:
@@ -25,14 +44,38 @@ on:
- ios
- android
- all
version:
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
required: false
type: string
message:
description: "OTA update message (mode=update only)"
required: false
type: string
push:
branches: [main]
paths:
- apps/mobile/**
- packages/client-runtime/**
- packages/contracts/**
- packages/shared/**
- assets/**
- scripts/**
- patches/**
- pnpm-lock.yaml
- pnpm-workspace.yaml
- .github/workflows/mobile-eas-production.yml
# Serialize runs so OTAs publish in merge order. GitHub keeps at most one
# queued run per group, so a burst of merges collapses into one run of the
# newest commit — intermediate commits don't need their own OTA.
concurrency:
group: mobile-eas-production
cancel-in-progress: false
jobs:
production:
name: EAS Production ${{ inputs.mode }}
name: EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
@@ -52,15 +95,25 @@ jobs:
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- id: version_app_token
name: Mint release app token for version override
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
token: ${{ steps.version_app_token.outputs.token || github.token }}
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
# when the partial clone can't serve the unfetched blobs.
- name: Setup Vite+
if: steps.expo-token.outputs.present == 'true'
@@ -98,15 +151,74 @@ jobs:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
- name: Apply manual version override
if: steps.version_app_token.outcome == 'success'
env:
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
RELEASE_VERSION: ${{ inputs.version }}
run: |
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
exit 1
fi
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
exit 1
fi
node --input-type=module -e '
import fs from "node:fs";
const path = "apps/mobile/app.config.ts";
const source = fs.readFileSync(path, "utf8");
const next = source.replace(
/^( version: ")[^"]+(".*)$/m,
`$1${process.env.RELEASE_VERSION}$2`,
);
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
throw new Error("Could not update app version");
}
fs.writeFileSync(path, next);
'
vp fmt apps/mobile/app.config.ts
if git diff --quiet -- apps/mobile/app.config.ts; then
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
exit 0
fi
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
git config user.name "${APP_SLUG}[bot]"
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
git add apps/mobile/app.config.ts
git commit \
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
-m "Co-authored-by: codex <[email protected]>"
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
- name: Summarize manual build version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
working-directory: apps/mobile
run: |
version="$(npx expo config --json --type public | jq -r '.version')"
{
echo "## Manual production build"
echo
echo "- App version: \`$version\`"
echo "- Platform: \`${{ inputs.platform }}\`"
echo
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
} >> "$GITHUB_STEP_SUMMARY"
- name: Build and submit (manual)
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
- name: Publish OTA update (manual)
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
@@ -117,3 +229,62 @@ jobs:
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
# No --status filter on build:list: an in-queue/in-progress build must
# count as existing, or every merge during the build window would cut a
# duplicate. After an errored build, retry via workflow_dispatch
# mode=build — pushes won't re-trigger it until the app version changes.
- id: store_builds
name: Ensure store builds exist for the current app version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
continue-on-error: true
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
failed=0
version="$(npx expo config --json --type public | jq -r '.version')"
for platform in ios android; do
latest="$(eas build:list --platform "$platform" --build-profile production --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')"
if [ "$latest" = "$version" ]; then
echo "$platform: production build for $version already exists (or is in progress)"
continue
fi
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
else
failed=1
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
fi
done
exit "$failed"
- name: Publish fingerprint-gated OTA
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))"
for platform in ios android; do
# eas-cli prints an environment-loaded notice to stdout before the
# JSON even with --json, so discard everything before the document.
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')"
matching="$(eas build:list --platform "$platform" --build-profile production --status finished --fingerprint-hash "$hash" --limit 1 --json --non-interactive | jq 'length')"
if [ "$matching" -gt 0 ]; then
eas update \
--channel production \
--environment production \
--platform "$platform" \
--message "$message" \
--non-interactive
echo ":white_check_mark: $platform: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
else
echo ":warning: $platform: no finished production build matches fingerprint \`$hash\` — OTA skipped; JS changes reach $platform only once a matching build ships" >> "$GITHUB_STEP_SUMMARY"
fi
done
- name: Propagate store build failure
if: steps.store_builds.outcome == 'failure'
run: exit 1
@@ -0,0 +1,205 @@
name: Mobile Fingerprint Check
# Detects whether a PR changes the native fingerprint — i.e. whether merging
# it would leave main un-OTA-able until a new store build ships. Native-change
# PRs get the "📱 Native Change" label so they can be held and merged as a
# batch right before the next store submission, keeping main OTA-able for
# everything else in between. (Once one native PR merges, every later merge
# inherits the drifted fingerprint and loses OTA reach too — that is why the
# signal has to fire before merge, not after.)
#
# The check is advisory: it always passes, the label is the signal. Both
# fingerprints are computed in this one job (same OS, same corepack-pinned
# pnpm), so the comparison is self-consistent; no EXPO_TOKEN needed.
on:
pull_request:
paths:
- apps/mobile/**
- packages/client-runtime/**
- packages/contracts/**
- packages/shared/**
- assets/**
- scripts/**
- patches/**
- pnpm-lock.yaml
- pnpm-workspace.yaml
- .github/workflows/mobile-fingerprint-check.yml
concurrency:
group: mobile-fingerprint-check-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
fingerprint:
name: Native fingerprint diff
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
issues: write
pull-requests: write
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- name: Checkout
uses: actions/checkout@v6
with:
# Default pull_request checkout is the merge commit (PR applied on
# top of base), so the "head" fingerprint is the state main would
# actually be in after merging — stale branches compare cleanly.
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/mobile...
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Fingerprint merge result
working-directory: apps/mobile
run: |
mkdir -p "$RUNNER_TEMP/fp/head" "$RUNNER_TEMP/fp/base"
for platform in ios android; do
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/head/$platform.json"
done
- name: Fingerprint base
run: |
git checkout --quiet "${{ github.event.pull_request.base.sha }}"
# Re-sync node_modules to the base commit's lockfile before
# fingerprinting — a dep-changing PR must not fingerprint the base
# against head's installed packages.
pnpm install --filter=@t3tools/mobile...
cd apps/mobile
for platform in ios android; do
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/base/$platform.json"
done
- id: compare
name: Compare fingerprints
run: |
changed=""
{
echo "## Native fingerprint diff"
echo
for platform in ios android; do
head_hash="$(jq -r .hash "$RUNNER_TEMP/fp/head/$platform.json")"
base_hash="$(jq -r .hash "$RUNNER_TEMP/fp/base/$platform.json")"
if [ "$head_hash" = "$base_hash" ]; then
echo "- ✅ **$platform**: unchanged (\`$head_hash\`) — OTA-compatible"
continue
fi
changed="$changed $platform"
echo "- 📱 **$platform**: \`$base_hash\` → \`$head_hash\` — merging requires a new native build before OTAs work again"
jq -r -n \
--slurpfile h "$RUNNER_TEMP/fp/head/$platform.json" \
--slurpfile b "$RUNNER_TEMP/fp/base/$platform.json" '
($b[0].sources | map({ (.filePath // .id): .hash }) | add // {}) as $bm
| $h[0].sources[]
| select($bm[(.filePath // .id)] != .hash)
| " - \(.type): `\(.filePath // .id)`"'
done
} >> "$GITHUB_STEP_SUMMARY"
echo "changed_platforms=${changed# }" >> "$GITHUB_OUTPUT"
- name: Sync native change label
# Fork PRs get a read-only token under pull_request; the check stays
# advisory there (summary only). This workflow must not move to
# pull_request_target — it installs and runs PR code.
if: github.event.pull_request.head.repo.full_name == github.repository
uses: actions/github-script@v8
env:
CHANGED_PLATFORMS: ${{ steps.compare.outputs.changed_platforms }}
with:
script: |
const managedLabel = {
name: "📱 Native Change",
color: "d93f0b",
description:
"Changes the native fingerprint; merging blocks production OTAs until a new store build ships.",
};
const nativeChanged = (process.env.CHANGED_PLATFORMS ?? "").trim() !== "";
const issueNumber = context.payload.pull_request.number;
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
});
if (
existing.color !== managedLabel.color ||
(existing.description ?? "") !== managedLabel.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
color: managedLabel.color,
description: managedLabel.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
color: managedLabel.color,
description: managedLabel.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
const hasLabel = currentLabels.some((label) => label.name === managedLabel.name);
if (nativeChanged && !hasLabel) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [managedLabel.name],
});
} else if (!nativeChanged && hasLabel) {
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: managedLabel.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
core.info(
`PR #${issueNumber}: native fingerprint ${nativeChanged ? `changed (${process.env.CHANGED_PLATFORMS})` : "unchanged"}`,
);
@@ -52,6 +52,7 @@ jobs:
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
- name: Expose pnpm
run: |
@@ -100,6 +101,7 @@ jobs:
args:
- --filter=@t3tools/mobile...
- --filter=@t3tools/scripts...
- --filter=t3...
- name: Expose pnpm
run: |
+65
View File
@@ -0,0 +1,65 @@
name: Publish AUR package
# See packaging/aur/README.md.
on:
workflow_call:
inputs:
release_tag:
required: true
type: string
pkgrel:
required: false
default: "1"
type: string
secrets:
AUR_SSH_PRIVATE_KEY:
required: true
workflow_dispatch:
inputs:
release_tag:
description: "Release tag to publish"
required: true
type: string
pkgrel:
description: "Arch package release override"
required: false
default: "1"
type: string
permissions:
contents: read
concurrency:
group: publish-aur
cancel-in-progress: false
jobs:
publish:
name: Validate and publish
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 30
container:
image: archlinux:base-devel
steps:
- name: Install Arch packaging tools
run: pacman -Syu --noconfirm --needed git github-cli jq namcap openssh sudo
- name: Checkout packaging sources
uses: actions/checkout@v6
- name: Create unprivileged build user
run: |
useradd --create-home builder
install -Dm0440 /dev/stdin /etc/sudoers.d/builder <<'EOF'
builder ALL=(root) NOPASSWD: /usr/bin/pacman
EOF
- name: Validate and publish package sources
env:
GH_TOKEN: ${{ github.token }}
RELEASE_TAG: ${{ inputs.release_tag }}
PKGREL: ${{ inputs.pkgrel || '1' }}
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
run: packaging/aur/scripts/release.sh
+17 -13
View File
@@ -746,16 +746,10 @@ jobs:
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
timeout-minutes: 30
permissions:
contents: write
steps:
- id: app_token
name: Mint release app token
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
uses: actions/checkout@v6
with:
@@ -823,7 +817,7 @@ jobs:
- name: Publish release
if: needs.preflight.outputs.previous_tag != ''
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -840,11 +834,11 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
token: ${{ github.token }}
- name: Publish first release
if: needs.preflight.outputs.previous_tag == ''
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v3
with:
tag_name: ${{ needs.preflight.outputs.tag }}
target_commitish: ${{ needs.preflight.outputs.ref }}
@@ -860,7 +854,17 @@ jobs:
release-assets/*.blockmap
release-assets/*.yml
fail_on_unmatched_files: true
token: ${{ steps.app_token.outputs.token }}
token: ${{ github.token }}
publish_aur:
name: Publish AUR package
needs: [preflight, release]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.release.result == 'success' }}
uses: ./.github/workflows/publish-aur.yml
with:
release_tag: ${{ needs.preflight.outputs.tag }}
secrets:
AUR_SSH_PRIVATE_KEY: ${{ secrets.AUR_SSH_PRIVATE_KEY }}
deploy_web:
name: Deploy hosted web app
@@ -0,0 +1,75 @@
name: Thread Transfer Report
on:
workflow_run:
workflows: [CI]
types: [completed]
permissions:
actions: read
contents: read
pull-requests: write
jobs:
publish:
name: Publish PR comment
if: github.event.workflow_run.event == 'pull_request'
runs-on: ubuntu-24.04
concurrency:
group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }}
cancel-in-progress: true
steps:
# workflow_run has a write-capable token even for fork PRs. Only load the
# publisher from the trusted default branch and never execute PR code.
- name: Checkout trusted publisher
uses: actions/checkout@v6
with:
ref: ${{ github.event.repository.default_branch }}
sparse-checkout: .github/scripts
- name: Test trusted publisher
run: node --test .github/scripts/thread-transfer-report.test.cjs
- id: resolve
name: Resolve PR and baseline artifacts
uses: actions/github-script@v8
with:
script: |
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
await reporter.resolve({ github, context, core });
- name: Download PR result
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true'
uses: actions/download-artifact@v8
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer/pr
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ steps.resolve.outputs.pr_run_id }}
- name: Download main baseline
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true'
uses: actions/download-artifact@v8
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer/main
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ steps.resolve.outputs.baseline_run_id }}
- name: Update thread transfer comment
if: steps.resolve.outputs.publish == 'true'
uses: actions/github-script@v8
env:
PR_NUMBER: ${{ steps.resolve.outputs.pull_number }}
PR_SHA: ${{ steps.resolve.outputs.pr_sha }}
PR_CONCLUSION: ${{ steps.resolve.outputs.pr_conclusion }}
PR_RUN_ID: ${{ steps.resolve.outputs.pr_run_id }}
PR_RESULT_DIR: ${{ runner.temp }}/thread-transfer/pr
BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }}
BASELINE_MATCHES_BASE: ${{ steps.resolve.outputs.baseline_matches_base }}
BASELINE_RUN_ID: ${{ steps.resolve.outputs.baseline_run_id }}
BASELINE_RESULT_DIR: ${{ runner.temp }}/thread-transfer/main
with:
script: |
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
await reporter.publish({ github, context, core });
+132
View File
@@ -0,0 +1,132 @@
name: Web Preview
# Label a PR `preview:web` to get a hosted-web preview deployment on Vercel for
# that push and every subsequent push. The deployment is a plain (non-prod,
# non-aliased) deploy into the existing hosted-web Vercel project, so the
# latest/nightly channel aliases are never touched.
#
# The build intentionally omits the T3 Connect cloud config (Clerk keys, relay
# URL): previews boot as the hosted-static app with manual pairing only. Pair a
# server into a preview with `t3 pair --tailscale` (or any reachable HTTPS
# backend) and open the pairing URL against the preview origin.
#
# The preview must be opened at the exact deployment URL from the PR comment.
# Vite bakes that URL in as the hosted origin (via VERCEL_URL), and
# `isHostedStaticApp` matches on origin, so branch-alias URLs will not
# self-identify as the hosted app.
on:
pull_request:
types: [labeled, synchronize, reopened]
permissions:
contents: read
pull-requests: write
concurrency:
group: web-preview-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
deploy:
name: Deploy web preview
# Same-repo PRs only: fork PRs do not receive the Vercel secrets, and this
# workflow should skip rather than fail for them. On `labeled` events, only
# the preview label itself triggers a deploy.
if: >-
github.event.pull_request.head.repo.full_name == github.repository &&
contains(github.event.pull_request.labels.*.name, 'preview:web') &&
(github.event.action != 'labeled' || github.event.label.name == 'preview:web')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- id: deploy
name: Deploy preview
shell: bash
run: |
set -euo pipefail
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
exit 1
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
deployment_url="$(
vp dlx [email protected] deploy \
--archive=tgz \
--yes \
--token "$VERCEL_TOKEN" \
--scope "$vercel_scope"
)"
echo "Deployed $deployment_url"
echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT"
- name: Comment deployment URL
uses: actions/github-script@v8
env:
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment_url }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
with:
script: |
const marker = "<!-- web-preview-deploy -->";
const body = [
marker,
"### Web preview",
"",
`${process.env.DEPLOYMENT_URL} (for ${process.env.HEAD_SHA.slice(0, 7)})`,
"",
"Open this exact URL — the hosted-app origin is baked in at build time.",
"Pair a server into it with `t3 pair --tailscale`, or paste a host + pairing",
"code under Settings → Connections.",
].join("\n");
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
per_page: 100,
});
const existing = comments.find((comment) => comment.body?.includes(marker));
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
body,
});
}
@@ -0,0 +1,82 @@
---
title: UI Consistency
model: claude-opus-5
effort: high
input: full_diff
tools:
- browse_code
- git_tools
- github_api_read_only
- modify_pr
include:
- "apps/web/src/**/*.ts"
- "apps/web/src/**/*.tsx"
- "apps/web/src/**/*.css"
conclusion: failure
showToolCalls: true
---
# UI consistency review
Review changed web UI code and directly affected call sites for consistency with the shared component system, Tailwind ownership, and the behavioral constraints below. Apply these rules when a pull request creates, moves, or modifies controls or styling. Do not demand unrelated repository-wide cleanup.
The goal is not to minimize CSS or class counts at any cost. The goal is to put each behavior in the smallest correct owner while preserving interaction, theming, accessibility, layout, and browser behavior.
## Shared controls and variants
- Prefer the core UI primitives in `apps/web/src/components/ui` over native controls or locally reconstructed primitives. In ordinary product UI, a raw `<button>` that recreates `Button`, a raw input that recreates `Input` or `InputGroup`, or a local trigger that recreates `Select`, `Toggle`, or `Menu` is a concrete finding.
- Do not flag raw elements that intentionally implement a semantic row, tab, resize handle, swatch, image target, editor surface, or another interaction whose behavior or geometry differs from the core primitive.
- When multiple call sites repeat the same durable geometry or treatment, prefer a named primitive size or variant. Examples include compact controls, micro icon actions, muted ghost actions, and glass actions. Keep contextual layout, width, and color at the call site.
- Flag large call-site class strings that override a primitive's core height, radius, padding, focus ring, cursor, hit target, or base state colors. Prefer extending the primitive contract when the same pattern is genuinely shared.
- Preserve accessibility and interaction semantics during migrations: focus-visible rings, disabled behavior, loading state, keyboard behavior, pointer cursor, `aria-*`, Base UI or Radix render/close props, and coarse-pointer hit targets.
- Do not require tests for a tiny visual-only class migration. Require focused tests when primitive composition changes behavior, prop forwarding, state transitions, keyboard handling, or width/defaulting logic.
## CSS and Tailwind ownership
- Ordinary one-owner presentation belongs in the owning TS or TSX module as static Tailwind classes or owner-level CSS variables. Examples include local geometry, spacing, typography, backgrounds, borders, simple vendor pseudo-elements, and component-only positioning.
- Keep global CSS when it is genuinely reusable or behaviorally complex: generated markdown or imperative DOM, custom elements and shadow roots, masks, shared or complex pseudo-elements, animations, glass composition, runtime theme variables, safe-area calculations, scrollbar-lane preservation, Electron drag regions, and browser/vendor integration. Simple owner-local pseudo-elements may still belong in the owning module.
- Before calling a selector dead, trace literal, dynamic, generated, imperative, test, custom-element, and shadow-root consumers. Search both the emitted class string and any class-valued field names through their final DOM sink. A helper returning a class is not proof that it is rendered, and a missed downstream property read can make a deletion unsafe.
- Flag duplicate declarations only after comparing cascade layer, selector specificity, inheritance, runtime theme scope, media/variant scope, and the final owning element. Textually identical declarations are not necessarily behaviorally redundant.
- When moving CSS into Tailwind, preserve selector scope and cascade ownership. A utility at the owner is preferable to a fragile global override that depends on stylesheet order.
- Do not request moving complex global behavior into arbitrary Tailwind merely to reduce `index.css`. Do not preserve ordinary one-owner CSS merely because it already exists globally.
## Themes and generated CSS
- Use the project variants for theme-only declarations:
- dark-only declarations use `@variant dark`;
- light-only declarations use `@variant light`;
- raw `.dark` should remain only in the `dark` and `light` custom-variant definitions.
- Preserve custom themes and runtime token bridges. Removing a variable or selector is safe only when all runtime, inspector, generated, and theme-palette consumers are accounted for.
- Inspect emitted production CSS after unusual variants, arbitrary selectors, nested pseudo-elements, or attribute matching. Source syntax that looks valid is insufficient.
- Flag malformed or empty emitted selectors such as empty `:is()` or `:not(:is())`, selector branches that can never match their own class attribute, and transformations that silently drop the intended rule.
- Prefer source-level logic over clever selectors when behavior depends on consumer-provided class strings. Preserve `MenuPopup`'s current defaulting contract: a string `className` containing a `w-*`, `min-w-*`, or `max-w-*` utility after variant prefixes are stripped suppresses `min-w-32`; a string without one and a functional/non-string `className` keep the default. Arbitrary width values count as width utilities, and the consumer class must be merged last so it retains control. Do not replace this with a raw class-attribute substring selector.
- Do not fail solely because a valid emitted selector is verbose or because a source rule uses an intentional custom property.
## Scroll and virtualized lists
- `ScrollArea` owns and masks its Base UI viewport. A virtualized list usually owns a native scrolling element and cannot automatically reuse viewport-specific `ScrollArea` behavior.
- Repeated native or virtualized overflow fades should use the shared virtualized-scroll-fade contract rather than component-named mask selectors.
- Preserve runtime top and bottom overflow state. Do not replace dynamic fades with an always-on static mask.
- Preserve fade geometry and keep the native scrollbar lane opaque so the track and thumb stay visible and usable. A visually similar mask that fades the scrollbar is a regression.
- Verify actual scroll behavior when changing virtualizers, masks, overflow ownership, or scrollbar selectors. Source-level class comparison is not enough.
## Visual and layout preservation
- Preserve responsive geometry, titlebar insets, panel and inline-preview modes, desktop Electron layout, light and dark contrast, clipping, radius, and composable shadows.
- For meaningful visual changes, prefer available real-app evidence using the actual component and state. A mock recreation does not validate the real component. Light and dark evidence is useful when theme-sensitive styles change, but missing or inaccessible evidence alone is not a finding; report only a concrete regression supported by the diff, code, or available artifacts.
- Do not treat a screenshot as proof of keyboard, overflow, scrollbar, responsive, or runtime-theme behavior. Pair visual evidence with source, computed-style, emitted-CSS, or interaction checks as appropriate.
- Be alert to shared primitive color indirection. When a primitive routes icon color through a CSS variable, ensure migrated contextual icons retain their intended tone, including pressed and disabled states.
## Change discipline
- Review the pull request's changed scope and directly affected consumers. Do not turn a focused PR into a demand for unrelated legacy cleanup.
- Prefer the smallest durable contract over a component-specific workaround or a broad abstraction with one consumer.
- Preserve intentional exceptions and comments that explain browser, virtualizer, theme, or Electron constraints.
- If a proposed cleanup cannot prove ownership or semantic equivalence, ask for evidence or leave it unchanged rather than guessing.
- Select verification gates according to the changed behavior: typecheck or focused tests for typing and interaction contracts, production build and emitted-CSS inspection for Tailwind or selector transformations, and real-app evidence for meaningful visual behavior when available. These gates are complementary when applicable, but do not require every gate for tiny visual-only migrations or fail solely because an artifact the configured tools cannot produce is absent.
## Reporting
Report only concrete violations introduced by changed lines or behavior, plus pre-existing behavior that the patch directly makes relevant or worsens. Touching a large file does not make unrelated retained issues reportable. Prefer precise inline comments on the smallest relevant line range. Explain the broken behavior or ownership rule, not merely the preferred syntax, and state the smallest expected fix. A clear consistency or regression risk may fail the check. Do not fail for optional aesthetic preferences, harmless class ordering, or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 295 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.3 KiB

+2 -3
View File
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
- Stop what you started, by the PID you tracked. See rule 1.
## Test data
@@ -114,7 +114,6 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
- Never make a PR unless the developer explicitly asks you to do so.
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
- UI changes need before/after images. Motion or timing needs a short video.
- One concern per PR. If the description says "also", split it.
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
+1 -1
View File
@@ -1 +1 @@
AGENTS.md
AGENTS.md
+5 -3
View File
@@ -4,7 +4,9 @@
We are not actively accepting contributions right now.
You can still open an issue or PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
You can still report a bug or open a PR, but please do so knowing there is a high chance we close it, defer it forever, or never look at it.
Feature requests and proposals belong in [Ideas discussions](https://github.com/pingdotgg/t3code/discussions/categories/ideas), not issues.
If that sounds annoying, that is because it is. This project is still early and we are trying to keep scope, quality, and direction under control.
@@ -50,9 +52,9 @@ If the change depends on motion, timing, transitions, or interaction details, in
If we have to guess what changed, we are much less likely to review it.
## Issues First
## Discuss Changes First
If you are thinking about a non-trivial change, open an issue first.
If you are thinking about a non-trivial change, start a discussion first. Issues are reserved for bug reports.
That still does not mean we will want the PR, but it gives you a chance to avoid wasting your time.
+14 -1
View File
@@ -51,10 +51,20 @@ brew install --cask t3-code
#### Arch Linux (AUR)
Stable:
```bash
yay -S t3code-bin
```
Nightly:
```bash
yay -S t3code-nightly-bin
```
The AUR packaging is maintained in this repository under [`packaging/aur`](./packaging/aur).
## Some notes
We are very very early in this project. Expect bugs.
@@ -68,6 +78,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Customize a project icon](./docs/user/project-settings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
@@ -102,6 +113,8 @@ Checkout their getting started guide for more information: https://viteplus.dev/
vp i
```
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before opening an issue or PR.
Read [CONTRIBUTING.md](./CONTRIBUTING.md) before reporting a bug or opening a PR.
Have a feature request? Start an [Ideas discussion](https://github.com/pingdotgg/t3code/discussions/categories/ideas).
Need support? Join the [Discord](https://discord.gg/jn4EGJjrvv).
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.31",
"version": "0.0.33",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -0,0 +1,33 @@
<svg width="1080" height="760" viewBox="0 0 540 380" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="latest-surface" x1="0" y1="0" x2="540" y2="380" gradientUnits="userSpaceOnUse">
<stop stop-color="#FAFAF9"/>
<stop offset="1" stop-color="#F5F5F4"/>
</linearGradient>
<radialGradient id="latest-light" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(430 0) rotate(152) scale(320 150)">
<stop stop-color="#FFFFFF"/>
<stop offset="1" stop-color="#FFFFFF" stop-opacity="0"/>
</radialGradient>
</defs>
<rect width="540" height="380" fill="url(#latest-surface)"/>
<rect width="540" height="112" fill="#EFEFED"/>
<rect width="540" height="112" fill="url(#latest-light)"/>
<path d="M0 111.5H540" stroke="#18181B" stroke-opacity="0.08"/>
<path d="M32 28H64" stroke="#18181B" stroke-width="2"/>
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" fill="#18181B">
<text x="32" y="50" font-size="12" font-weight="600" letter-spacing="1.4">T3 CODE</text>
<text x="32" y="82" font-size="22" font-weight="600" letter-spacing="-0.45">Desktop</text>
<text x="508" y="50" text-anchor="end" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="8.5" font-weight="600" letter-spacing="1.2" fill="#71717A">LATEST RELEASE</text>
</g>
<path d="M196 224C242 239 307 201 362 220" stroke="#71717A" stroke-width="1.5" stroke-linecap="round" stroke-dasharray="1 7" opacity="0.42"/>
<circle cx="362" cy="220" r="2" fill="#71717A" opacity="0.55"/>
<path d="M176 204V227L182 221L187.5 232L192 229.8L186.5 219H194L176 204Z" fill="#71717A" stroke="#F7F7F5" stroke-width="1.5" stroke-linejoin="round"/>
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" text-anchor="middle">
<text x="270" y="322" font-size="13" font-weight="600" letter-spacing="-0.1" fill="#18181B">Drag T3 Code to Applications</text>
<text x="270" y="345" font-size="9.5" fill="#71717A">Open it from Applications when the copy finishes.</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 2.0 KiB

@@ -0,0 +1,64 @@
<svg width="1080" height="760" viewBox="0 0 540 380" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="night-sky" x1="28" y1="0" x2="510" y2="112" gradientUnits="userSpaceOnUse">
<stop stop-color="#07152F"/>
<stop offset="0.52" stop-color="#151443"/>
<stop offset="1" stop-color="#32155B"/>
</linearGradient>
<radialGradient id="night-glow" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(420 18) rotate(157) scale(260 126)">
<stop stop-color="#5165D8" stop-opacity="0.42"/>
<stop offset="0.55" stop-color="#283075" stop-opacity="0.15"/>
<stop offset="1" stop-color="#111635" stop-opacity="0"/>
</radialGradient>
<linearGradient id="night-cloud" x1="18" y1="62" x2="260" y2="112" gradientUnits="userSpaceOnUse">
<stop stop-color="#4EA4FF" stop-opacity="0.5"/>
<stop offset="0.52" stop-color="#696FEA" stop-opacity="0.62"/>
<stop offset="1" stop-color="#A85BEA" stop-opacity="0.5"/>
</linearGradient>
<filter id="night-soft" x="-24" y="35" width="588" height="101" filterUnits="userSpaceOnUse">
<feGaussianBlur stdDeviation="4"/>
</filter>
</defs>
<rect width="540" height="380" fill="#F7F7F5"/>
<rect width="540" height="112" fill="url(#night-sky)"/>
<rect width="540" height="112" fill="url(#night-glow)"/>
<g fill="#E4EAFF">
<circle cx="20" cy="18" r="0.8" opacity="0.82"/>
<circle cx="76" cy="27" r="0.55" opacity="0.55"/>
<circle cx="133" cy="13" r="0.65" opacity="0.7"/>
<circle cx="198" cy="28" r="0.5" opacity="0.5"/>
<circle cx="258" cy="15" r="0.75" opacity="0.8"/>
<circle cx="326" cy="29" r="0.5" opacity="0.55"/>
<circle cx="384" cy="12" r="0.65" opacity="0.72"/>
<circle cx="455" cy="26" r="0.55" opacity="0.58"/>
<circle cx="517" cy="15" r="0.75" opacity="0.78"/>
</g>
<g stroke="#EEF2FF" stroke-linecap="round" stroke-width="0.65" opacity="0.68">
<path d="M104 30V34M102 32H106"/>
<path d="M448 24V28M446 26H450"/>
</g>
<g filter="url(#night-soft)">
<path d="M-12 112V101C-12 87 0 76 14 76C18 63 30 54 44 54C58 54 70 62 74 75C79 70 86 67 94 67C110 67 123 79 124 95C132 96 138 101 141 112H-12Z" fill="url(#night-cloud)"/>
<path d="M374 112C375 98 387 87 401 87C405 72 418 62 434 62C450 62 463 72 467 87C478 87 488 94 492 104C506 103 518 106 526 112H374Z" fill="url(#night-cloud)" opacity="0.82"/>
</g>
<path d="M0 111.5H540" stroke="#050A19" stroke-opacity="0.3"/>
<path d="M32 28H64" stroke="#FFFFFF" stroke-width="2"/>
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" fill="#FFFFFF">
<text x="32" y="50" font-size="12" font-weight="600" letter-spacing="1.4">T3 CODE</text>
<text x="32" y="82" font-size="22" font-weight="600" letter-spacing="-0.45">Desktop</text>
<text x="508" y="50" text-anchor="end" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="8.5" font-weight="600" letter-spacing="1.2" opacity="0.84">NIGHTLY BUILD</text>
</g>
<path d="M196 224C242 239 307 201 362 220" stroke="#71717A" stroke-width="1.5" stroke-linecap="round" stroke-dasharray="1 7" opacity="0.42"/>
<circle cx="362" cy="220" r="2" fill="#71717A" opacity="0.55"/>
<path d="M176 204V227L182 221L187.5 232L192 229.8L186.5 219H194L176 204Z" fill="#71717A" stroke="#F7F7F5" stroke-width="1.5" stroke-linejoin="round"/>
<g font-family="-apple-system, BlinkMacSystemFont, sans-serif" text-anchor="middle">
<text x="270" y="322" font-size="13" font-weight="600" letter-spacing="-0.1" fill="#18181B">Drag T3 Code to Applications</text>
<text x="270" y="345" font-size="9.5" fill="#71717A">Open it from Applications when the copy finishes.</text>
</g>
</svg>

After

Width:  |  Height:  |  Size: 3.7 KiB

Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 313 KiB

+17 -16
View File
@@ -20,14 +20,14 @@ export const APP_BUNDLE_ID = isDevelopment
? `com.t3tools.t3code.dev.${devBundleIdSuffix || "local"}`
: "com.t3tools.t3code";
const APP_PROTOCOL_SCHEMES = isDevelopment ? ["t3code-dev"] : ["t3code"];
const LAUNCHER_VERSION = 14;
const defaultIconPath = NodePath.join(desktopDir, "resources", "icon.icns");
const LAUNCHER_VERSION = 15;
const developmentMacIconPngPath = NodePath.join(
repoRoot,
"assets",
"dev",
"blueprint-macos-1024.png",
);
const productionMacIconPngPath = NodePath.join(repoRoot, "assets", "prod", "black-macos-1024.png");
// oxlint-disable-next-line t3code/no-global-process-runtime -- Standalone launcher script has no Effect runtime.
const hostPlatform = NodeOS.platform();
@@ -165,15 +165,22 @@ function registerMacLauncherBundle(appBundlePath) {
}
}
function ensureDevelopmentIconIcns(runtimeDir) {
const generatedIconPath = NodePath.join(runtimeDir, "icon-dev.icns");
export function resolveMacLauncherIconPaths(runtimeDir, development = isDevelopment) {
return {
sourceIconPath: development ? developmentMacIconPngPath : productionMacIconPngPath,
generatedIconPath: NodePath.join(runtimeDir, development ? "icon-dev.icns" : "icon-prod.icns"),
};
}
function ensureMacIconIcns(runtimeDir) {
const { sourceIconPath, generatedIconPath } = resolveMacLauncherIconPaths(runtimeDir);
NodeFS.mkdirSync(runtimeDir, { recursive: true });
if (!NodeFS.existsSync(developmentMacIconPngPath)) {
return defaultIconPath;
if (!NodeFS.existsSync(sourceIconPath)) {
throw new Error(`Desktop macOS icon source is missing at ${sourceIconPath}`);
}
const sourceMtimeMs = NodeFS.statSync(developmentMacIconPngPath).mtimeMs;
const sourceMtimeMs = NodeFS.statSync(sourceIconPath).mtimeMs;
if (
NodeFS.existsSync(generatedIconPath) &&
NodeFS.statSync(generatedIconPath).mtimeMs >= sourceMtimeMs
@@ -191,7 +198,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
"-z",
String(size),
String(size),
developmentMacIconPngPath,
sourceIconPath,
"--out",
NodePath.join(iconsetDir, `icon_${size}x${size}.png`),
]);
@@ -201,7 +208,7 @@ function ensureDevelopmentIconIcns(runtimeDir) {
"-z",
String(retinaSize),
String(retinaSize),
developmentMacIconPngPath,
sourceIconPath,
"--out",
NodePath.join(iconsetDir, `icon_${size}x${size}@2x.png`),
]);
@@ -209,12 +216,6 @@ function ensureDevelopmentIconIcns(runtimeDir) {
runChecked("iconutil", ["-c", "icns", iconsetDir, "-o", generatedIconPath]);
return generatedIconPath;
} catch (error) {
console.warn(
"[desktop-launcher] Failed to generate dev macOS icon, falling back to default icon.",
error,
);
return defaultIconPath;
} finally {
NodeFS.rmSync(iconsetRoot, { recursive: true, force: true });
}
@@ -297,7 +298,7 @@ function buildMacLauncher(electronBinaryPath) {
const launcherBinaryPath = isDevelopment
? developmentPaths.launcherBinaryPath
: runtimeElectronBinaryPath;
const iconPath = isDevelopment ? ensureDevelopmentIconIcns(runtimeDir) : defaultIconPath;
const iconPath = ensureMacIconIcns(runtimeDir);
const metadataPath = NodePath.join(runtimeDir, "metadata.json");
NodeFS.mkdirSync(runtimeDir, { recursive: true });
@@ -3,6 +3,7 @@ import { assert, describe, it } from "vite-plus/test";
import {
makeDevelopmentLauncherScript,
resolveElectronBinaryPath,
resolveMacLauncherIconPaths,
resolveMacLauncherPaths,
} from "./electron-launcher.mjs";
@@ -78,4 +79,14 @@ describe("electron development launcher", () => {
);
assert.notInclude(script, "node_modules/electron");
});
it("derives launcher icons from canonical development and production assets", () => {
const development = resolveMacLauncherIconPaths("/runtime", true);
const production = resolveMacLauncherIconPaths("/runtime", false);
assert.match(development.sourceIconPath, /assets\/dev\/blueprint-macos-1024\.png$/);
assert.equal(development.generatedIconPath, "/runtime/icon-dev.icns");
assert.match(production.sourceIconPath, /assets\/prod\/black-macos-1024\.png$/);
assert.equal(production.generatedIconPath, "/runtime/icon-prod.icns");
});
});
+41 -2
View File
@@ -9,6 +9,7 @@ import * as Crypto from "effect/Crypto";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronDialog from "../electron/ElectronDialog.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronSafeStorage from "../electron/ElectronSafeStorage.ts";
import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
@@ -17,7 +18,9 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
import * as DesktopBackendPool from "../backend/DesktopBackendPool.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLifecycle from "./DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
import * as DesktopObservability from "./DesktopObservability.ts";
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
import * as DesktopShutdown from "./DesktopShutdown.ts";
import * as DesktopServerExposure from "../backend/DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
@@ -220,20 +223,49 @@ const startup = Effect.gen(function* () {
const applicationMenu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
const electronApp = yield* ElectronApp.ElectronApp;
const lifecycle = yield* DesktopLifecycle.DesktopLifecycle;
const linuxUrlHandler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
const clerk = yield* DesktopClerk.DesktopClerk;
const shellEnvironment = yield* DesktopShellEnvironment.DesktopShellEnvironment;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const preReadyElectronOptions = yield* DesktopPreReadyPlatform.DesktopPreReadyElectronOptions;
const safeStorage = yield* ElectronSafeStorage.ElectronSafeStorage;
const updates = yield* DesktopUpdates.DesktopUpdates;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* shellEnvironment.installIntoProcess;
const hasCommandLinePasswordStore =
preReadyElectronOptions.linuxPasswordStoreCommandLine !== null;
const linuxElectronOptions =
environment.platform === "linux" && !hasCommandLinePasswordStore
? DesktopPreReadyPlatform.resolveEarlyLinuxElectronOptionsFromProcess()
: preReadyElectronOptions.linux;
if (linuxElectronOptions !== null && !hasCommandLinePasswordStore) {
if (
linuxElectronOptions.passwordStore !== null ||
preReadyElectronOptions.linux?.passwordStore !== null
) {
yield* electronApp.removeCommandLineSwitch("password-store");
}
if (linuxElectronOptions.passwordStore !== null) {
yield* electronApp.appendCommandLineSwitch(
"password-store",
linuxElectronOptions.passwordStore,
);
}
}
const userDataPath = yield* appIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
yield* logStartupInfo("runtime logging configured", { logDir: environment.logDir });
yield* desktopSettings.load;
if (environment.platform === "linux") {
yield* electronApp.appendCommandLineSwitch("class", environment.linuxWmClass);
if (linuxElectronOptions !== null) {
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,
});
}
yield* appIdentity.configure;
@@ -245,9 +277,16 @@ const startup = Effect.gen(function* () {
Effect.catchCause((cause) => fatalStartupCause("whenReady", cause)),
);
yield* logStartupInfo("app ready");
if (environment.platform === "linux") {
const selectedBackend = yield* safeStorage.selectedStorageBackend;
yield* logStartupInfo("safe storage ready", {
backend: Option.getOrElse(selectedBackend, () => "unknown"),
});
}
yield* appIdentity.configure;
yield* applicationMenu.configure;
yield* updates.configure;
yield* linuxUrlHandler.register;
yield* bootstrap.pipe(Effect.catchCause((cause) => fatalStartupCause("bootstrap", cause)));
}).pipe(Effect.withSpan("desktop.startup"));
@@ -40,6 +40,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
systemLocale: Effect.succeed("en-US"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
@@ -54,7 +55,6 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
calls.setAboutPanelOptions.push(options);
}),
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
@@ -65,6 +65,7 @@ const makeElectronAppLayer = (calls: ElectronAppCalls) =>
}),
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
+27 -19
View File
@@ -45,6 +45,27 @@ const normalizeCommitHash = (value: string): Option.Option<string> => {
: Option.none();
};
export const resolveUserDataPath = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
export const make = Effect.gen(function* () {
const assets = yield* DesktopAssets.DesktopAssets;
const electronApp = yield* ElectronApp.ElectronApp;
@@ -90,24 +111,11 @@ export const make = Effect.gen(function* () {
return commitHash;
});
const resolveUserDataPath = Effect.gen(function* () {
const legacyPath = environment.path.join(
environment.appDataDirectory,
environment.legacyUserDataDirName,
);
const legacyPathExists = yield* fileSystem.exists(legacyPath).pipe(
Effect.mapError(
(cause) =>
new DesktopUserDataPathResolutionError({
legacyPath,
cause,
}),
),
);
return legacyPathExists
? legacyPath
: environment.path.join(environment.appDataDirectory, environment.userDataDirName);
}).pipe(Effect.withSpan("desktop.appIdentity.resolveUserDataPath"));
const userDataPath = resolveUserDataPath.pipe(
Effect.provide(
yield* Effect.context<DesktopEnvironment.DesktopEnvironment | FileSystem.FileSystem>(),
),
);
const configure = Effect.gen(function* () {
const commitHash = yield* resolveAboutCommitHash;
@@ -136,7 +144,7 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.appIdentity.configure"));
return DesktopAppIdentity.of({
resolveUserDataPath,
resolveUserDataPath: userDataPath,
configure,
});
});
@@ -3,6 +3,7 @@ import { assert, describe, it } from "@effect/vitest";
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 PlatformError from "effect/PlatformError";
import * as DesktopAssets from "./DesktopAssets.ts";
@@ -22,6 +23,45 @@ const environmentLayer = DesktopEnvironment.layer({
}).pipe(Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))));
describe("DesktopAssets", () => {
it.effect("uses canonical source-tree icons for unpackaged development", () =>
Effect.gen(function* () {
const developmentEnvironmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "linux",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: false,
resourcesPath: "/repo/apps/desktop/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({ VITE_DEV_SERVER_URL: "http://localhost:5733" }),
),
),
);
const fileSystemLayer = FileSystem.layerNoop({
exists: (path) => Effect.succeed(String(path).includes("/assets/dev/")),
});
const assets = yield* DesktopAssets.DesktopAssets.pipe(
Effect.provide(
DesktopAssets.layer.pipe(
Layer.provide(Layer.merge(fileSystemLayer, developmentEnvironmentLayer)),
),
),
);
const icons = yield* assets.iconPaths;
assert.match(Option.getOrThrow(icons.ico), /assets\/dev\/blueprint-windows\.ico$/);
assert.match(Option.getOrThrow(icons.png), /assets\/dev\/blueprint-universal-1024\.png$/);
assert.isTrue(Option.isNone(icons.icns));
}),
);
it.effect("preserves the failed asset candidate and filesystem cause", () =>
Effect.gen(function* () {
const fileName = "custom.bin";
+36 -7
View File
@@ -61,6 +61,35 @@ const resolveResourcePath = Effect.fn("desktop.assets.resolveResourcePath")(func
return Option.none<string>();
});
const sourceTreeIconFileNames = {
dev: {
ico: "blueprint-windows.ico",
macPng: "blueprint-macos-1024.png",
universalPng: "blueprint-universal-1024.png",
},
prod: {
ico: "t3-black-windows.ico",
macPng: "black-macos-1024.png",
universalPng: "black-universal-1024.png",
},
} as const;
function resolveSourceTreeIconPath(
environment: DesktopEnvironment.DesktopEnvironment["Service"],
ext: keyof DesktopIconPaths,
): string | undefined {
if (environment.isPackaged || ext === "icns") return undefined;
const brand = environment.isDevelopment ? "dev" : "prod";
const fileNames = sourceTreeIconFileNames[brand];
const fileName =
ext === "ico"
? fileNames.ico
: environment.platform === "darwin"
? fileNames.macPng
: fileNames.universalPng;
return environment.path.join(environment.rootDir, "assets", brand, fileName);
}
const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
ext: keyof DesktopIconPaths,
): Effect.fn.Return<
@@ -70,20 +99,20 @@ const resolveIconPath = Effect.fn("desktop.assets.resolveIconPath")(function* (
> {
const fileSystem = yield* FileSystem.FileSystem;
const environment = yield* DesktopEnvironment.DesktopEnvironment;
if (environment.isDevelopment && environment.platform === "darwin" && ext === "png") {
const developmentDockIconPath = environment.developmentDockIconPath;
const developmentDockIconExists = yield* fileSystem.exists(developmentDockIconPath).pipe(
const sourceTreeIconPath = resolveSourceTreeIconPath(environment, ext);
if (sourceTreeIconPath !== undefined) {
const sourceTreeIconExists = yield* fileSystem.exists(sourceTreeIconPath).pipe(
Effect.mapError(
(cause) =>
new DesktopAssetProbeError({
fileName: "icon.png",
candidatePath: developmentDockIconPath,
fileName: `icon.${ext}`,
candidatePath: sourceTreeIconPath,
cause,
}),
),
);
if (developmentDockIconExists) {
return Option.some(developmentDockIconPath);
if (sourceTreeIconExists) {
return Option.some(sourceTreeIconPath);
}
}
+90 -5
View File
@@ -22,17 +22,38 @@ vi.mock("@clerk/electron/storage", () => ({
storage: storageMock,
}));
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopClerk from "./DesktopClerk.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const makeDesktopClerkLayer = (isDevelopment = true) => {
const makeDesktopClerkLayer = (isDevelopment = true, events: string[] = []) => {
const environment = DesktopEnvironment.DesktopEnvironment.of({
stateDir: "/tmp/t3-state",
isDevelopment,
appDataDirectory: "/tmp/app-data",
userDataDirName: isDevelopment ? "t3code-dev" : "t3code",
legacyUserDataDirName: isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)",
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const electronApp = {
setPath: (name: string, value: string) =>
Effect.sync(() => {
events.push(`setPath:${name}:${value}`);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
return DesktopClerk.layer.pipe(
Layer.provide(Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment)),
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, environment),
Layer.succeed(ElectronApp.ElectronApp, electronApp),
FileSystem.layerNoop({ exists: () => Effect.succeed(false) }),
),
),
);
};
@@ -55,11 +76,15 @@ describe("DesktopClerk", () => {
it.effect("acquires and releases the SDK bridge with the layer", () => {
const cleanup = vi.fn();
const events: string[] = [];
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup });
createClerkBridgeMock.mockImplementation(() => {
events.push("createClerkBridge");
return { cleanup, isPrimaryInstance: true };
});
return Effect.gen(function* () {
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer()));
yield* Effect.scoped(Layer.build(makeDesktopClerkLayer(true, events)));
assert.deepEqual(createClerkBridgeMock.mock.calls, [
[
@@ -71,6 +96,10 @@ describe("DesktopClerk", () => {
],
]);
assert.equal(cleanup.mock.calls.length, 1);
// The bridge acquires Electron's single-instance lock at creation, and
// the lock both lives in and creates the userData directory — so the
// real path must be set before the bridge exists.
assert.deepEqual(events, ["setPath:userData:/tmp/app-data/t3code-dev", "createClerkBridge"]);
storageMock.mockClear();
createClerkBridgeMock.mockClear();
});
@@ -124,11 +153,67 @@ describe("DesktopClerk", () => {
});
});
it.effect("registers the second-instance handler in the primary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: true });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.isSuccess(exit));
assert.equal(quit.mock.calls.length, 0);
assert.deepEqual(registeredEvents, ["second-instance"]);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
it.effect("quits and interrupts startup in a secondary instance", () => {
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue({ cleanup: vi.fn(), isPrimaryInstance: false });
const quit = vi.fn();
const registeredEvents: string[] = [];
const electronApp = {
quit: Effect.sync(quit),
on: (eventName: string) =>
Effect.sync(() => {
registeredEvents.push(eventName);
}),
} as unknown as ElectronApp.ElectronApp["Service"];
const electronWindow = {} as ElectronWindow.ElectronWindow["Service"];
return Effect.gen(function* () {
const clerk = yield* DesktopClerk.DesktopClerk;
const exit = yield* Effect.exit(Effect.scoped(clerk.configure));
assert.isTrue(Exit.hasInterrupts(exit));
assert.equal(quit.mock.calls.length, 1);
assert.deepEqual(registeredEvents, []);
}).pipe(
Effect.provide(makeDesktopClerkLayer()),
Effect.provideService(ElectronApp.ElectronApp, electronApp),
Effect.provideService(ElectronWindow.ElectronWindow, electronWindow),
);
});
it.each([
{ isDevelopment: true, scheme: "t3code-dev" },
{ isDevelopment: false, scheme: "t3code" },
])("configures the SDK with the $scheme renderer origin", ({ isDevelopment, scheme }) => {
const bridge = { cleanup: vi.fn() };
const bridge = { cleanup: vi.fn(), isPrimaryInstance: true };
storageMock.mockReturnValue(storageAdapter);
createClerkBridgeMock.mockReturnValue(bridge);
+19 -2
View File
@@ -11,6 +11,7 @@ import { clerkFrontendApiHostnameFromPublishableKey } from "@t3tools/shared/rela
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
declare const __T3CODE_BUILD_CLERK_PUBLISHABLE_KEY__: string | undefined;
@@ -84,7 +85,18 @@ export function createDesktopClerkBridge(stateDir: string, isDevelopment: boolea
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
yield* Effect.acquireRelease(
const electronApp = yield* ElectronApp.ElectronApp;
// Electron scopes the single-instance lock to the userData directory and
// creates that directory when the lock is acquired. The SDK bridge takes
// the lock at creation, so userData must already point at the real
// directory here — under the default productName-derived path, acquiring
// the lock would create "T3 Code (Alpha)" and make the legacy-install
// detection in resolveUserDataPath match on fresh installs.
const userDataPath = yield* DesktopAppIdentity.resolveUserDataPath;
yield* electronApp.setPath("userData", userDataPath);
const bridge = yield* Effect.acquireRelease(
Effect.try({
try: () => createDesktopClerkBridge(environment.stateDir, environment.isDevelopment),
catch: (cause) =>
@@ -113,7 +125,12 @@ export const make = Effect.gen(function* () {
const context = yield* Effect.context<ElectronWindow.ElectronWindow>();
const runPromise = Effect.runPromiseWith(context);
if (!(yield* electronApp.requestSingleInstanceLock)) {
// The SDK bridge holds Electron's single-instance lock (acquired at
// bridge creation) so OAuth deep-link callbacks on Windows/Linux are
// forwarded to the running app. In a secondary instance the bridge has
// already begun quitting the app; app.quit() is asynchronous, so stop
// bootstrap here before whenReady can fire.
if (!bridge.isPrimaryInstance) {
yield* electronApp.quit;
return yield* Effect.interrupt;
}
+1
View File
@@ -35,6 +35,7 @@ const compactEnv = (env: Readonly<Record<string, string | undefined>>): Record<s
export const DesktopConfig = Config.all({
appDataDirectory: trimmedString("APPDATA"),
xdgConfigHome: trimmedString("XDG_CONFIG_HOME"),
xdgDataHome: trimmedString("XDG_DATA_HOME"),
t3Home: trimmedString("T3CODE_HOME"),
devServerUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option),
appUserModelIdOverride: trimmedString("T3CODE_DESKTOP_APP_USER_MODEL_ID"),
@@ -39,6 +39,7 @@ function makeSafeStorageLayer(available: boolean, failDecrypt: Ref.Ref<boolean>
return decoded.slice("encrypted:".length);
});
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -0,0 +1,121 @@
// @effect-diagnostics nodeBuiltinImport:off - tests use POSIX path joining to match the Linux startup boundary.
import * as NodePath from "node:path";
import { assert, describe, it } from "@effect/vitest";
import {
resolveEarlyLinuxElectronOptions,
resolveEarlyLinuxPasswordStorePreference,
} from "./DesktopEarlyElectronStartup.ts";
describe("DesktopEarlyElectronStartup", () => {
const joinPath = NodePath.posix.join;
it("reads the persisted linux password-store preference before Electron is ready", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("accepts JSONC in the early desktop settings file", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/home/user/.t3-test" },
homeDirectory: "/home/user",
joinPath,
readFileString: () => `{
// manually edited setting
"linuxPasswordStore": "gnome-libsecret",
}`,
});
assert.equal(preference, "gnome-libsecret");
});
it("falls back to auto when the early settings document is missing or invalid", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {},
homeDirectory: "/home/user",
joinPath,
readFileString: () => {
throw new Error("missing");
},
});
assert.equal(preference, "auto");
});
it("preserves absolute root paths when resolving early settings", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: { T3CODE_HOME: "/" },
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet6" });
},
});
assert.equal(preference, "kwallet6");
});
it("resolves the early linux Electron switches", () => {
const options = resolveEarlyLinuxElectronOptions({
env: {
T3CODE_HOME: "/home/user/.t3-test",
XDG_CURRENT_DESKTOP: "niri",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3-test/userdata/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "auto" });
},
});
assert.deepEqual(options, {
linuxWmClass: "t3code-dev",
passwordStore: "gnome-libsecret",
});
});
it("keeps implicit development state under ~/.t3/dev when T3CODE_HOME is unset", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "kwallet" });
},
});
assert.equal(preference, "kwallet");
});
it("treats whitespace-only T3CODE_HOME as unconfigured in development", () => {
const preference = resolveEarlyLinuxPasswordStorePreference({
env: {
T3CODE_HOME: " ",
VITE_DEV_SERVER_URL: "http://127.0.0.1:5173",
},
homeDirectory: "/home/user",
joinPath,
readFileString: (path) => {
assert.equal(path, "/home/user/.t3/dev/desktop-settings.json");
return JSON.stringify({ linuxPasswordStore: "gnome-libsecret" });
},
});
assert.equal(preference, "gnome-libsecret");
});
});
@@ -0,0 +1,90 @@
import { fromLenientJson } from "@t3tools/shared/schemaJson";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
type LinuxPasswordStoreSwitch,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import {
resolveDesktopBaseDir,
resolveDesktopStateDir,
type JoinPath,
} from "./DesktopStatePaths.ts";
interface EarlyDesktopSettingsInput {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly readFileString: (path: string) => string;
}
type EarlyLinuxElectronOptionsInput = EarlyDesktopSettingsInput;
export interface EarlyLinuxElectronOptions {
readonly linuxWmClass: string;
readonly passwordStore: LinuxPasswordStoreSwitch | null;
}
const trimNonEmpty = (value: string | undefined): string | null => {
const trimmed = value?.trim();
return trimmed && trimmed.length > 0 ? trimmed : null;
};
const EarlyDesktopSettingsJson = fromLenientJson(
Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
}),
);
const decodeEarlyDesktopSettingsJson = Schema.decodeSync(EarlyDesktopSettingsJson);
const isDevelopmentEnvironment = (env: NodeJS.ProcessEnv): boolean =>
trimNonEmpty(env.VITE_DEV_SERVER_URL) !== null;
function resolveEarlyDesktopSettingsPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly homeDirectory: string;
readonly joinPath: JoinPath;
}): string {
const t3Home = Option.fromUndefinedOr(input.env.T3CODE_HOME);
const baseDir = resolveDesktopBaseDir({
homeDirectory: input.homeDirectory,
joinPath: input.joinPath,
t3Home,
});
const stateDir = resolveDesktopStateDir({
baseDir,
isDevelopment: isDevelopmentEnvironment(input.env),
joinPath: input.joinPath,
t3Home,
});
return input.joinPath(stateDir, "desktop-settings.json");
}
export function resolveEarlyLinuxPasswordStorePreference(
input: EarlyDesktopSettingsInput,
): LinuxPasswordStorePreference {
const settingsPath = resolveEarlyDesktopSettingsPath(input);
try {
const parsed = decodeEarlyDesktopSettingsJson(input.readFileString(settingsPath));
return normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore);
} catch {
return DEFAULT_LINUX_PASSWORD_STORE;
}
}
export function resolveEarlyLinuxElectronOptions(
input: EarlyLinuxElectronOptionsInput,
): EarlyLinuxElectronOptions {
const preference = resolveEarlyLinuxPasswordStorePreference(input);
return {
linuxWmClass: isDevelopmentEnvironment(input.env) ? "t3code-dev" : "t3code",
passwordStore: resolveLinuxPasswordStoreSwitch({
preference,
env: input.env,
}),
};
}
@@ -65,6 +65,7 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.rootDir, "/repo");
assert.equal(environment.appRoot, "/repo");
assert.equal(environment.serverRoot, "/repo");
assert.equal(environment.backendEntryPath, "/repo/apps/server/dist/bin.mjs");
assert.equal(environment.backendCwd, "/repo");
assert.equal(environment.appUserModelId, "com.t3tools.t3code.dev");
@@ -98,6 +99,24 @@ describe("DesktopEnvironment", () => {
}),
);
it.effect("uses the packaged Windows server sidecar as the backend root", () =>
Effect.gen(function* () {
const environment = yield* makeEnvironment({
platform: "win32",
isPackaged: true,
appPath: "/install/resources/app.asar",
resourcesPath: "/install/resources",
});
assert.equal(environment.appRoot, "/install/resources/app.asar");
assert.equal(environment.serverRoot, "/install/resources/server.asar");
assert.equal(
environment.backendEntryPath,
"/install/resources/server.asar/apps/server/dist/bin.mjs",
);
}),
);
it.effect("keeps implicit development state separate from production state", () =>
Effect.gen(function* () {
const development = yield* makeEnvironment(
+32 -8
View File
@@ -13,6 +13,7 @@ import * as Path from "effect/Path";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import { resolveDesktopBaseDir, resolveDesktopStateDir } from "./DesktopStatePaths.ts";
import { isNightlyDesktopVersion } from "../updates/updateChannels.ts";
export interface MakeDesktopEnvironmentInput {
@@ -51,6 +52,13 @@ export class DesktopEnvironment extends Context.Service<
readonly browserArtifactsDir: string;
readonly rootDir: string;
readonly appRoot: string;
// Root of the tree containing apps/server/dist and node_modules for the
// backend. Equals appRoot everywhere except packaged Windows, where the
// server tree ships as the resources/server.asar sidecar (see
// scripts/build-desktop-artifact.ts) that the asar-aware
// ELECTRON_RUN_AS_NODE primary reads in place and the WSL backend
// extracts on demand (see DesktopWslServerTree).
readonly serverRoot: string;
readonly backendEntryPath: string;
readonly backendCwd: string;
readonly preloadPath: string;
@@ -66,13 +74,14 @@ export class DesktopEnvironment extends Context.Service<
readonly appUserModelId: string;
readonly linuxDesktopEntryName: string;
readonly linuxWmClass: string;
readonly linuxApplicationsDir: string;
readonly appImagePath: Option.Option<string>;
readonly userDataDirName: string;
readonly legacyUserDataDirName: string;
readonly defaultDesktopSettings: DesktopAppSettings.DesktopSettings;
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
>()("@t3tools/desktop/app/DesktopEnvironment") {}
@@ -147,21 +156,34 @@ const make = Effect.fn("desktop.environment.make")(function* (
: input.platform === "darwin"
? path.join(homeDirectory, "Library", "Application Support")
: Option.getOrElse(config.xdgConfigHome, () => path.join(homeDirectory, ".config"));
const configuredBaseDir = config.t3Home;
const baseDir = Option.getOrElse(configuredBaseDir, () => path.join(homeDirectory, ".t3"));
const baseDir = resolveDesktopBaseDir({
homeDirectory,
joinPath: path.join,
t3Home: config.t3Home,
});
const rootDir = path.resolve(input.dirname, "../../..");
const appRoot = input.isPackaged ? input.appPath : rootDir;
const serverRoot =
input.isPackaged && input.platform === "win32"
? path.join(input.resourcesPath, "server.asar")
: appRoot;
const branding = resolveDesktopAppBranding({
isDevelopment,
appVersion: input.appVersion,
});
const displayName = branding.displayName;
const stateDir = path.join(
const stateDir = resolveDesktopStateDir({
baseDir,
isDevelopment && Option.isNone(configuredBaseDir) ? "dev" : "userdata",
);
isDevelopment,
joinPath: path.join,
t3Home: config.t3Home,
});
const userDataDirName = isDevelopment ? "t3code-dev" : "t3code";
const legacyUserDataDirName = isDevelopment ? "T3 Code (Dev)" : "T3 Code (Alpha)";
const linuxApplicationsDir = path.join(
Option.getOrElse(config.xdgDataHome, () => path.join(homeDirectory, ".local", "share")),
"applications",
);
const resourcesPath = input.resourcesPath;
return DesktopEnvironment.of({
@@ -186,7 +208,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
browserArtifactsDir: path.join(stateDir, "browser-artifacts"),
rootDir,
appRoot,
backendEntryPath: path.join(appRoot, "apps/server/dist/bin.mjs"),
serverRoot,
backendEntryPath: path.join(serverRoot, "apps/server/dist/bin.mjs"),
backendCwd: input.isPackaged ? homeDirectory : appRoot,
preloadPath: path.join(input.dirname, "preload.cjs"),
appUpdateYmlPath: input.isPackaged
@@ -205,6 +228,8 @@ const make = Effect.fn("desktop.environment.make")(function* (
),
linuxDesktopEntryName: isDevelopment ? "t3code-dev.desktop" : "t3code.desktop",
linuxWmClass: isDevelopment ? "t3code-dev" : "t3code",
linuxApplicationsDir,
appImagePath: config.appImagePath,
userDataDirName,
legacyUserDataDirName,
defaultDesktopSettings: DesktopAppSettings.resolveDefaultDesktopSettings(input.appVersion),
@@ -244,7 +269,6 @@ const make = Effect.fn("desktop.environment.make")(function* (
path.join(resourcesPath, "resources", fileName),
path.join(resourcesPath, fileName),
],
developmentDockIconPath: path.join(rootDir, "assets", "dev", "blueprint-macos-1024.png"),
});
});
@@ -21,6 +21,7 @@ describe("DesktopLifecycle", () => {
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
systemLocale: Effect.succeed("en-US"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
@@ -29,13 +30,13 @@ describe("DesktopLifecycle", () => {
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: (listener) =>
Effect.acquireRelease(
Effect.sync(() => {
@@ -78,6 +79,7 @@ describe("DesktopLifecycle", () => {
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.void,
zoomMain: () => Effect.void,
syncAppearance: Effect.void,
});
@@ -0,0 +1,229 @@
import { assert, describe, it } from "@effect/vitest";
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 PlatformError from "effect/PlatformError";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
interface RecordedRegistration {
readonly directories: string[];
readonly files: Array<{ readonly path: string; readonly content: string }>;
readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
}
const makeEnvironment = (overrides: Record<string, unknown> = {}) =>
DesktopEnvironment.DesktopEnvironment.of({
platform: "linux",
isPackaged: true,
isDevelopment: false,
displayName: "T3 Code (Alpha)",
linuxWmClass: "t3code",
linuxApplicationsDir: "/home/alice/.local/share/applications",
appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
path: { join: (...parts: ReadonlyArray<string>) => parts.join("/") },
...overrides,
} as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
const mockProcess = (exitCode: number) =>
ChildProcessSpawner.makeHandle({
pid: ChildProcessSpawner.ProcessId(1),
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
isRunning: Effect.succeed(false),
kill: () => Effect.void,
unref: Effect.succeed(Effect.void),
stdin: Sink.drain,
stdout: Stream.empty,
stderr: Stream.empty,
all: Stream.empty,
getInputFd: () => Sink.drain,
getOutputFd: () => Stream.empty,
});
const makeHandlerLayer = (
recorded: RecordedRegistration,
input: {
readonly environment?: Record<string, unknown>;
readonly xdgMimeExitCode?: number;
readonly writeError?: PlatformError.PlatformError;
} = {},
) =>
DesktopLinuxUrlHandler.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.succeed(DesktopEnvironment.DesktopEnvironment, makeEnvironment(input.environment)),
FileSystem.layerNoop({
makeDirectory: (path) =>
Effect.sync(() => {
recorded.directories.push(path);
}),
writeFileString: (path, content) =>
input.writeError
? Effect.fail(input.writeError)
: Effect.sync(() => {
recorded.files.push({ path, content });
}),
}),
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make((command) => {
const childProcess = command as unknown as {
readonly command: string;
readonly args: ReadonlyArray<string>;
};
recorded.commands.push({
command: childProcess.command,
args: childProcess.args,
});
return Effect.succeed(mockProcess(input.xdgMimeExitCode ?? 0));
}),
),
),
),
);
const runRegister = (
recorded: RecordedRegistration,
input: Parameters<typeof makeHandlerLayer>[1] = {},
) =>
Effect.gen(function* () {
const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
yield* handler.register;
}).pipe(Effect.provide(makeHandlerLayer(recorded, input)));
const emptyRecording = (): RecordedRegistration => ({
directories: [],
files: [],
commands: [],
});
describe("DesktopLinuxUrlHandler", () => {
it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
displayName: "T3 Code (Nightly)",
execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
scheme: "t3code",
});
assert.include(entry, "[Desktop Entry]");
assert.include(entry, "Name=T3 Code (Nightly)");
// Exec composes both escaping layers: a literal backslash becomes four
// backslashes in the file, a quote three characters, a dollar sign two
// backslashes plus the sign.
assert.include(
entry,
'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
);
assert.include(entry, "NoDisplay=true");
assert.notInclude(entry, "StartupWMClass=");
assert.include(entry, "MimeType=x-scheme-handler/t3code;");
});
it("carries structured context on registration errors", () => {
const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme: "t3code",
desktopEntryPath: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
cause: new Error("boom"),
});
assert.equal(
writeError.message,
"Failed to register the t3code:// URL handler (step: write-desktop-entry).",
);
assert.equal(
writeError.desktopEntryPath,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme: "t3code",
exitCode: 4,
});
assert.equal(
exitError.message,
"Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
);
});
it.effect("writes the handler entry and claims the scheme default via xdg-mime", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded);
assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
assert.equal(recorded.files.length, 1);
assert.equal(
recorded.files[0]?.path,
"/home/alice/.local/share/applications/t3code-url-handler.desktop",
);
assert.include(
recorded.files[0]?.content,
'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
);
assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
assert.deepEqual(recorded.commands, [
{
command: "xdg-mime",
args: ["default", "t3code-url-handler.desktop", "x-scheme-handler/t3code"],
},
]);
});
});
it.effect("falls back to the process executable outside an AppImage", () => {
const recorded = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
assert.include(
recorded.files[0]?.content,
`Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
);
});
});
it.effect("does nothing on other platforms or unpackaged builds", () => {
const nonLinux = emptyRecording();
const unpackaged = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
yield* runRegister(unpackaged, { environment: { isPackaged: false } });
for (const recorded of [nonLinux, unpackaged]) {
assert.deepEqual(recorded.directories, []);
assert.deepEqual(recorded.files, []);
assert.deepEqual(recorded.commands, []);
}
});
});
it.effect("never fails startup when registration cannot complete", () => {
const xdgMimeFailed = emptyRecording();
const writeFailed = emptyRecording();
return Effect.gen(function* () {
yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
yield* runRegister(writeFailed, {
writeError: PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFileString",
description: "read-only filesystem",
pathOrDescriptor: "/home/alice/.local/share/applications/t3code-url-handler.desktop",
}),
});
assert.equal(xdgMimeFailed.files.length, 1);
assert.deepEqual(writeFailed.commands, []);
});
});
});
@@ -0,0 +1,191 @@
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 Schema from "effect/Schema";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";
// Linux ships as an AppImage, so the .desktop entry users end up with is
// created by whatever integration tool they use (AppImageLauncher names it
// appimagekit_<hash>-….desktop) and its filename is not under our control.
// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
// setDesktopName, which cannot match those files — so the browser keeps
// prompting "Choose an application" for every OAuth callback. Instead, write
// our own handler entry pointing at the current AppImage and claim the
// scheme default via xdg-mime, exactly what the file manager's "set as
// default" checkbox would record in mimeapps.list.
export const URL_HANDLER_DESKTOP_ENTRY_NAME = "t3code-url-handler.desktop";
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedErrorClass<DesktopLinuxUrlHandlerRegistrationError>()(
"DesktopLinuxUrlHandlerRegistrationError",
{
step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
scheme: Schema.String,
desktopEntryPath: Schema.optionalKey(Schema.String),
exitCode: Schema.optionalKey(Schema.Number),
cause: Schema.optionalKey(Schema.Defect()),
},
) {
override get message(): string {
const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
}
}
const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
const escapeDesktopEntryString = (value: string): string =>
value
.replaceAll("\\", "\\\\")
.replaceAll("\n", "\\n")
.replaceAll("\r", "\\r")
.replaceAll("\t", "\\t");
// Exec values are unescaped twice by implementations: first the general
// string-value rules, then the Exec quoting rules — so writing composes the
// layers in reverse. The argument is double-quoted with reserved characters
// backslash-escaped and literal percent signs doubled (field codes), and the
// general string escaping is applied on top: a literal backslash ends up as
// four backslashes in the file, a quote as \\", a dollar sign as \\$.
export function escapeDesktopEntryExecArgument(value: string): string {
const quoted = value
.replaceAll("\\", () => "\\\\")
.replaceAll("`", () => "\\`")
.replaceAll("$", () => "\\$")
.replaceAll('"', () => '\\"')
.replaceAll("%", () => "%%");
return escapeDesktopEntryString(`"${quoted}"`);
}
// The AppImage integration entry owns the window identity and icon. This
// hidden URL-only entry must not compete with it for StartupWMClass matching.
export function renderUrlHandlerDesktopEntry(input: {
readonly displayName: string;
readonly execTarget: string;
readonly scheme: string;
}): string {
return [
"[Desktop Entry]",
"Type=Application",
`Name=${escapeDesktopEntryString(input.displayName)}`,
`Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
"Terminal=false",
"NoDisplay=true",
"StartupNotify=false",
`MimeType=x-scheme-handler/${input.scheme};`,
"",
].join("\n");
}
export class DesktopLinuxUrlHandler extends Context.Service<
DesktopLinuxUrlHandler,
{
readonly register: Effect.Effect<void>;
}
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
const desktopEntryPath = environment.path.join(
environment.linuxApplicationsDir,
URL_HANDLER_DESKTOP_ENTRY_NAME,
);
const writeDesktopEntry = Effect.gen(function* () {
// Inside the mounted AppImage, process.execPath points at a transient
// /tmp/.mount_* path — the handler must launch the AppImage itself.
const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
yield* fileSystem.writeFileString(
desktopEntryPath,
renderUrlHandlerDesktopEntry({
displayName: environment.displayName,
execTarget,
scheme,
}),
);
}).pipe(
Effect.mapError(
(cause) =>
new DesktopLinuxUrlHandlerRegistrationError({
step: "write-desktop-entry",
scheme,
desktopEntryPath,
cause,
}),
),
);
const setDefaultHandler = Effect.scoped(
Effect.gen(function* () {
const command = ChildProcess.make(
"xdg-mime",
["default", URL_HANDLER_DESKTOP_ENTRY_NAME, `x-scheme-handler/${scheme}`],
{
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
},
);
const handle = yield* spawner.spawn(command);
const exitCode = yield* handle.exitCode;
if ((exitCode as unknown as number) !== 0) {
return yield* new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
exitCode: Number(exitCode),
});
}
}),
).pipe(
Effect.mapError((error) =>
isRegistrationError(error)
? error
: new DesktopLinuxUrlHandlerRegistrationError({
step: "set-default-handler",
scheme,
cause: error,
}),
),
);
const register = Effect.gen(function* () {
if (environment.platform !== "linux" || !environment.isPackaged) {
return;
}
yield* writeDesktopEntry;
yield* setDefaultHandler;
yield* logInfo("registered URL scheme handler", { scheme });
}).pipe(
// Registration is best-effort: a missing xdg-mime or read-only home must
// never block startup — the OS chooser remains as fallback.
Effect.catch((error) =>
logWarning("URL scheme handler registration failed", {
scheme,
step: error.step,
message: error.message,
...(error.desktopEntryPath === undefined
? {}
: { desktopEntryPath: error.desktopEntryPath }),
...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
}),
),
Effect.withSpan("desktop.linuxUrlHandler.register"),
);
return DesktopLinuxUrlHandler.of({ register });
});
export const layer = Layer.effect(DesktopLinuxUrlHandler, make);
@@ -0,0 +1,130 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import { beforeEach, vi } from "vite-plus/test";
const { appendSwitchMock, getSwitchValueMock, hasSwitchMock, registerSchemesMock } = vi.hoisted(
() => ({
appendSwitchMock: vi.fn(),
getSwitchValueMock: vi.fn(),
hasSwitchMock: vi.fn(),
registerSchemesMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
getSwitchValue: getSwitchValueMock,
hasSwitch: hasSwitchMock,
},
},
protocol: {
registerSchemesAsPrivileged: registerSchemesMock,
},
}));
import * as DesktopPreReadyPlatform from "./DesktopPreReadyPlatform.ts";
describe("DesktopPreReadyPlatform", () => {
beforeEach(() => {
appendSwitchMock.mockReset();
getSwitchValueMock.mockReset();
hasSwitchMock.mockReset();
registerSchemesMock.mockReset();
});
it("reads an explicit Electron command-line switch value", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: (switchName) => switchName === "password-store",
getSwitchValue: (switchName) => {
assert.equal(switchName, "password-store");
return "basic";
},
},
"password-store",
);
assert.equal(value, "basic");
});
it("treats valueless Electron command-line switches as absent", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => true,
getSwitchValue: () => "",
},
"password-store",
);
assert.isNull(value);
});
it("returns null for missing Electron command-line switches", () => {
const value = DesktopPreReadyPlatform.readCommandLineSwitchValue(
{
hasSwitch: () => false,
getSwitchValue: () => {
throw new Error("Unexpected switch value read.");
},
},
"password-store",
);
assert.isNull(value);
});
it.effect(
"acquires a synchronous pre-ready layer before an asynchronous Clerk-shaped layer",
() =>
Effect.gen(function* () {
class ClerkShaped extends Context.Service<ClerkShaped, { readonly ready: true }>()(
"@t3tools/desktop/app/DesktopPreReadyPlatform.test/ClerkShaped",
) {}
const events: Array<string> = [];
registerSchemesMock.mockImplementation(() => {
events.push("pre-ready");
});
const preReadyLayer = DesktopPreReadyPlatform.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "darwin")),
);
const clerkShapedLayer = Layer.effect(
ClerkShaped,
Effect.promise(() => Promise.resolve()).pipe(
Effect.map(() => {
events.push("clerk");
return { ready: true as const };
}),
),
);
const runtimeLayer = clerkShapedLayer.pipe(
Layer.flatMap((clerkContext) => Layer.succeedContext(clerkContext)),
Layer.provideMerge(preReadyLayer),
);
const result = yield* Effect.all({
clerk: ClerkShaped,
preReady: DesktopPreReadyPlatform.DesktopPreReadyElectronOptions,
}).pipe(Effect.provide(runtimeLayer));
assert.deepEqual(result, {
clerk: { ready: true },
preReady: {
linux: null,
linuxPasswordStoreCommandLine: null,
},
});
assert.deepEqual(events, ["pre-ready", "clerk"]);
assert.equal(registerSchemesMock.mock.calls.length, 1);
assert.equal(appendSwitchMock.mock.calls.length, 0);
}),
);
});
@@ -0,0 +1,74 @@
// @effect-diagnostics nodeBuiltinImport:off - pre-ready Electron setup reads persisted settings synchronously before app services are available.
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as DesktopEarlyElectronStartup from "./DesktopEarlyElectronStartup.ts";
import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
export interface DesktopPreReadyCommandLineReader {
readonly hasSwitch: (switchName: string) => boolean;
readonly getSwitchValue: (switchName: string) => string;
}
export function readCommandLineSwitchValue(
commandLine: DesktopPreReadyCommandLineReader,
switchName: string,
): string | null {
if (!commandLine.hasSwitch(switchName)) {
return null;
}
const value = commandLine.getSwitchValue(switchName).trim();
return value.length > 0 ? value : null;
}
export const resolveEarlyLinuxElectronOptionsFromProcess =
(): DesktopEarlyElectronStartup.EarlyLinuxElectronOptions =>
DesktopEarlyElectronStartup.resolveEarlyLinuxElectronOptions({
env: process.env,
homeDirectory: NodeOS.homedir(),
joinPath: NodePath.posix.join,
readFileString: (path) => NodeFS.readFileSync(path, "utf8"),
});
export class DesktopPreReadyElectronOptions extends Context.Service<
DesktopPreReadyElectronOptions,
{
readonly linux: DesktopEarlyElectronStartup.EarlyLinuxElectronOptions | null;
readonly linuxPasswordStoreCommandLine: string | null;
}
>()("@t3tools/desktop/app/DesktopPreReadyPlatform/DesktopPreReadyElectronOptions") {}
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return yield* Effect.sync((): DesktopPreReadyElectronOptions["Service"] => {
const linuxPasswordStoreCommandLine =
platform === "linux"
? readCommandLineSwitchValue(Electron.app.commandLine, "password-store")
: null;
const linux = platform === "linux" ? resolveEarlyLinuxElectronOptionsFromProcess() : null;
if (linux !== null) {
Electron.app.commandLine.appendSwitch("class", linux.linuxWmClass);
if (linux.passwordStore !== null && linuxPasswordStoreCommandLine === null) {
Electron.app.commandLine.appendSwitch("password-store", linux.passwordStore);
}
}
return { linux, linuxPasswordStoreCommandLine };
});
}).pipe(Effect.withSpan("desktop.electron.configureBeforeReady"));
// Keep Electron's strict pre-ready setup isolated so later runtime layers cannot
// observe app readiness before scheme privileges and command-line switches exist.
export const layer = Layer.mergeAll(
ElectronProtocol.layerSchemePrivileges,
Layer.effect(DesktopPreReadyElectronOptions, make),
);
+32
View File
@@ -0,0 +1,32 @@
import * as Option from "effect/Option";
export type JoinPath = (first: string, ...segments: string[]) => string;
function normalizeConfiguredBaseDir(t3Home: Option.Option<string>): Option.Option<string> {
if (Option.isNone(t3Home)) {
return Option.none();
}
const trimmed = t3Home.value.trim();
return trimmed.length > 0 ? Option.some(trimmed) : Option.none();
}
export function resolveDesktopBaseDir(input: {
readonly homeDirectory: string;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
return Option.getOrElse(normalizeConfiguredBaseDir(input.t3Home), () =>
input.joinPath(input.homeDirectory, ".t3"),
);
}
export function resolveDesktopStateDir(input: {
readonly baseDir: string;
readonly isDevelopment: boolean;
readonly joinPath: JoinPath;
readonly t3Home: Option.Option<string>;
}): string {
const useDevSubdir =
input.isDevelopment && Option.isNone(normalizeConfiguredBaseDir(input.t3Home));
return input.joinPath(input.baseDir, useDevSubdir ? "dev" : "userdata");
}
@@ -17,6 +17,7 @@ import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
const PersistedServerObservabilitySettingsDocument = Schema.Struct({
observability: Schema.Struct({
@@ -115,6 +116,7 @@ const withHarness = <A, E, R>(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
),
),
@@ -153,6 +155,47 @@ describe("DesktopBackendConfiguration", () => {
),
);
it.effect("resolvePrimary starts from server.asar without materializing the WSL tree", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const resourcesPath = `${baseDir}/resources`;
const config = yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
return yield* configuration.resolvePrimary;
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
Layer.succeed(
DesktopWslServerTree.DesktopWslServerTree,
DesktopWslServerTree.DesktopWslServerTree.of({
ensure: Effect.die("Windows primary must not extract the WSL server tree"),
}),
),
),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
appPath: `${resourcesPath}/app.asar`,
platform: "win32",
resourcesPath,
}),
),
),
),
);
assert.equal(config.entryPath, `${resourcesPath}/server.asar/apps/server/dist/bin.mjs`);
assert.equal(config.env.ELECTRON_RUN_AS_NODE, "1");
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl reuses the primary's bootstrap token", () =>
withHarness(
Effect.gen(function* () {
@@ -173,7 +216,7 @@ describe("DesktopBackendConfiguration", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
@@ -186,6 +229,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -234,7 +278,7 @@ describe("DesktopBackendConfiguration", () => {
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
const entryPath = path.join(baseDir, "app.asar.unpacked/apps/server/dist/bin.mjs");
const entryPath = path.join(baseDir, "apps/server/dist/bin.mjs");
yield* fileSystem.makeDirectory(path.dirname(entryPath), { recursive: true });
yield* fileSystem.writeFileString(entryPath, "");
@@ -250,6 +294,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -386,6 +431,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(makeEnvironmentLayer(baseDir)),
Layer.provideMerge(failingFileSystemLayer),
@@ -427,6 +473,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
@@ -486,6 +533,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -536,6 +584,7 @@ describe("DesktopBackendConfiguration", () => {
wslOnly: true,
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
@@ -573,6 +622,7 @@ describe("DesktopBackendConfiguration", () => {
wslDistro: "Removed-Distro",
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -606,6 +656,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -640,6 +691,49 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
distros: [{ name: "Ubuntu", isDefault: true, version: 2 }],
}),
),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
),
);
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("resolveWsl surfaces sidecar extraction failures through typed preflight", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-desktop-backend-config-test-",
});
yield* Effect.gen(function* () {
const configuration = yield* DesktopBackendConfiguration.DesktopBackendConfiguration;
const config = yield* configuration.resolveWsl({ port: 5050, distro: "Ubuntu" });
const failure = Option.getOrThrow(config.preflightFailure);
assert.isFalse(failure.fatal);
assert.equal(failure.retryLimit, 12);
assert.include(failure.reason, "could not be extracted");
}).pipe(
Effect.provide(
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(
DesktopWslServerTree.layerTest({
result: {
ok: false,
reason: "WSL server files could not be extracted",
fatal: false,
},
}),
),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -672,6 +766,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(
DesktopWslEnvironment.layerTest({
isAvailable: true,
@@ -708,6 +803,7 @@ describe("DesktopBackendConfiguration", () => {
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: true })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
@@ -748,6 +844,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
@@ -793,6 +890,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest()),
Layer.provideMerge(
makeEnvironmentLayer(baseDir, {
@@ -843,6 +941,7 @@ describe("DesktopBackendConfiguration", () => {
wslDistro: "Ubuntu",
}),
),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layerTest({ isAvailable: false })),
Layer.provideMerge(makeEnvironmentLayer(baseDir, { platform: "win32" })),
),
@@ -864,6 +963,7 @@ describe("DesktopBackendConfiguration", () => {
DesktopBackendConfiguration.layer.pipe(
Layer.provideMerge(serverExposureLayer),
Layer.provideMerge(DesktopAppSettings.layerTest()),
Layer.provideMerge(DesktopWslServerTree.layerTest()),
Layer.provideMerge(DesktopWslEnvironment.layer),
// isAvailable on win32 only touches the filesystem, never the spawner,
// so a die-stub is enough to satisfy the layer's deps.
@@ -19,6 +19,7 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopServerExposure from "./DesktopServerExposure.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopWslEnvironment from "../wsl/DesktopWslEnvironment.ts";
import * as DesktopWslServerTree from "../wsl/DesktopWslServerTree.ts";
export class DesktopBackendObservabilitySettingsReadError extends Schema.TaggedErrorClass<DesktopBackendObservabilitySettingsReadError>()(
"DesktopBackendObservabilitySettingsReadError",
@@ -424,10 +425,12 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
never,
| DesktopEnvironment.DesktopEnvironment
| DesktopWslEnvironment.DesktopWslEnvironment
| DesktopWslServerTree.DesktopWslServerTree
| FileSystem.FileSystem
> {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
// Bind to 0.0.0.0 inside WSL so the backend is reachable both via
// WSL2's automatic localhost forwarding (wslhost: Windows 127.0.0.1
@@ -464,31 +467,31 @@ const resolveWslStartConfig = Effect.fn("desktop.backendConfiguration.resolveWsl
...buildObservabilityFragment(input.observabilitySettings),
};
// In packaged builds environment.appRoot is .../resources/app.asar — an
// archive FILE. The Windows primary reads its entry through
// ELECTRON_RUN_AS_NODE (asar-aware), but the WSL backend launches plain
// `wsl.exe -- node`, which can't read inside an asar. electron-builder unpacks
// the server bundle + node-pty (see asarUnpack in build-desktop-artifact.ts)
// to the app.asar.unpacked sibling, so point WSL there. In dev appRoot is
// already a real directory, so this is a no-op.
const wslAppRoot = environment.isPackaged
? environment.path.join(environment.resourcesPath, "app.asar.unpacked")
: environment.appRoot;
// In packaged builds the server tree ships inside resources/server.asar —
// an archive FILE the Windows primary reads through ELECTRON_RUN_AS_NODE
// (asar-aware). The WSL backend launches plain `wsl.exe -- node`, which
// can't read an asar, so materialize (or reuse) the extracted copy of the
// sidecar before preflighting. In dev the server tree is the real checkout
// directory and ensure returns it unchanged.
const serverTree = yield* wslServerTree.ensure;
const wslAppRoot = serverTree.ok ? serverTree.root : environment.serverRoot;
const wslEntryPath = environment.path.join(wslAppRoot, "apps/server/dist/bin.mjs");
const preflight = yield* runWslPreflight({
distro: input.distro,
windowsEntryPath: wslEntryPath,
windowsRepoRoot: wslAppRoot,
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
// WSL backend never needs a compiler, node-gyp, or network on first launch.
// Compiling from source is a dev-only convenience: a checkout has no shipped
// prebuilt, and developers have the toolchain. In packaged builds we instead
// surface a clear diagnostic if the prebuilt can't load (unsupported
// arch/distro), rather than silently dropping into a fragile runtime build.
allowBuild: !environment.isPackaged,
});
const preflight = serverTree.ok
? yield* runWslPreflight({
distro: input.distro,
windowsEntryPath: wslEntryPath,
windowsRepoRoot: wslAppRoot,
// Packaged builds ship a prebuilt Linux node-pty (built on Linux in CI and
// attached to the Windows artifact — see build-desktop-artifact.ts), so the
// WSL backend never needs a compiler, node-gyp, or network on first launch.
// Compiling from source is a dev-only convenience: a checkout has no shipped
// prebuilt, and developers have the toolchain. In packaged builds we instead
// surface a clear diagnostic if the prebuilt can't load (unsupported
// arch/distro), rather than silently dropping into a fragile runtime build.
allowBuild: !environment.isPackaged,
})
: ({ _tag: "Failed", reason: serverTree.reason, fatal: serverTree.fatal } as const);
// Every operation after preflight uses the same concrete distro. In
// default-tracking mode this closes the race where the system default
@@ -610,6 +613,7 @@ export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const serverExposure = yield* DesktopServerExposure.DesktopServerExposure;
const wslEnvironment = yield* DesktopWslEnvironment.DesktopWslEnvironment;
const wslServerTree = yield* DesktopWslServerTree.DesktopWslServerTree;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
const crypto = yield* Crypto.Crypto;
// SynchronizedRef (not a plain Ref) so the read-generate-write is atomic.
@@ -665,6 +669,7 @@ export const make = Effect.gen(function* () {
}).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
});
@@ -727,6 +732,7 @@ export const make = Effect.gen(function* () {
return yield* resolveWslStartConfig({ ...shared, ...input }).pipe(
Effect.provideService(DesktopEnvironment.DesktopEnvironment, environment),
Effect.provideService(DesktopWslEnvironment.DesktopWslEnvironment, wslEnvironment),
Effect.provideService(DesktopWslServerTree.DesktopWslServerTree, wslServerTree),
Effect.provideService(FileSystem.FileSystem, fileSystem),
);
}).pipe(
@@ -701,6 +701,84 @@ describe("DesktopBackendManager", () => {
),
);
it.effect(
"re-probes readiness after the first budget expires while the backend is still alive",
() =>
Effect.scoped(
Effect.gen(function* () {
const requestUrls: Array<string> = [];
let requestCount = 0;
let readyCount = 0;
let readinessTimeoutCount = 0;
const firstProbe = yield* Deferred.make<void>();
const childExit = yield* Deferred.make<void>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Deferred.await(childExit).pipe(
Effect.as(ChildProcessSpawner.ExitCode(0)),
),
}),
),
),
);
// The backend stays 503 through the first *two* readiness budgets
// and only becomes healthy (200) for the third round, i.e. it comes
// up well after the initial 50ms budget has expired.
const httpLayer = httpClientLayer((request) =>
Effect.gen(function* () {
requestCount += 1;
requestUrls.push(request.url);
yield* Deferred.succeed(firstProbe, void 0);
return responseForRequest(request, requestCount <= 2 ? 503 : 200);
}),
);
const runFiber = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
desktopTelemetryStream: Stream.empty,
readinessTimeout: Duration.millis(50),
onReady: () =>
Effect.sync(() => {
readyCount += 1;
}),
onReadinessFailure: () =>
Effect.sync(() => {
readinessTimeoutCount += 1;
}),
}).pipe(Effect.provide(Layer.merge(spawnerLayer, httpLayer)), Effect.forkChild);
yield* Deferred.await(firstProbe);
assert.equal(readyCount, 0);
assert.equal(readinessTimeoutCount, 0);
// The first 50ms readiness budget expires while the backend still
// answers 503. The child is alive and may yet become healthy, so the
// probe must start a fresh round instead of stopping permanently —
// the pre-fix behavior left the app stuck on "Connecting to WSL…"
// forever even though the backend kept running.
yield* TestClock.adjust(Duration.millis(50));
assert.equal(readinessTimeoutCount, 1);
assert.equal(readyCount, 0);
// The second budget also expires (backend still 503), then the third
// round connects. The point is the probe persisted across budgets
// while the process was alive instead of giving up after the first.
yield* TestClock.adjust(Duration.millis(100));
assert.equal(readinessTimeoutCount, 2);
assert.equal(readyCount, 1);
assert.equal(requestUrls.length, 3);
yield* Deferred.succeed(childExit, void 0);
assert.equal((yield* Fiber.join(runFiber)).code.pipe(Option.getOrUndefined), 0);
}).pipe(Effect.provide(TestClock.layer())),
),
);
it.effect("starts the configured backend and closes the scoped process on stop", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -563,20 +563,33 @@ export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
).pipe(Effect.forkScoped),
);
}
yield* waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
Effect.tap(() => options.onReady?.() ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.forkScoped,
// Probe readiness in a loop while the backend process is still alive
// instead of giving up after the first budget. A slow cold boot (the
// WSL bundle loading across /mnt/c, or a first launch right after an
// update) can exceed the initial readiness budget while the backend is
// about to come up moments later; a one-shot probe left the app stuck
// on "Connecting to WSL…" forever even though the backend kept running
// and became healthy. Each round gets a fresh budget, and the forked
// loop is torn down with the run scope once the child exits.
const probeReadiness = Effect.fn("desktop.backendProcess.probeReadiness")(() =>
waitForHttpReady({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
timeout: options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
}).pipe(
Effect.flatMap(() => options.onReady?.() ?? Effect.void),
Effect.as(true),
Effect.catchTags({
BackendReadinessTimeoutError: (error) =>
(options.onReadinessFailure?.(error) ?? Effect.void).pipe(Effect.as(false)),
}),
),
);
yield* probeReadiness().pipe(Effect.repeat({ while: (ready) => !ready }), Effect.forkScoped);
const exit = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
@@ -91,6 +91,7 @@ function makePoolLayer(
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
zoomMain: () => Effect.die("unexpected zoom"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
+33 -3
View File
@@ -8,13 +8,14 @@ const {
autoUpdaterRemoveListenerMock,
exitMock,
getAppPathMock,
getSystemLocaleMock,
getVersionMock,
isDefaultProtocolClientMock,
onMock,
quitMock,
relaunchMock,
removeListenerMock,
requestSingleInstanceLockMock,
removeSwitchMock,
setAboutPanelOptionsMock,
setAppUserModelIdMock,
setAsDefaultProtocolClientMock,
@@ -29,13 +30,14 @@ const {
autoUpdaterRemoveListenerMock: vi.fn(),
exitMock: vi.fn(),
getAppPathMock: vi.fn(() => "/app"),
getSystemLocaleMock: vi.fn(() => "en-GB"),
getVersionMock: vi.fn(() => "1.2.3"),
isDefaultProtocolClientMock: vi.fn(() => false),
onMock: vi.fn(),
quitMock: vi.fn(),
relaunchMock: vi.fn(),
removeListenerMock: vi.fn(),
requestSingleInstanceLockMock: vi.fn(() => true),
removeSwitchMock: vi.fn(),
setAboutPanelOptionsMock: vi.fn(),
setAppUserModelIdMock: vi.fn(),
setAsDefaultProtocolClientMock: vi.fn(() => true),
@@ -54,11 +56,13 @@ vi.mock("electron", () => ({
app: {
commandLine: {
appendSwitch: appendSwitchMock,
removeSwitch: removeSwitchMock,
},
dock: {
setIcon: setDockIconMock,
},
getAppPath: getAppPathMock,
getSystemLocale: getSystemLocaleMock,
getVersion: getVersionMock,
isDefaultProtocolClient: isDefaultProtocolClientMock,
isPackaged: true,
@@ -67,7 +71,6 @@ vi.mock("electron", () => ({
quit: quitMock,
relaunch: relaunchMock,
removeListener: removeListenerMock,
requestSingleInstanceLock: requestSingleInstanceLockMock,
runningUnderARM64Translation: false,
setAboutPanelOptions: setAboutPanelOptionsMock,
setAsDefaultProtocolClient: setAsDefaultProtocolClientMock,
@@ -92,6 +95,7 @@ describe("ElectronApp", () => {
quitMock.mockClear();
relaunchMock.mockClear();
removeListenerMock.mockClear();
removeSwitchMock.mockClear();
setPathMock.mockClear();
});
@@ -110,6 +114,23 @@ describe("ElectronApp", () => {
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("reads the OS locale through the service", () =>
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
assert.strictEqual(yield* electronApp.systemLocale, "en-GB");
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("normalizes POSIX-style locale identifiers that Intl rejects", () =>
Effect.gen(function* () {
getSystemLocaleMock.mockImplementationOnce(() => "en_GB");
const electronApp = yield* ElectronApp.ElectronApp;
assert.strictEqual(yield* electronApp.systemLocale, "en-GB");
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("reports which app metadata property failed", () =>
Effect.gen(function* () {
const cause = new Error("version unavailable");
@@ -181,4 +202,13 @@ describe("ElectronApp", () => {
]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
it.effect("removes command-line switches through the service", () =>
Effect.gen(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
yield* electronApp.removeCommandLineSwitch("password-store");
assert.deepEqual(removeSwitchMock.mock.calls, [["password-store"]]);
}).pipe(Effect.provide(ElectronApp.layer)),
);
});
+16 -2
View File
@@ -43,6 +43,13 @@ export class ElectronApp extends Context.Service<
{
readonly metadata: Effect.Effect<ElectronAppMetadata, ElectronAppMetadataReadError>;
readonly name: Effect.Effect<string>;
/**
* The OS locale, read from the operating system rather than from Chromium's
* resolved application locale — the packaged app ships only the `en-US`
* locale pak, so `app.getLocale()` and the renderer's `Intl` default are
* pinned to `en-US` however the machine is configured.
*/
readonly systemLocale: Effect.Effect<string>;
readonly whenReady: Effect.Effect<void, ElectronAppWhenReadyError>;
readonly quit: Effect.Effect<void>;
readonly exit: (code: number) => Effect.Effect<void>;
@@ -56,7 +63,6 @@ export class ElectronApp extends Context.Service<
options: Electron.AboutPanelOptionsOptions,
) => Effect.Effect<void>;
readonly setAppUserModelId: (id: string) => Effect.Effect<void>;
readonly requestSingleInstanceLock: Effect.Effect<boolean>;
readonly getAppMetrics: Effect.Effect<ReadonlyArray<Electron.ProcessMetric>>;
readonly isDefaultProtocolClient: (protocol: string) => Effect.Effect<boolean>;
readonly setAsDefaultProtocolClient: (
@@ -70,6 +76,7 @@ export class ElectronApp extends Context.Service<
readonly onBeforeQuitForUpdate: (
listener: () => void,
) => Effect.Effect<void, never, Scope.Scope>;
readonly removeCommandLineSwitch: (switchName: string) => Effect.Effect<void>;
readonly on: <Args extends ReadonlyArray<unknown>>(
eventName: string,
listener: (...args: Args) => void,
@@ -119,6 +126,10 @@ export const make = ElectronApp.of({
};
}),
name: Effect.sync(() => Electron.app.name),
// macOS derives this from NSLocale, which uses POSIX-style identifiers
// (`en_GB`). `Intl` rejects those outright rather than normalizing them, so
// the tag is normalized here rather than in the renderer that consumes it.
systemLocale: Effect.sync(() => Electron.app.getSystemLocale().replace(/_/g, "-")),
whenReady: Effect.gen(function* () {
const isPackaged = Electron.app.isPackaged;
yield* Effect.tryPromise({
@@ -153,7 +164,6 @@ export const make = ElectronApp.of({
Effect.sync(() => {
Electron.app.setAppUserModelId(id);
}),
requestSingleInstanceLock: Effect.sync(() => Electron.app.requestSingleInstanceLock()),
getAppMetrics: Effect.sync(() => Electron.app.getAppMetrics()),
isDefaultProtocolClient: (protocol) =>
Effect.sync(() => Electron.app.isDefaultProtocolClient(protocol)),
@@ -193,6 +203,10 @@ export const make = ElectronApp.of({
Electron.autoUpdater.removeListener("before-quit-for-update", listener);
}),
).pipe(Effect.asVoid),
removeCommandLineSwitch: (switchName) =>
Effect.sync(() => {
Electron.app.commandLine.removeSwitch(switchName);
}),
on: addScopedAppListener,
});
@@ -28,70 +28,6 @@ describe("ElectronDialog", () => {
showErrorBoxMock.mockReset();
});
it.effect("returns false without opening a confirm dialog for empty messages", () =>
Effect.gen(function* () {
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: " ",
owner: Option.none(),
});
assert.isFalse(result);
assert.equal(showMessageBoxMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens a confirm dialog for the owner window", () =>
Effect.gen(function* () {
const owner = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.some(owner),
});
assert.isTrue(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
owner,
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
Effect.gen(function* () {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.none(),
});
assert.isFalse(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves folder picker request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("folder picker failed");
@@ -117,31 +53,6 @@ describe("ElectronDialog", () => {
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves confirmation request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("confirmation failed");
const owner = { id: 9 } as BrowserWindow;
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.confirm({
owner: Option.some(owner),
message: " Confirm removal? ",
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
assert.strictEqual(error.ownerWindowId, 9);
assert.strictEqual(error.promptLength, "Confirm removal?".length);
assert.notProperty(error, "promptMessage");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 9");
assert.notInclude(error.message, "Confirm removal?");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
+24 -31
View File
@@ -6,8 +6,6 @@ import * as Schema from "effect/Schema";
import * as Electron from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
"ElectronDialogPickFolderError",
{
@@ -23,17 +21,18 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
}
}
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
"ElectronDialogPickFilesError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
promptLength: Schema.Number,
defaultPath: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
return `Failed to open the Electron file picker for ${owner} with ${defaultPath}.`;
}
}
@@ -69,7 +68,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogConfirmError,
ElectronDialogPickFilesError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
]);
@@ -81,9 +80,10 @@ export interface ElectronDialogPickFolderInput {
readonly defaultPath: Option.Option<string>;
}
export interface ElectronDialogConfirmInput {
export interface ElectronDialogPickFilesInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly message: string;
readonly defaultPath: Option.Option<string>;
readonly filters: readonly Electron.FileFilter[];
}
export class ElectronDialog extends Context.Service<
@@ -92,9 +92,9 @@ export class ElectronDialog extends Context.Service<
readonly pickFolder: (
input: ElectronDialogPickFolderInput,
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
readonly pickFiles: (
input: ElectronDialogPickFilesInput,
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
@@ -137,38 +137,31 @@ export const make = ElectronDialog.of({
}
return Option.fromNullishOr(result.filePaths[0]);
}),
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
const normalizedMessage = input.message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const defaultPath = Option.getOrNull(input.defaultPath);
const openDialogOptions: Electron.OpenDialogOptions = {
properties: ["openFile", "multiSelections"],
filters: [...input.filters],
...(defaultPath === null ? {} : { defaultPath }),
};
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showMessageBox(options),
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
}),
catch: (cause) =>
new ElectronDialogConfirmError({
new ElectronDialogPickFilesError({
ownerWindowId,
promptLength: normalizedMessage.length,
defaultPath,
cause,
}),
});
return result.response === CONFIRM_BUTTON_INDEX;
return result.canceled ? [] : result.filePaths;
}),
showMessageBox: (options) =>
Effect.tryPromise({
@@ -57,7 +57,7 @@ describe("ElectronProtocol", () => {
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
response.headers.get("content-security-policy") ?? "",
"script-src 'self' 'unsafe-inline' https://clerk.t3.codes https://challenges.cloudflare.com",
"script-src 'self' 'unsafe-inline' 'wasm-unsafe-eval' https://clerk.t3.codes https://challenges.cloudflare.com",
);
assert.include(
response.headers.get("content-security-policy") ?? "",
@@ -212,6 +212,7 @@ describe("ElectronProtocol", () => {
assert.deepEqual(directives["script-src"], [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
"https://clerk.t3.codes",
"https://challenges.cloudflare.com",
]);
@@ -71,6 +71,7 @@ export function makeDesktopContentSecurityPolicy(input: DesktopProtocolRegistrat
const scriptSources = [
"'self'",
"'unsafe-inline'",
"'wasm-unsafe-eval'",
...(clerkOrigin ? [clerkOrigin] : []),
"https://challenges.cloudflare.com",
];
@@ -104,6 +105,38 @@ function withContentSecurityPolicy(response: Response, policy: string): Response
});
}
/**
* Must run synchronously during process bootstrap, before Electron emits `ready`.
*/
export function registerDesktopSchemePrivilegesSync(): void {
Electron.protocol.registerSchemesAsPrivileged([
{
scheme: DESKTOP_PRODUCTION_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
{
scheme: DESKTOP_DEVELOPMENT_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: true,
},
},
]);
}
const registerDesktopSchemePrivileges = Effect.sync(registerDesktopSchemePrivilegesSync).pipe(
Effect.withSpan("desktop.electron.protocol.registerSchemePrivileges"),
);
export const layerSchemePrivileges = Layer.effectDiscard(registerDesktopSchemePrivileges);
async function proxyRequest(
request: Request,
targetOrigin: URL,
@@ -1,9 +1,11 @@
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 Schema from "effect/Schema";
import * as Electron from "electron";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
const electronSafeStorageErrorFields = {
cause: Schema.Defect(),
@@ -60,24 +62,39 @@ export class ElectronSafeStorage extends Context.Service<
readonly decryptString: (
value: Uint8Array,
) => Effect.Effect<string, ElectronSafeStorageDecryptError>;
readonly selectedStorageBackend: Effect.Effect<Option.Option<string>>;
}
>()("@t3tools/desktop/electron/ElectronSafeStorage") {}
export const make = ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
return ElectronSafeStorage.of({
isEncryptionAvailable: Effect.try({
try: () => Electron.safeStorage.isEncryptionAvailable(),
catch: (cause) => new ElectronSafeStorageAvailabilityError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
encryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.encryptString(value),
catch: (cause) => new ElectronSafeStorageEncryptError({ cause }),
}),
decryptString: (value) =>
Effect.try({
try: () => Electron.safeStorage.decryptString(Buffer.from(value)),
catch: (cause) => new ElectronSafeStorageDecryptError({ cause }),
}),
selectedStorageBackend: Effect.sync(() => {
if (platform !== "linux") {
return Option.none();
}
try {
return Option.fromNullishOr(Electron.safeStorage.getSelectedStorageBackend());
} catch {
return Option.none();
}
}),
});
});
export const layer = Layer.succeed(ElectronSafeStorage, make);
export const layer = Layer.effect(ElectronSafeStorage, make);
+11 -1
View File
@@ -1,3 +1,4 @@
import { REMOTE_CAPABLE_EDITOR_IDS, remoteSchemeForEditor } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -5,7 +6,16 @@ import * as Option from "effect/Option";
import * as Electron from "electron";
const SAFE_EXTERNAL_PROTOCOLS = new Set(["http:", "https:"]);
// Remote open-in-editor deep links (`vscode://vscode-remote/ssh-remote+…`)
// must reach the OS handler; every other non-web scheme stays blocked.
const SAFE_EXTERNAL_PROTOCOLS = new Set([
"http:",
"https:",
...REMOTE_CAPABLE_EDITOR_IDS.flatMap((id) => {
const scheme = remoteSchemeForEditor(id);
return scheme === undefined ? [] : [`${scheme}:`];
}),
]);
export function parseSafeExternalUrl(rawUrl: unknown): Option.Option<string> {
if (typeof rawUrl !== "string") {
+6 -2
View File
@@ -31,13 +31,15 @@ import {
setUpdateChannel,
} from "./methods/updates.ts";
import {
confirm,
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getSystemLocale,
getWindowFullscreenState,
openExternal,
probeRemoteEditors,
pickFolder,
pickThemeFiles,
setTheme,
showContextMenu,
} from "./methods/window.ts";
@@ -49,6 +51,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* PreviewIpc.installPreviewEventForwarding();
yield* ipc.handleSync(getAppBranding);
yield* ipc.handleSync(getSystemLocale);
yield* ipc.handleSync(getWindowFullscreenState);
yield* ipc.handleSync(getLocalEnvironmentBootstraps);
yield* ipc.handle(getLocalEnvironmentBearerToken);
@@ -79,10 +82,11 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(setWslOnly);
yield* ipc.handle(pickFolder);
yield* ipc.handle(confirm);
yield* ipc.handle(pickThemeFiles);
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
yield* ipc.handle(probeRemoteEditors);
yield* ipc.handle(getUpdateState);
yield* ipc.handle(setUpdateChannel);
yield* ipc.handle(downloadUpdate);
+4 -1
View File
@@ -1,9 +1,11 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
export const CONFIRM_CHANNEL = "desktop:confirm";
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
export const PROBE_REMOTE_EDITORS_CHANNEL = "desktop:probe-remote-editors";
export const MENU_ACTION_CHANNEL = "desktop:menu-action";
export const QUIT_SHORTCUT_CHANNEL = "desktop:quit-shortcut";
export const GET_WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:get-window-fullscreen-state";
export const WINDOW_FULLSCREEN_STATE_CHANNEL = "desktop:window-fullscreen-state";
export const UPDATE_STATE_CHANNEL = "desktop:update-state";
@@ -13,6 +15,7 @@ export const UPDATE_DOWNLOAD_CHANNEL = "desktop:update-download";
export const UPDATE_INSTALL_CHANNEL = "desktop:update-install";
export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale";
export const GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL = "desktop:get-local-environment-bootstraps";
export const GET_LOCAL_ENVIRONMENT_BEARER_TOKEN_CHANNEL =
"desktop:get-local-environment-bearer-token";
+10 -5
View File
@@ -14,9 +14,10 @@ import {
DesktopPreviewRegisterWebviewInputSchema,
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewCreateTabInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationPayloadSchema,
PreviewAnnotationSubmissionResultSchema,
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
@@ -48,11 +49,15 @@ export const installPreviewEventForwarding = Effect.fn(
export const createTab = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_CREATE_TAB_CHANNEL,
payload: DesktopPreviewTabInputSchema,
payload: DesktopPreviewCreateTabInputSchema,
result: Schema.Void,
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({ tabId }) {
handler: Effect.fn("desktop.ipc.preview.createTab")(function* ({
tabId,
zoomFactor,
colorScheme,
}) {
const manager = yield* PreviewManager.PreviewManager;
yield* manager.createTab(tabId);
yield* manager.createTab(tabId, { zoomFactor, colorScheme });
}),
});
@@ -227,7 +232,7 @@ export const setAnnotationTheme = DesktopIpc.makeIpcMethod({
export const pickElement = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PREVIEW_PICK_ELEMENT_CHANNEL,
payload: DesktopPreviewTabInputSchema,
result: Schema.NullOr(PreviewAnnotationPayloadSchema),
result: Schema.NullOr(PreviewAnnotationSubmissionResultSchema),
handler: Effect.fn("desktop.ipc.preview.pickElement")(function* ({ tabId }) {
const manager = yield* PreviewManager.PreviewManager;
return yield* manager.pickElement(tabId);
+89 -13
View File
@@ -3,10 +3,19 @@ import {
DesktopAppBrandingSchema,
DesktopEnvironmentBootstrapSchema,
DesktopThemeSchema,
EDITORS,
EditorId,
PickedThemeFileSchema,
PickFolderOptionsSchema,
PRIMARY_LOCAL_ENVIRONMENT_ID,
REMOTE_CAPABLE_EDITOR_IDS,
type DesktopEnvironmentBootstrap,
type PickedThemeFile,
} from "@t3tools/contracts";
import { isCommandAvailable } from "@t3tools/shared/shell";
import * as NodeOS from "node:os";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -17,6 +26,7 @@ import * as DesktopEnvironment from "../../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
import * as ElectronApp from "../../electron/ElectronApp.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronMenu from "../../electron/ElectronMenu.ts";
import * as ElectronShell from "../../electron/ElectronShell.ts";
@@ -55,6 +65,15 @@ export const getAppBranding = DesktopIpc.makeSyncIpcMethod({
}),
});
export const getSystemLocale = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_SYSTEM_LOCALE_CHANNEL,
result: Schema.String,
handler: Effect.fn("desktop.ipc.window.getSystemLocale")(function* () {
const electronApp = yield* ElectronApp.ElectronApp;
return yield* electronApp.systemLocale;
}),
});
export const getWindowFullscreenState = DesktopIpc.makeSyncIpcMethod({
channel: IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL,
result: Schema.Boolean,
@@ -215,19 +234,6 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
}),
});
export const confirm = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CONFIRM_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
return yield* electronWindow.focusedMainOrFirst.pipe(
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
);
}),
});
export const setTheme = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema,
@@ -268,3 +274,73 @@ export const openExternal = DesktopIpc.makeIpcMethod({
return yield* shell.openExternal(url);
}),
});
export const probeRemoteEditors = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL,
payload: Schema.Undefined,
result: Schema.Array(EditorId),
// Probes THIS machine (where the renderer runs) for remote-capable editor
// CLIs, unlike the server's probe which walks the environment host's PATH.
// A Finder-launched app can miss PATH entries; an empty result makes the
// renderer fall back to VS Code only, so that fails soft.
handler: Effect.fn("desktop.ipc.window.probeRemoteEditors")(function* () {
const available: Array<EditorId> = [];
for (const editorId of REMOTE_CAPABLE_EDITOR_IDS) {
const commands = EDITORS.find((editor) => editor.id === editorId)?.commands;
if (!commands) continue;
for (const command of commands) {
if (yield* isCommandAvailable(command, { env: process.env })) {
available.push(editorId);
break;
}
}
}
return available;
}),
});
/** Theme files are a few KB; anything larger returns empty text and lets the
* renderer reject it by size without the contents ever crossing the bridge. */
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
export const pickThemeFiles = DesktopIpc.makeIpcMethod({
channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
payload: Schema.Undefined,
result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
// The VS Code extensions directory is the same dotfolder on Windows,
// macOS, and Linux; when it is missing the picker opens wherever the
// platform would by default.
const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
const defaultPath = yield* fileSystem
.exists(extensionsDir)
.pipe(Effect.orElseSucceed(() => false));
const paths = yield* dialog.pickFiles({
owner: yield* electronWindow.focusedMainOrFirst,
defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
filters: [{ name: "JSON", extensions: ["json"] }],
});
if (paths.length === 0) {
return null;
}
return yield* Effect.forEach(paths, (filePath) => {
const name = path.basename(filePath);
return Effect.gen(function* () {
const info = yield* fileSystem.stat(filePath);
const size = Number(info.size);
if (size > PICKED_THEME_FILE_MAX_BYTES) {
return { name, size, text: "" } satisfies PickedThemeFile;
}
const text = yield* fileSystem.readFileString(filePath);
return { name, size, text } satisfies PickedThemeFile;
}).pipe(
// An unreadable file degrades to an entry the renderer reports.
Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
);
});
}),
});
+12
View File
@@ -10,8 +10,11 @@ import * as DesktopLifecycle from "../../app/DesktopLifecycle.ts";
import * as DesktopShutdown from "../../app/DesktopShutdown.ts";
import * as DesktopState from "../../app/DesktopState.ts";
import * as ElectronApp from "../../electron/ElectronApp.ts";
import * as ElectronDialog from "../../electron/ElectronDialog.ts";
import * as ElectronTheme from "../../electron/ElectronTheme.ts";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as DesktopAppSettings from "../../settings/DesktopAppSettings.ts";
import * as DesktopClientSettings from "../../settings/DesktopClientSettings.ts";
import * as DesktopWindow from "../../window/DesktopWindow.ts";
import * as DesktopWslBackend from "../../wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "../../wsl/DesktopWslEnvironment.ts";
@@ -70,6 +73,15 @@ const unusedLifecycleRuntimeLayer = Layer.mergeAll(
ElectronTheme.ElectronTheme,
ElectronTheme.ElectronTheme.of({} as ElectronTheme.ElectronTheme["Service"]),
),
Layer.succeed(
ElectronDialog.ElectronDialog,
ElectronDialog.ElectronDialog.of({} as ElectronDialog.ElectronDialog["Service"]),
),
Layer.succeed(
ElectronWindow.ElectronWindow,
ElectronWindow.ElectronWindow.of({} as ElectronWindow.ElectronWindow["Service"]),
),
DesktopClientSettings.layerTest(),
);
describe("WSL IPC", () => {
+203
View File
@@ -0,0 +1,203 @@
import { describe, expect, it } from "vite-plus/test";
import {
normalizeLinuxPasswordStorePreference,
resolveLinuxPasswordStoreSwitch,
resolveLinuxSecretStorageUnavailableMessage,
} from "./linuxSecretStorage.ts";
const autoSwitch = (env: NodeJS.ProcessEnv) =>
resolveLinuxPasswordStoreSwitch({ preference: "auto", env });
describe("linuxSecretStorage", () => {
it("preserves explicit supported password-store preferences", () => {
expect(normalizeLinuxPasswordStorePreference("gnome-libsecret")).toBe("gnome-libsecret");
expect(normalizeLinuxPasswordStorePreference("kwallet")).toBe("kwallet");
expect(normalizeLinuxPasswordStorePreference("kwallet5")).toBe("kwallet5");
expect(normalizeLinuxPasswordStorePreference("kwallet6")).toBe("kwallet6");
});
it("falls back to auto for missing or unsupported preferences", () => {
expect(normalizeLinuxPasswordStorePreference(undefined)).toBe("auto");
expect(normalizeLinuxPasswordStorePreference("basic")).toBe("auto");
});
it("uses explicit preferences instead of the auto heuristic", () => {
for (const preference of ["gnome-libsecret", "kwallet", "kwallet5", "kwallet6"] as const) {
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "niri" } }),
).toBe(preference);
// An explicit preference also wins where auto would have stayed out of the way.
expect(
resolveLinuxPasswordStoreSwitch({ preference, env: { XDG_CURRENT_DESKTOP: "KDE" } }),
).toBe(preference);
}
});
it("leaves canonical KDE sessions to Electron's own wallet selection", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "6" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE", KDE_SESSION_VERSION: "5" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "KDE:plasma" })).toBeNull();
});
it("does not force a password-store for desktops Electron already recognizes", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "GNOME" })).toBeNull();
for (const desktop of ["Deepin", "Pantheon", "UKUI", "Unity", "X-Cinnamon", "XFCE"]) {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: desktop })).toBeNull();
}
});
it("recognizes a known desktop later in a colon-separated XDG_CURRENT_DESKTOP list", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:GNOME" })).toBeNull();
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "ubuntu:GNOME" })).toBeNull();
});
it("forces gnome-libsecret for unrecognized Linux desktop sessions", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "Hyprland" })).toBe("gnome-libsecret");
expect(autoSwitch({})).toBe("gnome-libsecret");
});
it("forces gnome-libsecret for desktops Electron recognizes but leaves on basic text", () => {
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt" })).toBe("gnome-libsecret");
// Chromium stops at the first recognized value, so a later name cannot rescue the session.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:GNOME" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:KDE" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "LXQt:plasma" })).toBe("gnome-libsecret");
});
it("does not treat lowercase desktop names as ones Electron recognizes", () => {
// Chromium matches these case-sensitively, so lowercase spellings reach basic text.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "gnome" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "xfce" })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("overrides KDE sessions identified only by legacy variables", () => {
// Chromium reaches KWallet4 for some of these, such as DESKTOP_SESSION=kde with a version, and
// basic text for the rest. Either way these are the variables a previous session leaves behind,
// so they are treated as unproven and forced to a real keyring rather than a guessed wallet.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "plasma" })).toBe("gnome-libsecret");
for (const session of [
"kde",
"kde-plasma",
"kde4",
"plasma",
"plasmawayland",
"plasmawayland-dev",
"plasmax11",
"plasmax11-dev",
]) {
expect(autoSwitch({ DESKTOP_SESSION: session })).toBe("gnome-libsecret");
expect(autoSwitch({ XDG_SESSION_DESKTOP: session })).toBe("gnome-libsecret");
expect(autoSwitch({ GDMSESSION: session })).toBe("gnome-libsecret");
}
expect(autoSwitch({ DESKTOP_SESSION: "kde", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ KDE_SESSION_VERSION: "6" })).toBe("gnome-libsecret");
expect(autoSwitch({ KDE_FULL_SESSION: "true", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
});
it("ignores stale session hints when XDG_CURRENT_DESKTOP is authoritative", () => {
expect(
autoSwitch({ XDG_CURRENT_DESKTOP: "niri", DESKTOP_SESSION: "gnome", GDMSESSION: "gnome" }),
).toBe("gnome-libsecret");
// A previous KDE session left these behind; the compositor running now is not KDE.
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", KDE_SESSION_VERSION: "6" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri", XDG_SESSION_DESKTOP: "GNOME" })).toBe(
"gnome-libsecret",
);
expect(autoSwitch({ XDG_CURRENT_DESKTOP: "niri:plasma" })).toBe("gnome-libsecret");
expect(
autoSwitch({
XDG_CURRENT_DESKTOP: "Hyprland",
XDG_SESSION_DESKTOP: "KDE",
KDE_SESSION_VERSION: "6",
}),
).toBe("gnome-libsecret");
});
it("uses GNOME Keyring remediation for libsecret and unknown backends", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit libsecret selection over KDE desktop heuristics", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "gnome-libsecret",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("GNOME Keyring");
});
it("prefers explicit KWallet preference over selected gnome-libsecret backend", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet6",
selectedBackend: "gnome_libsecret",
env: { XDG_CURRENT_DESKTOP: "niri" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "kwallet",
selectedBackend: "gnome-libsecret",
env: {},
}),
).toContain("KWallet");
});
it("uses KWallet remediation wording for KDE-looking sessions", () => {
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "kwallet6",
env: {},
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { XDG_CURRENT_DESKTOP: "KDE" },
}),
).toContain("KWallet");
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { DESKTOP_SESSION: "plasmawayland" },
}),
).toContain("KWallet");
// A desktop name outranks a bare KDE marker when choosing the wording.
expect(
resolveLinuxSecretStorageUnavailableMessage({
configuredPreference: "auto",
selectedBackend: "unknown",
env: { GDMSESSION: "gnome", KDE_FULL_SESSION: "true" },
}),
).toContain("GNOME Keyring");
});
});
+178
View File
@@ -0,0 +1,178 @@
export type LinuxPasswordStorePreference =
| "auto"
| "gnome-libsecret"
| "kwallet"
| "kwallet5"
| "kwallet6";
export type LinuxPasswordStoreSwitch = Exclude<LinuxPasswordStorePreference, "auto">;
export const DEFAULT_LINUX_PASSWORD_STORE: LinuxPasswordStorePreference = "auto";
// Chromium matches XDG_CURRENT_DESKTOP values case-sensitively and returns on the first value it
// recognizes, so these stay exact literals and are scanned in order. Omitting a real desktop fails
// safe: we force gnome-libsecret, which is the backend Chromium selects for all of these anyway.
const ELECTRON_LIBSECRET_DESKTOPS = new Set([
"Deepin",
"GNOME",
"Pantheon",
"UKUI",
"Unity",
"X-Cinnamon",
"XFCE",
]);
// Chromium selects a KWallet generation for KDE from KDE_SESSION_VERSION, so it needs no help.
const ELECTRON_KDE_DESKTOP = "KDE";
// Chromium recognizes LXQt and still selects basic text for it, so it does need a forced backend.
const ELECTRON_UNPROTECTED_DESKTOPS = new Set(["LXQt"]);
const KDE_NAME_PREFIXES = ["kde", "plasma"];
const NEGATIVE_FLAG_VALUES = new Set(["0", "false", "no", "off"]);
export function normalizeLinuxPasswordStorePreference(
value: unknown,
): LinuxPasswordStorePreference {
return value === "gnome-libsecret" ||
value === "kwallet" ||
value === "kwallet5" ||
value === "kwallet6"
? value
: DEFAULT_LINUX_PASSWORD_STORE;
}
// Auto mode asks one question: will Electron select a real keyring on its own? If so, stay out of
// the way, which is how canonical KDE sessions keep the KWallet generation Chromium picks for them.
// Otherwise force gnome-libsecret, because the alternative is basic text, which is barely
// encryption at all. Forcing never guesses a KWallet generation; a KDE session that needs a
// specific one sets linuxPasswordStore explicitly.
export function resolveLinuxPasswordStoreSwitch(input: {
readonly preference: LinuxPasswordStorePreference;
readonly env: NodeJS.ProcessEnv;
}): LinuxPasswordStoreSwitch | null {
if (input.preference !== "auto") {
return input.preference;
}
return electronSelectsProtectedBackend(input.env) ? null : "gnome-libsecret";
}
// Only an exact XDG_CURRENT_DESKTOP literal proves Electron will protect the session. Chromium can
// also reach a real backend through DESKTOP_SESSION and the legacy KDE markers, but those are the
// variables a previous session leaves behind, and trusting them is what let stale hints suppress
// the forced backend before. Forcing where Chromium would have chosen libsecret is harmless, since
// it lands on the same backend.
function electronSelectsProtectedBackend(env: NodeJS.ProcessEnv): boolean {
for (const name of splitDesktopNameList(env.XDG_CURRENT_DESKTOP)) {
const trimmed = name.trim();
if (trimmed.length === 0) {
continue;
}
if (trimmed === ELECTRON_KDE_DESKTOP || ELECTRON_LIBSECRET_DESKTOPS.has(trimmed)) {
return true;
}
if (ELECTRON_UNPROTECTED_DESKTOPS.has(trimmed)) {
return false;
}
}
return false;
}
export function resolveLinuxSecretStorageUnavailableMessage(input: {
readonly configuredPreference: LinuxPasswordStorePreference;
readonly selectedBackend: string | null;
readonly env: NodeJS.ProcessEnv;
}): string {
if (input.configuredPreference === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
input.configuredPreference === "kwallet" ||
input.configuredPreference === "kwallet5" ||
input.configuredPreference === "kwallet6"
) {
return getKWalletRemediationMessage();
}
const backend = normalizeSelectedStorageBackend(input.selectedBackend);
if (backend === "gnome-libsecret") {
return getGnomeKeyringRemediationMessage();
}
if (
backend === "kwallet" ||
backend === "kwallet5" ||
backend === "kwallet6" ||
looksLikeKdeSession(input.env)
) {
return getKWalletRemediationMessage();
}
return getGnomeKeyringRemediationMessage();
}
function getGnomeKeyringRemediationMessage(): string {
return "T3 Code could not access GNOME Keyring to save this environment credential. Install and start GNOME Keyring, then restart T3 Code.";
}
function getKWalletRemediationMessage(): string {
return "T3 Code could not access KWallet to save this environment credential. Enable the KDE wallet subsystem in System Settings, then restart T3 Code.";
}
// Advisory only: this picks between the GNOME Keyring and KWallet wording in the failure notice. It
// never decides which backend to select, so a loose match costs a user slightly wrong instructions
// rather than an unprotected credential store.
function looksLikeKdeSession(env: NodeJS.ProcessEnv): boolean {
const currentDesktopNames = nonEmptyDesktopNames(env.XDG_CURRENT_DESKTOP);
if (currentDesktopNames.length > 0) {
return currentDesktopNames.some(isKdeDesktopName);
}
const legacyNames = legacyDesktopNames(env);
if (legacyNames.length > 0) {
return legacyNames.some(isKdeDesktopName);
}
return isSet(env.KDE_SESSION_VERSION) || isAffirmativeFlag(env.KDE_FULL_SESSION);
}
function isKdeDesktopName(name: string): boolean {
return KDE_NAME_PREFIXES.some((prefix) => name.startsWith(prefix));
}
function legacyDesktopNames(env: NodeJS.ProcessEnv): string[] {
return [env.XDG_SESSION_DESKTOP, env.DESKTOP_SESSION, env.GDMSESSION].flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function nonEmptyDesktopNames(value: string | undefined): string[] {
return splitDesktopNameList(value).flatMap((entry) => {
const normalized = normalizeDesktopName(entry);
return normalized ? [normalized] : [];
});
}
function isSet(value: string | undefined): boolean {
return Boolean(value?.trim());
}
function isAffirmativeFlag(value: string | undefined): boolean {
const normalized = value?.trim().toLowerCase();
return normalized ? !NEGATIVE_FLAG_VALUES.has(normalized) : false;
}
function splitDesktopNameList(value: string | undefined): string[] {
return value?.split(":") ?? [];
}
function normalizeDesktopName(value: string | undefined): string | null {
const normalized = value?.trim().toLowerCase();
return normalized && normalized.length > 0 ? normalized : null;
}
function normalizeSelectedStorageBackend(value: string | null): string | null {
const normalized = value?.trim().toLowerCase().replace(/_/gu, "-");
return normalized && normalized.length > 0 ? normalized : null;
}
+16 -7
View File
@@ -43,12 +43,14 @@ import * as DesktopLocalEnvironmentAuth from "./backend/DesktopLocalEnvironmentA
import * as DesktopNetworkInterfaces from "./backend/DesktopNetworkInterfaces.ts";
import * as DesktopEnvironment from "./app/DesktopEnvironment.ts";
import * as DesktopLifecycle from "./app/DesktopLifecycle.ts";
import * as DesktopLinuxUrlHandler from "./app/DesktopLinuxUrlHandler.ts";
import * as DesktopShutdown from "./app/DesktopShutdown.ts";
import * as DesktopObservability from "./app/DesktopObservability.ts";
import * as DesktopServerExposure from "./backend/DesktopServerExposure.ts";
import * as DesktopClientSettings from "./settings/DesktopClientSettings.ts";
import * as DesktopSavedEnvironments from "./settings/DesktopSavedEnvironments.ts";
import * as DesktopAppSettings from "./settings/DesktopAppSettings.ts";
import * as DesktopPreReadyPlatform from "./app/DesktopPreReadyPlatform.ts";
import * as DesktopShellEnvironment from "./shell/DesktopShellEnvironment.ts";
import * as DesktopSshEnvironment from "./ssh/DesktopSshEnvironment.ts";
import * as DesktopSshPasswordPrompts from "./ssh/DesktopSshPasswordPrompts.ts";
@@ -60,6 +62,7 @@ import * as PreviewManager from "./preview/Manager.ts";
import * as DesktopWindow from "./window/DesktopWindow.ts";
import * as DesktopWslBackend from "./wsl/DesktopWslBackend.ts";
import * as DesktopWslEnvironment from "./wsl/DesktopWslEnvironment.ts";
import * as DesktopWslServerTree from "./wsl/DesktopWslServerTree.ts";
const desktopEnvironmentLayer = Layer.unwrap(
Effect.gen(function* () {
@@ -163,6 +166,7 @@ const desktopBackendLayer = DesktopBackendPool.layer.pipe(
Layer.provideMerge(DesktopAppIdentity.layer),
Layer.provideMerge(DesktopBackendConfiguration.layer),
Layer.provideMerge(DesktopWslEnvironment.layer),
Layer.provideMerge(DesktopWslServerTree.layer),
Layer.provideMerge(DesktopTelemetryPublisher.layer),
Layer.provideMerge(desktopWindowLayer),
);
@@ -181,6 +185,7 @@ const desktopLocalEnvironmentAuthLayer = DesktopLocalEnvironmentAuth.layer.pipe(
const desktopApplicationLayer = Layer.mergeAll(
DesktopLifecycle.layer,
DesktopApplicationMenu.layer,
DesktopLinuxUrlHandler.layer,
DesktopShellEnvironment.layer,
desktopSshLayer,
).pipe(
@@ -195,16 +200,20 @@ const desktopClerkLayer = DesktopClerk.layer.pipe(
Layer.provideMerge(ElectronApp.layer),
);
const desktopApplicationRuntimeLayer = desktopApplicationLayer.pipe(
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
);
// Acquire strict pre-ready setup before Clerk, whose userData resolution can
// yield and let Electron emit ready.
const desktopRuntimeLayer = desktopClerkLayer.pipe(
Layer.flatMap((clerkContext) =>
desktopApplicationLayer.pipe(
Layer.provideMerge(Layer.succeedContext(clerkContext)),
Layer.provideMerge(NodeServices.layer),
Layer.provideMerge(NodeHttpClient.layerUndici),
Layer.provideMerge(NetService.layer),
Layer.provideMerge(electronLayer),
),
desktopApplicationRuntimeLayer.pipe(Layer.provideMerge(Layer.succeedContext(clerkContext))),
),
Layer.provideMerge(DesktopPreReadyPlatform.layer),
);
DesktopApp.program.pipe(Effect.provide(desktopRuntimeLayer), NodeRuntime.runMain);
+23 -2
View File
@@ -35,6 +35,10 @@ contextBridge.exposeInMainWorld("desktopBridge", {
}
return result as ReturnType<DesktopBridge["getAppBranding"]>;
},
getSystemLocale: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_SYSTEM_LOCALE_CHANNEL);
return typeof result === "string" ? result : null;
},
getLocalEnvironmentBootstraps: () => {
const result = ipcRenderer.sendSync(IpcChannels.GET_LOCAL_ENVIRONMENT_BOOTSTRAPS_CHANNEL);
if (!Array.isArray(result)) {
@@ -97,7 +101,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) =>
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
@@ -105,6 +109,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
...(position === undefined ? {} : { position }),
}),
openExternal: (url: string) => ipcRenderer.invoke(IpcChannels.OPEN_EXTERNAL_CHANNEL, url),
probeRemoteEditors: () => ipcRenderer.invoke(IpcChannels.PROBE_REMOTE_EDITORS_CHANNEL, undefined),
onMenuAction: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, action: unknown) => {
if (typeof action !== "string") return;
@@ -116,6 +121,17 @@ contextBridge.exposeInMainWorld("desktopBridge", {
ipcRenderer.removeListener(IpcChannels.MENU_ACTION_CHANNEL, wrappedListener);
};
},
onQuitShortcut: (listener) => {
const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
if (state !== "down" && state !== "up") return;
listener(state);
};
ipcRenderer.on(IpcChannels.QUIT_SHORTCUT_CHANNEL, wrappedListener);
return () => {
ipcRenderer.removeListener(IpcChannels.QUIT_SHORTCUT_CHANNEL, wrappedListener);
};
},
getWindowFullscreenState: () =>
ipcRenderer.sendSync(IpcChannels.GET_WINDOW_FULLSCREEN_STATE_CHANNEL) === true,
onWindowFullscreenStateChange: (listener) => {
@@ -147,7 +163,12 @@ contextBridge.exposeInMainWorld("desktopBridge", {
};
},
preview: {
createTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, { tabId }),
createTab: (tabId, defaults) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_CREATE_TAB_CHANNEL, {
tabId,
zoomFactor: defaults?.zoomFactor,
colorScheme: defaults?.colorScheme,
}),
closeTab: (tabId) => ipcRenderer.invoke(IpcChannels.PREVIEW_CLOSE_TAB_CHANNEL, { tabId }),
registerWebview: (tabId, webContentsId) =>
ipcRenderer.invoke(IpcChannels.PREVIEW_REGISTER_WEBVIEW_CHANNEL, { tabId, webContentsId }),
@@ -0,0 +1,28 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
const keyboardEvent = (
overrides: Partial<Parameters<typeof resolveAnnotationSubmission>[0]> = {},
) => ({
key: "Enter",
metaKey: false,
ctrlKey: false,
shiftKey: false,
isComposing: false,
...overrides,
});
describe("resolveAnnotationSubmission", () => {
it("attaches on Enter and sends on Cmd/Ctrl+Enter", () => {
expect(resolveAnnotationSubmission(keyboardEvent())).toBe("attach");
expect(resolveAnnotationSubmission(keyboardEvent({ metaKey: true }))).toBe("send");
expect(resolveAnnotationSubmission(keyboardEvent({ ctrlKey: true }))).toBe("send");
});
it("leaves Shift+Enter and composition events available for editing", () => {
expect(resolveAnnotationSubmission(keyboardEvent({ shiftKey: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ isComposing: true }))).toBeNull();
expect(resolveAnnotationSubmission(keyboardEvent({ key: " " }))).toBeNull();
});
});
@@ -0,0 +1,16 @@
import type { PreviewAnnotationSubmission } from "@t3tools/contracts";
interface AnnotationKeyboardEvent {
readonly key: string;
readonly metaKey: boolean;
readonly ctrlKey: boolean;
readonly shiftKey: boolean;
readonly isComposing: boolean;
}
export function resolveAnnotationSubmission(
event: AnnotationKeyboardEvent,
): PreviewAnnotationSubmission | null {
if (event.key !== "Enter" || event.shiftKey || event.isComposing) return null;
return event.metaKey || event.ctrlKey ? "send" : "attach";
}
@@ -23,6 +23,10 @@ const ALLOWED_PREVIEW_PERMISSIONS: ReadonlySet<string> = new Set([
"clipboard-sanitized-write",
"notifications",
"geolocation",
// Deliberately NOT local-fonts: preview sessions run untrusted web content,
// and silently granting it would hand every page the user's installed-font
// fingerprint (and font file bytes via FontData.blob()). The app's own font
// picker runs in the main window session, which is unaffected by this list.
]);
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
@@ -0,0 +1,999 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
MAX_FAVICON_CANDIDATES,
MAX_FAVICON_RESPONSE_BYTES,
captureFavicon,
selectFaviconCandidates,
} from "./FaviconCapture.ts";
const PNG = "data:image/png;base64,cG5n";
const SOURCE_PNG = Buffer.alloc(24);
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(SOURCE_PNG);
SOURCE_PNG.writeUInt32BE(1, 16);
SOURCE_PNG.writeUInt32BE(1, 20);
const SOURCE_PNG_URL = `data:image/png;base64,${SOURCE_PNG.toString("base64")}`;
function sourceGif(
width: number,
height: number,
frameWidth = width,
frameHeight = height,
additionalFrames: ReadonlyArray<{
readonly left?: number;
readonly top?: number;
readonly width: number;
readonly height: number;
}> = [],
): Buffer {
const frames = [{ width: frameWidth, height: frameHeight }, ...additionalFrames];
const buffer = Buffer.alloc(13 + frames.length * 12 + 1);
buffer.write("GIF89a", 0, "ascii");
buffer.writeUInt16LE(width, 6);
buffer.writeUInt16LE(height, 8);
let offset = 13;
for (const frame of frames) {
buffer[offset] = 0x2c;
buffer.writeUInt16LE(frame.left ?? 0, offset + 1);
buffer.writeUInt16LE(frame.top ?? 0, offset + 3);
buffer.writeUInt16LE(frame.width, offset + 5);
buffer.writeUInt16LE(frame.height, offset + 7);
offset += 10;
buffer[offset] = 2;
buffer[offset + 1] = 0;
offset += 2;
}
buffer[offset] = 0x3b;
return buffer;
}
function sourceJpeg(
width: number,
height: number,
orientations: number | ReadonlyArray<number> = [],
): Buffer {
const frame = Buffer.from([
0xff,
0xd8,
0xff,
0xc0,
0x00,
0x07,
0x08,
height >>> 8,
height & 0xff,
width >>> 8,
width & 0xff,
]);
const app1Segments = (typeof orientations === "number" ? [orientations] : orientations).map(
(orientation) => sourceJpegExifSegment([orientation]),
);
return Buffer.concat([frame.subarray(0, 2), ...app1Segments, frame.subarray(2)]);
}
function sourceJpegApp1Segment(payload: Buffer): Buffer {
const app1 = Buffer.alloc(4 + payload.byteLength);
app1[0] = 0xff;
app1[1] = 0xe1;
app1.writeUInt16BE(payload.byteLength + 2, 2);
payload.copy(app1, 4);
return app1;
}
function sourceJpegExifSegment(
orientations: ReadonlyArray<number>,
options?: {
readonly byteOrder?: "II" | "MM";
readonly magic?: number;
readonly padding?: number;
},
): Buffer {
const exif = Buffer.alloc(20 + orientations.length * 12);
exif.write("Exif\0\0", 0, "binary");
exif[5] = options?.padding ?? 0;
const littleEndian = options?.byteOrder !== "MM";
exif.write(littleEndian ? "II" : "MM", 6, "ascii");
const writeUInt16 = (value: number, offset: number) =>
littleEndian ? exif.writeUInt16LE(value, offset) : exif.writeUInt16BE(value, offset);
const writeUInt32 = (value: number, offset: number) =>
littleEndian ? exif.writeUInt32LE(value, offset) : exif.writeUInt32BE(value, offset);
writeUInt16(options?.magic ?? 42, 8);
writeUInt32(8, 10);
writeUInt16(orientations.length, 14);
orientations.forEach((orientation, index) => {
const entryOffset = 16 + index * 12;
writeUInt16(0x0112, entryOffset);
writeUInt16(3, entryOffset + 2);
writeUInt32(1, entryOffset + 4);
writeUInt16(orientation, entryOffset + 8);
});
return sourceJpegApp1Segment(exif);
}
function sourceJpegWithApp1Segments(
width: number,
height: number,
segments: ReadonlyArray<Buffer>,
): Buffer {
const frame = sourceJpeg(width, height);
return Buffer.concat([frame.subarray(0, 2), ...segments, frame.subarray(2)]);
}
function sourceJpegWithOrientationEntries(
width: number,
height: number,
orientations: ReadonlyArray<number>,
): Buffer {
return sourceJpegWithApp1Segments(width, height, [sourceJpegExifSegment(orientations)]);
}
function sourceJpegWithEndianAlias(alias: number, byteOrder: "II" | "MM"): Buffer {
const exif = sourceJpegExifSegment([6], { byteOrder });
exif[10] = alias;
exif[11] = alias;
return sourceJpegWithApp1Segments(64, 32, [exif]);
}
function sourceJpegExifWithSubIfd(options: {
readonly rootOrientation?: number;
readonly subIfdFirst?: boolean;
readonly subIfdOrientation: number;
}): Buffer {
const rootEntries = options.rootOrientation === undefined ? 1 : 2;
const rootIfdOffset = 14;
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
const exif = Buffer.alloc(subIfdOffset + 2 + 12 + 4);
exif.write("Exif\0\0", 0, "binary");
exif.write("II", 6, "ascii");
exif.writeUInt16LE(42, 8);
exif.writeUInt32LE(8, 10);
exif.writeUInt16LE(rootEntries, rootIfdOffset);
const writeOrientation = (offset: number, orientation: number) => {
exif.writeUInt16LE(0x0112, offset);
exif.writeUInt16LE(3, offset + 2);
exif.writeUInt32LE(1, offset + 4);
exif.writeUInt16LE(orientation, offset + 8);
};
const writeSubIfdPointer = (offset: number) => {
exif.writeUInt16LE(0x8769, offset);
exif.writeUInt16LE(4, offset + 2);
exif.writeUInt32LE(1, offset + 4);
exif.writeUInt32LE(subIfdOffset - 6, offset + 8);
};
const firstRootEntryOffset = rootIfdOffset + 2;
if (options.rootOrientation === undefined) {
writeSubIfdPointer(firstRootEntryOffset);
} else if (options.subIfdFirst) {
writeSubIfdPointer(firstRootEntryOffset);
writeOrientation(firstRootEntryOffset + 12, options.rootOrientation);
} else {
writeOrientation(firstRootEntryOffset, options.rootOrientation);
writeSubIfdPointer(firstRootEntryOffset + 12);
}
exif.writeUInt16LE(1, subIfdOffset);
writeOrientation(subIfdOffset + 2, options.subIfdOrientation);
return sourceJpegApp1Segment(exif);
}
function sourceJpegExifWithSubIfdPointers(options: {
readonly pointerCount: number;
readonly subIfdEntries: number;
}): Buffer {
const { pointerCount, subIfdEntries } = options;
const rootIfdOffset = 14;
const rootEntries = pointerCount + 1;
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
const exif = Buffer.alloc(subIfdOffset + 2 + subIfdEntries * 12 + 4);
exif.write("Exif\0\0", 0, "binary");
exif.write("II", 6, "ascii");
exif.writeUInt16LE(42, 8);
exif.writeUInt32LE(8, 10);
exif.writeUInt16LE(rootEntries, rootIfdOffset);
for (let index = 0; index < pointerCount; index += 1) {
const entryOffset = rootIfdOffset + 2 + index * 12;
exif.writeUInt16LE(0x8769, entryOffset);
exif.writeUInt16LE(4, entryOffset + 2);
exif.writeUInt32LE(1, entryOffset + 4);
exif.writeUInt32LE(subIfdOffset - 6, entryOffset + 8);
}
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
exif.writeUInt16LE(0x0112, orientationOffset);
exif.writeUInt16LE(3, orientationOffset + 2);
exif.writeUInt32LE(1, orientationOffset + 4);
exif.writeUInt16LE(6, orientationOffset + 8);
exif.writeUInt16LE(subIfdEntries, subIfdOffset);
for (let index = 0; index < subIfdEntries; index += 1) {
const entryOffset = subIfdOffset + 2 + index * 12;
exif.writeUInt16LE(1, entryOffset);
exif.writeUInt16LE(3, entryOffset + 2);
exif.writeUInt32LE(1, entryOffset + 4);
}
return sourceJpegApp1Segment(exif);
}
function sourceJpegExifWithOverlappingSubIfds(pointerCount: number, subIfdEntries: number): Buffer {
const rootIfdOffset = 14;
const rootEntries = pointerCount + 1;
const subIfdOffset = rootIfdOffset + 2 + rootEntries * 12 + 4;
const exif = Buffer.alloc(subIfdOffset + pointerCount * 2 + 2 + subIfdEntries * 12);
exif.write("Exif\0\0", 0, "binary");
exif.write("II", 6, "ascii");
exif.writeUInt32LE(8, 10);
exif.writeUInt16LE(rootEntries, rootIfdOffset);
for (let index = 0; index < pointerCount; index += 1) {
const entryOffset = rootIfdOffset + 2 + index * 12;
exif.writeUInt16LE(0x8769, entryOffset);
exif.writeUInt16LE(4, entryOffset + 2);
exif.writeUInt32LE(1, entryOffset + 4);
exif.writeUInt32LE(subIfdOffset + index * 2 - 6, entryOffset + 8);
exif.writeUInt16LE(subIfdEntries, subIfdOffset + index * 2);
}
const orientationOffset = rootIfdOffset + 2 + pointerCount * 12;
exif.writeUInt16LE(0x0112, orientationOffset);
exif.writeUInt16LE(3, orientationOffset + 2);
exif.writeUInt32LE(1, orientationOffset + 4);
exif.writeUInt16LE(6, orientationOffset + 8);
return sourceJpegApp1Segment(exif);
}
function sourceWebp(width: number, height: number): Buffer {
const buffer = Buffer.alloc(30);
buffer.write("RIFF", 0, "ascii");
buffer.write("WEBP", 8, "ascii");
buffer.write("VP8X", 12, "ascii");
buffer.writeUIntLE(width - 1, 24, 3);
buffer.writeUIntLE(height - 1, 27, 3);
return buffer;
}
function sourceIco(embedded: Buffer): Buffer {
const buffer = Buffer.alloc(22 + embedded.byteLength);
buffer.writeUInt16LE(1, 2);
buffer.writeUInt16LE(1, 4);
buffer.writeUInt32LE(embedded.byteLength, 14);
buffer.writeUInt32LE(22, 18);
embedded.copy(buffer, 22);
return buffer;
}
function makeUnsafePng(): Buffer {
const buffer = Buffer.from(SOURCE_PNG);
buffer.writeUInt32BE(4096, 16);
buffer.writeUInt32BE(4096, 20);
return buffer;
}
function sourcePng(width: number, height: number): Buffer {
const buffer = Buffer.from(SOURCE_PNG);
buffer.writeUInt32BE(width, 16);
buffer.writeUInt32BE(height, 20);
return buffer;
}
function makeUnsafeDib(): Buffer {
const buffer = Buffer.alloc(40);
buffer.writeUInt32LE(40, 0);
buffer.writeInt32LE(4096, 4);
buffer.writeInt32LE(4096, 8);
return buffer;
}
function makeWebContents(options?: {
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
readonly rasterize?: (code: string) => Promise<unknown>;
}) {
const fetch = vi.fn(
options?.fetch ??
(async () =>
new Response(new Uint8Array(SOURCE_PNG), {
headers: { "content-type": "image/png" },
})),
);
const executeJavaScriptInIsolatedWorld = vi.fn(
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : PNG,
);
return {
webContents: {
session: { fetch },
executeJavaScriptInIsolatedWorld,
} as never,
executeJavaScriptInIsolatedWorld,
fetch,
};
}
const JPEG_LANDSCAPE_LAYOUT = {
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
resizeHeight: 16,
resizeWidth: 32,
} as const;
const JPEG_PORTRAIT_LAYOUT = {
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
resizeHeight: 32,
resizeWidth: 16,
} as const;
async function expectJpegLayout(
source: Buffer,
layout: typeof JPEG_LANDSCAPE_LAYOUT | typeof JPEG_PORTRAIT_LAYOUT,
): Promise<void> {
const { webContents } = makeWebContents({
rasterize: async (code) => {
expect(code).toContain(`resizeWidth: ${layout.resizeWidth}`);
expect(code).toContain(`resizeHeight: ${layout.resizeHeight}`);
expect(code).toContain(layout.draw);
return PNG;
},
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
}
describe("selectFaviconCandidates", () => {
it("filters and deduplicates before applying the candidate cap", () => {
const valid = Array.from(
{ length: MAX_FAVICON_CANDIDATES + 2 },
(_, index) => `https://example.com/favicon-${index}.png`,
);
expect(
selectFaviconCandidates([
...Array.from({ length: 64 }, () => "javascript:alert(1)"),
valid[0]!,
valid[0]!,
...valid.slice(1),
]),
).toEqual(valid.slice(0, MAX_FAVICON_CANDIDATES));
});
it("bounds raw candidate scanning independently of the usable-candidate cap", () => {
const oversizedInvalid = `javascript:${"x".repeat(2_048)}`;
expect(
selectFaviconCandidates([
...Array.from({ length: 128 }, () => oversizedInvalid),
"https://example.com/too-late.png",
]),
).toEqual([]);
});
});
describe("captureFavicon", () => {
it.each([
{
label: "same-origin",
pageUrl: "https://example.com/page",
faviconUrl: "https://example.com/favicon.png",
credentials: "include",
},
{
label: "cross-origin",
pageUrl: "https://example.com/page",
faviconUrl: "https://cdn.example.net/favicon.png",
credentials: "omit",
},
])("uses the explicit credential policy for $label requests", async (testCase) => {
const { webContents, fetch } = makeWebContents();
const result = await captureFavicon({
webContents,
pageUrl: testCase.pageUrl,
candidates: [testCase.faviconUrl],
signal: new AbortController().signal,
});
expect(result).toEqual({ kind: "captured", dataUrl: PNG });
expect(fetch).toHaveBeenCalledWith(
testCase.faviconUrl,
expect.objectContaining({ credentials: testCase.credentials, redirect: "error" }),
);
});
it("decodes base64 and percent-encoded inline images without fetching", async () => {
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents();
const percentEncodedPng = [...SOURCE_PNG]
.map((byte) => `%${byte.toString(16).padStart(2, "0")}`)
.join("");
for (const candidate of [SOURCE_PNG_URL, `data:image/png,${percentEncodedPng}`]) {
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [candidate],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
}
expect(fetch).not.toHaveBeenCalled();
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(2);
});
it("tries the next candidate after an ordinary rejection", async () => {
const { webContents, fetch } = makeWebContents({
fetch: async (url) =>
url.endsWith("first.png")
? new Response(null, { status: 404 })
: new Response(new Uint8Array(SOURCE_PNG), {
headers: { "content-type": "image/png" },
}),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
expect(fetch).toHaveBeenCalledTimes(2);
});
it("cancels a rejected response body before trying the next candidate", async () => {
const cancel = vi.fn();
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(1));
},
cancel,
});
const { webContents, fetch } = makeWebContents({
fetch: async (url) =>
url.endsWith("first.png")
? new Response(body, { status: 404 })
: new Response(new Uint8Array(SOURCE_PNG), {
headers: { "content-type": "image/png" },
}),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
expect(cancel).toHaveBeenCalledOnce();
expect(fetch).toHaveBeenCalledTimes(2);
});
it("stops a pending fetch when its capture is aborted", async () => {
const controller = new AbortController();
const { webContents } = makeWebContents({
fetch: (_url, init) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
once: true,
});
}),
});
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: controller.signal,
});
controller.abort();
expect(await capture).toEqual({ kind: "none" });
});
it("ends candidate fallback when the overall capture deadline expires", async () => {
const timeoutController = new AbortController();
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
const { webContents, fetch } = makeWebContents({
fetch: (url, init) => {
if (url.endsWith("first.png")) return Promise.resolve(new Response(null, { status: 404 }));
return new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), {
once: true,
});
});
},
});
try {
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [
"https://example.com/first.png",
"https://example.com/second.png",
"https://example.com/third.png",
],
signal: new AbortController().signal,
});
await vi.waitFor(() => expect(fetch).toHaveBeenCalledTimes(2));
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
expect(await capture).toEqual({ kind: "timed-out" });
expect(fetch).toHaveBeenCalledTimes(2);
expect(timeout).toHaveBeenCalledOnce();
} finally {
timeout.mockRestore();
}
});
it("does not publish a rasterization that completes after the capture deadline", async () => {
const captureTimeoutController = new AbortController();
const rasterTimeoutController = new AbortController();
const timeout = vi
.spyOn(AbortSignal, "timeout")
.mockImplementation((milliseconds) =>
milliseconds === 5_000 ? captureTimeoutController.signal : rasterTimeoutController.signal,
);
let resolveRasterization!: (value: unknown) => void;
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
rasterize: () =>
new Promise((resolve) => {
resolveRasterization = resolve;
}),
});
try {
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
});
await vi.waitFor(() => expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce());
captureTimeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
expect(await capture).toEqual({ kind: "timed-out" });
resolveRasterization(PNG);
} finally {
timeout.mockRestore();
}
});
it("cancels a stalled response body when the capture deadline expires", async () => {
const timeoutController = new AbortController();
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(timeoutController.signal);
const cancel = vi.fn();
const { webContents } = makeWebContents({
fetch: async () =>
new Response(
new ReadableStream<Uint8Array>({
cancel,
}),
{ headers: { "content-type": "image/png" } },
),
});
try {
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: new AbortController().signal,
});
timeoutController.abort(new DOMException("capture timed out", "TimeoutError"));
expect(await capture).toEqual({ kind: "timed-out" });
expect(cancel).toHaveBeenCalledOnce();
} finally {
timeout.mockRestore();
}
});
it("rejects and cancels an oversized streamed response", async () => {
const cancel = vi.fn();
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new Uint8Array(MAX_FAVICON_RESPONSE_BYTES));
controller.enqueue(new Uint8Array(1));
},
cancel,
});
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
fetch: async () => new Response(body, { headers: { "content-type": "image/png" } }),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(cancel).toHaveBeenCalledOnce();
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("retains bounded compatibility with common favicon formats", async () => {
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
for (const [mime, buffer] of [
["image/gif", sourceGif(32, 32)],
["image/jpeg", sourceJpeg(32, 32)],
["image/webp", sourceWebp(32, 32)],
["image/x-icon", sourceIco(SOURCE_PNG)],
] as const) {
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:${mime};base64,${buffer.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
}
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledTimes(4);
});
it.each([
{
label: "landscape",
source: sourcePng(64, 32),
resizeWidth: 32,
resizeHeight: 16,
draw: "context.drawImage(bitmap, 0, 8, 32, 16)",
},
{
label: "portrait",
source: sourcePng(32, 64),
resizeWidth: 16,
resizeHeight: 32,
draw: "context.drawImage(bitmap, 8, 0, 16, 32)",
},
])("preserves $label aspect ratio within the 32x32 output", async (testCase) => {
const { webContents } = makeWebContents({
rasterize: async (code) => {
expect(code).toContain(`resizeWidth: ${testCase.resizeWidth}`);
expect(code).toContain(`resizeHeight: ${testCase.resizeHeight}`);
expect(code).toContain('resizeQuality: "high"');
expect(code).toContain(testCase.draw);
return PNG;
},
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/png;base64,${testCase.source.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "captured", dataUrl: PNG });
});
it.each([
...[1, 2, 3, 4].map((orientation) => ({
label: `keeps stored dimensions for orientation ${orientation}`,
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpeg(64, 32, orientation),
})),
...[5, 6, 7, 8].map((orientation) => ({
label: `uses display dimensions for orientation ${orientation}`,
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpeg(64, 32, orientation),
})),
{
label: "uses the first separate EXIF segment when it is transposed",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpeg(64, 32, [6, 1]),
},
{
label: "uses the first separate EXIF segment when it is untransposed",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpeg(64, 32, [1, 6]),
},
{
label: "does not consult a later EXIF segment after an invalid orientation",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpeg(64, 32, [9, 6]),
},
{
label: "uses a later valid orientation in the same IFD",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithOrientationEntries(64, 32, [9, 6]),
},
{
label: "skips a non-EXIF APP1 segment",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegApp1Segment(Buffer.from("not-exif")),
sourceJpegExifSegment([6]),
]),
},
{
label: "skips an empty EXIF APP1 segment",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegApp1Segment(Buffer.from("Exif\0\0", "binary")),
sourceJpegExifSegment([6]),
]),
},
{
label: "stops after a malformed qualifying EXIF APP1 segment",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegApp1Segment(Buffer.from("Exif\0\0broken", "binary")),
sourceJpegExifSegment([6]),
]),
},
{
label: "ignores the EXIF padding byte",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { padding: 0xff })]),
},
{
label: "reads big-endian EXIF",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { byteOrder: "MM" })]),
},
{
label: "matches Chromium for a nonstandard TIFF magic field",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [sourceJpegExifSegment([6], { magic: 0 })]),
},
{
label: "rejects a high-bit little-endian alias",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithEndianAlias(0xc9, "II"),
},
{
label: "rejects a high-bit big-endian alias",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithEndianAlias(0xcd, "MM"),
},
{
label: "reads an orientation from a SubIFD",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfd({ subIfdOrientation: 6 }),
]),
},
{
label: "uses a SubIFD orientation before a later root orientation",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfd({
rootOrientation: 1,
subIfdFirst: true,
subIfdOrientation: 6,
}),
]),
},
{
label: "uses a root orientation before a later SubIFD orientation",
layout: JPEG_LANDSCAPE_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfd({ rootOrientation: 1, subIfdOrientation: 6 }),
]),
},
{
label: "memoizes repeated aliases to the same SubIFD",
layout: JPEG_PORTRAIT_LAYOUT,
source: sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithSubIfdPointers({ pointerCount: 32, subIfdEntries: 32 }),
]),
},
])("matches Chromium JPEG layout: $label", async ({ source, layout }) => {
await expectJpegLayout(source, layout);
});
it("rejects JPEG metadata when distinct SubIFDs exhaust the linear work budget", async () => {
const source = sourceJpegWithApp1Segments(64, 32, [
sourceJpegExifWithOverlappingSubIfds(32, 32),
]);
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/jpeg;base64,${source.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("rejects JPEGs with multiple frame headers before rasterization", async () => {
const buffer = Buffer.concat([sourceJpeg(4096, 4096), sourceJpeg(1, 1).subarray(2)]);
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [`data:image/jpeg;base64,${buffer.toString("base64")}`],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("rejects an unsafe PNG size before rasterization", async () => {
const buffer = makeUnsafePng();
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents({
fetch: async () =>
new Response(new Uint8Array(buffer), {
headers: { "content-type": "image/png" },
}),
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/favicon.png"],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it.each([
["GIF", "image/gif", sourceGif(4096, 4096)],
["GIF frame", "image/gif", sourceGif(1, 1, 4096, 4096)],
["GIF later frame", "image/gif", sourceGif(1, 1, 1, 1, [{ width: 4096, height: 4096 }])],
[
"GIF cumulative frames",
"image/gif",
sourceGif(
64,
64,
64,
64,
Array.from({ length: 256 }, () => ({ width: 64, height: 64 })),
),
],
["JPEG", "image/jpeg", sourceJpeg(4096, 4096)],
["WebP", "image/webp", sourceWebp(4096, 4096)],
["ICO with PNG", "image/x-icon", sourceIco(makeUnsafePng())],
["ICO with DIB", "image/x-icon", sourceIco(makeUnsafeDib())],
["SVG", "image/svg+xml", Buffer.from('<svg width="1" height="1"/>')],
[
"SVG with embedded bitmap",
"image/svg+xml",
Buffer.from(
`<svg width="1" height="1"><image href="data:image/png;base64,${makeUnsafePng().toString("base64")}"/></svg>`,
),
],
[
"ICO invalid payload span",
"image/x-icon",
(() => {
const buffer = Buffer.alloc(22);
buffer.writeUInt16LE(1, 2);
buffer.writeUInt16LE(1, 4);
buffer.writeUInt32LE(100, 14);
buffer.writeUInt32LE(22, 18);
return buffer;
})(),
],
])("rejects unsafe or unsupported %s before rasterization", async (_label, mime, buffer) => {
const { webContents, executeJavaScriptInIsolatedWorld } = makeWebContents();
const candidate = `data:${mime};base64,${buffer.toString("base64")}`;
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [candidate],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
expect(executeJavaScriptInIsolatedWorld).not.toHaveBeenCalled();
});
it("ignores output that is not a bounded PNG data URL", async () => {
const { webContents } = makeWebContents({
rasterize: async () => "data:image/svg+xml;base64,c3Zn",
});
expect(
await captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
}),
).toEqual({ kind: "none" });
});
it("waits for physical rasterization settlement after a logical timeout", async () => {
vi.useFakeTimers();
try {
let resolveOld!: (value: unknown) => void;
let executions = 0;
const { webContents } = makeWebContents({
rasterize: () => {
executions += 1;
return executions === 1
? new Promise((resolve) => {
resolveOld = resolve;
})
: Promise.resolve(PNG);
},
});
const input = {
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
};
const timedOut = captureFavicon(input);
await vi.advanceTimersByTimeAsync(1_001);
expect(await timedOut).toEqual({ kind: "timed-out" });
const newer = captureFavicon(input);
await Promise.resolve();
expect(executions).toBe(1);
resolveOld(PNG);
expect(await newer).toEqual({ kind: "captured", dataUrl: PNG });
expect(executions).toBe(2);
} finally {
vi.useRealTimers();
}
});
it("ends candidate fallback after a rasterization timeout", async () => {
vi.useFakeTimers();
try {
let resolveRasterization!: (value: unknown) => void;
const { webContents, fetch, executeJavaScriptInIsolatedWorld } = makeWebContents({
rasterize: () =>
new Promise((resolve) => {
resolveRasterization = resolve;
}),
});
const capture = captureFavicon({
webContents,
pageUrl: "https://example.com/page",
candidates: ["https://example.com/first.png", "https://example.com/second.png"],
signal: new AbortController().signal,
});
await vi.advanceTimersByTimeAsync(1_001);
expect(await capture).toEqual({ kind: "timed-out" });
expect(fetch).toHaveBeenCalledOnce();
expect(executeJavaScriptInIsolatedWorld).toHaveBeenCalledOnce();
resolveRasterization(PNG);
} finally {
vi.useRealTimers();
}
});
it("coalesces queued rasterizations so only the latest pending capture launches", async () => {
let resolveFirst!: (value: unknown) => void;
let executions = 0;
const { webContents } = makeWebContents({
rasterize: () => {
executions += 1;
return executions === 1
? new Promise((resolve) => {
resolveFirst = resolve;
})
: Promise.resolve(PNG);
},
});
const input = {
webContents,
pageUrl: "https://example.com/page",
candidates: [SOURCE_PNG_URL],
signal: new AbortController().signal,
};
const first = captureFavicon(input);
const superseded = captureFavicon(input);
const newest = captureFavicon(input);
expect(executions).toBe(1);
resolveFirst(PNG);
expect(await first).toEqual({ kind: "captured", dataUrl: PNG });
expect(await superseded).toEqual({ kind: "none" });
expect(await newest).toEqual({ kind: "captured", dataUrl: PNG });
expect(executions).toBe(2);
});
});
+679
View File
@@ -0,0 +1,679 @@
import { FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
export const MAX_FAVICON_RESPONSE_BYTES = 100_000;
export const MAX_FAVICON_CANDIDATES = 8;
export const MAX_FAVICON_HTTP_URL_LENGTH = 2_048;
const MAX_FAVICON_CANDIDATE_INPUT_UNITS = 262_144;
const MIN_FAVICON_CANDIDATE_INPUT_UNITS = 256;
const MAX_FAVICON_SOURCE_PIXELS = 1_048_576;
const MAX_FAVICON_INLINE_URL_LENGTH = Math.ceil((MAX_FAVICON_RESPONSE_BYTES * 4) / 3) + 128;
const FAVICON_CAPTURE_TIMEOUT_MS = 5_000;
const FAVICON_RASTER_WORLD_ID = 1001;
const FAVICON_RASTER_TIMEOUT_MS = 1_000;
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
interface RasterizationGate {
generation: number;
launchAllowed?: Promise<void>;
}
const rasterizationGates = new WeakMap<Electron.WebContents, RasterizationGate>();
async function waitForRasterLaunch(previous: Promise<void>, signal: AbortSignal): Promise<void> {
if (signal.aborted) return;
await new Promise<void>((resolve) => {
const finish = () => {
signal.removeEventListener("abort", finish);
resolve();
};
signal.addEventListener("abort", finish, { once: true });
void previous.then(finish);
});
}
export type FaviconCaptureResult =
| { readonly kind: "captured"; readonly dataUrl: string }
| { readonly kind: "none" }
| { readonly kind: "timed-out" };
type RasterizationResult =
| { readonly kind: "completed"; readonly value: unknown }
| { readonly kind: "timed-out" };
export function safeHttpOrigin(url: string): string | null {
try {
const parsed = new URL(url);
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.origin : null;
} catch {
return null;
}
}
export function selectFaviconCandidates(candidates: ReadonlyArray<string>): ReadonlyArray<string> {
const selected: string[] = [];
const seen = new Set<string>();
let inputUnits = 0;
for (const candidate of candidates) {
// Charge a minimum per entry so a large array of tiny malformed values is bounded too.
inputUnits += Math.max(MIN_FAVICON_CANDIDATE_INPUT_UNITS, candidate.length);
if (inputUnits > MAX_FAVICON_CANDIDATE_INPUT_UNITS) break;
if (!isSupportedFaviconUrl(candidate) || seen.has(candidate)) continue;
seen.add(candidate);
selected.push(candidate);
if (selected.length === MAX_FAVICON_CANDIDATES) break;
}
return selected;
}
export async function captureFavicon(input: {
readonly webContents: Electron.WebContents;
readonly pageUrl: string;
readonly candidates: ReadonlyArray<string>;
readonly signal: AbortSignal;
}): Promise<FaviconCaptureResult> {
const pageOrigin = safeHttpOrigin(input.pageUrl);
if (!pageOrigin) return { kind: "none" };
const captureTimeout = AbortSignal.timeout(FAVICON_CAPTURE_TIMEOUT_MS);
const captureSignal = AbortSignal.any([input.signal, captureTimeout]);
for (const candidate of selectFaviconCandidates(input.candidates)) {
if (captureSignal.aborted) {
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
}
const captured = await captureCandidate({
webContents: input.webContents,
pageOrigin,
candidate,
signal: captureSignal,
});
if (captureSignal.aborted) {
return input.signal.aborted ? { kind: "none" } : { kind: "timed-out" };
}
if (captured.kind === "captured" || captured.kind === "timed-out") return captured;
}
return { kind: "none" };
}
async function captureCandidate(input: {
readonly webContents: Electron.WebContents;
readonly pageOrigin: string;
readonly candidate: string;
readonly signal: AbortSignal;
}): Promise<FaviconCaptureResult> {
try {
const inline = parseInlineFavicon(input.candidate);
if (inline) {
return await normalizeFaviconBuffer(
input.webContents,
inline.mime,
inline.buffer,
input.signal,
);
}
const candidateOrigin = safeHttpOrigin(input.candidate);
if (!candidateOrigin) return { kind: "none" };
const response = await input.webContents.session.fetch(input.candidate, {
credentials: candidateOrigin === input.pageOrigin ? "include" : "omit",
redirect: "error",
signal: input.signal,
});
if (!response.ok) {
await response.body?.cancel();
return { kind: "none" };
}
const buffer = await readFaviconResponse(response, input.signal);
if (!buffer || input.signal.aborted) return { kind: "none" };
const mime = response.headers.get("content-type")?.split(";", 1)[0] ?? null;
return await normalizeFaviconBuffer(input.webContents, mime, buffer, input.signal);
} catch {
return { kind: "none" };
}
}
async function readFaviconResponse(
response: Response,
signal: AbortSignal,
): Promise<Buffer | null> {
const contentLength = Number(response.headers.get("content-length"));
if (Number.isFinite(contentLength) && contentLength > MAX_FAVICON_RESPONSE_BYTES) {
await response.body?.cancel();
return null;
}
if (!response.body) {
const buffer = Buffer.from(await response.arrayBuffer());
return buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES ? buffer : null;
}
const reader = response.body.getReader();
const cancelForAbort = () => {
void reader.cancel(signal.reason).catch(() => undefined);
};
signal.addEventListener("abort", cancelForAbort, { once: true });
if (signal.aborted) cancelForAbort();
const chunks: Buffer[] = [];
let byteLength = 0;
try {
while (true) {
const next = await reader.read();
if (next.done) return Buffer.concat(chunks, byteLength);
byteLength += next.value.byteLength;
if (byteLength > MAX_FAVICON_RESPONSE_BYTES) {
await reader.cancel();
return null;
}
chunks.push(Buffer.from(next.value));
}
} finally {
signal.removeEventListener("abort", cancelForAbort);
reader.releaseLock();
}
}
function isSupportedFaviconUrl(url: string): boolean {
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return false;
if (/^data:/i.test(url)) return /^data:image\/[a-z0-9.+-]+(?:;[^,]*)?,/i.test(url);
try {
const protocol = new URL(url).protocol;
return (
(protocol === "http:" || protocol === "https:") && url.length <= MAX_FAVICON_HTTP_URL_LENGTH
);
} catch {
return false;
}
}
function decodeInlineFaviconPayload(payload: string): Buffer | null {
const decoded = Buffer.allocUnsafe(Buffer.byteLength(payload));
let inputOffset = 0;
let outputOffset = 0;
while (inputOffset < payload.length) {
const escapeOffset = payload.indexOf("%", inputOffset);
const literalEnd = escapeOffset === -1 ? payload.length : escapeOffset;
outputOffset += decoded.write(payload.slice(inputOffset, literalEnd), outputOffset, "utf8");
if (escapeOffset === -1) break;
const hex = payload.slice(escapeOffset + 1, escapeOffset + 3);
if (!/^[0-9a-f]{2}$/i.test(hex)) return null;
decoded[outputOffset] = Number.parseInt(hex, 16);
outputOffset += 1;
inputOffset = escapeOffset + 3;
}
return decoded.subarray(0, outputOffset);
}
function parseInlineFavicon(
url: string,
): { readonly buffer: Buffer; readonly mime: string } | null {
if (url.length > MAX_FAVICON_INLINE_URL_LENGTH) return null;
const match = /^data:(image\/[a-z0-9.+-]+)((?:;[^,]*)?),(.*)$/is.exec(url);
if (!match) return null;
const mime = match[1]?.toLowerCase();
const parameters = match[2]
?.split(";")
.filter(Boolean)
.map((parameter) => parameter.toLowerCase());
const payload = match[3];
if (!mime || !parameters || !payload) return null;
const base64 = parameters.at(-1) === "base64";
if (parameters.includes("base64") && !base64) return null;
let buffer: Buffer;
try {
if (base64) {
if (!/^[a-z0-9+/]*={0,2}$/i.test(payload) || payload.length % 4 === 1) return null;
buffer = Buffer.from(payload, "base64");
if (buffer.toString("base64").replace(/=+$/, "") !== payload.replace(/=+$/, "")) {
return null;
}
} else {
const decoded = decodeInlineFaviconPayload(payload);
if (!decoded) return null;
buffer = decoded;
}
} catch {
return null;
}
return buffer.byteLength > 0 && buffer.byteLength <= MAX_FAVICON_RESPONSE_BYTES
? { buffer, mime }
: null;
}
interface ImageDimensions {
readonly width: number;
readonly height: number;
}
function safeDimensions(dimensions: ImageDimensions | null): dimensions is ImageDimensions {
return (
dimensions !== null &&
Number.isSafeInteger(dimensions.width) &&
Number.isSafeInteger(dimensions.height) &&
dimensions.width > 0 &&
dimensions.height > 0 &&
dimensions.width * dimensions.height <= MAX_FAVICON_SOURCE_PIXELS
);
}
function pngDimensions(buffer: Buffer): ImageDimensions | null {
if (!buffer.subarray(0, PNG_SIGNATURE.length).equals(PNG_SIGNATURE) || buffer.byteLength < 24) {
return null;
}
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) };
}
function skipGifSubBlocks(buffer: Buffer, startOffset: number): number | null {
let offset = startOffset;
while (offset < buffer.byteLength) {
const blockLength = buffer[offset]!;
offset += 1;
if (blockLength === 0) return offset;
if (offset + blockLength > buffer.byteLength) return null;
offset += blockLength;
}
return null;
}
function gifDimensions(buffer: Buffer): ImageDimensions | null {
if (buffer.byteLength < 13 || !/^GIF8[79]a$/u.test(buffer.subarray(0, 6).toString("ascii"))) {
return null;
}
const logicalWidth = buffer.readUInt16LE(6);
const logicalHeight = buffer.readUInt16LE(8);
if (!safeDimensions({ width: logicalWidth, height: logicalHeight })) return null;
const packed = buffer[10]!;
let offset = 13 + ((packed & 0x80) === 0 ? 0 : 3 * 2 ** ((packed & 0x07) + 1));
if (offset > buffer.byteLength) return null;
let width = logicalWidth;
let height = logicalHeight;
let frameCount = 0;
let framePixels = 0;
while (offset < buffer.byteLength) {
const marker = buffer[offset];
if (marker === 0x3b) return frameCount > 0 ? { width, height } : null;
if (marker === 0x2c) {
if (offset + 10 > buffer.byteLength) return null;
const left = buffer.readUInt16LE(offset + 1);
const top = buffer.readUInt16LE(offset + 3);
const frameWidth = buffer.readUInt16LE(offset + 5);
const frameHeight = buffer.readUInt16LE(offset + 7);
if (frameWidth === 0 || frameHeight === 0) return null;
framePixels += frameWidth * frameHeight;
if (framePixels > MAX_FAVICON_SOURCE_PIXELS) return null;
width = Math.max(width, left + frameWidth);
height = Math.max(height, top + frameHeight);
if (!safeDimensions({ width, height })) return null;
const framePacked = buffer[offset + 9]!;
offset += 10;
if ((framePacked & 0x80) !== 0) {
offset += 3 * 2 ** ((framePacked & 0x07) + 1);
}
if (offset >= buffer.byteLength) return null;
const minimumCodeSize = buffer[offset]!;
if (minimumCodeSize < 2 || minimumCodeSize > 8) return null;
offset += 1;
const nextOffset = skipGifSubBlocks(buffer, offset);
if (nextOffset === null) return null;
offset = nextOffset;
frameCount += 1;
continue;
}
if (marker !== 0x21 || offset + 2 > buffer.byteLength) return null;
const nextOffset = skipGifSubBlocks(buffer, offset + 2);
if (nextOffset === null) return null;
offset = nextOffset;
}
return null;
}
interface JpegExifMetadata {
readonly complete: boolean;
readonly orientation: number | null;
}
function jpegExifMetadata(segment: Buffer): JpegExifMetadata | null {
if (segment.byteLength <= 6 || segment.subarray(0, 5).toString("binary") !== "Exif\0") {
return null;
}
const metadataWithoutOrientation = (): JpegExifMetadata => ({
complete: true,
orientation: null,
});
if (segment.byteLength < 14) return metadataWithoutOrientation();
const tiffOffset = 6;
const littleEndian = segment[tiffOffset] === 0x49 && segment[tiffOffset + 1] === 0x49;
const bigEndian = segment[tiffOffset] === 0x4d && segment[tiffOffset + 1] === 0x4d;
if (!littleEndian && !bigEndian) return metadataWithoutOrientation();
const readUInt16 = (offset: number): number | null => {
if (offset < 0 || offset + 2 > segment.byteLength) return null;
return littleEndian ? segment.readUInt16LE(offset) : segment.readUInt16BE(offset);
};
const readUInt32 = (offset: number): number | null => {
if (offset < 0 || offset + 4 > segment.byteLength) return null;
return littleEndian ? segment.readUInt32LE(offset) : segment.readUInt32BE(offset);
};
const relativeIfdOffset = readUInt32(tiffOffset + 4);
if (relativeIfdOffset === null) return metadataWithoutOrientation();
// Keep untrusted metadata parsing linear even when IFD pointers overlap.
let remainingIfdEntryVisits = Math.ceil(segment.byteLength / 12);
const budgetExhausted = Symbol("ifd-entry-budget-exhausted");
type IfdOrientation = number | null | typeof budgetExhausted;
const subIfdOrientationByOffset = new Map<number, number | null>();
const readIfdOrientation = (ifdOffset: number, isRoot: boolean): IfdOrientation => {
if (!isRoot && subIfdOrientationByOffset.has(ifdOffset)) {
return subIfdOrientationByOffset.get(ifdOffset) ?? null;
}
const entryCount = readUInt16(ifdOffset);
if (entryCount === null) return null;
let result: IfdOrientation = null;
for (let index = 0; index < entryCount; index += 1) {
if (remainingIfdEntryVisits === 0) return budgetExhausted;
remainingIfdEntryVisits -= 1;
const entryOffset = ifdOffset + 2 + index * 12;
if (entryOffset + 12 > segment.byteLength) break;
const tag = readUInt16(entryOffset);
const type = readUInt16(entryOffset + 2);
const count = readUInt32(entryOffset + 4);
if (tag === 0x0112 && type === 3 && count === 1) {
const orientation = readUInt16(entryOffset + 8);
if (orientation !== null && orientation >= 1 && orientation <= 8) {
result = orientation;
break;
}
} else if (isRoot && tag === 0x8769 && type === 4 && count === 1) {
const relativeSubIfdOffset = readUInt32(entryOffset + 8);
if (relativeSubIfdOffset !== null) {
const orientation = readIfdOrientation(tiffOffset + relativeSubIfdOffset, false);
if (orientation === budgetExhausted) return budgetExhausted;
if (orientation !== null) {
result = orientation;
break;
}
}
}
}
if (!isRoot) subIfdOrientationByOffset.set(ifdOffset, result);
return result;
};
const orientation = readIfdOrientation(tiffOffset + relativeIfdOffset, true);
return orientation === budgetExhausted
? { complete: false, orientation: null }
: { complete: true, orientation };
}
function jpegDimensions(buffer: Buffer): ImageDimensions | null {
if (buffer.byteLength < 4 || buffer[0] !== 0xff || buffer[1] !== 0xd8) return null;
const startOfFrameMarkers = new Set([
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
]);
let offset = 2;
let dimensions: ImageDimensions | null = null;
let exifMetadata: JpegExifMetadata | null = null;
while (offset + 3 < buffer.byteLength) {
if (buffer[offset] !== 0xff) {
offset += 1;
continue;
}
while (buffer[offset] === 0xff) offset += 1;
const marker = buffer[offset];
offset += 1;
if (marker === undefined || marker === 0xd9 || marker === 0xda) break;
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) continue;
if (offset + 1 >= buffer.byteLength) return null;
const length = buffer.readUInt16BE(offset);
if (length < 2 || offset + length > buffer.byteLength) return null;
if (marker === 0xe1 && exifMetadata === null) {
exifMetadata = jpegExifMetadata(buffer.subarray(offset + 2, offset + length));
}
if (startOfFrameMarkers.has(marker)) {
if (length < 7) return null;
if (dimensions !== null) return null;
dimensions = {
height: buffer.readUInt16BE(offset + 3),
width: buffer.readUInt16BE(offset + 5),
};
}
offset += length;
}
if (!dimensions) return null;
if (exifMetadata?.complete === false) return null;
const orientation = exifMetadata?.orientation;
return orientation !== undefined && orientation !== null && orientation >= 5 && orientation <= 8
? { width: dimensions.height, height: dimensions.width }
: dimensions;
}
function webpDimensions(buffer: Buffer): ImageDimensions | null {
if (
buffer.byteLength < 30 ||
buffer.subarray(0, 4).toString("ascii") !== "RIFF" ||
buffer.subarray(8, 12).toString("ascii") !== "WEBP"
) {
return null;
}
const kind = buffer.subarray(12, 16).toString("ascii");
if (kind === "VP8X") {
return {
width: 1 + buffer.readUIntLE(24, 3),
height: 1 + buffer.readUIntLE(27, 3),
};
}
if (kind === "VP8 " && buffer.subarray(23, 26).equals(Buffer.from([0x9d, 0x01, 0x2a]))) {
return {
width: buffer.readUInt16LE(26) & 0x3fff,
height: buffer.readUInt16LE(28) & 0x3fff,
};
}
if (kind === "VP8L" && buffer[20] === 0x2f) {
return {
width: 1 + buffer[21]! + ((buffer[22]! & 0x3f) << 8),
height: 1 + (buffer[22]! >> 6) + (buffer[23]! << 2) + ((buffer[24]! & 0x0f) << 10),
};
}
return null;
}
function dibDimensions(buffer: Buffer): ImageDimensions | null {
if (buffer.byteLength < 12) return null;
const headerSize = buffer.readUInt32LE(0);
if (headerSize === 12) {
return {
width: buffer.readUInt16LE(4),
height: buffer.readUInt16LE(6),
};
}
if (headerSize < 40 || buffer.byteLength < 12) return null;
return {
width: Math.abs(buffer.readInt32LE(4)),
height: Math.abs(buffer.readInt32LE(8)),
};
}
function icoDimensions(buffer: Buffer): ImageDimensions | null {
if (
buffer.byteLength < 22 ||
buffer.readUInt16LE(0) !== 0 ||
(buffer.readUInt16LE(2) !== 1 && buffer.readUInt16LE(2) !== 2)
) {
return null;
}
const count = buffer.readUInt16LE(4);
if (count === 0 || count > 256 || buffer.byteLength < 6 + count * 16) return null;
let width = 0;
let height = 0;
for (let index = 0; index < count; index += 1) {
const offset = 6 + index * 16;
width = Math.max(width, buffer[offset] === 0 ? 256 : buffer[offset]!);
height = Math.max(height, buffer[offset + 1] === 0 ? 256 : buffer[offset + 1]!);
if (!safeDimensions({ width, height })) return null;
const byteLength = buffer.readUInt32LE(offset + 8);
const imageOffset = buffer.readUInt32LE(offset + 12);
if (
byteLength === 0 ||
imageOffset < 6 + count * 16 ||
imageOffset > buffer.byteLength ||
byteLength > buffer.byteLength - imageOffset
)
return null;
const embedded = buffer.subarray(imageOffset, imageOffset + byteLength);
const embeddedDimensions = pngDimensions(embedded) ?? dibDimensions(embedded);
if (!safeDimensions(embeddedDimensions)) return null;
}
return { width, height };
}
function sourceDimensions(buffer: Buffer): ImageDimensions | null {
return (
pngDimensions(buffer) ??
gifDimensions(buffer) ??
jpegDimensions(buffer) ??
webpDimensions(buffer) ??
icoDimensions(buffer)
);
}
async function normalizeFaviconBuffer(
webContents: Electron.WebContents,
mime: string | null,
buffer: Buffer,
signal: AbortSignal,
): Promise<FaviconCaptureResult> {
const declaredMime = mime?.trim().toLowerCase() || null;
const normalizedMime =
declaredMime === "application/x-icon"
? "image/x-icon"
: declaredMime === "application/octet-stream" || declaredMime === "binary/octet-stream"
? null
: declaredMime;
const dimensions = sourceDimensions(buffer);
if (
(normalizedMime !== null && !/^image\/[a-z0-9.+-]+$/i.test(normalizedMime)) ||
normalizedMime === "image/svg+xml" ||
buffer.byteLength > MAX_FAVICON_RESPONSE_BYTES ||
!safeDimensions(dimensions)
) {
return { kind: "none" };
}
const rasterized = await rasterizeFavicon(
webContents,
normalizedMime,
buffer,
dimensions,
signal,
);
if (rasterized.kind === "timed-out") return rasterized;
return typeof rasterized.value === "string" &&
rasterized.value.startsWith("data:image/png;base64,") &&
rasterized.value.length <= FAVICON_DATA_URL_MAX_LENGTH
? { kind: "captured", dataUrl: rasterized.value }
: { kind: "none" };
}
async function rasterizeFavicon(
webContents: Electron.WebContents,
mime: string | null,
buffer: Buffer,
dimensions: ImageDimensions,
signal: AbortSignal,
): Promise<RasterizationResult> {
const gate = rasterizationGates.get(webContents) ?? { generation: 0 };
rasterizationGates.set(webContents, gate);
const generation = ++gate.generation;
const previousLaunchAllowed = gate.launchAllowed;
if (previousLaunchAllowed) {
await waitForRasterLaunch(previousLaunchAllowed, signal);
}
if (signal.aborted || generation !== gate.generation) {
return { kind: "completed", value: null };
}
const payload = buffer.toString("base64");
const blobType = mime ?? "";
const scale = Math.min(32 / dimensions.width, 32 / dimensions.height);
const decodeWidth = Math.max(1, Math.round(dimensions.width * scale));
const decodeHeight = Math.max(1, Math.round(dimensions.height * scale));
const drawX = (32 - decodeWidth) / 2;
const drawY = (32 - decodeHeight) / 2;
const code = `
(() => {
const rasterize = async () => {
try {
const source = Uint8Array.from(atob("${payload}"), (char) => char.charCodeAt(0));
const bitmap = await createImageBitmap(new Blob([source], { type: "${blobType}" }), {
resizeWidth: ${decodeWidth},
resizeHeight: ${decodeHeight},
resizeQuality: "high",
});
try {
if (bitmap.width <= 0 || bitmap.height <= 0 || bitmap.width * bitmap.height > ${MAX_FAVICON_SOURCE_PIXELS}) {
return null;
}
const canvas = new OffscreenCanvas(32, 32);
const context = canvas.getContext("2d");
if (!context) return null;
context.drawImage(bitmap, ${drawX}, ${drawY}, ${decodeWidth}, ${decodeHeight});
const blob = await canvas.convertToBlob({ type: "image/png" });
const output = new Uint8Array(await blob.arrayBuffer());
let binary = "";
for (const byte of output) binary += String.fromCharCode(byte);
return "data:image/png;base64," + btoa(binary);
} finally {
bitmap.close();
}
} catch {
return null;
}
};
return rasterize();
})()
`;
const execution = webContents.executeJavaScriptInIsolatedWorld(FAVICON_RASTER_WORLD_ID, [
{ code },
]);
const result = new Promise<RasterizationResult>((resolve, reject) => {
// Electron cannot cancel isolated-world execution. This timeout ends only
// the logical attempt; renderer work may finish after a newer attempt starts.
const timeout = AbortSignal.timeout(FAVICON_RASTER_TIMEOUT_MS);
let settled = false;
const finish = (complete: () => void) => {
if (settled) return;
settled = true;
timeout.removeEventListener("abort", onTimeout);
signal.removeEventListener("abort", onAbort);
complete();
};
const onTimeout = () => {
finish(() => resolve({ kind: "timed-out" }));
};
const onAbort = () => {
finish(() => resolve({ kind: "completed", value: null }));
};
timeout.addEventListener("abort", onTimeout, { once: true });
signal.addEventListener("abort", onAbort, { once: true });
void execution.then(
(value) => {
finish(() => resolve({ kind: "completed", value }));
},
(cause: unknown) => {
finish(() => reject(cause));
},
);
if (signal.aborted) onAbort();
});
// The logical timeout does not cancel Electron's renderer work. Keep the
// gate closed until that physical execution actually settles.
const launchAllowed = execution.then(
() => undefined,
() => undefined,
);
gate.launchAllowed = launchAllowed;
void launchAllowed.then(() => {
if (gate.launchAllowed === launchAllowed) delete gate.launchAllowed;
});
return await result;
}
@@ -4,3 +4,4 @@ export const ELEMENT_PICKED_CHANNEL = "preview:element-picked";
export const ANNOTATION_CAPTURED_CHANNEL = "preview:annotation-captured";
export const ANNOTATION_THEME_CHANNEL = "preview:annotation-theme";
export const HUMAN_INPUT_CHANNEL = "preview:human-input";
export const MOUSE_NAVIGATE_CHANNEL = "preview:mouse-navigate";
+808 -15
View File
@@ -36,6 +36,28 @@ describe("fitPictureInPictureContentSize", () => {
});
});
describe("isPreviewRefreshShortcut", () => {
const input = (overrides: Partial<Electron.Input> = {}) =>
({
type: "keyDown",
key: "r",
meta: true,
control: false,
shift: false,
alt: false,
...overrides,
}) as Electron.Input;
it("recognizes the platform refresh chord without matching modified variants", () => {
expect(PreviewManager.isPreviewRefreshShortcut(input())).toBe(true);
expect(PreviewManager.isPreviewRefreshShortcut(input({ meta: false, control: true }))).toBe(
true,
);
expect(PreviewManager.isPreviewRefreshShortcut(input({ shift: true }))).toBe(false);
expect(PreviewManager.isPreviewRefreshShortcut(input({ type: "keyUp" }))).toBe(false);
});
});
const {
browserWindowConstructor,
createFromPath,
@@ -164,6 +186,102 @@ const makeTestPreviewWebContents = (
capturePage,
}) as never;
const TEST_FAVICON = "data:image/png;base64,cG5n";
const makeSourcePng = (width = 1, height = 1): Buffer => {
const buffer = Buffer.alloc(24);
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(buffer);
buffer.writeUInt32BE(width, 16);
buffer.writeUInt32BE(height, 20);
return buffer;
};
const makeFaviconWebContents = (options?: {
readonly fetch?: (url: string, init?: RequestInit) => Promise<Response>;
readonly id?: number;
readonly rasterize?: (code: string) => Promise<unknown>;
readonly url?: string;
}) => {
const sourcePng = makeSourcePng();
const listeners = new Map<string, (...args: never[]) => void>();
let currentUrl = options?.url ?? "http://localhost:3200/";
let destroyed = false;
let loading = false;
const fetch = vi.fn(
options?.fetch ??
(async () =>
new Response(new Uint8Array(sourcePng), {
headers: { "content-type": "image/png" },
})),
);
const executeJavaScriptInIsolatedWorld = vi.fn(
async (_worldId: number, scripts: ReadonlyArray<{ readonly code: string }>) =>
options?.rasterize ? options.rasterize(scripts[0]?.code ?? "") : TEST_FAVICON,
);
const reload = vi.fn();
const loadURL = vi.fn(async (url: string) => {
currentUrl = url;
});
const off = vi.fn();
const debuggerOff = vi.fn();
const webContents = {
id: options?.id ?? 42,
isDestroyed: () => destroyed,
getType: () => "webview",
getURL: () => currentUrl,
getTitle: () => "Preview",
isLoading: () => loading,
isDevToolsOpened: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
reload,
reloadIgnoringCache: vi.fn(),
loadURL,
on: vi.fn((event: string, listener: (...args: never[]) => void) => {
listeners.set(event, listener);
}),
off,
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
session: { fetch },
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
executeJavaScriptInIsolatedWorld,
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: debuggerOff,
},
};
return {
executeJavaScriptInIsolatedWorld,
fetch,
debuggerOff,
listeners,
loadURL,
off,
reload,
setDestroyed: (value: boolean) => {
destroyed = value;
},
setLoading: (value: boolean) => {
loading = value;
},
setUrl: (url: string) => {
currentUrl = url;
},
webContents: webContents as never,
};
};
const settle = function* (until: () => boolean) {
for (let attempt = 0; attempt < 30 && !until(); attempt++) {
yield* Effect.promise(() => Promise.resolve());
}
};
const makeTestPictureInPictureWindow = (loadURL: () => Promise<void> = async () => undefined) => {
const listeners = new Map<string, () => void>();
const send = vi.fn();
@@ -235,6 +353,32 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("rejects a destroyed webview during registration", () =>
withManager((manager) =>
Effect.gen(function* () {
const getType = vi.fn(() => "webview" as const);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => true,
getType,
} as never);
yield* manager.createTab("tab_destroyed_registration");
const exit = yield* Effect.exit(manager.registerWebview("tab_destroyed_registration", 42));
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Option.getOrThrow(Cause.findErrorOption(exit.cause))).toMatchObject({
_tag: "PreviewWebContentsNotFoundError",
tabId: "tab_destroyed_registration",
webContentsId: 42,
});
}
expect(getType).not.toHaveBeenCalled();
}),
),
);
effectIt.effect("isolates failed state listeners and continues delivery", () => {
const loggedErrors: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
@@ -353,7 +497,492 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
effectIt.effect("detaches a destroyed webview instead of navigating it", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_destroyed_navigation");
yield* manager.registerWebview("tab_destroyed_navigation", 42);
yield* manager.setColorScheme("tab_destroyed_navigation", "dark");
preview.setDestroyed(true);
yield* manager.navigate("tab_destroyed_navigation", "https://example.com/");
expect(preview.loadURL).not.toHaveBeenCalled();
expect(preview.reload).not.toHaveBeenCalled();
expect(preview.off).toHaveBeenCalled();
expect(preview.debuggerOff).toHaveBeenCalled();
expect(states.at(-1)).toMatchObject({
webContentsId: null,
navStatus: { kind: "Loading", url: "https://example.com/" },
});
}),
),
);
effectIt.effect("does not let destroyed-webview cleanup detach a same-id replacement", () =>
withManager((manager) =>
Effect.gen(function* () {
const previous = makeFaviconWebContents();
const replacement = makeFaviconWebContents({ url: "https://example.com/" });
let current = previous.webContents;
let startReplacementRegistration: () => void = () => void 0;
const replacementReady = new Promise<void>((resolve) => {
startReplacementRegistration = resolve;
});
fromId.mockImplementation(() => current);
yield* manager.createTab("tab_destroyed_replacement_race");
yield* manager.registerWebview("tab_destroyed_replacement_race", 42);
yield* manager.setColorScheme("tab_destroyed_replacement_race", "dark");
const replacementRegistration = yield* Effect.promise(() => replacementReady).pipe(
Effect.flatMap(() => manager.registerWebview("tab_destroyed_replacement_race", 42)),
Effect.forkChild({ startImmediately: true }),
);
previous.setDestroyed(true);
previous.debuggerOff.mockImplementationOnce(() => {
current = replacement.webContents;
startReplacementRegistration();
});
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.navigate("tab_destroyed_replacement_race", "https://example.com/");
const registrationExit = yield* Fiber.await(replacementRegistration);
expect(Exit.isSuccess(registrationExit)).toBe(true);
expect(previous.off).toHaveBeenCalled();
expect(replacement.off).not.toHaveBeenCalled();
expect(states.at(-1)).toMatchObject({
webContentsId: 42,
navStatus: { kind: "Loading", url: "https://example.com/" },
});
}),
),
);
effectIt.effect("publishes a canonical favicon origin while the page is loading", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents({
url: `http://localhost:3200/${"x".repeat(3_000)}`,
});
preview.setLoading(true);
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_loading");
yield* manager.registerWebview("tab_favicon_loading", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
expect(states.at(-1)?.favicon).toMatchObject({
dataUrl: TEST_FAVICON,
pageUrl: "http://localhost:3200",
});
expect(states.at(-1)?.favicon?.capturedAt).toEqual(expect.any(Number));
}),
),
);
effectIt.effect("shares an identical in-flight event and lets a changed event win", () =>
withManager((manager) =>
Effect.gen(function* () {
let resolveFirst!: (response: Response) => void;
const firstResponse = new Promise<Response>((resolve) => {
resolveFirst = resolve;
});
const preview = makeFaviconWebContents({
fetch: (url) =>
url.endsWith("first.png")
? firstResponse
: Promise.resolve(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
),
});
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_latest");
yield* manager.registerWebview("tab_favicon_latest", 42);
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
faviconUpdated({} as never, ["http://localhost:3200/first.png"] as never);
yield* settle(() => preview.fetch.mock.calls.length === 1);
faviconUpdated({} as never, ["http://localhost:3200/second.png"] as never);
yield* settle(() => states.at(-1)?.favicon !== undefined);
resolveFirst(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
);
yield* settle(() => false);
expect(preview.fetch).toHaveBeenCalledTimes(2);
expect(states.filter((state) => state.favicon !== undefined)).toHaveLength(1);
}),
),
);
effectIt.effect("allows an identical retry after an undecodable capture", () =>
withManager((manager) =>
Effect.gen(function* () {
let rasterizations = 0;
const preview = makeFaviconWebContents({
rasterize: async () => (++rasterizations === 1 ? null : TEST_FAVICON),
});
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_retry");
yield* manager.registerWebview("tab_favicon_retry", 42);
const faviconUpdated = preview.listeners.get("page-favicon-updated")!;
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
yield* settle(() => rasterizations === 1);
yield* settle(() => false);
faviconUpdated({} as never, ["http://localhost:3200/favicon.png"] as never);
yield* settle(() => states.at(-1)?.favicon !== undefined);
expect(rasterizations).toBe(2);
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
effectIt.effect("does not publish a capture invalidated by navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let resolveFetch!: (response: Response) => void;
const preview = makeFaviconWebContents({
fetch: () =>
new Promise<Response>((resolve) => {
resolveFetch = resolve;
}),
});
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_navigation");
yield* manager.registerWebview("tab_favicon_navigation", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => preview.fetch.mock.calls.length === 1);
preview.listeners.get("did-start-navigation")?.({
isMainFrame: true,
isSameDocument: false,
} as never);
preview.setUrl("https://example.com/");
resolveFetch(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
);
yield* settle(() => false);
expect(states.some((state) => state.favicon !== undefined)).toBe(false);
}),
),
);
effectIt.effect("retains a favicon when reloading the current URL without a new event", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_reload");
yield* manager.registerWebview("tab_favicon_reload", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
yield* manager.navigate("tab_favicon_reload", "http://localhost:3200/");
expect(preview.reload).toHaveBeenCalledOnce();
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
effectIt.effect("clears a published favicon after a confirmed cross-origin navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_origin");
yield* manager.registerWebview("tab_favicon_origin", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
preview.setUrl("https://example.com/");
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
expect(states.at(-1)?.favicon).toBeUndefined();
}),
),
);
effectIt.effect(
"retains the previous document icon across a failed cross-origin navigation",
() =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_failed_origin");
yield* manager.registerWebview("tab_favicon_failed_origin", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
preview.listeners.get("did-fail-load")?.(
{} as never,
-105 as never,
"Name not resolved" as never,
"https://unreachable.example/" as never,
true as never,
);
yield* settle(() => states.at(-1)?.navStatus.kind === "LoadFailed");
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
effectIt.effect("does not resurrect an icon after a confirmed about:blank document", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_blank");
yield* manager.registerWebview("tab_favicon_blank", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
preview.setUrl("about:blank");
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Idle");
expect(states.at(-1)?.favicon).toBeUndefined();
preview.setUrl("http://localhost:3200/");
preview.listeners.get("did-navigate")?.({} as never);
yield* settle(() => states.at(-1)?.navStatus.kind === "Success");
expect(states.at(-1)?.favicon).toBeUndefined();
}),
),
);
effectIt.effect("clears a published favicon when a replacement webview attaches", () =>
withManager((manager) =>
Effect.gen(function* () {
const initial = makeFaviconWebContents({ id: 42 });
const replacement = makeFaviconWebContents({ id: 43 });
fromId.mockImplementation((id?: number) => {
if (id === 42) return initial.webContents;
if (id === 43) return replacement.webContents;
return null;
});
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_replace");
yield* manager.registerWebview("tab_favicon_replace", 42);
initial.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
yield* manager.registerWebview("tab_favicon_replace", 43);
expect(states.at(-1)?.webContentsId).toBe(43);
expect(states.at(-1)?.favicon).toBeUndefined();
}),
),
);
effectIt.effect("ignores an old capture that completes after webview replacement", () =>
withManager((manager) =>
Effect.gen(function* () {
let resolveFetch!: (response: Response) => void;
const initial = makeFaviconWebContents({
id: 42,
fetch: () =>
new Promise<Response>((resolve) => {
resolveFetch = resolve;
}),
});
const replacement = makeFaviconWebContents({ id: 43 });
fromId.mockImplementation((id?: number) =>
id === 42 ? initial.webContents : id === 43 ? replacement.webContents : null,
);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_late_replace");
yield* manager.registerWebview("tab_favicon_late_replace", 42);
initial.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => initial.fetch.mock.calls.length === 1);
yield* manager.registerWebview("tab_favicon_late_replace", 43);
resolveFetch(
new Response(new Uint8Array(makeSourcePng()), {
headers: { "content-type": "image/png" },
}),
);
yield* settle(() => false);
expect(states.at(-1)?.webContentsId).toBe(43);
expect(
states.some((state) => state.webContentsId === 43 && state.favicon !== undefined),
).toBe(false);
}),
),
);
effectIt.effect("treats a reused WebContents id as a new attachment", () =>
withManager((manager) =>
Effect.gen(function* () {
const initial = makeFaviconWebContents({ id: 42 });
const replacement = makeFaviconWebContents({ id: 42 });
let active = initial.webContents;
fromId.mockImplementation(() => active);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_reused_id");
yield* manager.registerWebview("tab_favicon_reused_id", 42);
initial.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
active = replacement.webContents;
yield* manager.registerWebview("tab_favicon_reused_id", 42);
expect(states.at(-1)?.favicon).toBeUndefined();
expect(initial.off).toHaveBeenCalled();
expect(replacement.listeners.has("page-favicon-updated")).toBe(true);
}),
),
);
effectIt.effect("preserves a favicon when the active attachment registers again", () =>
withManager((manager) =>
Effect.gen(function* () {
const preview = makeFaviconWebContents();
fromId.mockReturnValue(preview.webContents);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_favicon_reregister");
yield* manager.registerWebview("tab_favicon_reregister", 42);
preview.listeners.get("page-favicon-updated")?.(
{} as never,
["http://localhost:3200/favicon.png"] as never,
);
yield* settle(() => states.at(-1)?.favicon !== undefined);
yield* manager.registerWebview("tab_favicon_reregister", 42);
expect(states.at(-1)?.favicon?.dataUrl).toBe(TEST_FAVICON);
}),
),
);
// The guest reports whatever zoom level Chromium handed it from the app
// window, so the tab's own zoom is the source of truth in both directions:
// asserted onto every guest, never read back off one.
effectIt.effect("keeps the tab's own zoom instead of the guest's reported zoom", () =>
withManager((manager) =>
Effect.gen(function* () {
let effectiveZoom = 0.9;
@@ -399,18 +1028,13 @@ describe("PreviewManager", () => {
yield* manager.createTab("tab_zoom");
yield* manager.registerWebview("tab_zoom", 42);
expect(states.at(-1)?.zoomFactor).toBe(0.9);
expect(setZoomFactor).not.toHaveBeenCalled();
expect(states.at(-1)?.zoomFactor).toBe(1);
expect(setZoomFactor).toHaveBeenCalledWith(1);
effectiveZoom = 1.25;
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(setZoomFactor).not.toHaveBeenCalled();
zoomReadable = false;
url = "https://example.com/after-zoom-read-failed";
// An app zoom leaves the guest reporting the inherited level. Navigating
// must not adopt it as the preview's zoom.
effectiveZoom = 0.8;
url = "https://example.com/after-app-zoom";
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
@@ -419,7 +1043,18 @@ describe("PreviewManager", () => {
url,
title: "Example",
});
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1);
// Only the preview's own zoom controls move it.
yield* manager.zoomIn("tab_zoom");
expect(setZoomFactor).toHaveBeenCalledWith(1.1);
expect(states.at(-1)?.zoomFactor).toBe(1.1);
zoomReadable = false;
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.zoomFactor).toBe(1.1);
const replacementSetZoomFactor = vi.fn();
fromId.mockReturnValue({
@@ -448,8 +1083,103 @@ describe("PreviewManager", () => {
yield* manager.registerWebview("tab_zoom", 43);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1.25);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.1);
expect(states.at(-1)?.zoomFactor).toBe(1.1);
}),
),
);
// Zooming the app UI pushes the window's zoom level onto every guest, so the
// preview has to be put back at the zoom the user gave it.
effectIt.effect("re-applies each tab's own zoom when the app window zooms", () =>
withManager((manager) =>
Effect.gen(function* () {
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor,
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_reapply");
yield* manager.registerWebview("tab_reapply", 42);
yield* manager.zoomIn("tab_reapply");
setZoomFactor.mockClear();
yield* manager.reapplyZoom();
expect(setZoomFactor).toHaveBeenCalledTimes(1);
expect(setZoomFactor).toHaveBeenCalledWith(1.1);
}),
),
);
// did-attach and dom-ready both re-register the guest that is already
// attached, and a guest that just inherited the app window's zoom needs its
// own back — without that round trip republishing tab state.
effectIt.effect("re-asserts the tab's zoom when the active guest registers again", () =>
withManager((manager) =>
Effect.gen(function* () {
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor,
on: vi.fn(),
off: vi.fn(),
ipc: { on: vi.fn(), off: vi.fn() },
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
const states: PreviewManager.PreviewTabState[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
states.push(state);
}),
);
yield* manager.createTab("tab_reregister_zoom");
yield* manager.registerWebview("tab_reregister_zoom", 42);
yield* manager.zoomIn("tab_reregister_zoom");
setZoomFactor.mockClear();
const publishedBefore = states.length;
yield* manager.registerWebview("tab_reregister_zoom", 42);
expect(setZoomFactor).toHaveBeenCalledWith(1.1);
expect(states.length).toBe(publishedBefore);
expect(states.at(-1)?.zoomFactor).toBe(1.1);
}),
),
);
@@ -1509,6 +2239,69 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("navigates the guest history when the thumb-button ipc fires", () =>
withManager((manager) =>
Effect.gen(function* () {
let mouseNavigate: ((event: unknown, payload: unknown) => void) | undefined;
const goBack = vi.fn();
const goForward = vi.fn();
let canGoBack = true;
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof mouseNavigate) => {
if (channel === "preview:mouse-navigate") mouseNavigate = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: {
canGoBack: () => canGoBack,
canGoForward: () => true,
goBack,
goForward,
},
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand: vi.fn(async () => undefined),
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_nav");
yield* manager.registerWebview("tab_nav", 42);
expect(mouseNavigate).toBeDefined();
mouseNavigate?.({}, { direction: "back" });
yield* Effect.yieldNow;
expect(goBack).toHaveBeenCalledOnce();
mouseNavigate?.({}, { direction: "forward" });
yield* Effect.yieldNow;
expect(goForward).toHaveBeenCalledOnce();
// Ignores unknown payloads and never navigates when history is exhausted.
mouseNavigate?.({}, { direction: "sideways" });
canGoBack = false;
mouseNavigate?.({}, { direction: "back" });
yield* Effect.yieldNow;
expect(goBack).toHaveBeenCalledOnce();
}),
),
);
effectIt.effect("reveals only files inside the configured browser artifact directory", () =>
withManager((manager) =>
Effect.gen(function* () {
+326 -56
View File
@@ -8,12 +8,15 @@
import type {
DesktopPreviewAnnotationTheme,
DesktopPreviewColorScheme,
DesktopPreviewFavicon,
DesktopPreviewPointerEvent,
PreviewAnnotationPayload,
PreviewAnnotationRect,
PreviewAnnotationSubmissionResult,
DesktopPreviewRecordingArtifact,
DesktopPreviewRecordingFrame,
DesktopPreviewScreenshotArtifact,
DesktopPreviewTabDefaults,
PreviewAutomationClickInput,
PreviewAutomationActionEvent,
PreviewAutomationConsoleEntry,
@@ -56,11 +59,13 @@ import {
CANCEL_PICK_CHANNEL,
ELEMENT_PICKED_CHANNEL,
HUMAN_INPUT_CHANNEL,
MOUSE_NAVIGATE_CHANNEL,
START_PICK_CHANNEL,
} from "./GuestProtocol.ts";
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
import { captureFavicon, safeHttpOrigin, selectFaviconCandidates } from "./FaviconCapture.ts";
export type PreviewNavStatus =
| { kind: "Idle" }
@@ -84,6 +89,7 @@ export interface PreviewTabState {
pictureInPicture: boolean;
colorScheme: DesktopPreviewColorScheme;
controller: "human" | "agent" | "none";
favicon?: DesktopPreviewFavicon;
updatedAt: string;
}
@@ -109,7 +115,7 @@ const DIAGNOSTIC_BUFFER_LIMIT = 200;
const MAX_ARTIFACT_SITE_SLUG_LENGTH = 80;
const AGENT_CURSOR_MOVE_MS = 160;
const AGENT_CURSOR_CLICK_LEAD_MS = 40;
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const DEFAULT_ANNOTATION_THEME: DesktopPreviewAnnotationTheme = {
colorScheme: "light",
radius: "0.625rem",
@@ -329,6 +335,21 @@ const findZoomStep = (current: number): number => {
return Math.abs(ZOOM_LEVELS[index]! - current) < ZOOM_EPSILON ? index : index - 1;
};
/**
* Clamp a client-supplied zoom factor onto the discrete ladder. The setting is
* chosen from the same ladder, but it arrives over IPC from a schema that only
* guarantees a positive number, so an out-of-band value snaps to the nearest
* step rather than leaving the guest at a zoom the zoom controls can't reach.
*/
const normalizeZoomFactor = (value: number | undefined): number => {
if (value === undefined || !Number.isFinite(value)) return DEFAULT_ZOOM_FACTOR;
let closest = ZOOM_LEVELS[0]!;
for (const level of ZOOM_LEVELS) {
if (Math.abs(level - value) < Math.abs(closest - value)) closest = level;
}
return closest;
};
const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
const step = findZoomStep(current);
if (direction === "in") {
@@ -345,7 +366,10 @@ type PreviewInputSignal =
| { readonly kind: "key"; readonly key: string; readonly code: string };
interface ManagedListeners {
readonly attachmentId: symbol;
readonly cancelFaviconCapture: () => void;
readonly scope: Scope.Closeable;
readonly webContents: Electron.WebContents;
}
type FrameCaptureConsumer = "picture-in-picture" | "recording";
@@ -406,6 +430,13 @@ const APP_FORWARDED_SHORTCUTS: ReadonlyArray<{
{ key: "w", meta: true, shift: false, control: false },
]);
export const isPreviewRefreshShortcut = (input: Electron.Input): boolean =>
input.type === "keyDown" &&
input.key.toLowerCase() === "r" &&
(input.meta || input.control) &&
!input.shift &&
!input.alt;
const isPreviewInputSignal = (value: unknown): value is PreviewInputSignal => {
if (typeof value !== "object" || value === null || !("kind" in value)) return false;
if (value.kind === "pointer") {
@@ -605,6 +636,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const emitIfCurrent = Effect.fn("PreviewManager.emitIfCurrent")(function* (
tabId: string,
state: PreviewTabState,
) {
if ((yield* SynchronizedRef.get(tabsRef)).get(tabId) === state) {
yield* emit(tabId, state);
}
});
const update = Effect.fn("PreviewManager.update")(function* (
tabId: string,
patch: Partial<PreviewTabState>,
@@ -624,6 +664,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
if (Option.isSome(next)) yield* emit(tabId, next.value);
});
/**
* Pushes a tab's zoom factor onto whichever guest it currently owns, reading
* both at call time. Anything that applies zoom after an await goes through
* here: a snapshot taken before the await can be older than a zoom action that
* landed in between, and re-applying it would roll that action back.
*/
const assertTabZoom = Effect.fn("PreviewManager.assertTabZoom")(function* (tabId: string) {
const tab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
if (!tab || tab.webContentsId == null) return;
const wc = webContents.fromId(tab.webContentsId);
if (!wc || wc.isDestroyed()) return;
yield* attempt({ operation: "assertTabZoom", tabId, webContentsId: wc.id }, () =>
wc.setZoomFactor(tab.zoomFactor),
).pipe(Effect.ignore);
});
const requireWebContents = Effect.fn("PreviewManager.requireWebContents")(function* (
tabId: string,
) {
@@ -1196,7 +1252,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
copy.delete(webContentsId);
}),
]);
if (managed) yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
if (managed) {
managed.cancelFaviconCapture();
yield* Scope.close(managed.scope, Exit.void).pipe(Effect.ignore);
}
});
const isAppShortcut = (input: Electron.Input): boolean =>
@@ -1260,21 +1319,34 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc: Electron.WebContents,
) {
const scope = yield* Scope.fork(parentScope, "sequential");
const attachmentId = Symbol();
let documentId = 0;
let nextRequestId = 0;
let activeCapture: {
readonly controller: AbortController;
readonly documentId: number;
readonly eventKey: string;
readonly requestId: number;
} | null = null;
const cancelFaviconCapture = () => {
documentId += 1;
activeCapture?.controller.abort();
activeCapture = null;
};
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
preserveLoadFailure: boolean,
confirmedNavigation = false,
) {
if (wc.isDestroyed()) return;
const zoomFactor = yield* attempt(
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
() => wc.getZoomFactor(),
).pipe(Effect.option);
const computedNavStatus = computeNavStatus(wc);
const canGoBack = wc.navigationHistory.canGoBack();
const canGoForward = wc.navigationHistory.canGoForward();
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
if (!current || current.webContentsId !== wc.id || webContents.fromId(wc.id) !== wc) {
return [Option.none<PreviewTabState>(), tabs] as const;
}
// Electron emits did-stop-loading after did-fail-load. At that point the
// failed guest is no longer "loading", but it has not successfully
// navigated anywhere. Keep the failure until a new load actually starts.
@@ -1284,12 +1356,20 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
computedNavStatus.kind === "Success"
? current.navStatus
: computedNavStatus;
const clearFavicon =
confirmedNavigation &&
current.favicon !== undefined &&
safeHttpOrigin(current.favicon.pageUrl) !==
safeHttpOrigin(navStatus.kind === "Idle" ? wc.getURL() : navStatus.url);
const { favicon: _favicon, ...currentWithoutFavicon } = current;
const state: PreviewTabState = {
...current,
...(clearFavicon ? currentWithoutFavicon : current),
navStatus,
canGoBack,
canGoForward,
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
// zoomFactor is deliberately not read back from the guest: Chromium
// reports the level it inherited from the app window, so mirroring it
// would turn an app zoom into the preview's own zoom.
updatedAt,
};
return [
@@ -1299,10 +1379,109 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}),
] as const;
});
if (Option.isSome(next)) yield* emit(tabId, next.value);
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
});
const sync = () => runFork(syncState(true));
const syncNavigation = () => runFork(syncState(false));
const syncNavigation = () => runFork(syncState(false, true));
const syncInPageNavigation = () => runFork(syncState(false));
const navigationStarted = (
event: Electron.Event<Electron.WebContentsDidStartNavigationEventParams>,
) => {
if (event.isMainFrame && !event.isSameDocument) cancelFaviconCapture();
};
const publishFavicon = Effect.fn("PreviewManager.publishFavicon")(function* (input: {
readonly captureDocumentId: number;
readonly dataUrl: string;
readonly pageUrl: string;
readonly requestId: number;
}) {
const pageOrigin = safeHttpOrigin(input.pageUrl);
const managed = (yield* Ref.get(attachedRef)).get(wc.id);
if (
!pageOrigin ||
wc.isDestroyed() ||
webContents.fromId(wc.id) !== wc ||
managed?.attachmentId !== attachmentId ||
activeCapture?.documentId !== input.captureDocumentId ||
activeCapture.requestId !== input.requestId ||
safeHttpOrigin(wc.getURL()) !== pageOrigin
) {
return;
}
const capturedAt = yield* currentMillis;
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (
!current ||
current.webContentsId !== wc.id ||
webContents.fromId(wc.id) !== wc ||
activeCapture?.documentId !== input.captureDocumentId ||
activeCapture.requestId !== input.requestId
) {
return [Option.none<PreviewTabState>(), tabs] as const;
}
const state: PreviewTabState = {
...current,
favicon: { dataUrl: input.dataUrl, pageUrl: pageOrigin, capturedAt },
updatedAt,
};
return [
Option.some(state),
replaceMap(tabs, (copy) => {
copy.set(tabId, state);
}),
] as const;
});
if (Option.isSome(next)) yield* emitIfCurrent(tabId, next.value);
});
const faviconUpdated = (_event: Event, rawCandidates: ReadonlyArray<string>): void => {
const pageUrl = wc.getURL();
if (!safeHttpOrigin(pageUrl)) return;
const candidates = selectFaviconCandidates(rawCandidates);
if (candidates.length === 0) return;
const eventKey = JSON.stringify([pageUrl, ...candidates]);
if (activeCapture?.eventKey === eventKey) return;
activeCapture?.controller.abort();
const captureDocumentId = documentId;
const requestId = ++nextRequestId;
const controller = new AbortController();
activeCapture = { controller, documentId: captureDocumentId, eventKey, requestId };
runFork(
Effect.tryPromise({
try: () =>
captureFavicon({ webContents: wc, pageUrl, candidates, signal: controller.signal }),
catch: (cause) =>
new PreviewOperationError({
operation: "captureFavicon",
tabId,
webContentsId: wc.id,
cause,
}),
}).pipe(
Effect.flatMap((result) =>
result.kind === "captured"
? publishFavicon({
captureDocumentId,
dataUrl: result.dataUrl,
pageUrl,
requestId,
})
: Effect.void,
),
Effect.catch((error) =>
controller.signal.aborted
? Effect.void
: Effect.logDebug("Favicon capture failed.", { error, tabId, webContentsId: wc.id }),
),
Effect.ensuring(
Effect.sync(() => {
if (activeCapture?.requestId === requestId) activeCapture = null;
}),
),
),
);
};
const failed = (
_event: Event,
code: number,
@@ -1344,6 +1523,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const humanInput = (_event: unknown, rawSignal?: unknown): void => {
runFork(handleHumanInput(rawSignal));
};
const mouseNavigate = (_event: unknown, payload?: unknown): void => {
const direction =
typeof payload === "object" && payload !== null && "direction" in payload
? (payload as { direction?: unknown }).direction
: undefined;
if (direction !== "back" && direction !== "forward") return;
runFork(
attempt({ operation: "mouseNavigate", tabId, webContentsId: wc.id }, () => {
if (direction === "back") {
if (wc.navigationHistory.canGoBack()) wc.navigationHistory.goBack();
} else if (wc.navigationHistory.canGoForward()) {
wc.navigationHistory.goForward();
}
}).pipe(Effect.ignore),
);
};
const forwardShortcut = Effect.fn("PreviewManager.forwardShortcut")(function* (
event: Electron.Event,
input: Electron.Input,
@@ -1365,30 +1560,46 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
});
const beforeInput = (event: Electron.Event, input: Electron.Input): void => {
if (isPreviewRefreshShortcut(input)) {
event.preventDefault();
runFork(
attempt({ operation: "shortcut.refresh", tabId, webContentsId: wc.id }, () =>
wc.reload(),
).pipe(Effect.ignore),
);
return;
}
runFork(forwardShortcut(event, input));
};
yield* Scope.addFinalizer(
scope,
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
cancelFaviconCapture();
wc.off("did-start-navigation", navigationStarted);
wc.off("did-navigate", syncNavigation);
wc.off("did-navigate-in-page", syncNavigation);
wc.off("did-navigate-in-page", syncInPageNavigation);
wc.off("page-title-updated", sync);
wc.off("page-favicon-updated", faviconUpdated as never);
wc.off("did-start-loading", sync);
wc.off("did-stop-loading", sync);
wc.off("did-fail-load", failed as never);
wc.off("before-input-event", beforeInput);
wc.ipc.off(HUMAN_INPUT_CHANNEL, humanInput);
wc.ipc.off(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
}).pipe(Effect.ignore),
);
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
wc.on("did-start-navigation", navigationStarted);
wc.on("did-navigate", syncNavigation);
wc.on("did-navigate-in-page", syncNavigation);
wc.on("did-navigate-in-page", syncInPageNavigation);
wc.on("page-title-updated", sync);
wc.on("page-favicon-updated", faviconUpdated as never);
wc.on("did-start-loading", sync);
wc.on("did-stop-loading", sync);
wc.on("did-fail-load", failed as never);
wc.ipc.on(HUMAN_INPUT_CHANNEL, humanInput);
wc.ipc.on(MOUSE_NAVIGATE_CHANNEL, mouseNavigate);
wc.setWindowOpenHandler(({ url }) => {
runFork(
attemptPromise({ operation: "openPreviewWindow", tabId, webContentsId: wc.id }, () =>
@@ -1401,7 +1612,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
yield* Ref.update(attachedRef, (attached) =>
replaceMap(attached, (copy) => {
copy.set(wc.id, { scope });
copy.set(wc.id, { attachmentId, cancelFaviconCapture, scope, webContents: wc });
}),
);
});
@@ -1419,6 +1630,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const createTabUnlocked = Effect.fn("PreviewManager.createTabUnlocked")(function* (
tabId: string,
defaults?: DesktopPreviewTabDefaults,
) {
const updatedAt = yield* currentIso;
const result = yield* SynchronizedRef.modify(
@@ -1437,9 +1649,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
navStatus: { kind: "Idle" },
canGoBack: false,
canGoForward: false,
zoomFactor: DEFAULT_ZOOM_FACTOR,
zoomFactor: normalizeZoomFactor(defaults?.zoomFactor),
pictureInPicture: false,
colorScheme: "system",
colorScheme: defaults?.colorScheme ?? "system",
controller: "none",
updatedAt,
};
@@ -1458,8 +1670,11 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return result.state;
});
const createTab = Effect.fn("PreviewManager.createTab")(function* (tabId: string) {
return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId));
const createTab = Effect.fn("PreviewManager.createTab")(function* (
tabId: string,
defaults?: DesktopPreviewTabDefaults,
) {
return yield* withTabLifecycleLock(tabId, createTabUnlocked(tabId, defaults));
});
const closeTabUnlocked = Effect.fn("PreviewManager.closeTabUnlocked")(function* (tabId: string) {
@@ -1544,6 +1759,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const mainWindow = yield* Ref.get(mainWindowRef);
if (
!wc ||
wc.isDestroyed() ||
wc.getType() !== "webview" ||
(Option.isSome(mainWindow) && wc.hostWebContents !== mainWindow.value.webContents)
) {
@@ -1551,19 +1767,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
const attached = yield* Ref.get(attachedRef);
const annotationTheme = yield* Ref.get(annotationThemeRef);
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
const zoomFactor = yield* attempt(
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
() => wc.getZoomFactor(),
);
yield* update(tabId, { zoomFactor });
const currentAttachment = attached.get(webContentsId);
if (tab.webContentsId === webContentsId && currentAttachment?.webContents === wc) {
// The guest we already own re-announced itself, so nothing about the tab
// changed. Only push its zoom back down — Chromium may have just handed
// this guest the app window's zoom level.
yield* assertTabZoom(tabId);
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
return;
}
const replacedWebContentsId =
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
tab.webContentsId != null &&
(tab.webContentsId !== webContentsId || currentAttachment?.webContents !== wc)
? tab.webContentsId
: null;
if (replacedWebContentsId !== null) {
yield* Effect.all(
[
@@ -1582,18 +1801,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
) {
return yield* new PreviewTabNotFoundError({ tabId });
}
const zoomFactor =
replacedWebContentsId !== null
? yield* attempt(
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
() => {
wc.setZoomFactor(currentTab.zoomFactor);
return currentTab.zoomFactor;
},
)
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
wc.getZoomFactor(),
);
// Always assert the tab's own zoom rather than reading the guest's: a guest
// attaching while the app UI is zoomed starts at the embedder's inherited
// zoom level, which is not the preview's zoom. Done before the guest is
// published so it never paints a frame at the inherited zoom.
yield* attempt({ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId }, () =>
wc.setZoomFactor(currentTab.zoomFactor),
);
yield* attachListeners(tabId, wc);
const registeredAt = yield* currentIso;
const registration = yield* SynchronizedRef.modifyEffect(tabsRef, (tabs) =>
@@ -1610,13 +1824,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
] as const;
}
const pendingUrl = current.navStatus.kind === "Loading" ? current.navStatus.url : null;
const { favicon: _favicon, ...currentWithoutFavicon } = current;
const next: PreviewTabState = {
...current,
...currentWithoutFavicon,
webContentsId,
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor,
updatedAt: registeredAt,
};
return [
@@ -1638,6 +1852,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return yield* new PreviewTabNotFoundError({ tabId });
}
const { state: registered, pendingUrl } = registration.value;
// A zoom action that landed while this attach was in flight addressed the
// guest this one replaced, so settle the new guest on the committed factor.
yield* assertTabZoom(tabId);
runFork(restoreControlSession(tabId, wc));
yield* emit(tabId, registered);
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
@@ -1690,6 +1907,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
pictureInPicture: current?.pictureInPicture ?? false,
colorScheme: current?.colorScheme ?? "system",
controller: current?.controller ?? "none",
...(current?.favicon ? { favicon: current.favicon } : {}),
updatedAt,
};
return [
@@ -1701,17 +1919,48 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
});
yield* emit(tabId, pending);
if (pending.webContentsId == null) return;
const wc = webContents.fromId(pending.webContentsId);
if (!wc) {
const detached = { ...pending, webContentsId: null };
yield* SynchronizedRef.update(tabsRef, (tabs) =>
tabs.get(tabId)?.webContentsId !== pending.webContentsId
? tabs
: replaceMap(tabs, (copy) => {
copy.set(tabId, detached);
}),
const webContentsId = pending.webContentsId;
const wc = webContents.fromId(webContentsId);
if (!wc || wc.isDestroyed()) {
const expectedAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
yield* withTabLifecycleLock(
tabId,
Effect.gen(function* () {
const currentTab = (yield* SynchronizedRef.get(tabsRef)).get(tabId);
const currentAttachment = (yield* Ref.get(attachedRef)).get(webContentsId);
const currentWebContents = webContents.fromId(webContentsId);
if (
currentTab?.webContentsId !== webContentsId ||
currentAttachment !== expectedAttachment ||
(currentWebContents && !currentWebContents.isDestroyed())
) {
return;
}
yield* Effect.all(
[
detachControlSession(webContentsId),
detachListeners(webContentsId),
cancelPickElement(tabId),
],
{ concurrency: 3, discard: true },
);
const detached = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (current?.webContentsId !== webContentsId) {
return [Option.none<PreviewTabState>(), tabs] as const;
}
const { favicon: _favicon, ...currentWithoutFavicon } = current;
const next: PreviewTabState = { ...currentWithoutFavicon, webContentsId: null };
return [
Option.some(next),
replaceMap(tabs, (copy) => {
copy.set(tabId, next);
}),
] as const;
});
if (Option.isSome(detached)) yield* emitIfCurrent(tabId, detached.value);
}),
);
yield* emit(tabId, detached);
return;
}
if (wc.getURL() === url) {
@@ -1792,7 +2041,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const wc = yield* requireWebContents(tabId);
yield* cancelPickElement(tabId);
const annotationTheme = yield* Ref.get(annotationThemeRef);
return yield* Effect.callback<PreviewAnnotationPayload | null, PreviewManagerError>(
return yield* Effect.callback<PreviewAnnotationSubmissionResult | null, PreviewManagerError>(
(resume) => {
const cleanup = Effect.fn("PreviewManager.cleanupPickElement")(function* () {
yield* attempt({ operation: "pickElement.cleanup", tabId, webContentsId: wc.id }, () => {
@@ -1807,14 +2056,14 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const settlePick = Effect.fn("PreviewManager.settlePickElement")(function* (
payload: PreviewAnnotationPayload | null,
payload: PreviewAnnotationSubmissionResult | null,
) {
const active = (yield* Ref.get(pickSessionsRef)).get(tabId);
if (!active || active.cancel !== cancel) return;
yield* cleanup();
resume(Effect.succeed(payload));
});
const settle = (payload: PreviewAnnotationPayload | null) => {
const settle = (payload: PreviewAnnotationSubmissionResult | null) => {
runFork(settlePick(payload));
};
const cancelPickSession = Effect.fn("PreviewManager.cancelPickSession")(function* () {
@@ -1844,11 +2093,13 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return;
}
const cropRect = normalizeCaptureRect(args[1]);
const submission = args[2] === "send" ? "send" : "attach";
runFork(
captureAnnotationScreenshot(tabId, wc, cropRect).pipe(
Effect.matchEffect({
onFailure: () => Effect.sync(() => settle(payload)),
onSuccess: (screenshot) => Effect.sync(() => settle({ ...payload, screenshot })),
onFailure: () => Effect.sync(() => settle({ annotation: payload, submission })),
onSuccess: (screenshot) =>
Effect.sync(() => settle({ annotation: { ...payload, screenshot }, submission })),
}),
Effect.ensuring(
attempt(
@@ -1897,6 +2148,17 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
/**
* Chromium hands every guest `<webview>` the embedder's zoom level, so zooming
* the app UI drags the previewed page along with it. The preview browser owns
* its own zoom factor, so re-assert it on each attached guest whenever the main
* window's zoom changes (see DesktopWindow.zoomMain).
*/
const reapplyZoom = Effect.fn("PreviewManager.reapplyZoom")(function* () {
const tabIds = Array.from((yield* SynchronizedRef.get(tabsRef)).keys());
yield* Effect.forEach(tabIds, assertTabZoom, { discard: true });
});
const applyZoom = Effect.fn("PreviewManager.applyZoom")(function* (
tabId: string,
transform: (current: number) => number,
@@ -3274,6 +3536,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
openPictureInPicture,
openDevTools,
pickElement,
reapplyZoom,
refresh,
registerWebview,
resetZoom: (tabId: string) => applyZoom(tabId, () => DEFAULT_ZOOM_FACTOR),
@@ -3559,7 +3822,10 @@ export class PreviewManager extends Context.Service<
readonly setMainWindow: (window: BrowserWindow) => Effect.Effect<void, PreviewManagerError>;
readonly getBrowserSession: (scope?: string) => Effect.Effect<Session, PreviewManagerError>;
readonly isBrowserPartition: (partition: string) => boolean;
readonly createTab: (tabId: string) => Effect.Effect<PreviewTabState, PreviewManagerError>;
readonly createTab: (
tabId: string,
defaults?: DesktopPreviewTabDefaults,
) => Effect.Effect<PreviewTabState, PreviewManagerError>;
readonly closeTab: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly registerWebview: (
tabId: string,
@@ -3572,6 +3838,9 @@ export class PreviewManager extends Context.Service<
readonly zoomIn: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly zoomOut: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly resetZoom: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
// Re-applies every attached guest's own zoom factor, undoing the zoom level
// Chromium inherits from the embedder when the app UI zooms.
readonly reapplyZoom: () => Effect.Effect<void>;
readonly hardReload: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly setColorScheme: (
tabId: string,
@@ -3586,7 +3855,7 @@ export class PreviewManager extends Context.Service<
) => Effect.Effect<void, PreviewManagerError>;
readonly pickElement: (
tabId: string,
) => Effect.Effect<PreviewAnnotationPayload | null, PreviewManagerError>;
) => Effect.Effect<PreviewAnnotationSubmissionResult | null, PreviewManagerError>;
readonly cancelPickElement: (tabId: string) => Effect.Effect<void, PreviewManagerError>;
readonly captureScreenshot: (
tabId: string,
@@ -3672,6 +3941,7 @@ export const make = Effect.gen(function* PreviewManagerMake() {
zoomIn: operations.zoomIn,
zoomOut: operations.zoomOut,
resetZoom: operations.resetZoom,
reapplyZoom: operations.reapplyZoom,
hardReload: operations.hardReload,
setColorScheme: operations.setColorScheme,
openDevTools: operations.openDevTools,
+49 -7
View File
@@ -11,8 +11,10 @@ import type {
PreviewAnnotationRegionTarget,
PreviewAnnotationStrokeTarget,
PreviewAnnotationStyleChange,
PreviewAnnotationSubmission,
} from "@t3tools/contracts";
import { resolveAnnotationSubmission } from "./AnnotationKeyboard.ts";
import { previewAnnotationStyles } from "./AnnotationStyles.generated.ts";
import {
ANNOTATION_CAPTURED_CHANNEL,
@@ -20,6 +22,7 @@ import {
CANCEL_PICK_CHANNEL,
ELEMENT_PICKED_CHANNEL,
HUMAN_INPUT_CHANNEL,
MOUSE_NAVIGATE_CHANNEL,
START_PICK_CHANNEL,
} from "./GuestProtocol.ts";
const OVERLAY_ATTRIBUTE = "data-t3code-annotation-ui";
@@ -100,6 +103,40 @@ const reportHumanKeyInput = (event: KeyboardEvent): void => {
window.addEventListener("pointerdown", reportHumanPointerInput, true);
window.addEventListener("keydown", reportHumanKeyInput, true);
// Mouse thumb buttons: `button === 3` is Back, `button === 4` is Forward.
const MOUSE_BUTTON_BACK = 3;
const MOUSE_BUTTON_FORWARD = 4;
const navigationDirectionForButton = (button: number): "back" | "forward" | null => {
if (button === MOUSE_BUTTON_BACK) return "back";
if (button === MOUSE_BUTTON_FORWARD) return "forward";
return null;
};
// Chromium routes thumb-button history navigation to the *focused* WebContents,
// so hovering this guest without focusing it sends the host app's router back
// instead of the preview. Suppress Chromium's default here and drive this tab's
// history explicitly so the buttons always navigate the browser the pointer is
// over — never the host app.
const suppressNavigationButton = (event: MouseEvent): void => {
if (!event.isTrusted || navigationDirectionForButton(event.button) === null) return;
event.preventDefault();
event.stopImmediatePropagation();
};
const requestNavigationForButton = (event: MouseEvent): void => {
if (!event.isTrusted) return;
const direction = navigationDirectionForButton(event.button);
if (direction === null) return;
event.preventDefault();
event.stopImmediatePropagation();
ipcRenderer.send(MOUSE_NAVIGATE_CHANNEL, { direction });
};
window.addEventListener("mousedown", suppressNavigationButton, true);
window.addEventListener("mouseup", requestNavigationForButton, true);
window.addEventListener("auxclick", suppressNavigationButton, true);
const nextId = (prefix: string): string => {
idSequence += 1;
return `${prefix}_${idSequence.toString(36)}`;
@@ -426,7 +463,7 @@ function startAnnotation(): void {
"hidden h-8 w-6 shrink-0 cursor-grab select-none border-0 bg-transparent p-0 font-sans text-lg font-bold leading-5 text-muted-foreground";
composerRow.appendChild(dragHandle);
const submit = createButton("Attach", "Attach annotation and screenshot");
const submit = createButton("Attach", "Attach annotation and screenshot (Enter)");
submit.className +=
" h-8 shrink-0 border-primary bg-primary px-3 text-primary-foreground shadow-sm hover:bg-primary/90";
composerRow.appendChild(submit);
@@ -1182,7 +1219,7 @@ function startAnnotation(): void {
refreshToolButtons();
};
submit.addEventListener("click", () => {
const submitAnnotation = (submission: PreviewAnnotationSubmission): void => {
if (pendingCapture || (selected.size === 0 && regions.length === 0 && strokes.length === 0))
return;
pendingCapture = true;
@@ -1223,13 +1260,18 @@ function startAnnotation(): void {
...regions.map((region) => region.rect),
...strokes.map((stroke) => stroke.bounds),
]);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect);
ipcRenderer.send(ELEMENT_PICKED_CHANNEL, annotation, screenshotRect, submission);
});
});
comment.addEventListener("keydown", (event) => {
if (event.key !== "Enter" || !(event.metaKey || event.ctrlKey)) return;
};
submit.addEventListener("click", () => submitAnnotation("attach"));
root.addEventListener("keydown", (event) => {
const submission = event.target === comment ? resolveAnnotationSubmission(event) : null;
// Keep this in the bubble phase so editor inputs receive the event before
// it is isolated from listeners installed by the inspected page.
event.stopImmediatePropagation();
if (!submission) return;
event.preventDefault();
submit.click();
submitAnnotation(submission);
});
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
@@ -8,7 +8,7 @@ import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
const require = NodeModule.createRequire(import.meta.url);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.UnknownFromJsonString);
const encodeUnknownJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Schema.Unknown));
const PLAYWRIGHT_PACKAGE_SPECIFIER = "playwright-core/package.json";
const PLAYWRIGHT_SOURCE_MARKER = "source3 = ";
const PLAYWRIGHT_SOURCE_TERMINATOR = ";\n }\n});";
@@ -11,6 +11,9 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopAppSettings from "./DesktopAppSettings.ts";
const DesktopSettingsPatch = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(
Schema.Literals(["auto", "gnome-libsecret", "kwallet", "kwallet5", "kwallet6"]),
),
mainWindowBounds: Schema.optionalKey(
Schema.NullOr(
Schema.Struct({
@@ -102,6 +105,7 @@ describe("DesktopSettings", () => {
assert.deepEqual(
DesktopAppSettings.resolveDefaultDesktopSettings("0.0.17-nightly.20260415.1"),
{
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -121,6 +125,7 @@ describe("DesktopSettings", () => {
Effect.gen(function* () {
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* writeSettingsPatch({
linuxPasswordStore: "gnome-libsecret",
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
@@ -129,6 +134,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "gnome-libsecret",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -235,6 +241,7 @@ describe("DesktopSettings", () => {
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: { x: 120, y: 80, width: 1280, height: 900 },
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
@@ -268,6 +275,44 @@ describe("DesktopSettings", () => {
),
);
it.effect(
"normalizes unsupported linux password-store values without dropping other settings",
() =>
withSettings(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const settings = yield* DesktopAppSettings.DesktopAppSettings;
yield* fileSystem.makeDirectory(environment.stateDir, { recursive: true });
yield* fileSystem.writeFileString(
environment.desktopSettingsPath,
`{
"linuxPasswordStore": "unsupported-store",
"serverExposureMode": "network-accessible",
"tailscaleServeEnabled": true,
"tailscaleServePort": 8443,
"updateChannel": "nightly",
"updateChannelConfiguredByUser": true
}\n`,
);
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "network-accessible",
tailscaleServeEnabled: true,
tailscaleServePort: 8443,
updateChannel: "nightly",
updateChannelConfiguredByUser: true,
wslBackendEnabled: false,
wslOnly: false,
wslDistro: null,
} satisfies DesktopAppSettings.DesktopSettings);
}),
),
);
it.effect("persists sparse desktop settings documents", () =>
withSettings(
Effect.gen(function* () {
@@ -300,6 +345,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -327,6 +373,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -353,6 +400,7 @@ describe("DesktopSettings", () => {
});
assert.deepEqual(yield* settings.load, {
linuxPasswordStore: "auto",
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -16,10 +16,16 @@ import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import {
DEFAULT_LINUX_PASSWORD_STORE,
normalizeLinuxPasswordStorePreference,
type LinuxPasswordStorePreference,
} from "../linuxSecretStorage.ts";
import { resolveDefaultDesktopUpdateChannel } from "../updates/updateChannels.ts";
import { isValidDistroName } from "../wsl/wslPathParsing.ts";
export interface DesktopSettings {
readonly linuxPasswordStore: LinuxPasswordStorePreference;
readonly mainWindowBounds: DesktopWindowBounds | null;
readonly mainWindowMaximized: boolean;
readonly serverExposureMode: DesktopServerExposureMode;
@@ -67,6 +73,7 @@ export const DEFAULT_MAIN_WINDOW_SIZE = {
} as const;
export const DEFAULT_DESKTOP_SETTINGS: DesktopSettings = {
linuxPasswordStore: DEFAULT_LINUX_PASSWORD_STORE,
mainWindowBounds: null,
mainWindowMaximized: false,
serverExposureMode: "local-only",
@@ -87,6 +94,7 @@ const DesktopWindowBoundsDocument = Schema.Struct({
});
const DesktopSettingsDocument = Schema.Struct({
linuxPasswordStore: Schema.optionalKey(Schema.Unknown),
mainWindowBounds: Schema.optionalKey(Schema.NullOr(DesktopWindowBoundsDocument)),
mainWindowMaximized: Schema.optionalKey(Schema.Boolean),
serverExposureMode: Schema.optionalKey(DesktopServerExposureModeSchema),
@@ -216,6 +224,7 @@ function normalizeDesktopSettingsDocument(
(parsed.wslBackendEnabled === undefined && parsed.wslMode === "wsl");
return {
linuxPasswordStore: normalizeLinuxPasswordStorePreference(parsed.linuxPasswordStore),
mainWindowBounds,
mainWindowMaximized: mainWindowBounds !== null && parsed.mainWindowMaximized === true,
serverExposureMode:
@@ -238,6 +247,9 @@ function toDesktopSettingsDocument(
): DesktopSettingsDocument {
const document: Mutable<DesktopSettingsDocument> = {};
if (settings.linuxPasswordStore !== defaults.linuxPasswordStore) {
document.linuxPasswordStore = settings.linuxPasswordStore;
}
if (settings.mainWindowBounds !== null) {
document.mainWindowBounds = settings.mainWindowBounds;
}
@@ -13,16 +13,31 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
const clientSettings: ClientSettings = {
autoOpenPlanSidebar: false,
browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },
browserDefaultZoomFactor: 1.25,
browserDefaultAppearance: "dark",
browserAutoShowFloatingPreview: false,
confirmQuit: true,
confirmThreadArchive: true,
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
environmentIdentificationMode: "artwork",
favorites: [],
fontFamilyCode: "",
fontFamilyComposer: "",
fontFamilySans: "",
fontFamilyTerminal: "",
fontSizeCode: 13,
fontSizeInterface: 16,
fontSizePrompt: 14,
fontSizeTerminal: 12,
fontSmoothing: true,
glassOpacity: 80,
planModeEnabled: false,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -30,8 +45,7 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
sidebarV2Enabled: false,
sidebarV2ConfiguredByUser: false,
legacySidebarEnabled: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -86,6 +86,7 @@ function makeSafeStorageLayer(input: {
}
return Effect.succeed(decoded.slice("enc:".length));
},
selectedStorageBackend: Effect.succeed(Option.none()),
} satisfies ElectronSafeStorage.ElectronSafeStorage["Service"]);
}
@@ -1,3 +1,4 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, describe, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -90,7 +91,7 @@ function runShellEnvironment(input: {
}).pipe(
Effect.provide(
DesktopShellEnvironment.layer.pipe(
Layer.provide(Layer.mergeAll(environmentLayer, spawnerLayer)),
Layer.provide(Layer.mergeAll(environmentLayer, NodeServices.layer, spawnerLayer)),
),
),
);
@@ -151,6 +152,108 @@ describe("DesktopShellEnvironment", () => {
}),
);
it.effect("hydrates the locale from the login shell on macOS", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
yield* runShellEnvironment({
env,
platform: "darwin",
handler: () =>
envOutput({
PATH: "/opt/homebrew/bin:/usr/bin",
LANG: "de_DE.UTF-8",
}),
});
assert.equal(env.LANG, "de_DE.UTF-8");
}),
);
it.effect("preserves an inherited locale over the login shell on macOS", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
LANG: "en_US.UTF-8",
};
yield* runShellEnvironment({
env,
platform: "darwin",
handler: () =>
envOutput({
PATH: "/opt/homebrew/bin:/usr/bin",
LANG: "de_DE.UTF-8",
}),
});
assert.equal(env.LANG, "en_US.UTF-8");
}),
);
it.effect("does not mix login-shell locale categories into an inherited locale", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
LANG: "en_US.UTF-8",
};
yield* runShellEnvironment({
env,
platform: "darwin",
handler: () =>
envOutput({
PATH: "/opt/homebrew/bin:/usr/bin",
LC_ALL: "de_DE.UTF-8",
}),
});
assert.equal(env.LANG, "en_US.UTF-8");
assert.equal(env.LC_ALL, undefined);
}),
);
it.effect("falls back to a UTF-8 LC_CTYPE when no locale is available on macOS", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
yield* runShellEnvironment({
env,
platform: "darwin",
handler: () => envOutput({ PATH: "/opt/homebrew/bin:/usr/bin" }),
});
assert.equal(env.LANG, undefined);
assert.equal(env.LC_ALL, undefined);
assert.equal(env.LC_CTYPE, "en_US.UTF-8");
}),
);
it.effect("does not apply the locale fallback on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () => envOutput({ PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin" }),
});
assert.equal(env.LANG, undefined);
}),
);
it.effect("hydrates PATH and missing SSH_AUTH_SOCK from the login shell on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
@@ -230,6 +333,7 @@ describe("DesktopShellEnvironment", () => {
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.local\\bin",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
@@ -243,6 +347,65 @@ describe("DesktopShellEnvironment", () => {
}),
);
it.effect("prefers login-shell desktop session hints over inherited values on linux", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
XDG_CURRENT_DESKTOP: "wrong-launcher",
XDG_SESSION_DESKTOP: "wrong-launcher",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/home/linuxbrew/.linuxbrew/bin:/usr/bin",
XDG_CURRENT_DESKTOP: "KDE",
XDG_SESSION_DESKTOP: "KDE",
XDG_SESSION_TYPE: "wayland",
}),
});
assert.equal(env.XDG_CURRENT_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_DESKTOP, "KDE");
assert.equal(env.XDG_SESSION_TYPE, "wayland");
}),
);
it.effect("overrides stale dbus session addresses from the login shell", () =>
Effect.gen(function* () {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/zsh",
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/tmp/stale-bus",
};
yield* runShellEnvironment({
env,
platform: "linux",
handler: () =>
envOutput({
PATH: "/usr/bin",
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
}),
});
assert.equal(env.DBUS_SESSION_BUS_ADDRESS, "unix:path=/run/user/1000/bus");
}),
);
it("resolves dbus runtime dir candidates with existence checks", () => {
const busPath = DesktopShellEnvironment.resolveDefaultLinuxDbusSessionBusAddress({
env: { XDG_RUNTIME_DIR: "/tmp/stale-runtime" },
uid: 1000,
exists: (path) => path === "/run/user/1000/bus",
});
assert.equal(busPath, "unix:path=/run/user/1000/bus");
});
it.effect("logs command failures with safe probe context and the exact cause", () => {
const env: NodeJS.ProcessEnv = {
SHELL: "/bin/bash",
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
@@ -68,14 +69,26 @@ export class DesktopShellEnvironment extends Context.Service<
const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"LANG",
"LC_ALL",
"LC_CTYPE",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_CURRENT_DESKTOP",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
"WAYLAND_DISPLAY",
] as const;
const WINDOWS_PROFILE_ENV_NAMES = ["PATH", "FNM_DIR", "FNM_MULTISHELL_PATH"] as const;
const LOCALE_ENV_NAMES = ["LANG", "LC_ALL", "LC_CTYPE"] as const;
const FALLBACK_LC_CTYPE = "en_US.UTF-8";
const WINDOWS_SHELL_CANDIDATES = ["pwsh.exe", "powershell.exe"] as const;
const LOGIN_SHELL_TIMEOUT = Duration.seconds(5);
const LAUNCHCTL_TIMEOUT = Duration.seconds(2);
@@ -92,6 +105,47 @@ const pathDelimiter = (platform: NodeJS.Platform) => (platform === "win32" ? ";"
const readEnvPath = (env: NodeJS.ProcessEnv): Option.Option<string> =>
trimNonEmpty(env.PATH ?? env.Path ?? env.path);
const normalizeRuntimeDir = (value: string): string => value.replace(/\/+$/u, "");
const linuxRuntimeDirCandidates = (
env: NodeJS.ProcessEnv,
uid: number | undefined,
): ReadonlyArray<string> => {
const candidates: string[] = [];
const fromEnv = trimNonEmpty(env.XDG_RUNTIME_DIR);
if (Option.isSome(fromEnv)) {
candidates.push(normalizeRuntimeDir(fromEnv.value));
}
if (uid !== undefined) {
candidates.push(`/run/user/${uid}`);
}
return candidates.filter((candidate) => candidate.length > 0);
};
function resolveDefaultLinuxDbusSessionBusPath(input: {
readonly env: NodeJS.ProcessEnv;
readonly uid: number | undefined;
readonly exists?: (path: string) => boolean;
}): string | null {
for (const runtimeDir of linuxRuntimeDirCandidates(input.env, input.uid)) {
const busPath = `${runtimeDir}/bus`;
if (input.exists === undefined || input.exists(busPath)) {
return busPath;
}
}
return null;
}
export function resolveDefaultLinuxDbusSessionBusAddress(input: {
readonly env: NodeJS.ProcessEnv;
readonly exists: (path: string) => boolean;
readonly uid: number | undefined;
}): string | null {
const busPath = resolveDefaultLinuxDbusSessionBusPath(input);
return busPath !== null && input.exists(busPath) ? `unix:path=${busPath}` : null;
}
const pathComparisonKey = (entry: string, platform: NodeJS.Platform) => {
const normalized = entry.trim().replace(/^"+|"+$/g, "");
return platform === "win32" ? normalized.toLowerCase() : normalized;
@@ -158,7 +212,7 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
...trimNonEmpty(env.USERPROFILE).pipe(
Option.match({
onNone: () => [],
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
}),
),
];
@@ -330,10 +384,18 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
loadProfile: true,
});
// Concurrent, not sequential: these two probes are independent (only their
// results are combined below) and each spawns its own PowerShell. Run in
// series they sit at offset 0 of desktop.startup, before anything else, and
// launch traces measured them at 2718ms then 2066ms — the entire 4.8s
// startup span, of which desktop.bootstrap is ~30ms.
const [noProfile, profile] = yield* Effect.all(
[
readWindowsEnvironment(["PATH"], { loadProfile: false }),
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
],
{ concurrency: 2 },
);
const mergedPath = mergePaths("win32", [
trimNonEmpty(profile.PATH),
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
@@ -356,7 +418,12 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosixEnvironment")(
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
): Effect.fn.Return<
void,
never,
ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
> {
const fileSystem = yield* FileSystem.FileSystem;
const shellEnvironment: EnvironmentPatch = {};
for (const shell of listLoginShellCandidates(config)) {
@@ -383,23 +450,77 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
config.env.SSH_AUTH_SOCK = shellEnvironment.SSH_AUTH_SOCK;
}
const shellPreferredEnvNames = [
"DBUS_SESSION_BUS_ADDRESS",
"XDG_CURRENT_DESKTOP",
"XDG_SESSION_DESKTOP",
"XDG_SESSION_TYPE",
] as const;
for (const name of shellPreferredEnvNames) {
if (shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
for (const name of [
"DISPLAY",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
"HOMEBREW_REPOSITORY",
"XDG_CONFIG_HOME",
"XDG_DATA_HOME",
"XDG_RUNTIME_DIR",
"WAYLAND_DISPLAY",
] as const) {
if (!config.env[name] && shellEnvironment[name]) {
config.env[name] = shellEnvironment[name];
}
}
// Locale variables form one precedence group: LC_ALL can override an inherited
// LANG or LC_CTYPE, so only hydrate the group when the process has none of them.
if (
config.platform === "darwin" &&
LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))
) {
for (const name of LOCALE_ENV_NAMES) {
const value = trimNonEmpty(shellEnvironment[name]);
if (Option.isSome(value)) {
config.env[name] = value.value;
}
}
// GUI launches inherit no locale from launchd, so spawned agents land in the C
// locale and pbcopy decodes their UTF-8 output as MacRoman. Older supported
// macOS releases do not provide C.UTF-8, so set only LC_CTYPE to a UTF-8 locale
// available on those releases. Leaving LANG unset keeps C-stable collation and
// formatting, so output parsing is unaffected.
if (LOCALE_ENV_NAMES.every((name) => Option.isNone(trimNonEmpty(config.env[name])))) {
config.env.LC_CTYPE = FALLBACK_LC_CTYPE;
}
}
if (
config.platform === "linux" &&
Option.isNone(trimNonEmpty(config.env.DBUS_SESSION_BUS_ADDRESS))
) {
for (const runtimeDir of linuxRuntimeDirCandidates(config.env, process.getuid?.())) {
const dbusSessionBusPath = `${runtimeDir}/bus`;
const busExists = yield* fileSystem
.exists(dbusSessionBusPath)
.pipe(Effect.orElseSucceed(() => false));
if (busExists) {
config.env.DBUS_SESSION_BUS_ADDRESS = `unix:path=${dbusSessionBusPath}`;
break;
}
}
}
},
);
const installShellEnvironment = (
config: ShellEnvironmentConfig,
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner> => {
): Effect.Effect<void, never, ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem> => {
if (config.platform === "win32") {
return installWindowsEnvironment(config);
}
@@ -411,6 +532,7 @@ const installShellEnvironment = (
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fileSystem = yield* FileSystem.FileSystem;
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const installIntoProcess: DesktopShellEnvironment["Service"]["installIntoProcess"] =
installShellEnvironment({
@@ -418,6 +540,7 @@ export const make = Effect.gen(function* () {
platform: environment.platform,
userShell: Option.none(),
}).pipe(
Effect.provideService(FileSystem.FileSystem, fileSystem),
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.withSpan("desktop.shellEnvironment.installIntoProcess"),
);
@@ -26,6 +26,7 @@ function makeElectronAppLayer(
return Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
systemLocale: Effect.succeed("en-US"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
@@ -34,7 +35,6 @@ function makeElectronAppLayer(
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.sync(() => {
onMetricsRead();
return metrics;
@@ -44,6 +44,7 @@ function makeElectronAppLayer(
setDesktopName: () => Effect.void,
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
@@ -31,6 +31,7 @@ const environmentInput = {
const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
metadata: Effect.die("unexpected metadata read"),
name: Effect.succeed("T3 Code"),
systemLocale: Effect.succeed("en-US"),
whenReady: Effect.void,
quit: Effect.void,
exit: () => Effect.void,
@@ -39,7 +40,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setName: () => Effect.void,
setAboutPanelOptions: () => Effect.void,
setAppUserModelId: () => Effect.void,
requestSingleInstanceLock: Effect.succeed(true),
getAppMetrics: Effect.succeed([]),
isDefaultProtocolClient: () => Effect.succeed(false),
setAsDefaultProtocolClient: () => Effect.succeed(true),
@@ -47,12 +47,13 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
setDockIcon: () => Effect.void,
appendCommandLineSwitch: () => Effect.void,
onBeforeQuitForUpdate: () => Effect.void,
removeCommandLineSwitch: () => Effect.void,
on: () => Effect.void,
} satisfies ElectronApp.ElectronApp["Service"]);
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
confirm: () => Effect.succeed(false),
pickFiles: () => Effect.succeed([]),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
@@ -80,6 +81,8 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
zoomMain: (direction) =>
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
@@ -93,6 +96,30 @@ const makeElectronMenuLayer = (
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
const configureMenu = (
selectedAction: Deferred.Deferred<string>,
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
Effect.gen(function* () {
@@ -100,25 +127,7 @@ describe("DesktopApplicationMenu", () => {
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
@@ -137,4 +146,38 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
// Zoom must route through DesktopWindow.zoomMain instead of the Electron
// zoom roles: the roles zoom whichever webContents has focus, which breaks
// app zoom while an embedded preview WebContentsView holds focus.
it.effect("routes View menu zoom to the main window instead of zoom roles", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const viewMenu = template.find((item) => item.label === "View");
assert.isDefined(viewMenu);
if (!Array.isArray(viewMenu.submenu)) {
throw new Error("Expected View menu submenu to be an array.");
}
assert.isUndefined(
viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")),
);
const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In");
assert.isDefined(zoomIn);
assert.equal(zoomIn.accelerator, "CmdOrCtrl+=");
if (typeof zoomIn.click !== "function") {
throw new Error("Expected Zoom In menu item to have a click handler.");
}
zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
}),
);
});
@@ -49,6 +49,13 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
yield* desktopWindow.dispatchMenuAction(action);
});
const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
direction: DesktopWindow.MainWindowZoomDirection,
): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.zoomMain(direction);
});
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -127,6 +134,9 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -181,10 +191,21 @@ export const make = Effect.gen(function* () {
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
/*
Not the zoom roles: those act on the focused webContents, so with
an embedded preview WebContentsView focused they zoom the guest
page and the app UI appears stuck. These always zoom the main
window (see DesktopWindow.zoomMain).
*/
{ label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
{ label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
{
label: "Zoom In",
accelerator: "CmdOrCtrl+Plus",
visible: false,
click: zoomClick("in"),
},
{ label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
{ type: "separator" },
{ role: "togglefullscreen" },
],
@@ -37,6 +37,8 @@ import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import * as ElectronMenu from "../electron/ElectronMenu.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
@@ -61,9 +63,14 @@ const environmentInput = {
function makeFakeBrowserWindow() {
const windowListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
let zoomLevel = 0;
const webContents = {
copyImageAt: vi.fn(),
getURL: vi.fn(() => "t3code-dev://app/"),
getZoomLevel: vi.fn(() => zoomLevel),
setZoomLevel: vi.fn((level: number) => {
zoomLevel = level;
}),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
@@ -116,12 +123,21 @@ function makeFakeBrowserWindow() {
openDevTools: webContents.openDevTools,
reload: webContents.reload,
send: webContents.send,
setZoomLevel: webContents.setZoomLevel,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
windowListeners,
};
}
const desktopClientSettingsLayer = Layer.mock(DesktopClientSettings.DesktopClientSettings)({
get: Effect.succeed(Option.none()),
});
const electronAppLayer = Layer.mock(ElectronApp.ElectronApp)({
quit: Effect.void,
});
const desktopAssetsLayer = Layer.succeed(DesktopAssets.DesktopAssets, {
iconPaths: Effect.succeed({
ico: Option.none<string>(),
@@ -186,6 +202,7 @@ function makeTestLayer(input: {
bounds: DesktopAppSettings.DesktopWindowBounds,
) => Effect.Effect<void>;
readonly openedExternalUrls?: unknown[];
readonly previewZoomReapplies?: number[];
}) {
let desktopSettings = input.desktopSettings ?? DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS;
const desktopAppSettingsLayer = Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
@@ -246,8 +263,10 @@ function makeTestLayer(input: {
desktopAssetsLayer,
desktopEnvironmentLayer,
desktopAppSettingsLayer,
desktopClientSettingsLayer,
desktopServerExposureLayer,
DesktopState.layer,
electronAppLayer,
electronMenuLayer,
Layer.succeed(ElectronShell.ElectronShell, {
openExternal: (url) =>
@@ -264,6 +283,10 @@ function makeTestLayer(input: {
setMainWindow: () => Effect.void,
isBrowserPartition: (partition) => partition.startsWith("persist:t3code-preview-"),
getBrowserPartition: () => Effect.succeed("persist:t3code-preview-test"),
reapplyZoom: () =>
Effect.sync(() => {
input.previewZoomReapplies?.push(input.window.webContents.getZoomLevel());
}),
}),
),
),
@@ -345,7 +368,9 @@ const makeSplashScenario = (createOutcomes: readonly (Electron.BrowserWindow | n
desktopAssetsLayer,
desktopEnvironmentLayer,
DesktopAppSettings.layerTest(),
desktopClientSettingsLayer,
desktopServerExposureLayer,
electronAppLayer,
electronMenuLayer,
Layer.succeed(ElectronShell.ElectronShell, {
openExternal: () => Effect.succeed(true),
@@ -438,6 +463,87 @@ describe("DesktopWindow", () => {
}),
);
it.effect("blocks only repeated Cmd+W input before it reaches the native window menu", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
const beforeInput = fakeWindow.webContentsListeners.get("before-input-event");
if (!beforeInput) {
return yield* Effect.die("before-input-event listener was not registered");
}
let prevented = false;
const event = { preventDefault: () => (prevented = true) };
const input = {
type: "keyDown",
isAutoRepeat: true,
key: "W",
meta: true,
control: false,
alt: false,
shift: false,
};
beforeInput(event, input);
assert.isTrue(prevented);
prevented = false;
beforeInput(event, { ...input, isAutoRepeat: false });
assert.isFalse(prevented);
prevented = false;
beforeInput(event, { ...input, meta: false });
assert.isFalse(prevented);
}).pipe(Effect.provide(layer));
}),
);
// Chromium hands the main window's zoom level down to embedded preview
// guests, so every app zoom has to put the preview browser back at its own
// zoom or zooming the UI drags the previewed page with it.
it.effect("restores the preview browser's own zoom after zooming the app", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const previewZoomReapplies: number[] = [];
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
previewZoomReapplies,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady(new URL("http://127.0.0.1:3773"));
yield* desktopWindow.zoomMain("out");
yield* desktopWindow.zoomMain("out");
yield* desktopWindow.zoomMain("in");
yield* desktopWindow.zoomMain("reset");
assert.deepEqual(
fakeWindow.setZoomLevel.mock.calls.map(([level]) => level),
[-0.5, -1, -0.5, 0],
);
// Recorded after the window level moved, so the preview is put back at
// its own zoom on every step rather than left on the inherited one.
assert.deepEqual(previewZoomReapplies, [-0.5, -1, -0.5, 0]);
}).pipe(Effect.provide(layer));
}),
);
it.effect("uses the persisted main window bounds when opening the window", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
Loaded 100 of 1192 files, more files were not shown because too many files have changed in this diff. Show more