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
1172 changed files with 98806 additions and 189439 deletions

No files matched your search

+1
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
+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.
-102
View File
@@ -1,102 +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
- apps/mobile
- 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.
+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);
});
-10
View File
@@ -70,16 +70,6 @@ jobs:
!/.repos/
sparse-checkout-cone-mode: false
# Blacksmith boots GitHub's Ubuntu runner image (gcc is usually present),
# but ACP process-tree live tests compile a small pthread fixture with `cc`
# and soft-skip when it is missing. Install build-essential so that path
# always runs in CI instead of silently no-oping.
- name: Install C toolchain for process-tree fixtures
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends build-essential
command -v cc
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
+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
+10
View File
@@ -856,6 +856,16 @@ jobs:
fail_on_unmatched_files: true
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
needs: [preflight, relay_public_config, release]
@@ -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 });
@@ -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.
@@ -1,246 +0,0 @@
# Plan: Thread Lineage And Lazy Context Transfer
## Summary
Implement the shared backend foundation for forking, provider handoff, merge-back, and future subagents without forcing provider selection at fork time. The first slice should create cheap app-level fork lineage and defer expensive context materialization until a run starts and the target provider is known.
Architecture reference: `docs/orchestration-v2/thread-lineage-and-context-transfer.md`.
## Goals
- Support user-created fork threads for exploration.
- Keep fork creation provider-neutral and cheap.
- Reuse the same source-point/context-transfer model for provider switching, merge-back, and future subagents.
- Prefer native same-provider fork at first dispatch when available.
- Fall back to portable context only when native transfer is unavailable or target provider differs.
- Keep all behavior replayable through V2 events/projections.
## Non-Goals For First Slice
- Full portable context generation quality.
- Cross-provider adapter implementation beyond the data/runtime hook.
- Merge-back UI.
- Native or custom subagent orchestration.
- Forking from actively streaming provider state.
- Backward compatibility with old dev databases.
## Core Data Model
Add schema/contracts for:
```ts
type ContextTransferType =
| "fork"
| "provider_handoff"
| "merge_back"
| "subagent_spawn"
| "subagent_result";
type ContextSourcePoint = {
threadId: ThreadId;
runId?: RunId;
checkpointId?: CheckpointId;
turnItemId?: TurnItemId;
providerThreadRef?: NativeThreadRef;
providerTurnRef?: NativeTurnRef;
};
type ContextTransferStatus =
| "pending"
| "resolved_native"
| "resolved_portable"
| "failed"
| "consumed"
| "superseded";
```
Persist:
- `orchestration_v2_projection_context_transfers`
- optional later portable handoff payload columns/table if the existing context handoff projection is not enough
For the first slice, `ContextTransfer` is required. Materialized `ContextHandoff` payloads can be deferred until portable context is implemented.
## Events
Add V2 events:
- `context-transfer.created`
- `context-transfer.updated`
- possibly `context-handoff.created` later
Do not emit provider-native fork details as app identity. Native fork refs belong in the transfer resolution payload and provider thread refs.
## Commands
Add:
```ts
type ThreadForkCommand = {
type: "thread.fork";
commandId: CommandId;
sourceThreadId: ThreadId;
targetThreadId: ThreadId;
sourcePoint:
| { type: "latest_stable" }
| { type: "run"; runId: RunId }
| { type: "checkpoint"; checkpointId: CheckpointId };
title?: string;
createdAt: string;
};
```
First-slice policy:
- `latest_stable` resolves to latest completed run checkpoint.
- explicit completed run/checkpoint is accepted.
- active run source is rejected or resolved to latest stable checkpoint; choose one policy and test it.
- target thread starts idle.
- no provider session/thread is created by `thread.fork`.
## Runtime Hook
Add a provider-neutral start-context resolver used by run startup:
```ts
resolveStartContext({
threadId,
runId,
provider,
modelSelection,
userMessage,
}): Effect<StartContextResolution, StartContextResolutionError>
```
Resolution order:
1. No pending transfer targeting the thread/run: normal run start.
2. Pending fork transfer and same provider with native fork support: resolve native fork.
3. Pending transfer requiring portable context: return explicit unsupported/stub result in first slice, or build minimal portable context if cheap.
4. Failed resolution: fail command before provider side effects.
The resolver should be called before provider thread creation/startTurn so the adapter can decide whether to create, resume, or native-fork provider state.
## Codex Native Fork Path
Investigate the app-server native fork API in `effect-codex-app-server` and Codex docs/probes.
Implementation target:
- use native fork only when source provider is Codex and source native refs are strong;
- create or bind a new `ProviderThread` for the forked native thread;
- when the source point is an earlier completed Codex provider turn, fork the latest native thread first and then rollback the forked native thread by later terminal provider turns;
- mark `ContextTransfer.status = resolved_native` and then `consumed` when the first run starts;
- preserve source app thread lineage separately from native thread refs.
If native API details are not clean, land the data model and resolver first with native fork marked unsupported, then add Codex native fork in a follow-up.
## Portable Context Fallback
The first slice should define the fallback boundary even if it does not fully implement high-quality summarization.
Minimum viable fallback:
- detect cross-provider fork/handoff need;
- create failed/unsupported transfer resolution with a clear command error, or
- generate a deterministic minimal context handoff from app projection if we want a usable MVP.
Do not silently concatenate hidden summaries into the user message without a `ContextTransfer`/`ContextHandoff` record.
## Merge-Back Preparation
Do not implement merge-back in the first slice, but keep model support:
- `ContextTransfer.type = "merge_back"`
- `basePoint` on transfer
- source thread may differ from target thread
The later merge-back command should create a transfer from fork latest stable point back to source thread and consume it with the next user message.
## Subagent Preparation
Do not implement subagents in this slice, but keep model support:
- `createdBy: "agent"`
- `type: "subagent_spawn"` and `"subagent_result"`
- source/target thread relationship fields
Native subagent ingestion can later map provider-native child refs into the same graph. Cross-provider app-owned subagents can later create child app threads using the same transfer primitive.
## Projection And Debugger
Backend projection first:
- expose thread lineage in thread projection;
- expose context transfers in debug projection;
- expose transfer status and resolution strategy.
Debugger after backend:
- fork button/control from stable source point;
- show thread lineage/source point;
- show pending/resolved/failed transfers;
- show native vs portable resolution.
Do not build debugger controls before the backend projection is authoritative.
## Tests
Use `bun run test`, not `bun test`.
Required backend tests:
- `thread.fork` from latest completed checkpoint creates target thread and pending transfer.
- fork command is idempotent through command receipts.
- fork does not create provider session/thread eagerly.
- first run on same-provider fork invokes native resolution path when capability exists.
- unsupported native fork falls back or fails according to explicit policy.
- active-run fork policy is deterministic.
- replay/recovery preserves target thread lineage and pending transfer.
Add test provider layers only at external service boundaries. Do not mock core orchestration policy.
## Implementation Order
1. Add contract schemas and ids for context transfers/source points.
2. Add migration/projection table for context transfers.
3. Add event store/projection handling for transfer events.
4. Add `thread.fork` command policy and orchestrator path.
5. Add tests for cheap idle fork creation and recovery.
6. Add start-context resolver interface.
7. Wire resolver into run startup with no-op behavior.
8. Add Codex native fork capability investigation and adapter path.
9. Add tests for same-provider native fork resolution.
10. Add debug projection surface after backend behavior is stable.
## Validation
Before considering the slice complete:
- `bun fmt`
- `bun lint`
- `bun typecheck`
- targeted backend tests with `bun run test`
If backend code changes are included, tests must cover the new orchestration behavior before the task is considered done.
## Implementation Status
Implemented in this slice:
- context transfer ids, schemas, JSON codecs, events, and projection storage
- app-thread lineage on thread creation and fork creation
- `thread.fork` command using `latest_stable`, explicit run, or explicit checkpoint source points
- cheap idle fork creation with no eager provider session/thread/run
- Codex same-provider native `thread/fork` resolution on first target dispatch
- Codex native fork-from-earlier-run resolution with `thread/fork` plus fork-local `thread/rollback`
- transfer status progression through `pending`, `resolved_native`, and `consumed`
- command receipt idempotency for duplicate fork commands
- replay-backed integration coverage for lazy fork creation and native Codex fork consumption
Explicitly deferred:
- portable `ContextHandoff` materialization for cross-provider forks/provider handoff
- merge-back command/runtime
- subagent spawn/result runtime
- debugger controls for creating/inspecting transfers
File diff suppressed because it is too large. Load diff
-1
View File
@@ -12,4 +12,3 @@
10. `10-unify-process-session-abstraction.md`
19. `19-version-control-phase-1-vcs-driver-foundation.md`
20. `20-version-control-phase-2-source-control-provider-foundation.md`
21. `21-orchestration-v2-application-integration.md`
+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.
+13 -2
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.
@@ -69,7 +79,6 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Customize a project icon](./docs/user/project-settings.md)
- [Appearance preferences](./docs/user/appearance.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)
@@ -104,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).
@@ -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");
});
});
@@ -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,
@@ -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);
}
}
@@ -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");
@@ -95,8 +96,24 @@ describe("DesktopEnvironment", () => {
assert.equal(environment.logDir, "/tmp/t3/userdata/logs");
assert.equal(environment.browserArtifactsDir, "/tmp/t3/userdata/browser-artifacts");
assert.equal(environment.serverSettingsPath, "/tmp/t3/userdata/settings.json");
assert.equal(environment.userDataDirName, "t3code");
assert.equal(environment.legacyUserDataDirName, "T3 Code (Alpha)");
}),
);
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",
);
}),
);
+13 -3
View File
@@ -52,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;
@@ -75,7 +82,6 @@ export class DesktopEnvironment extends Context.Service<
readonly runtimeInfo: DesktopRuntimeInfo;
readonly resolvePickFolderDefaultPath: (rawOptions: unknown) => Option.Option<string>;
readonly resolveResourcePathCandidates: (fileName: string) => readonly string[];
readonly developmentDockIconPath: string;
}
>()("@t3tools/desktop/app/DesktopEnvironment") {}
@@ -157,6 +163,10 @@ const make = Effect.fn("desktop.environment.make")(function* (
});
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,
@@ -198,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
@@ -258,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,
@@ -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) =>
@@ -121,7 +121,7 @@ export const resolveTailscaleAdvertisedEndpoints = Effect.fn("resolveTailscaleAd
input.readMagicDnsName ??
readTailscaleStatus.pipe(
Effect.map((status) => status.magicDnsName),
Effect.orElseSucceed((): string | null => null),
Effect.orElseSucceed(() => null),
);
const dnsName =
input.statusJson === undefined
@@ -8,6 +8,7 @@ const {
autoUpdaterRemoveListenerMock,
exitMock,
getAppPathMock,
getSystemLocaleMock,
getVersionMock,
isDefaultProtocolClientMock,
onMock,
@@ -29,6 +30,7 @@ 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(),
@@ -60,6 +62,7 @@ vi.mock("electron", () => ({
setIcon: setDockIconMock,
},
getAppPath: getAppPathMock,
getSystemLocale: getSystemLocaleMock,
getVersion: getVersionMock,
isDefaultProtocolClient: isDefaultProtocolClientMock,
isPackaged: true,
@@ -111,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");
+11
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>;
@@ -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({
+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") {
@@ -34,8 +34,10 @@ import {
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
getSystemLocale,
getWindowFullscreenState,
openExternal,
probeRemoteEditors,
pickFolder,
pickThemeFiles,
setTheme,
@@ -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);
@@ -83,6 +86,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
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);
+3
View File
@@ -3,7 +3,9 @@ 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";
+8 -3
View File
@@ -14,6 +14,7 @@ import {
DesktopPreviewRegisterWebviewInputSchema,
DesktopPreviewScreenshotArtifactSchema,
DesktopPreviewSetColorSchemeInputSchema,
DesktopPreviewCreateTabInputSchema,
DesktopPreviewTabInputSchema,
DesktopPreviewWebviewConfigSchema,
PreviewAnnotationSubmissionResultSchema,
@@ -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 });
}),
});
+38
View File
@@ -3,12 +3,16 @@ 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";
@@ -22,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";
@@ -60,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,
@@ -261,6 +275,30 @@ export const openExternal = DesktopIpc.makeIpcMethod({
}),
});
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;
+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", () => {
+2
View File
@@ -62,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* () {
@@ -165,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),
);
+22 -1
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)) {
@@ -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 }),
@@ -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";
+182 -15
View File
@@ -979,7 +979,10 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
// 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;
@@ -1025,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;
@@ -1045,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({
@@ -1074,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);
}),
),
);
@@ -2135,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* () {
+96 -28
View File
@@ -16,6 +16,7 @@ import type {
DesktopPreviewRecordingArtifact,
DesktopPreviewRecordingFrame,
DesktopPreviewScreenshotArtifact,
DesktopPreviewTabDefaults,
PreviewAutomationClickInput,
PreviewAutomationActionEvent,
PreviewAutomationConsoleEntry,
@@ -58,6 +59,7 @@ import {
CANCEL_PICK_CHANNEL,
ELEMENT_PICKED_CHANNEL,
HUMAN_INPUT_CHANNEL,
MOUSE_NAVIGATE_CHANNEL,
START_PICK_CHANNEL,
} from "./GuestProtocol.ts";
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
@@ -333,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") {
@@ -647,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,
) {
@@ -1305,10 +1338,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
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();
@@ -1338,7 +1367,9 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
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 [
@@ -1492,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,
@@ -1538,6 +1585,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
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* () {
@@ -1551,6 +1599,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
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 }, () =>
@@ -1581,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(
@@ -1599,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,
};
@@ -1620,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) {
@@ -1716,11 +1769,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const annotationTheme = yield* Ref.get(annotationThemeRef);
const currentAttachment = attached.get(webContentsId);
if (tab.webContentsId === webContentsId && currentAttachment?.webContents === wc) {
const zoomFactor = yield* attempt(
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
() => wc.getZoomFactor(),
);
yield* update(tabId, { zoomFactor });
// 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),
);
@@ -1749,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) =>
@@ -1784,7 +1831,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
navStatus: pendingUrl === null ? computeNavStatus(wc) : current.navStatus,
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
zoomFactor,
updatedAt: registeredAt,
};
return [
@@ -1806,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 }, () =>
@@ -2099,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,
@@ -3476,6 +3536,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
openPictureInPicture,
openDevTools,
pickElement,
reapplyZoom,
refresh,
registerWebview,
resetZoom: (tabId: string) => applyZoom(tabId, () => DEFAULT_ZOOM_FACTOR),
@@ -3761,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,
@@ -3774,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,
@@ -3874,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,
+35
View File
@@ -22,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";
@@ -102,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)}`;
@@ -13,6 +13,11 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
const clientSettings: ClientSettings = {
browserDefaultViewport: { _tag: "preset", width: 1024, height: 600, presetId: "nest-hub" },
browserDefaultZoomFactor: 1.25,
browserDefaultAppearance: "dark",
browserAutoShowFloatingPreview: false,
confirmQuit: true,
confirmThreadArchive: true,
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
@@ -30,7 +35,6 @@ const clientSettings: ClientSettings = {
fontSmoothing: true,
glassOpacity: 80,
planModeEnabled: false,
persistComposerContextStrip: true,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
@@ -152,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 = {
@@ -71,6 +71,9 @@ const LOGIN_SHELL_ENV_NAMES = [
"PATH",
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"LANG",
"LC_ALL",
"LC_CTYPE",
"SSH_AUTH_SOCK",
"HOMEBREW_PREFIX",
"HOMEBREW_CELLAR",
@@ -84,6 +87,8 @@ const LOGIN_SHELL_ENV_NAMES = [
"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);
@@ -472,6 +477,29 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
}
}
// 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))
@@ -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,
@@ -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,
@@ -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),
@@ -483,6 +508,42 @@ describe("DesktopWindow", () => {
}),
);
// 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();
+43 -1
View File
@@ -8,6 +8,8 @@ import * as Ref from "effect/Ref";
import * as Electron from "electron";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts";
import * as DesktopAssets from "../app/DesktopAssets.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import { makeComponentLogger } from "../app/DesktopObservability.ts";
@@ -16,9 +18,16 @@ import { getDesktopUrl } from "../electron/ElectronProtocol.ts";
import * as ElectronShell from "../electron/ElectronShell.ts";
import * as ElectronTheme from "../electron/ElectronTheme.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import { MENU_ACTION_CHANNEL, WINDOW_FULLSCREEN_STATE_CHANNEL } from "../ipc/channels.ts";
import {
MENU_ACTION_CHANNEL,
QUIT_SHORTCUT_CHANNEL,
WINDOW_FULLSCREEN_STATE_CHANNEL,
} from "../ipc/channels.ts";
import * as PreviewManager from "../preview/Manager.ts";
import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
import * as DesktopClientSettings from "../settings/DesktopClientSettings.ts";
import * as ElectronApp from "../electron/ElectronApp.ts";
import { makeQuitHoldHandler } from "./QuitHold.ts";
const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
@@ -51,6 +60,8 @@ type DesktopWindowRuntimeServices =
| DesktopEnvironment.DesktopEnvironment
| DesktopAssets.DesktopAssets
| DesktopAppSettings.DesktopAppSettings
| DesktopClientSettings.DesktopClientSettings
| ElectronApp.ElectronApp
| ElectronMenu.ElectronMenu
| ElectronShell.ElectronShell
| ElectronTheme.ElectronTheme
@@ -261,6 +272,8 @@ export const make = Effect.gen(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const previewManager = yield* PreviewManager.PreviewManager;
const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
const clientSettings = yield* DesktopClientSettings.DesktopClientSettings;
const electronApp = yield* ElectronApp.ElectronApp;
// Window-side latch for the primary backend's readiness. Set by
// handleBackendReady (driven by the pool's onReady callback), cleared
// by handleBackendNotReady (driven by onShutdown). Only consumed by
@@ -533,7 +546,32 @@ export const make = Effect.gen(function* () {
// close-terminal shortcut can outlive the terminal that handled its first
// press, so reject repeats before they reach the native window accelerator.
// Deliberate presses still flow through the renderer or native menu.
// Chrome-style hold-to-quit: intercept the quit accelerator before the
// native menu sees it and only quit after the shortcut is held. The
// renderer shows the "Hold to Quit" hint via QUIT_SHORTCUT_CHANNEL.
const quitHoldHandler = makeQuitHoldHandler({
platform: environment.platform,
isEnabled: () =>
runPromise(
Effect.map(
clientSettings.get,
Option.match({
onNone: () => DEFAULT_CLIENT_SETTINGS.confirmQuit,
onSome: (settings) => settings.confirmQuit,
}),
),
),
notify: (state) => {
if (!window.isDestroyed()) {
window.webContents.send(QUIT_SHORTCUT_CHANNEL, state);
}
},
quit: () => {
void runPromise(electronApp.quit);
},
});
window.webContents.on("before-input-event", (event, input) => {
quitHoldHandler(event, input);
if (input.type !== "keyDown" || !input.isAutoRepeat) return;
const modifier = environment.platform === "darwin" ? input.meta : input.control;
if (modifier && !input.alt && !input.shift && input.key.toLowerCase() === "w") {
@@ -855,6 +893,10 @@ export const make = Effect.gen(function* () {
webContents.setZoomLevel(
direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
);
// Chromium pushes the new level down to embedded guests, which would zoom
// the previewed page along with the app UI. The preview browser keeps its
// own zoom, so put each guest back where the preview left it.
yield* previewManager.reapplyZoom();
}),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
+201
View File
@@ -0,0 +1,201 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
import {
makeQuitHoldHandler,
QUIT_DOUBLE_TAP_MS,
QUIT_HOLD_DURATION_MS,
QUIT_HOLD_RELEASE_GRACE_MS,
} from "./QuitHold.ts";
import type { QuitHoldKeyInput, QuitHoldState } from "./QuitHold.ts";
function makeInput(overrides: Partial<QuitHoldKeyInput>): QuitHoldKeyInput {
return {
type: "keyDown",
key: "q",
meta: true,
control: false,
alt: false,
shift: false,
isAutoRepeat: false,
...overrides,
};
}
function makeHarness(options?: {
enabled?: boolean;
platform?: NodeJS.Platform;
isEnabled?: () => Promise<boolean>;
}) {
const notifications: Array<QuitHoldState> = [];
const quit = vi.fn();
const handler = makeQuitHoldHandler({
platform: options?.platform ?? "darwin",
isEnabled: options?.isEnabled ?? (() => Promise.resolve(options?.enabled ?? true)),
notify: (state) => notifications.push(state),
quit,
});
const preventDefault = vi.fn();
const send = async (input: QuitHoldKeyInput) => {
handler({ preventDefault }, input);
// Let the isEnabled promise settle.
await Promise.resolve();
await Promise.resolve();
};
// Simulates the OS auto-repeating the held shortcut every `intervalMs`.
const holdFor = async (
durationMs: number,
repeatOverrides: Partial<QuitHoldKeyInput> = {},
intervalMs = 100,
) => {
for (let elapsed = 0; elapsed < durationMs; elapsed += intervalMs) {
vi.advanceTimersByTime(intervalMs);
await send(makeInput({ isAutoRepeat: true, ...repeatOverrides }));
}
};
return { notifications, quit, preventDefault, send, holdFor };
}
describe("makeQuitHoldHandler", () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it("shows the hint on a tap without quitting, even when the release is never seen", async () => {
// macOS suppresses the letter's keyUp while Cmd is held, so a tap may
// produce no keyUp at all. Quit must still not fire.
const harness = makeHarness();
await harness.send(makeInput({}));
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
expect(harness.notifications).toEqual(["down"]);
vi.advanceTimersByTime(QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
expect(harness.quit).not.toHaveBeenCalled();
// The watchdog dismisses the hint once the press is clearly over.
expect(harness.notifications).toEqual(["down", "up"]);
});
it("quits once the shortcut auto-repeats past the hold duration", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
await harness.holdFor(QUIT_HOLD_DURATION_MS - 200);
expect(harness.quit).not.toHaveBeenCalled();
await harness.holdFor(400);
expect(harness.quit).toHaveBeenCalledTimes(1);
// Exactly one hint cycle for the whole hold.
expect(harness.notifications).toEqual(["down", "up"]);
});
it("does not quit when the hold stops before the duration", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
await harness.holdFor(500);
await harness.send(makeInput({ type: "keyUp" }));
expect(harness.notifications).toEqual(["down", "up"]);
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
expect(harness.quit).not.toHaveBeenCalled();
});
it("cancels the hold when the modifier is released first", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
await harness.send(makeInput({ type: "keyUp", key: "Meta", meta: false }));
expect(harness.notifications).toEqual(["down", "up"]);
vi.advanceTimersByTime((QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS) * 2);
expect(harness.quit).not.toHaveBeenCalled();
});
it("quits immediately on a single press when disabled", async () => {
const harness = makeHarness({ enabled: false });
await harness.send(makeInput({}));
expect(harness.quit).toHaveBeenCalledTimes(1);
// The hint is dismissed in case the quit gets cancelled downstream.
expect(harness.notifications).toEqual(["down", "up"]);
});
it("discards a stale isEnabled resolution from a superseded press", async () => {
// Press #1's isEnabled is still pending when the user releases and
// presses again; its late resolution must not act for press #2.
const resolvers: Array<(enabled: boolean) => void> = [];
const harness = makeHarness({
isEnabled: () => new Promise((resolve) => resolvers.push(resolve)),
});
await harness.send(makeInput({}));
await harness.send(makeInput({ type: "keyUp" }));
// Outside the double-tap window, so the second press starts a new hold.
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS + 100);
await harness.send(makeInput({}));
expect(resolvers).toHaveLength(2);
// Press #1 resolves late with "disabled" — it must not quit press #2.
resolvers[0]?.(false);
await Promise.resolve();
await Promise.resolve();
expect(harness.quit).not.toHaveBeenCalled();
// Press #2 resolves enabled and completes a full hold.
resolvers[1]?.(true);
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200);
expect(harness.quit).toHaveBeenCalledTimes(1);
});
it("quits on a quick double tap, even when the first release was never seen", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS - 100);
await harness.send(makeInput({}));
expect(harness.quit).toHaveBeenCalledTimes(1);
});
it("treats two slow taps as separate presses", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
await harness.send(makeInput({ type: "keyUp" }));
vi.advanceTimersByTime(QUIT_DOUBLE_TAP_MS + 100);
await harness.send(makeInput({}));
expect(harness.quit).not.toHaveBeenCalled();
expect(harness.notifications).toEqual(["down", "up", "down"]);
});
it("cancels the hold when another key interrupts it", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
await harness.holdFor(500);
// Shift pressed mid-hold breaks the gesture...
await harness.send(makeInput({ shift: true }));
expect(harness.notifications).toEqual(["down", "up"]);
// ...so later repeats past the threshold must not quit.
await harness.holdFor(QUIT_HOLD_DURATION_MS);
expect(harness.quit).not.toHaveBeenCalled();
});
it("does not count an interrupted press toward a double tap", async () => {
const harness = makeHarness();
await harness.send(makeInput({}));
await harness.send(makeInput({ shift: true }));
// A fresh press right after the interruption starts a new hold, not a
// double-tap quit.
await harness.send(makeInput({}));
expect(harness.quit).not.toHaveBeenCalled();
expect(harness.notifications).toEqual(["down", "up", "down"]);
});
it("ignores other shortcuts", async () => {
const harness = makeHarness();
await harness.send(makeInput({ key: "w" }));
await harness.send(makeInput({ shift: true }));
await harness.send(makeInput({ meta: false }));
expect(harness.preventDefault).not.toHaveBeenCalled();
expect(harness.notifications).toEqual([]);
});
it("uses control on non-mac platforms", async () => {
const harness = makeHarness({ platform: "linux" });
await harness.send(makeInput({ meta: false, control: true }));
expect(harness.preventDefault).toHaveBeenCalledTimes(1);
await harness.holdFor(QUIT_HOLD_DURATION_MS + 200, { meta: false, control: true });
expect(harness.quit).toHaveBeenCalledTimes(1);
});
});
+148
View File
@@ -0,0 +1,148 @@
// @effect-diagnostics globalDate:off globalTimers:off -- Synchronous before-input-event handler; key events must be timed and the watchdog scheduled outside any Effect runtime.
// Chrome-style hold-to-quit. The quit accelerator is intercepted in
// before-input-event (which runs before the native menu accelerator), and the
// app only quits once the shortcut has been held for QUIT_HOLD_DURATION_MS.
// A quick tap just shows the renderer's "Hold to Quit" hint, and a second tap
// within QUIT_DOUBLE_TAP_MS quits immediately. Quitting from the application
// menu itself is untouched and quits immediately.
export const QUIT_HOLD_DURATION_MS = 1200;
// A second quick tap of the shortcut is the user insisting: quit immediately.
export const QUIT_DOUBLE_TAP_MS = 500;
// "Still held" is proven by auto-repeat keydowns, not by the absence of a
// release: macOS suppresses a letter's keyUp while the command key is down, so
// a tap's release can go completely unseen and a release-based timer would
// quit anyway. The press is treated as released once no key event has arrived
// for QUIT_HOLD_RELEASE_GRACE_MS past the hold duration. Keyboards with
// auto-repeat disabled cannot hold-to-quit and fall back to the menu's Quit.
export const QUIT_HOLD_RELEASE_GRACE_MS = 600;
export type QuitHoldState = "down" | "up";
export interface QuitHoldKeyInput {
readonly type: string;
readonly key: string;
readonly meta: boolean;
readonly control: boolean;
readonly alt: boolean;
readonly shift: boolean;
readonly isAutoRepeat: boolean;
}
export interface QuitHoldOptions {
readonly platform: NodeJS.Platform;
readonly isEnabled: () => Promise<boolean>;
readonly notify: (state: QuitHoldState) => void;
readonly quit: () => void;
}
export function makeQuitHoldHandler(
options: QuitHoldOptions,
): (event: { preventDefault: () => void }, input: QuitHoldKeyInput) => void {
const modifierKey = options.platform === "darwin" ? "meta" : "control";
let watchdog: NodeJS.Timeout | undefined;
let holding = false;
// Set once isEnabled resolves true; auto-repeats may only quit when armed.
let armed = false;
let heldSince = 0;
let lastPressAt = 0;
// Incremented on every new press and every release/quit so a pending
// isEnabled() resolution from a superseded press cannot arm (or quit for)
// the current one.
let generation = 0;
const clearWatchdog = () => {
if (watchdog !== undefined) {
clearTimeout(watchdog);
watchdog = undefined;
}
};
const release = () => {
if (!holding) return;
generation += 1;
holding = false;
armed = false;
clearWatchdog();
options.notify("up");
};
// Dismisses the overlay first: if the quit is cancelled downstream the
// renderer must not be left with a stuck "Hold to Quit" hint.
const quitNow = () => {
release();
options.quit();
};
return (event, input) => {
const key = input.key.toLowerCase();
if (input.type === "keyUp") {
if (key === "q" || key === modifierKey) release();
return;
}
if (input.type !== "keyDown") return;
const modifierDown = options.platform === "darwin" ? input.meta : input.control;
if (!modifierDown || input.alt || input.shift || key !== "q") {
// Any other key (or an extra modifier) pressed mid-hold breaks the
// gesture; without this the hold timer keeps running through the
// interruption and the next qualifying repeat would quit early. The
// interrupted press also stops counting toward a double tap — but only
// here, not in release(), which runs mid-restart on an unseen-release
// re-press and must not wipe that press's own tap timestamp.
if (holding && !input.isAutoRepeat) {
lastPressAt = 0;
release();
}
return;
}
event.preventDefault();
if (input.isAutoRepeat) {
if (armed && Date.now() - heldSince >= QUIT_HOLD_DURATION_MS) {
quitNow();
}
return;
}
const now = Date.now();
const previousPressAt = lastPressAt;
lastPressAt = now;
// A fresh keydown while "holding" means the key came back down after a
// release macOS never delivered — so both branches below see real taps.
if (previousPressAt !== 0 && now - previousPressAt <= QUIT_DOUBLE_TAP_MS) {
quitNow();
return;
}
if (holding) release();
generation += 1;
const pressGeneration = generation;
holding = true;
heldSince = now;
options.notify("down");
void options.isEnabled().then(
(enabled) => {
if (generation !== pressGeneration) return;
if (!enabled) {
// Hold-to-quit disabled: a single press quits immediately.
quitNow();
return;
}
armed = true;
// No auto-repeat by then means the key was released (possibly with a
// suppressed keyUp) or repeat is disabled; either way, don't quit.
watchdog = setTimeout(() => {
watchdog = undefined;
release();
}, QUIT_HOLD_DURATION_MS + QUIT_HOLD_RELEASE_GRACE_MS);
},
// A failed settings read must never strand the quit request.
() => {
if (generation !== pressGeneration) return;
quitNow();
},
);
};
}
@@ -77,6 +77,7 @@ const backendConfigurationLayer = Layer.succeed(
const netLayer = Layer.succeed(NetService.NetService, {
canListenOnHost: () => Effect.succeed(true),
isPortAvailableOnLoopback: () => Effect.succeed(true),
hasListenerOnHost: () => Effect.succeed(false),
reserveLoopbackPort: () => Effect.succeed(41773),
findAvailablePort: (preferred) => Effect.succeed(preferred),
} satisfies NetService.NetService["Service"]);
@@ -0,0 +1,323 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
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 Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Scope from "effect/Scope";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopWslServerTree from "./DesktopWslServerTree.ts";
// The service reads packaged Windows roots through the (asar-aware, in
// Electron) fs, so a plain directory named server.asar exercises the full
// extraction path under plain Node.
const environmentLayer = (input: {
readonly baseDir: string;
readonly resourcesPath: string;
readonly appVersion?: string;
readonly isPackaged?: boolean;
}) =>
DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: input.baseDir,
platform: "win32",
processArch: "x64",
appVersion: input.appVersion ?? "1.2.3",
appPath: "/repo",
isPackaged: input.isPackaged ?? true,
resourcesPath: input.resourcesPath,
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(
NodeServices.layer,
DesktopConfig.layerTest({
T3CODE_HOME: input.baseDir,
T3CODE_MODE: "desktop",
}),
),
),
);
const withTempDir = <A, E, R>(
run: (tempDir: string) => Effect.Effect<A, E, R>,
): Effect.Effect<
A,
E | PlatformError.PlatformError,
FileSystem.FileSystem | Exclude<R, Scope.Scope>
> =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const tempDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-wsl-server-tree-test-",
});
return yield* run(tempDir);
}).pipe(Effect.scoped);
const ensureWith = (input: {
readonly baseDir: string;
readonly resourcesPath: string;
readonly appVersion?: string;
readonly isPackaged?: boolean;
}) =>
Effect.gen(function* () {
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
return yield* tree.ensure;
}).pipe(
Effect.provide(DesktopWslServerTree.layer.pipe(Layer.provideMerge(environmentLayer(input)))),
);
describe("DesktopWslServerTree", () => {
it.effect("bounds entry work across an eight-way nested tree", () =>
Effect.gen(function* () {
const active = yield* Ref.make(0);
const maxActive = yield* Ref.make(0);
const visited = yield* Ref.make(0);
yield* DesktopWslServerTree.forEachBoundedTree([{ depth: 0, id: "root" }], (node) =>
Effect.acquireUseRelease(
Effect.gen(function* () {
const current = yield* Ref.updateAndGet(active, (count) => count + 1);
yield* Ref.update(maxActive, (maximum) => Math.max(maximum, current));
yield* Ref.update(visited, (count) => count + 1);
}),
() =>
Effect.gen(function* () {
// Give every task in the current batch a chance to overlap.
yield* Effect.yieldNow;
if (node.depth === 4) return [];
return Array.from({ length: 8 }, (_, index) => ({
depth: node.depth + 1,
id: `${node.id}.${String(index)}`,
}));
}),
() => Ref.update(active, (count) => count - 1),
),
);
assert.equal(yield* Ref.get(active), 0);
assert.equal(yield* Ref.get(maxActive), 8);
assert.equal(yield* Ref.get(visited), 4_681);
}),
);
it.effect("returns the server root unchanged when it is a plain directory (dev)", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const result = yield* ensureWith({
baseDir: tempDir,
resourcesPath: tempDir,
isPackaged: false,
});
assert.isTrue(result.ok);
assert.isFalse(result.ok && result.root.endsWith(".asar"));
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("extracts an archive root into a version-keyed state directory", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(
path.join(serverRoot, "apps/server/dist/bin.mjs"),
"server-entry",
);
yield* fileSystem.makeDirectory(path.join(serverRoot, "node_modules/effect"), {
recursive: true,
});
yield* fileSystem.writeFileString(
path.join(serverRoot, "node_modules/effect/package.json"),
"{}",
);
const result = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(result.ok);
const root = result.ok ? result.root : "";
assert.include(root, path.join("wsl-server-tree", "1.2.3"));
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
assert.equal(entry, "server-entry");
const dep = yield* fileSystem.exists(path.join(root, "node_modules/effect/package.json"));
assert.isTrue(dep);
const marker = yield* fileSystem.readFileString(
path.join(root, "t3code-wsl-server-tree.json"),
);
assert.include(marker, '"version":"1.2.3"');
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("serializes concurrent extraction callers and publishes one complete tree", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const resourcesPath = path.join(tempDir, "resources");
const serverRoot = path.join(resourcesPath, "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(
path.join(serverRoot, "apps/server/dist/bin.mjs"),
"server-entry",
);
const results = yield* Effect.gen(function* () {
const tree = yield* DesktopWslServerTree.DesktopWslServerTree;
return yield* Effect.all([tree.ensure, tree.ensure], { concurrency: "unbounded" });
}).pipe(
Effect.provide(
DesktopWslServerTree.layer.pipe(
Layer.provideMerge(environmentLayer({ baseDir: tempDir, resourcesPath })),
),
),
);
assert.isTrue(results.every((result) => result.ok));
const roots = results.flatMap((result) => (result.ok ? [result.root] : []));
assert.lengthOf(new Set(roots), 1);
assert.equal(
yield* fileSystem.readFileString(path.join(roots[0] ?? "", "apps/server/dist/bin.mjs")),
"server-entry",
);
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reuses a completed extraction instead of copying again", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "v1");
const first = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(first.ok);
// Mutate the source; a reused tree must keep the first copy.
yield* fileSystem.writeFileString(
path.join(serverRoot, "apps/server/dist/bin.mjs"),
"v2-should-not-appear",
);
const second = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(second.ok);
const root = second.ok ? second.root : "";
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
assert.equal(entry, "v1");
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("sweeps stale version directories and leftover partials after extraction", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "x");
// T3CODE_HOME is set to tempDir, so the desktop state dir resolves to
// <tempDir>/userdata (no .t3 segment).
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.0.0"), { recursive: true });
yield* fileSystem.makeDirectory(path.join(treeRoot, "1.2.3.partial"), { recursive: true });
const result = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
});
assert.isTrue(result.ok);
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.0.0")));
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3.partial")));
assert.isTrue(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("re-extracts when the app version changes", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const serverRoot = path.join(tempDir, "resources", "server.asar");
yield* fileSystem.makeDirectory(path.join(serverRoot, "apps/server/dist"), {
recursive: true,
});
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "old");
const first = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
appVersion: "1.2.3",
});
assert.isTrue(first.ok);
yield* fileSystem.writeFileString(path.join(serverRoot, "apps/server/dist/bin.mjs"), "new");
const second = yield* ensureWith({
baseDir: tempDir,
resourcesPath: path.join(tempDir, "resources"),
appVersion: "1.2.4",
});
assert.isTrue(second.ok);
const root = second.ok ? second.root : "";
assert.include(root, "1.2.4");
const entry = yield* fileSystem.readFileString(path.join(root, "apps/server/dist/bin.mjs"));
assert.equal(entry, "new");
// The previous version's tree is gone.
const treeRoot = path.dirname(root);
assert.isFalse(yield* fileSystem.exists(path.join(treeRoot, "1.2.3")));
}),
).pipe(Effect.provide(NodeServices.layer)),
);
it.effect("reports a retryable failure when the archive cannot be read", () =>
withTempDir((tempDir) =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const result = yield* ensureWith({
baseDir: tempDir,
// resources dir exists but server.asar does not
resourcesPath: path.join(tempDir, "resources"),
});
assert.isFalse(result.ok);
if (!result.ok) {
assert.include(result.reason, "could not be extracted");
assert.isFalse(result.fatal);
}
const treeRoot = path.join(tempDir, "userdata", "wsl-server-tree");
const leftovers = yield* fileSystem
.readDirectory(treeRoot)
.pipe(Effect.orElseSucceed(() => []));
assert.deepStrictEqual(leftovers, []);
}),
).pipe(Effect.provide(NodeServices.layer)),
);
});
@@ -0,0 +1,226 @@
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 PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
// Packaged Windows builds ship the server tree inside resources/server.asar
// (see scripts/build-desktop-artifact.ts). The Windows primary reads it in
// place through the asar-aware ELECTRON_RUN_AS_NODE runtime, but the WSL
// backend launches plain `wsl.exe -- node`, which cannot read an asar
// archive. This service materializes the archive into a real, version-keyed
// directory the first time the WSL backend starts, and reuses it afterwards —
// so only users who enable WSL ever pay for a loose copy of the server tree.
//
// Reading through Electron's patched fs also transparently returns the
// contents of files that electron-builder/asar left in the server.asar.unpacked
// sibling (native binaries), so a single walk of the archive yields the
// complete tree.
export type WslServerTreeResult =
| { readonly ok: true; readonly root: string }
| { readonly ok: false; readonly reason: string; readonly fatal: boolean };
const MARKER_FILE_NAME = "t3code-wsl-server-tree.json";
const COPY_CONCURRENCY = 8;
const Marker = Schema.Struct({ version: Schema.String });
const decodeMarker = Schema.decodeUnknownEffect(Schema.fromJsonString(Marker));
const encodeMarker = Schema.encodeEffect(Schema.fromJsonString(Marker));
export class DesktopWslServerTreeExtractError extends Schema.TaggedErrorClass<DesktopWslServerTreeExtractError>()(
"DesktopWslServerTreeExtractError",
{
targetDir: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to extract the WSL server tree to ${this.targetDir}.`;
}
}
export class DesktopWslServerTree extends Context.Service<
DesktopWslServerTree,
{
// Resolves the directory the WSL backend should treat as the app root
// (the directory containing apps/server/dist and node_modules). In dev
// the checkout already is that directory; packaged Windows builds extract
// server.asar on first use.
readonly ensure: Effect.Effect<WslServerTreeResult>;
}
>()("@t3tools/desktop/wsl/DesktopWslServerTree") {}
// Child scheduling stays here instead of inside `visit`, so nested directories
// cannot create independent concurrency pools. The LIFO work list also keeps
// traversal memory proportional to the remaining frontier rather than the
// number of active fibers.
export const forEachBoundedTree = <Node, E, R>(
roots: ReadonlyArray<Node>,
visit: (node: Node) => Effect.Effect<ReadonlyArray<Node>, E, R>,
): Effect.Effect<void, E, R> =>
Effect.gen(function* () {
const pending = [...roots];
while (pending.length > 0) {
const batch = pending.splice(-COPY_CONCURRENCY);
const children = yield* Effect.forEach(batch, visit, {
concurrency: COPY_CONCURRENCY,
});
for (const entries of children) {
pending.push(...entries);
}
}
});
interface CopyTreeEntry {
readonly sourcePath: string;
readonly targetPath: string;
}
// Copy using only operations supported by Electron's asar-patched fs. Symlinks
// are not expected because the sidecar is installed with a hoisted, physical
// layout; anything that is neither a file nor a directory is skipped.
const copyTree = (
fs: FileSystem.FileSystem,
join: (first: string, ...rest: string[]) => string,
from: string,
to: string,
): Effect.Effect<void, PlatformError.PlatformError> =>
forEachBoundedTree<CopyTreeEntry, PlatformError.PlatformError, never>(
[{ sourcePath: from, targetPath: to }],
({ sourcePath, targetPath }) =>
Effect.gen(function* () {
const info = yield* fs.stat(sourcePath);
if (info.type === "Directory") {
yield* fs.makeDirectory(targetPath, { recursive: true });
const entries = yield* fs.readDirectory(sourcePath);
return entries.map((entry) => ({
sourcePath: join(sourcePath, entry),
targetPath: join(targetPath, entry),
}));
}
if (info.type === "File") {
// Read and write stay in the same bounded task, so at most eight file
// buffers can be retained while their writes complete.
const bytes = yield* fs.readFile(sourcePath);
yield* fs.writeFile(targetPath, bytes);
}
return [];
}),
);
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const fs = yield* FileSystem.FileSystem;
const join = environment.path.join;
const serverRoot = environment.serverRoot;
const needsExtraction = environment.isPackaged && environment.platform === "win32";
const treeRoot = join(environment.stateDir, "wsl-server-tree");
const version = environment.appVersion;
const versionDir = join(treeRoot, version);
// Remove sibling trees left behind by previous app versions (and aborted
// extractions). Best-effort: a locked file must not block the backend.
const sweepStale = Effect.gen(function* () {
const entries = yield* fs.readDirectory(treeRoot).pipe(Effect.orElseSucceed(() => []));
yield* Effect.forEach(
entries.filter((entry) => entry !== version),
(entry) => fs.remove(join(treeRoot, entry), { recursive: true }).pipe(Effect.ignore),
{ discard: true },
);
});
const markerMatches = Effect.gen(function* () {
const raw = yield* fs.readFileString(join(versionDir, MARKER_FILE_NAME));
const marker = yield* decodeMarker(raw);
return marker.version === version;
}).pipe(Effect.orElseSucceed(() => false));
const extract = Effect.gen(function* () {
yield* Effect.log(`[wsl-server-tree] Extracting ${serverRoot} to ${versionDir}...`);
yield* fs.makeDirectory(treeRoot, { recursive: true });
// Keep the temporary tree beside the target so rename is atomic. Cleanup
// is owned explicitly because a scoped temp-directory finalizer treats the
// successful rename (and therefore missing original path) as an error.
const partialDir = yield* fs.makeTempDirectory({
directory: treeRoot,
prefix: `.${version}.extract-`,
});
yield* Effect.gen(function* () {
yield* copyTree(fs, join, serverRoot, partialDir);
const markerJson = yield* encodeMarker({ version });
yield* fs.writeFileString(join(partialDir, MARKER_FILE_NAME), `${markerJson}\n`);
// The marker is written before the rename, so a directory named after
// the version is complete by construction.
yield* fs.remove(versionDir, { recursive: true }).pipe(Effect.ignore);
yield* fs.rename(partialDir, versionDir);
}).pipe(
Effect.ensuring(fs.remove(partialDir, { recursive: true, force: true }).pipe(Effect.ignore)),
);
yield* Effect.log(`[wsl-server-tree] Extraction complete at ${versionDir}.`);
}).pipe(
Effect.mapError(
(cause) => new DesktopWslServerTreeExtractError({ targetDir: versionDir, cause }),
),
);
// Serialize concurrent ensure calls (backend restarts can overlap): the
// first caller extracts, later callers see the marker and reuse the tree.
const gate = yield* Semaphore.make(1);
const ensure: Effect.Effect<WslServerTreeResult> = gate
.withPermits(1)(
Effect.gen(function* () {
if (!needsExtraction) {
return { ok: true, root: serverRoot } as const;
}
if (yield* markerMatches) {
yield* sweepStale;
return { ok: true, root: versionDir } as const;
}
const result = yield* extract.pipe(
Effect.map(() => ({ ok: true, root: versionDir }) as const),
// Retryable: transient antivirus locks and slow disks are the common
// causes, and the backend manager already bounds preflight retries.
Effect.catch((error) =>
Effect.succeed({
ok: false,
reason: `WSL server files could not be extracted to ${versionDir}: ${
error.cause instanceof Error ? error.cause.message : String(error.cause)
}`,
fatal: false,
} as const),
),
);
if (result.ok) {
yield* sweepStale;
}
return result;
}),
)
.pipe(Effect.withSpan("desktop.wslServerTree.ensure"));
return DesktopWslServerTree.of({ ensure });
});
export const layer = Layer.effect(DesktopWslServerTree, make);
export interface DesktopWslServerTreeTestStub {
readonly result?: WslServerTreeResult;
}
export const layerTest = (stub: DesktopWslServerTreeTestStub = {}) =>
Layer.effect(
DesktopWslServerTree,
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
return DesktopWslServerTree.of({
ensure: Effect.succeed(stub.result ?? { ok: true, root: environment.appRoot }),
});
}),
);
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vite-plus/test";
import { macArchFromGpuRenderer } from "./macArch";
describe("macArchFromGpuRenderer", () => {
it("detects explicit Apple Silicon renderers", () => {
expect(macArchFromGpuRenderer("Apple M4 Pro")).toBe("arm64");
});
it("prefers an Intel GPU marker even when the renderer also mentions Apple", () => {
expect(macArchFromGpuRenderer("ANGLE Metal Renderer: Apple, Intel Iris Plus Graphics")).toBe(
"x64",
);
});
it("uses x64 for ambiguous Safari and unavailable renderer values", () => {
expect(macArchFromGpuRenderer("Apple GPU")).toBe("x64");
expect(macArchFromGpuRenderer("")).toBe("x64");
});
});
+16
View File
@@ -0,0 +1,16 @@
const INTEL_GPU_PATTERN = /intel|amd|radeon|nvidia|geforce/i;
const APPLE_SILICON_GPU_PATTERN = /\bapple\s+m\d/i;
export function macArchFromGpuRenderer(renderer: string): "arm64" | "x64" {
if (INTEL_GPU_PATTERN.test(renderer)) {
return "x64";
}
if (APPLE_SILICON_GPU_PATTERN.test(renderer)) {
return "arm64";
}
// Generic "Apple GPU" renderers are ambiguous on Safari. x64 is the safe
// fallback because Apple Silicon can run it through Rosetta, while Intel
// Macs cannot run an arm64 build.
return "x64";
}
+26 -7
View File
@@ -218,7 +218,7 @@ const mobileEndorsementRows = [
<div class="harness-mark"><img src="/harnesses/cursor_light.svg" alt="" /></div>
<div class="harness-meta">
<div class="harness-name">Cursor</div>
<div class="harness-tag">@cursor/sdk</div>
<div class="harness-tag">cursor-agent</div>
</div>
</div>
<div class="harness">
@@ -391,14 +391,33 @@ const mobileEndorsementRows = [
<script>
import { fetchLatestRelease, RELEASES_URL, type ReleaseAsset } from "../lib/releases";
import { macArchFromGpuRenderer } from "../lib/macArch";
type Platform = { os: "mac" | "win" | "linux"; label: string; arch?: string };
// navigator.userAgent reports "Intel Mac OS X" on both Intel and Apple Silicon
// Macs, so probe the GPU renderer instead: Apple Silicon exposes an "Apple" GPU.
function detectMacArch(): "arm64" | "x64" {
try {
const canvas = document.createElement("canvas");
const gl = (canvas.getContext("webgl") ||
canvas.getContext("experimental-webgl")) as WebGLRenderingContext | null;
const debugInfo = gl?.getExtension("WEBGL_debug_renderer_info");
if (gl && debugInfo) {
const renderer = String(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) ?? "");
return macArchFromGpuRenderer(renderer);
}
} catch {
// fall through to the default below
}
return macArchFromGpuRenderer("");
}
function detectPlatform(): Platform | null {
const ua = navigator.userAgent;
if (/Win/i.test(ua)) return { os: "win", label: "Download for Windows" };
if (/Mac/i.test(ua)) {
return { os: "mac", label: "Download for macOS", arch: "arm64" };
return { os: "mac", label: "Download for macOS", arch: detectMacArch() };
}
if (/Linux/i.test(ua)) return { os: "linux", label: "Download for Linux" };
return null;
@@ -704,7 +723,7 @@ const mobileEndorsementRows = [
height: 44px;
}
/* Three stacked on the left, two on the right — keeps the center CTA clear. */
/* Three above the headline, two beside the CTA — keeps the copy clear. */
.hero-float-mark.hf-claude {
top: 44px;
left: 10px;
@@ -712,8 +731,8 @@ const mobileEndorsementRows = [
}
.hero-float-mark.hf-grok {
top: 240px;
left: 4px;
top: 44px;
left: calc(50% - 39px);
right: auto;
transform: rotate(-4deg);
}
@@ -741,8 +760,8 @@ const mobileEndorsementRows = [
@media (max-width: 340px) {
.hero-float-mark.hf-grok {
top: 220px;
left: 0;
top: 57px;
left: calc(50% - 26px);
width: 52px;
height: 52px;
border-radius: 14px;
+4
View File
@@ -4,6 +4,10 @@
/* ─── Theme tokens ──────────────────────────────────────────────────── */
@layer theme {
:root {
@variant android {
--font-mono: "monospace";
}
@variant light {
/* Page backgrounds */
--color-screen: #f2f2f7;
+7 -2
View File
@@ -3,9 +3,14 @@ import { Image } from "expo-image";
import { View } from "react-native";
import { AppText as Text } from "./AppText";
import { T3_CODE_BRAND_MARK_SOURCE } from "./brandAssets";
const appVariant = Constants.expoConfig?.extra?.appVariant;
const BRAND_MARK_SOURCE =
appVariant === "development"
? require("../../../../assets/dev/blueprint-ios-1024.png")
: appVariant === "preview"
? require("../../../../assets/nightly/nightly-ios-1024.png")
: require("../../../../assets/prod/black-ios-1024.png");
const DEFAULT_STAGE_LABEL =
appVariant === "development" ? "Dev" : appVariant === "preview" ? "Preview" : "Alpha";
@@ -17,7 +22,7 @@ export function BrandMark(props: { readonly compact?: boolean; readonly stageLab
return (
<View className="flex-row items-center gap-3">
<Image
source={T3_CODE_BRAND_MARK_SOURCE}
source={BRAND_MARK_SOURCE}
accessibilityIgnoresInvertColors
style={{
width: iconSize,
-10
View File
@@ -1,10 +0,0 @@
import Constants from "expo-constants";
const appVariant = Constants.expoConfig?.extra?.appVariant;
export const T3_CODE_BRAND_MARK_SOURCE =
appVariant === "development"
? require("../../../../assets/dev/blueprint-ios-1024.png")
: appVariant === "preview"
? require("../../../../assets/nightly/nightly-ios-1024.png")
: require("../../../../assets/prod/black-ios-1024.png");
@@ -1,16 +1,5 @@
import { ORCHESTRATION_CACHE_SCHEMA_VERSION } from "@t3tools/client-runtime/platform";
import {
CommandId,
EnvironmentId,
ProjectId,
ProviderInstanceId,
ThreadId,
type OrchestrationV2ShellSnapshot,
type OrchestrationV2ThreadDetailSnapshot,
type VcsListRefsResult,
} from "@t3tools/contracts";
import { EnvironmentId, type VcsListRefsResult } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
@@ -18,125 +7,6 @@ import { type ClientCacheKind, MobileDatabase } from "../persistence/mobile-data
import { make } from "./environment-cache-store";
const ENVIRONMENT_ID = EnvironmentId.make("environment-1");
const PROJECT_ID = ProjectId.make("project-1");
const THREAD_ID = ThreadId.make("thread-1");
const PROVIDER_INSTANCE_ID = ProviderInstanceId.make("codex");
const NOW = DateTime.makeUnsafe("2026-07-29T12:00:00.000Z");
const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
schemaVersion: 1,
snapshotSequence: 3,
projects: [
{
id: PROJECT_ID,
title: "Project",
workspaceRoot: "/repo",
repositoryIdentity: null,
defaultModelSelection: null,
scripts: [],
createdAt: "2026-07-29T12:00:00.000Z",
updatedAt: "2026-07-29T12:00:00.000Z",
},
],
threads: [
{
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
providerInstanceId: PROVIDER_INSTANCE_ID,
modelSelection: {
instanceId: PROVIDER_INSTANCE_ID,
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
rootThreadId: THREAD_ID,
parentThreadId: null,
relationshipToParent: null,
},
forkedFrom: null,
createdBy: "user",
creationSource: "mobile",
latestRunId: null,
activeRunId: null,
status: "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestUserMessageAt: NOW,
hasActionableProposedPlan: false,
itemCount: 0,
visibleItemCount: 0,
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride: null,
settledAt: NOW,
lastVisitedAt: null,
titleRegeneration: {
requestId: CommandId.make("title-regeneration-1"),
startedAt: NOW,
},
deletedAt: null,
},
],
archivedThreads: [],
};
const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
snapshotSequence: 4,
projection: {
thread: {
id: THREAD_ID,
projectId: PROJECT_ID,
title: "Thread",
providerInstanceId: PROVIDER_INSTANCE_ID,
modelSelection: {
instanceId: PROVIDER_INSTANCE_ID,
model: "gpt-5.4",
},
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: {
rootThreadId: THREAD_ID,
parentThreadId: null,
relationshipToParent: null,
},
forkedFrom: null,
createdBy: "user",
creationSource: "mobile",
createdAt: NOW,
updatedAt: NOW,
archivedAt: null,
settledOverride: null,
settledAt: NOW,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
attempts: [],
nodes: [],
subagents: [],
subagentActivations: [],
providerSessions: [],
providerThreads: [],
providerTurns: [],
runtimeRequests: [],
messages: [],
plans: [],
turnItems: [],
checkpointScopes: [],
checkpoints: [],
contextHandoffs: [],
contextTransfers: [],
visibleTurnItems: [],
updatedAt: NOW,
},
};
const REFS: VcsListRefsResult = {
refs: [
{
@@ -158,16 +28,13 @@ function cacheId(environmentId: EnvironmentId, kind: ClientCacheKind, cacheKey:
function makeDatabase() {
const values = new Map<string, string>();
const schemaVersions = new Map<string, number>();
const removed: Array<string> = [];
const database = MobileDatabase.of({
loadCache: (environmentId, kind, cacheKey) =>
Effect.succeed(Option.fromUndefinedOr(values.get(cacheId(environmentId, kind, cacheKey)))),
saveCache: (environmentId, kind, cacheKey, schemaVersion, payload) =>
saveCache: (environmentId, kind, cacheKey, _schemaVersion, payload) =>
Effect.sync(() => {
const id = cacheId(environmentId, kind, cacheKey);
values.set(id, payload);
schemaVersions.set(id, schemaVersion);
values.set(cacheId(environmentId, kind, cacheKey), payload);
}),
removeCache: (environmentId, kind, cacheKey) =>
Effect.sync(() => {
@@ -192,40 +59,10 @@ function makeDatabase() {
loadPreferencesJson: Effect.succeed(Option.none()),
savePreferencesJson: () => Effect.void,
});
return { database, removed, schemaVersions, values };
return { database, removed, values };
}
describe("mobile SQLite environment cache store", () => {
it.effect("round-trips V2 shell and thread DateTime fields with the shared cache schema", () =>
Effect.gen(function* () {
const memory = makeDatabase();
const store = yield* make().pipe(Effect.provideService(MobileDatabase, memory.database));
yield* store.saveShell(ENVIRONMENT_ID, SHELL_SNAPSHOT);
yield* store.saveThread(ENVIRONMENT_ID, THREAD_SNAPSHOT);
const shell = Option.getOrThrow(yield* store.loadShell(ENVIRONMENT_ID));
const thread = Option.getOrThrow(yield* store.loadThread(ENVIRONMENT_ID, THREAD_ID));
expect(DateTime.formatIso(shell.threads[0]!.updatedAt)).toBe("2026-07-29T12:00:00.000Z");
expect(DateTime.formatIso(shell.threads[0]!.latestUserMessageAt!)).toBe(
"2026-07-29T12:00:00.000Z",
);
expect(DateTime.formatIso(shell.threads[0]!.titleRegeneration!.startedAt)).toBe(
"2026-07-29T12:00:00.000Z",
);
expect(DateTime.formatIso(thread.projection.thread.updatedAt)).toBe(
"2026-07-29T12:00:00.000Z",
);
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "shell", "snapshot"))).toBe(
ORCHESTRATION_CACHE_SCHEMA_VERSION,
);
expect(memory.schemaVersions.get(cacheId(ENVIRONMENT_ID, "thread", THREAD_ID))).toBe(
ORCHESTRATION_CACHE_SCHEMA_VERSION,
);
}),
);
it.effect("round-trips schema-validated VCS refs", () =>
Effect.gen(function* () {
const memory = makeDatabase();
@@ -1,11 +1,14 @@
import {
ConnectionPersistenceError,
EnvironmentCacheStore,
ORCHESTRATION_CACHE_SCHEMA_VERSION,
StoredOrchestrationShellSnapshot,
StoredOrchestrationThreadSnapshot,
} from "@t3tools/client-runtime/platform";
import { type EnvironmentId, ServerConfig, VcsListRefsResult } from "@t3tools/contracts";
import {
type EnvironmentId,
OrchestrationShellSnapshot,
OrchestrationThreadDetailSnapshot,
ServerConfig,
VcsListRefsResult,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
@@ -13,9 +16,25 @@ import * as Schema from "effect/Schema";
import * as MobileDatabase from "../persistence/mobile-database";
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
// makes pre-pagination clients discard the record instead of decoding a
// partial thread as complete (rollback safety).
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
snapshot: OrchestrationShellSnapshot,
});
const StoredThreadSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
threadId: Schema.String,
snapshot: OrchestrationThreadDetailSnapshot,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
environmentId: Schema.String,
@@ -29,17 +48,13 @@ const StoredVcsRefs = Schema.Struct({
});
const decodeStoredShellSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
);
const encodeStoredShellSnapshot = Schema.encodeEffect(
Schema.fromJsonString(StoredOrchestrationShellSnapshot),
Schema.fromJsonString(StoredShellSnapshot),
);
const encodeStoredShellSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredShellSnapshot));
const decodeStoredThreadSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
);
const encodeStoredThreadSnapshot = Schema.encodeEffect(
Schema.fromJsonString(StoredOrchestrationThreadSnapshot),
Schema.fromJsonString(StoredThreadSnapshot),
);
const encodeStoredThreadSnapshot = Schema.encodeEffect(Schema.fromJsonString(StoredThreadSnapshot));
const decodeStoredServerConfig = Schema.decodeUnknownEffect(
Schema.fromJsonString(StoredServerConfig),
);
@@ -115,12 +130,12 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
),
saveShell: Effect.fn("MobileEnvironmentCache.saveShell")(function* (environmentId, snapshot) {
const payload = yield* encodeStoredShellSnapshot({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
schemaVersion: SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-shell", cause)));
yield* database
.saveCache(environmentId, "shell", "snapshot", ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
.saveCache(environmentId, "shell", "snapshot", SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-shell")));
}),
loadThread: Effect.fn("MobileEnvironmentCache.loadThread")((environmentId, threadId) =>
@@ -138,15 +153,15 @@ export const make = Effect.fn("MobileEnvironmentCacheStore.make")(function* () {
}),
),
saveThread: Effect.fn("MobileEnvironmentCache.saveThread")(function* (environmentId, snapshot) {
const threadId = snapshot.projection.thread.id;
const threadId = snapshot.thread.id;
const payload = yield* encodeStoredThreadSnapshot({
schemaVersion: ORCHESTRATION_CACHE_SCHEMA_VERSION,
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId,
snapshot,
}).pipe(Effect.mapError((cause) => persistenceError("save-thread", cause)));
yield* database
.saveCache(environmentId, "thread", threadId, ORCHESTRATION_CACHE_SCHEMA_VERSION, payload)
.saveCache(environmentId, "thread", threadId, THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION, payload)
.pipe(Effect.mapError(mapDatabaseError("save-thread")));
}),
removeThread: Effect.fn("MobileEnvironmentCache.removeThread")((environmentId, threadId) =>
+2 -9
View File
@@ -1,9 +1,6 @@
import { Connection } from "@t3tools/client-runtime/connection";
import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";
import {
boundedThreadSnapshotLoaderLayer,
threadHistoryControllerLayer,
} from "@t3tools/client-runtime/state/threads";
import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";
import * as Layer from "effect/Layer";
import { Atom } from "effect/unstable/reactivity";
@@ -18,11 +15,7 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(
Layer.provide(runtimeContextLayer),
);
const snapshotLoaderLayer = Layer.mergeAll(
boundedThreadSnapshotLoaderLayer,
shellSnapshotLoaderLayer,
threadHistoryControllerLayer,
);
const snapshotLoaderLayer = Layer.merge(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);
type ConnectionLayerSource =
| typeof Connection.layer
-1
View File
@@ -17,7 +17,6 @@ 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 CatalogStore from "./catalog-store";
function targetPersistenceError(
@@ -1,11 +1,9 @@
import type { ArchivedSnapshotEntry } from "@t3tools/client-runtime/state/threads";
import type { OrchestrationProjectShell, OrchestrationV2ThreadShell } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import type { OrchestrationProjectShell, OrchestrationThreadShell } from "@t3tools/contracts";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import * as DateTime from "effect/DateTime";
import { buildArchivedThreadGroups } from "./archivedThreadList";
import { makeRawThreadShell } from "../../test-fixtures";
const environmentId = EnvironmentId.make("environment-1");
@@ -24,30 +22,42 @@ function makeProject(
}
function makeThread(
input: Pick<OrchestrationV2ThreadShell, "id" | "projectId" | "title"> & {
readonly branch?: string | null;
readonly archivedAt?: string | null;
},
): OrchestrationV2ThreadShell {
const archivedAt = input.archivedAt === undefined ? "2026-06-02T00:00:00.000Z" : input.archivedAt;
return makeRawThreadShell({
input: Partial<OrchestrationThreadShell> &
Pick<OrchestrationThreadShell, "id" | "projectId" | "title">,
): OrchestrationThreadShell {
return {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: "2026-06-02T00:00:00.000Z",
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
archivedAt: archivedAt === null ? null : DateTime.makeUnsafe(archivedAt),
});
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
function makeSnapshot(
projects: ReadonlyArray<OrchestrationProjectShell>,
threads: ReadonlyArray<OrchestrationV2ThreadShell>,
threads: ReadonlyArray<OrchestrationThreadShell>,
targetEnvironmentId = environmentId,
): ArchivedSnapshotEntry {
return {
environmentId: targetEnvironmentId,
snapshot: {
schemaVersion: 1,
snapshotSequence: 1,
projects,
threads,
updatedAt: "2026-06-04T00:00:00.000Z",
},
};
}
@@ -3,7 +3,7 @@ import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/Stac
import { StackActions, useNavigation, type StaticScreenProps } from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useCallback, useEffect, useRef, useState } from "react";
import { Alert, Platform, ScrollView, View } from "react-native";
import { Alert, Linking, Platform, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
@@ -95,9 +95,21 @@ export function ConnectionsNewRouteScreen({
return;
}
if (permission.canAskAgain) {
Alert.alert(
"Camera access needed",
"Allow camera access to scan an environment pairing QR code.",
);
return;
}
Alert.alert(
"Camera access needed",
"Allow camera access to scan an environment pairing QR code.",
"Camera access was denied for this app. Open Settings to enable it.",
[
{ text: "Cancel", style: "cancel" },
{ text: "Open Settings", onPress: () => void Linking.openSettings() },
],
);
}, [cameraPermission?.granted, requestCameraPermission]);
+3 -3
View File
@@ -190,7 +190,7 @@ function deriveEmptyState(props: {
return {
title: "No threads yet",
detail: "Create a task to start a new coding runtime in one of your connected projects.",
detail: "Create a task to start a new coding session in one of your connected projects.",
loading: false,
};
}
@@ -814,7 +814,7 @@ export function HomeScreen(props: HomeScreenProps) {
?.providers.find(
(provider) =>
provider.instanceId ===
(thread.runtime?.providerInstanceId ?? thread.modelSelection.instanceId),
(thread.session?.providerInstanceId ?? thread.modelSelection.instanceId),
)?.driver ?? null
}
environmentLabel={
@@ -1101,7 +1101,7 @@ export function HomeScreen(props: HomeScreenProps) {
detail="Choose another environment or create a new task."
/>
) : (
<EmptyState title="No threads yet" detail="Create a task to start a new coding runtime." />
<EmptyState title="No threads yet" detail="Create a task to start a new coding session." />
)
) : null;
// Self-contained: v1's listEmpty keys off projectGroups, which ignores the
@@ -1,10 +1,8 @@
import {
presentThreadShell,
type EnvironmentProject,
type EnvironmentThreadShell,
import type {
EnvironmentProject,
EnvironmentThreadShell,
} from "@t3tools/client-runtime/state/shell";
import { EnvironmentId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -34,41 +32,29 @@ function makeProject(id: string, title: string): EnvironmentProject {
};
}
const threadTimestamp = DateTime.makeUnsafe("2026-06-01T00:00:00.000Z");
function makeThread(id: string, projectId: ProjectId): EnvironmentThreadShell {
const threadId = ThreadId.make(id);
return presentThreadShell(environmentId, {
id: threadId,
return {
environmentId,
id: ThreadId.make(id),
projectId,
title: `Thread ${id}`,
providerInstanceId: ProviderInstanceId.make("codex"),
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
activeProviderThreadId: null,
lineage: { rootThreadId: threadId, parentThreadId: null, relationshipToParent: null },
forkedFrom: null,
createdBy: "user",
creationSource: "mobile",
latestRunId: null,
activeRunId: null,
status: "idle",
pendingRuntimeRequest: null,
latestVisibleMessage: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
settledOverride: null,
settledAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
itemCount: 0,
visibleItemCount: 0,
createdAt: threadTimestamp,
updatedAt: threadTimestamp,
archivedAt: null,
deletedAt: null,
});
};
}
function makeGroup(key: string, threadCount: number): HomeThreadGroup {
@@ -11,7 +11,6 @@ import {
buildHomeThreadGroups,
sortHomeProjectScopes,
} from "./homeThreadList";
import { makeThreadShellFixture } from "../../test-fixtures";
function makeProject(
input: Partial<EnvironmentProject> & Pick<EnvironmentProject, "environmentId" | "id" | "title">,
@@ -31,21 +30,25 @@ function makeThread(
input: Partial<EnvironmentThreadShell> &
Pick<EnvironmentThreadShell, "environmentId" | "id" | "projectId" | "title">,
): EnvironmentThreadShell {
return makeThreadShellFixture({
return {
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
latestTurn: null,
createdAt: "2026-06-01T00:00:00.000Z",
updatedAt: "2026-06-01T00:00:00.000Z",
archivedAt: null,
session: null,
latestUserMessageAt: null,
hasPendingApprovals: false,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
...input,
});
settledOverride: input.settledOverride ?? null,
settledAt: input.settledAt ?? null,
};
}
const NOW = Date.parse("2026-06-29T00:00:00.000Z");
@@ -1,40 +0,0 @@
import { ProviderInstanceId, RunId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
import { threadCanArchive } from "./threadArchive";
function runtime(
status: ThreadRuntimeSummary["status"],
activeRunId: ThreadRuntimeSummary["activeRunId"],
): ThreadRuntimeSummary {
return {
status,
activeRunId,
providerInstanceId: ProviderInstanceId.make("codex"),
providerName: "codex",
lastError: null,
updatedAt: "2026-07-28T10:00:00.000Z",
};
}
describe("threadCanArchive", () => {
it("blocks provider-active work", () => {
const activeRunId = RunId.make("run-live");
expect(threadCanArchive(runtime("preparing", activeRunId))).toBe(false);
expect(threadCanArchive(runtime("starting", activeRunId))).toBe(false);
expect(threadCanArchive(runtime("running", activeRunId))).toBe(false);
});
it("only allows queued work when no provider run remains active", () => {
const activeRunId = RunId.make("run-live");
expect(threadCanArchive(runtime("queued", null))).toBe(true);
expect(threadCanArchive(runtime("queued", activeRunId))).toBe(false);
});
it("allows post-provider waiting work despite a retained active run id", () => {
const staleActiveRunId = RunId.make("run-finished");
expect(threadCanArchive(runtime("waiting", null))).toBe(true);
expect(threadCanArchive(runtime("waiting", staleActiveRunId))).toBe(true);
});
});
@@ -1,16 +0,0 @@
import type { ThreadRuntimeSummary } from "@t3tools/client-runtime/state/models";
/**
* Archiving may discard queued work, but it must not detach a provider while
* that provider is still executing a turn.
*/
export function threadCanArchive(runtime: ThreadRuntimeSummary | null | undefined): boolean {
if (runtime?.status === "queued") {
return runtime.activeRunId === null;
}
return (
runtime?.status !== "preparing" &&
runtime?.status !== "starting" &&
runtime?.status !== "running"
);
}
@@ -17,7 +17,6 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { threadCanArchive } from "./threadArchive";
/** Version skew: never send settle/unsettle to a server that predates them
(capability defaults false on decode for older servers). */
@@ -129,9 +128,13 @@ function useThreadActionExecutor(
);
return false;
}
// The server cancels queued runs on archive. Only an actual provider
// turn still needs the user to interrupt it first.
if (action === "archive" && !threadCanArchive(thread.runtime)) {
// Archive keeps its original, narrower guard: never interrupt a
// thread mid-turn.
if (
action === "archive" &&
thread.session?.status === "running" &&
thread.session.activeTurnId != null
) {
Alert.alert(
actionFailureTitle(action),
"This thread is working. Interrupt it first, then try again.",
@@ -55,10 +55,7 @@ export function subscribeToHardwareKeyboardCommandRegistrations(listener: () =>
export function dispatchHardwareKeyboardCommand(command: HardwareKeyboardCommand): boolean {
const commandHandlers = handlers.get(command);
if (!commandHandlers) return false;
const handlersInRegistrationOrder = Array.from(commandHandlers);
for (let index = handlersInRegistrationOrder.length - 1; index >= 0; index -= 1) {
const handler = handlersInRegistrationOrder[index];
if (!handler) continue;
for (const handler of [...commandHandlers].toReversed()) {
if (handler() !== false) return true;
}
return false;
@@ -6,6 +6,7 @@ type AddProjectDestinationRouteParams = {
readonly source?: string | string[];
readonly remoteUrl?: string | string[];
readonly repositoryTitle?: string | string[];
readonly repositoryName?: string | string[];
};
export function AddProjectDestinationRoute({
@@ -7,6 +7,9 @@ import {
canCreateProjectInEnvironment,
findExistingAddProject,
getAddProjectInitialQuery,
getCloneDestinationBrowsePath,
getCloneDestinationPath,
getCloneDirectoryName,
resolveAddProjectPath,
sortAddProjectProviderSources,
type AddProjectRemoteSource,
@@ -23,8 +26,8 @@ import {
} from "@t3tools/client-runtime/state/filesystem";
import {
appendBrowsePathSegment,
ensureBrowseDirectoryPath,
inferProjectTitleFromPath,
isWindowsPlatform,
} from "@t3tools/client-runtime/state/projects";
import { CommandId, type EnvironmentId, ProjectId } from "@t3tools/contracts";
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
@@ -236,11 +239,18 @@ function ProjectPathInput(props: {
);
}
function useBrowsePathInput(environment: EnvironmentOption | null) {
// `pinnedDirectoryName` is the repository folder the clone destination keeps
// appended to whatever folder the user browses to. The plain add-project flow
// passes nothing, so it keeps proposing the browsed folder itself.
function useBrowsePathInput(environment: EnvironmentOption | null, pinnedDirectoryName = "") {
const environmentId = environment?.environmentId ?? null;
const environmentBaseDirectory = environment?.baseDirectory ?? null;
const clonePathCaseSensitive = !isWindowsPlatform(environment?.platform ?? "");
const [pathInput, commitPathInput] = useState(() =>
getAddProjectInitialQuery(environmentBaseDirectory),
getCloneDestinationPath(
getAddProjectInitialQuery(environmentBaseDirectory),
pinnedDirectoryName,
),
);
const previousEnvironmentIdRef = useRef(environmentId);
const environmentRuntime = useRemoteEnvironmentRuntime(environmentId);
@@ -259,33 +269,60 @@ function useBrowsePathInput(environment: EnvironmentOption | null) {
[browseNavigation],
);
const navigateToBrowsePath = useCallback(
async (path: string) => {
async (input: {
readonly browseDirectoryPath: string;
readonly selectedDirectoryName?: string;
}) => {
const selectedDirectoryPath = input.selectedDirectoryName
? appendBrowsePathSegment(input.browseDirectoryPath, input.selectedDirectoryName)
: input.browseDirectoryPath;
const nextPathInput =
pinnedDirectoryName && input.selectedDirectoryName
? getCloneDestinationBrowsePath({
browseDirectoryPath: input.browseDirectoryPath,
selectedDirectoryName: input.selectedDirectoryName,
cloneDirectoryName: pinnedDirectoryName,
caseSensitive: clonePathCaseSensitive,
})
: getCloneDestinationPath(selectedDirectoryPath, pinnedDirectoryName);
setIsBrowseNavigating(true);
const committed = await browseNavigation.run(
async () => {
if (environment && canPreloadBrowsePath(environmentRuntime?.connectionState)) {
await loadBrowsePath({
environmentId: environment.environmentId,
input: { partialPath: path },
input: { partialPath: selectedDirectoryPath },
});
}
},
() => commitPathInput(path),
() => commitPathInput(nextPathInput),
);
if (committed) {
setIsBrowseNavigating(false);
}
return committed;
},
[browseNavigation, environment, environmentRuntime?.connectionState, loadBrowsePath],
[
browseNavigation,
clonePathCaseSensitive,
environment,
environmentRuntime?.connectionState,
loadBrowsePath,
pinnedDirectoryName,
],
);
useEffect(() => {
if (environmentId !== null && environmentId !== previousEnvironmentIdRef.current) {
previousEnvironmentIdRef.current = environmentId;
setPathInput(getAddProjectInitialQuery(environmentBaseDirectory));
setPathInput(
getCloneDestinationPath(
getAddProjectInitialQuery(environmentBaseDirectory),
pinnedDirectoryName,
),
);
}
}, [environmentBaseDirectory, environmentId, setPathInput]);
}, [environmentBaseDirectory, environmentId, pinnedDirectoryName, setPathInput]);
useEffect(
() => () => {
@@ -567,6 +604,7 @@ function useCreateProject(environment: EnvironmentOption | null) {
commandId: CommandId.make(uuidv4()),
projectId,
workspaceRoot,
createdAt: new Date().toISOString(),
});
const result = await createProject({
environmentId: environment.environmentId,
@@ -631,6 +669,7 @@ export function AddProjectRepositoryScreen(props: {
source,
remoteUrl,
repositoryTitle: remoteUrl,
repositoryName: getCloneDirectoryName(remoteUrl),
}),
);
setIsSubmitting(false);
@@ -654,6 +693,7 @@ export function AddProjectRepositoryScreen(props: {
source,
remoteUrl: repository.sshUrl,
repositoryTitle: repository.nameWithOwner,
repositoryName: getCloneDirectoryName(repository.nameWithOwner),
}),
);
}
@@ -697,7 +737,11 @@ function FolderBrowser(props: {
readonly environment: EnvironmentOption;
readonly pathInput: string;
readonly setPathInput: (path: string) => void;
readonly navigateToBrowsePath: (path: string) => Promise<boolean>;
readonly navigateToBrowsePath: (input: {
readonly browseDirectoryPath: string;
readonly selectedDirectoryName?: string;
}) => Promise<boolean>;
readonly pinnedDirectoryName?: string;
}) {
const accentColor = useThemeColor("--color-icon-muted");
const browsePath = useMemo(
@@ -716,9 +760,16 @@ function FolderBrowser(props: {
input: browseInput,
}),
);
// A pinned repository folder does not exist yet, so filtering the listing by
// it would empty the folder picker. Anything the user typed still filters.
const pinnedDirectoryName = props.pinnedDirectoryName ?? "";
const pinnedDirectoryMatches = isWindowsPlatform(props.environment.platform)
? browsePath.filterQuery.toLowerCase() === pinnedDirectoryName.toLowerCase()
: browsePath.filterQuery === pinnedDirectoryName;
const browseFilterQuery = pinnedDirectoryMatches ? "" : browsePath.filterQuery;
const { visibleEntries: visibleBrowseEntries } = useMemo(
() => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browsePath.filterQuery),
[browsePath.filterQuery, browseState.data?.entries],
() => filterFilesystemBrowseEntries(browseState.data?.entries ?? [], browseFilterQuery),
[browseFilterQuery, browseState.data?.entries],
);
return (
@@ -746,7 +797,9 @@ function FolderBrowser(props: {
right={null}
onPress={() => {
if (browsePath.parentPath) {
void props.navigateToBrowsePath(browsePath.parentPath);
void props.navigateToBrowsePath({
browseDirectoryPath: browsePath.parentPath,
});
}
}}
/>
@@ -759,11 +812,10 @@ function FolderBrowser(props: {
isFirst={index === 0 && !browsePath.canBrowseUp}
right={null}
onPress={() => {
const nextPath =
browsePath.directoryPath.length > 0
? appendBrowsePathSegment(browsePath.directoryPath, entry.name)
: ensureBrowseDirectoryPath(entry.fullPath);
void props.navigateToBrowsePath(nextPath);
void props.navigateToBrowsePath({
browseDirectoryPath: browsePath.directoryPath,
selectedDirectoryName: entry.name,
});
}}
/>
))}
@@ -835,6 +887,7 @@ export function AddProjectDestinationScreen(props: {
readonly environmentId?: string | string[];
readonly remoteUrl?: string | string[];
readonly repositoryTitle?: string | string[];
readonly repositoryName?: string | string[];
}) {
const cloneRepository = useAtomCommand(sourceControlEnvironment.cloneRepository, {
reportFailure: false,
@@ -843,8 +896,15 @@ export function AddProjectDestinationScreen(props: {
const createProject = useCreateProject(environment);
const remoteUrl = stringParam(props.remoteUrl);
const repositoryTitle = stringParam(props.repositoryTitle);
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } =
useBrowsePathInput(environment);
// A lookup derives this from "owner/repo", a pasted clone URL from its own
// last segment. Older links without the param keep the browsed folder.
// Trim once here: the path input and the folder-list filter must compare the
// same value, or a deep link with a padded param empties the folder picker.
const repositoryName = stringParam(props.repositoryName)?.trim() ?? "";
const { isBrowseNavigating, navigateToBrowsePath, pathInput, setPathInput } = useBrowsePathInput(
environment,
repositoryName,
);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -917,6 +977,7 @@ export function AddProjectDestinationScreen(props: {
navigateToBrowsePath={navigateToBrowsePath}
pathInput={pathInput}
setPathInput={setPathInput}
pinnedDirectoryName={repositoryName}
/>
</>
) : (
@@ -1,7 +1,11 @@
import { describe, expect, it } from "vite-plus/test";
import { MessageId, RunId, type ReviewDiffPreviewSource } from "@t3tools/contracts";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import {
MessageId,
TurnId,
type OrchestrationCheckpointSummary,
type ReviewDiffPreviewSource,
} from "@t3tools/contracts";
import {
buildReviewListItems,
@@ -14,9 +18,9 @@ import {
} from "./reviewModel";
function makeCheckpoint(
input: Partial<ThreadCheckpointSummary> &
Pick<ThreadCheckpointSummary, "runId" | "checkpointTurnCount" | "completedAt">,
): ThreadCheckpointSummary {
input: Partial<OrchestrationCheckpointSummary> &
Pick<OrchestrationCheckpointSummary, "turnId" | "checkpointTurnCount" | "completedAt">,
): OrchestrationCheckpointSummary {
return {
checkpointRef: `refs/t3/checkpoints/thread/${input.checkpointTurnCount}` as any,
status: "ready",
@@ -48,12 +52,12 @@ describe("buildReviewSectionItems", () => {
it("keeps one chip per checkpoint and appends git sources", () => {
const checkpoints = [
makeCheckpoint({
runId: RunId.make("run-1"),
turnId: TurnId.make("turn-1"),
checkpointTurnCount: 1,
completedAt: "2026-04-01T00:00:00.000Z",
}),
makeCheckpoint({
runId: RunId.make("run-2"),
turnId: TurnId.make("turn-2"),
checkpointTurnCount: 2,
completedAt: "2026-04-02T00:00:00.000Z",
}),
+10 -11
View File
@@ -1,7 +1,6 @@
import { parsePatchFiles } from "@pierre/diffs/utils/parsePatchFiles";
import type { ChangeTypes, FileDiffMetadata } from "@pierre/diffs/types";
import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
import type { ReviewDiffPreviewSource } from "@t3tools/contracts";
import type { OrchestrationCheckpointSummary, ReviewDiffPreviewSource } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
import * as Order from "effect/Order";
@@ -129,11 +128,11 @@ export type ReviewParsedDiff =
readonly notice: string | null;
};
function checkpointTitle(checkpoint: ThreadCheckpointSummary): string {
function checkpointTitle(checkpoint: OrchestrationCheckpointSummary): string {
return `Turn ${checkpoint.checkpointTurnCount}`;
}
function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
function checkpointSubtitle(checkpoint: OrchestrationCheckpointSummary): string {
const fileCount = checkpoint.files.length;
if (checkpoint.status !== "ready") {
return `Diff ${checkpoint.status}`;
@@ -142,8 +141,8 @@ function checkpointSubtitle(checkpoint: ThreadCheckpointSummary): string {
}
function compareCheckpointTurnCountDescending(
left: ThreadCheckpointSummary,
right: ThreadCheckpointSummary,
left: OrchestrationCheckpointSummary,
right: OrchestrationCheckpointSummary,
): -1 | 0 | 1 {
if (left.checkpointTurnCount === right.checkpointTurnCount) {
return 0;
@@ -152,7 +151,7 @@ function compareCheckpointTurnCountDescending(
return left.checkpointTurnCount > right.checkpointTurnCount ? -1 : 1;
}
const readyCheckpointOrder = Order.make<ThreadCheckpointSummary>(
const readyCheckpointOrder = Order.make<OrchestrationCheckpointSummary>(
compareCheckpointTurnCountDescending,
);
@@ -511,14 +510,14 @@ function mapRenderableFile(file: FileDiffMetadata): ReviewRenderableFile {
}
export function getReviewSectionIdForCheckpoint(
checkpoint: Pick<ThreadCheckpointSummary, "checkpointTurnCount">,
checkpoint: Pick<OrchestrationCheckpointSummary, "checkpointTurnCount">,
): string {
return `turn:${checkpoint.checkpointTurnCount}`;
}
export function getReadyReviewCheckpoints(
checkpoints: ReadonlyArray<ThreadCheckpointSummary>,
): ReadonlyArray<ThreadCheckpointSummary> {
checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>,
): ReadonlyArray<OrchestrationCheckpointSummary> {
return pipe(
checkpoints,
Arr.filter((checkpoint) => checkpoint.status === "ready"),
@@ -527,7 +526,7 @@ export function getReadyReviewCheckpoints(
}
export function buildReviewSectionItems(input: {
readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
readonly checkpoints: ReadonlyArray<OrchestrationCheckpointSummary>;
readonly gitSections: ReadonlyArray<ReviewDiffPreviewSource>;
readonly turnDiffById: Readonly<Record<string, string | undefined>>;
readonly loadingTurnIds: Readonly<Record<string, boolean | undefined>>;
@@ -1,15 +1,11 @@
import { useCallback, useEffect, useMemo } from "react";
import {
deriveThreadCheckpointSummaries,
type ThreadCheckpointSummary,
} from "@t3tools/client-runtime/state/thread-checkpoints";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import type { EnvironmentId, OrchestrationCheckpointSummary, ThreadId } from "@t3tools/contracts";
import { useCheckpointDiff } from "../../state/queries";
import { useEnvironmentQuery } from "../../state/query";
import { reviewEnvironment } from "../../state/review";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import {
buildReviewSectionItems,
@@ -34,7 +30,7 @@ export function useReviewSections(input: {
}) {
const { environmentId, reviewCache, threadId } = input;
const enabled = input.enabled ?? true;
const selectedThread = useSelectedThreadProjection();
const selectedThread = useSelectedThreadDetail();
const { selectedThreadCwd } = useSelectedThreadWorktree();
const diffPreview = useEnvironmentQuery(
enabled && environmentId !== undefined && selectedThreadCwd !== null
@@ -53,11 +49,8 @@ export function useReviewSections(input: {
}, [diffPreview.data, reviewCache.threadKey]);
const readyCheckpoints = useMemo(
() =>
getReadyReviewCheckpoints(
selectedThread === null ? [] : deriveThreadCheckpointSummaries(selectedThread.projection),
),
[selectedThread],
() => getReadyReviewCheckpoints(selectedThread?.checkpoints ?? []),
[selectedThread?.checkpoints],
);
const checkpointBySectionId = useMemo(
() =>
@@ -66,7 +59,7 @@ export function useReviewSections(input: {
getReviewSectionIdForCheckpoint(checkpoint),
checkpoint,
]),
) as Record<string, ThreadCheckpointSummary>,
) as Record<string, OrchestrationCheckpointSummary>,
[readyCheckpoints],
);
const reviewSections = useMemo(
@@ -1,7 +1,7 @@
import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { StackActions, useNavigation } from "@react-navigation/native";
import { useCallback, useLayoutEffect } from "react";
import { useCallback, useEffect, useLayoutEffect, useRef } from "react";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -25,11 +25,21 @@ function ConfiguredSettingsAuthRouteScreen() {
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
[navigation],
);
const hasBeenSignedIn = useRef(isSignedIn);
if (isSignedIn) {
hasBeenSignedIn.current = true;
}
useEffect(() => {
if (hasBeenSignedIn.current && isLoaded && isSignedIn === false) {
navigation.dispatch(StackActions.popTo("SettingsContent"));
}
}, [isLoaded, isSignedIn, navigation]);
return (
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
hasBeenSignedIn.current ? (
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
) : (
<AuthView isDismissible={false} onHostBack={handleHostBack} />
@@ -0,0 +1,19 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
describe("resolveAgentAwarenessPlatformPresentation", () => {
it("explains that agent awareness settings are unavailable on Android", () => {
expect(resolveAgentAwarenessPlatformPresentation("android")).toEqual({
supported: false,
subtitle: "iOS only",
});
});
it("leaves supported iOS settings unchanged", () => {
expect(resolveAgentAwarenessPlatformPresentation("ios")).toEqual({
supported: true,
subtitle: undefined,
});
});
});
@@ -0,0 +1,8 @@
export function resolveAgentAwarenessPlatformPresentation(platform: string): {
readonly supported: boolean;
readonly subtitle: string | undefined;
} {
return platform === "ios"
? { supported: true, subtitle: undefined }
: { supported: false, subtitle: "iOS only" };
}
@@ -46,6 +46,7 @@ import { useSavedRemoteConnections } from "../../state/use-remote-environment-re
import { SettingsRow } from "./components/SettingsRow";
import { SettingsSection } from "./components/SettingsSection";
import { SettingsSwitchRow } from "./components/SettingsSwitchRow";
import { resolveAgentAwarenessPlatformPresentation } from "./SettingsRouteScreen.logic";
type NotificationStatus = "checking" | "enabled" | "disabled" | "unsupported";
type LiveActivityStatus = "checking" | "enabled" | "disabled" | "signed-out" | "linking";
@@ -144,6 +145,7 @@ function ConfiguredSettingsRouteScreen() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
const agentAwarenessPlatform = resolveAgentAwarenessPlatformPresentation(Platform.OS);
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
@@ -473,10 +475,12 @@ function ConfiguredSettingsRouteScreen() {
icon="bell.badge"
label="Device Notifications"
disabled={
!agentAwarenessPlatform.supported ||
!agentAwarenessPushAvailable ||
notificationStatus === "checking" ||
notificationStatus === "unsupported"
}
subtitle={agentAwarenessPlatform.subtitle}
// Only reads as on when this device is actually registered with the
// relay; otherwise notifications cannot be delivered regardless of
// the local iOS permission.
@@ -487,6 +491,7 @@ function ConfiguredSettingsRouteScreen() {
/>
<SettingsSwitchRow
disabled={
!agentAwarenessPlatform.supported ||
!agentAwarenessPushAvailable ||
!isLoaded ||
liveActivityStatus === "checking" ||
@@ -494,6 +499,7 @@ function ConfiguredSettingsRouteScreen() {
}
icon="bolt.circle"
label="Live Activity Updates"
subtitle={agentAwarenessPlatform.subtitle}
// Same gate: a saved preference is meaningless until the device
// registration the relay needs to push updates has succeeded.
value={
@@ -11,6 +11,7 @@ export function SettingsSwitchRow(props: {
readonly disabled?: boolean;
readonly icon: SymbolName;
readonly label: string;
readonly subtitle?: string;
readonly value: boolean;
readonly onValueChange: (value: boolean) => void;
}) {
@@ -27,7 +28,12 @@ export function SettingsSwitchRow(props: {
}
>
<SymbolView name={props.icon} size={22} tintColor={icon} type="monochrome" weight="regular" />
<Text className="flex-1 text-lg text-foreground">{props.label}</Text>
<View className="min-w-0 flex-1">
<Text className="text-lg text-foreground">{props.label}</Text>
{props.subtitle ? (
<Text className="text-sm text-foreground-muted">{props.subtitle}</Text>
) : null}
</View>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
@@ -1,4 +1,5 @@
import {
isProviderSendTurnSupportedImageMimeType,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
} from "@t3tools/contracts";
@@ -162,6 +163,13 @@ export async function buildIncomingShareDraft(input: {
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
continue;
}
if (!isProviderSendTurnSupportedImageMimeType(mimeType)) {
warnings.push(
`'${resolved?.originalName ?? fallbackName(uri, index, mimeType)}' is not a supported image type.`,
);
await releaseOwnedFiles(input.fileReader, [uri, payload.value]);
continue;
}
if (
resolved?.contentSize !== null &&
resolved?.contentSize !== undefined &&
@@ -40,7 +40,7 @@ import {
useKnownTerminalSessions,
} from "../../state/use-terminal-session";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadProjection } from "../../state/use-thread-detail";
import { useSelectedThreadDetail } from "../../state/use-thread-detail";
import { EnvironmentConnectionNotice } from "../connection/EnvironmentConnectionNotice";
import { useAdaptiveWorkspaceLayout } from "../layout/AdaptiveWorkspaceLayout";
import { TerminalSurface } from "./NativeTerminalSurface";
@@ -172,9 +172,7 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
const params = props.route.params;
const { selectedThread, selectedThreadProject, selectedEnvironmentConnection } =
useThreadSelection();
const selectedThreadDetail = useSelectedThreadProjection();
const selectedThreadDetailWorktreePath =
selectedThreadDetail?.projection.thread.worktreePath ?? null;
const selectedThreadDetail = useSelectedThreadDetail();
const routeEnvironmentIdRaw = firstRouteParam(params.environmentId);
const routeThreadIdRaw = firstRouteParam(params.threadId);
const routeEnvironmentId = routeEnvironmentIdRaw
@@ -285,13 +283,13 @@ export function ThreadTerminalRouteScreen(props: ThreadTerminalRouteScreenProps)
activeSessionLocation: activeKnownSession?.state.summary ?? null,
workspaceRoot: selectedThreadProject.workspaceRoot,
threadShellWorktreePath: selectedThread.worktreePath ?? null,
threadDetailWorktreePath: selectedThreadDetailWorktreePath,
threadDetailWorktreePath: selectedThreadDetail?.worktreePath ?? null,
});
}, [
activeKnownSession?.state.summary,
pendingLaunch,
selectedThread,
selectedThreadDetailWorktreePath,
selectedThreadDetail?.worktreePath,
selectedThreadProject?.workspaceRoot,
]);
const [initialLaunchLocationEntry, setInitialLaunchLocationEntry] = useState(() => ({
@@ -20,7 +20,6 @@ import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { ComposerEditor, type ComposerEditorHandle } from "../../components/ComposerEditor";
import {
@@ -51,12 +50,13 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry";
import { useNewTaskFlow } from "./new-task-flow-provider";
import { resolveProjectThreadCreationBranch } from "./projectThreadCreationValidation";
import { useCreateProjectThread } from "./use-project-actions";
import { resolveDraftProjectSelection } from "./new-task-project-selection";
import {
@@ -584,11 +584,17 @@ export function NewTaskDraftScreen(props: {
flow.environments.find(
(environment) => environment.environmentId === flow.selectedEnvironmentId,
)?.environmentLabel ?? "Environment";
const currentBranchName =
const availableCurrentBranchName =
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const selectedBranchName = flow.selectedBranchName ?? currentBranchName;
const selectedBranchName = resolveProjectThreadCreationBranch({
workspaceMode: flow.workspaceMode,
selectedBranch:
flow.selectedBranchName ??
(flow.workspaceMode === "worktree" ? availableCurrentBranchName : null),
currentCheckoutBranch: flow.currentCheckoutBranchName,
});
const selectedBranchLabel = resolveNewTaskBranchLabel({
branchName: selectedBranchName,
startFromOrigin: flow.startFromOrigin,
@@ -711,17 +717,19 @@ export function NewTaskDraftScreen(props: {
// finds no work and ends the card within seconds.
armAgentAwarenessLiveActivityForLocalWork({
environmentId: selectedProject.environmentId,
threadTitle: deriveThreadTitleSeed({
text: initialMessageText,
attachments: draft.attachments,
}),
threadTitle: deriveThreadTitleFromPrompt(initialMessageText),
projectTitle: selectedProject.title,
});
const creationBranch = resolveProjectThreadCreationBranch({
workspaceMode,
selectedBranch: selectedBranchName,
currentCheckoutBranch: flow.currentCheckoutBranchName,
});
const result = await createProjectThread({
project: selectedProject,
modelSelection,
envMode: workspaceMode,
branch: selectedBranchName,
branch: creationBranch,
worktreePath: workspaceMode === "worktree" ? null : selectedWorktreePath,
startFromOrigin,
runtimeMode,
@@ -1,4 +1,4 @@
import type { ProviderApprovalDecision, RuntimeRequestId } from "@t3tools/contracts";
import type { ApprovalRequestId, ProviderApprovalDecision } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
@@ -6,9 +6,9 @@ import type { PendingApproval } from "../../lib/threadActivity";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
readonly respondingApprovalId: RuntimeRequestId | null;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly onRespond: (
requestId: RuntimeRequestId,
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<unknown>;
}
@@ -16,8 +16,6 @@ export interface PendingApprovalCardProps {
export function PendingApprovalCard(props: PendingApprovalCardProps) {
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
// behind this card, so a translucent surface bleeds messages through it.
const canRespond = props.approval.responseCapability === "live";
const disabled = !canRespond || props.respondingApprovalId === props.approval.requestId;
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
@@ -31,23 +29,17 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
{props.approval.detail}
</Text>
) : null}
{!canRespond ? (
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
The provider process for this request is no longer available. Interrupt or restart the run
to continue.
</Text>
) : null}
<View className="flex-row flex-wrap gap-2.5">
<Pressable
className="items-center justify-center rounded-[14px] bg-blue-500 px-3.5 py-3"
disabled={disabled}
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "accept")}
>
<Text className="font-t3-extrabold text-sm text-white">Allow once</Text>
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-neutral-200 px-3.5 py-3 dark:bg-neutral-800"
disabled={disabled}
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "acceptForSession")}
>
<Text className="font-t3-bold text-sm text-neutral-950 dark:text-neutral-50">
@@ -56,7 +48,7 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
</Pressable>
<Pressable
className="items-center justify-center rounded-[14px] bg-rose-100 px-3.5 py-3 dark:bg-rose-500/18"
disabled={disabled}
disabled={props.respondingApprovalId === props.approval.requestId}
onPress={() => void props.onRespond(props.approval.requestId, "decline")}
>
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
@@ -1,5 +1,4 @@
import type { RuntimeRequestId } from "@t3tools/contracts";
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
import { useCallback, useRef } from "react";
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
import Animated, {
@@ -56,14 +55,14 @@ export interface PendingUserInputCardProps {
readonly onInputFocusChange?: (focused: boolean) => void;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: RuntimeRequestId | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (
requestId: RuntimeRequestId,
question: ThreadUserInputQuestion,
requestId: ApprovalRequestId,
question: UserInputQuestion,
label: string,
) => void;
readonly onChangeCustomAnswer: (
requestId: RuntimeRequestId,
requestId: ApprovalRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -90,9 +89,6 @@ const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
export function PendingUserInputCard(props: PendingUserInputCardProps) {
const iconSubtle = useThemeColor("--color-icon-subtle");
const questionCount = props.pendingUserInput.questions.length;
// V2 runtime requests carry response capability: a dead provider process
// cannot accept answers, so the card reads-only until the run restarts.
const canRespond = props.pendingUserInput.responseCapability === "live";
const cardCoverage = props.cardCoverage;
const barHeightRef = useRef(0);
@@ -251,12 +247,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
showsVerticalScrollIndicator
style={{ flexShrink: 1 }}
>
{!canRespond ? (
<Text className="font-sans text-sm leading-5 text-neutral-600 dark:text-neutral-400">
The provider process for this request is no longer available. Interrupt or restart the
run to continue.
</Text>
) : null}
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
@@ -273,7 +263,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
return (
<Pressable
key={option.label}
disabled={!canRespond}
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
@@ -303,7 +292,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
})}
</View>
<TextInput
editable={canRespond}
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
@@ -323,9 +311,7 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
props.answers ? "bg-blue-500" : "bg-neutral-200 dark:bg-neutral-700/60",
)}
disabled={
!canRespond ||
props.answers === null ||
props.respondingUserInputId === props.pendingUserInput.requestId
props.answers === null || props.respondingUserInputId === props.pendingUserInput.requestId
}
onPress={() => void props.onSubmit()}
>
@@ -1,203 +0,0 @@
import * as Haptics from "expo-haptics";
import { SymbolView } from "expo-symbols";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { useNavigation } from "@react-navigation/native";
import { useMemo, useState } from "react";
import { Linking, Pressable, ScrollView, type ColorValue, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import type { ThreadFeedActivity } from "../../lib/threadActivity";
import { buildThreadActivityInspector } from "../../lib/threadActivityInspector";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import { useV2ItemSupport } from "../../state/v2-item-support";
import { buildThreadActivityFileParams } from "./threadActivityFileNavigation";
export function ThreadActivityInspector(props: {
readonly activity: ThreadFeedActivity;
readonly currentThreadId: ThreadId;
readonly environmentId: EnvironmentId;
readonly iconColor: ColorValue;
readonly workspaceRoot?: string | null;
}) {
const navigation = useNavigation();
const row = props.activity.projectedItem;
const support = useV2ItemSupport({
environmentId: props.environmentId,
sourceThreadId: row.sourceThreadId,
sourceItemId: row.sourceItemId,
});
const model = useMemo(
() => buildThreadActivityInspector(props.activity, support, props.currentThreadId),
[props.activity, props.currentThreadId, support],
);
const revertCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, {
label: "checkpoint rollback",
reportFailure: true,
});
const [rollingBack, setRollingBack] = useState(false);
return (
<View className="gap-3">
<View className="flex-row flex-wrap gap-x-4 gap-y-2 rounded-lg border border-neutral-300/50 bg-black/[0.025] p-2.5 dark:border-white/[0.1] dark:bg-white/[0.025]">
{model.fields.map((field) => (
<View key={`${field.label}:${field.value}`} className="min-w-[42%] flex-1 gap-0.5">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
{field.label}
</Text>
<Text selectable className="text-2xs leading-4 text-foreground">
{field.value}
</Text>
</View>
))}
</View>
{model.blocks.map((block) => (
<View key={`${block.label}:${block.value}`} className="gap-1">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
{block.label}
</Text>
<ScrollView
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
style={{ maxHeight: 240 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="text-2xs leading-[17px] text-foreground-muted"
style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}
>
{block.value}
</Text>
</ScrollView>
</View>
))}
{model.fileLinks.length > 0 ? (
<View className="gap-1">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
Files
</Text>
{model.fileLinks.map((link) => {
const relativePath =
resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
(link.path.startsWith("/") ? null : link.path);
return (
<Pressable
key={`${link.path}:${link.line ?? 0}:${link.label}`}
accessibilityRole={relativePath ? "link" : undefined}
disabled={relativePath === null}
onPress={() => {
if (!relativePath) return;
void Haptics.selectionAsync();
navigation.navigate(
"ThreadFile",
buildThreadActivityFileParams({
environmentId: props.environmentId,
currentThreadId: props.currentThreadId,
activitySourceThreadId: row.sourceThreadId,
relativePath,
line: link.line,
}),
);
}}
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
>
<SymbolView
name="doc.text"
size={13}
tintColor={props.iconColor}
type="monochrome"
/>
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
{link.label}
</Text>
</Pressable>
);
})}
</View>
) : null}
{model.webLinks.length > 0 ? (
<View className="gap-1">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
Sources
</Text>
{model.webLinks.map((link) => (
<Pressable
key={link.url}
accessibilityRole="link"
onPress={() => void Linking.openURL(link.url)}
className="min-h-9 flex-row items-center gap-2 rounded-md border border-neutral-300/50 px-2.5 py-1.5 dark:border-white/[0.1]"
>
<SymbolView
name="arrow.up.right.square"
size={13}
tintColor={props.iconColor}
type="monochrome"
/>
<Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
{link.label}
</Text>
</Pressable>
))}
</View>
) : null}
{model.rollbackTarget ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Roll back to this checkpoint"
disabled={rollingBack}
onPress={() => {
setRollingBack(true);
void Haptics.selectionAsync();
void revertCheckpoint({
environmentId: props.environmentId,
input: {
threadId: model.rollbackTarget!.threadId,
checkpointId: model.rollbackTarget!.checkpointId,
scopeId: model.rollbackTarget!.scopeId,
},
}).finally(() => setRollingBack(false));
}}
className="min-h-10 flex-row items-center justify-center gap-2 rounded-lg border border-neutral-300/60 px-3 py-2 dark:border-white/[0.12]"
>
<SymbolView
name={rollingBack ? "hourglass" : "arrow.counterclockwise"}
size={14}
tintColor={props.iconColor}
type="monochrome"
/>
<Text className="font-t3-medium text-xs text-foreground">
{rollingBack ? "Rolling back…" : "Roll back to checkpoint"}
</Text>
</Pressable>
) : null}
<View className="gap-1 border-t border-neutral-300/50 pt-2 dark:border-white/[0.1]">
<Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
Structured details
</Text>
<ScrollView
nestedScrollEnabled
directionalLockEnabled
showsVerticalScrollIndicator
style={{ maxHeight: 280 }}
contentContainerStyle={{ paddingRight: 8 }}
>
<Text
selectable
className="text-2xs leading-[17px] text-foreground-muted"
style={{ fontFamily: "ui-monospace" }}
>
{model.structuredDetails}
</Text>
</ScrollView>
</View>
</View>
);
}
@@ -1,9 +1,8 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type {
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderInteractionMode,
RuntimeMode,
ServerConfig as T3ServerConfig,
@@ -103,11 +102,9 @@ export interface ThreadComposerProps {
* are on screen while they reconcile with the server.
*/
readonly threadSyncPhase?: "loading" | "syncing" | null;
readonly selectedThread: EnvironmentThreadShell;
readonly selectedThread: OrchestrationThreadShell;
readonly serverConfig: T3ServerConfig | null;
readonly queueCount: number;
readonly activeThreadBusy: boolean;
readonly canStopThread: boolean;
readonly environmentId: EnvironmentId;
readonly projectCwd: string | null;
readonly editorRef?: RefObject<ComposerEditorHandle | null>;
@@ -324,12 +321,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
setIsFocused(false);
onEditorFocusChange?.(false);
}, [onEditorFocusChange]);
const showStopAction = props.canStopThread;
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
const sendLabel =
props.connectionState !== "connected" || props.activeThreadBusy || props.queueCount > 0
? "Queue"
: "Send";
props.connectionState !== "connected" || props.queueCount > 0 ? "Queue" : "Send";
const currentModelSelection = props.selectedThread.modelSelection;
const currentRuntimeMode = props.selectedThread.runtimeMode;
const connectionStatus = composerConnectionStatus({
@@ -1,21 +1,21 @@
import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connection";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import type { LegendListRef } from "@legendapp/list/react-native";
import { HeaderHeightContext } from "@react-navigation/elements";
import type {
ApprovalRequestId,
EnvironmentId,
MessageId,
ModelSelection,
OrchestrationThreadShell,
ProviderApprovalDecision,
ProviderInteractionMode,
RuntimeMode,
RuntimeRequestId,
ServerConfig as T3ServerConfig,
ThreadId,
UserInputQuestion,
} from "@t3tools/contracts";
import type { ThreadUserInputQuestion } from "@t3tools/client-runtime/state/thread-requests";
import * as Haptics from "expo-haptics";
import {
memo,
@@ -57,15 +57,13 @@ import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
import { IOS_NAV_BAR_HEIGHT } from "../../lib/layoutMetrics";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import type {
PendingApproval,
PendingUserInput,
PendingUserInputDraftAnswer,
ThreadFeedEntry,
ThreadFeedLatestRun,
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { PendingUserInputCard } from "./PendingUserInputCard";
@@ -79,35 +77,30 @@ import {
COMPOSER_EXPANDED_CHROME,
ThreadComposer,
} from "./ThreadComposer";
import { ThreadFeed, type ThreadFeedHistoryControls } from "./ThreadFeed";
import { ThreadRelationshipsBanner } from "./ThreadRelationshipsBanner";
import { ThreadQueueControl } from "./ThreadQueueControl";
import { ThreadFeed } from "./ThreadFeed";
import type { ThreadContentPresentation } from "./threadContentPresentation";
export interface ThreadDetailScreenProps {
readonly selectedThread: EnvironmentThreadShell;
readonly selectedThread: OrchestrationThreadShell;
readonly contentPresentation: ThreadContentPresentation;
readonly screenTone: StatusTone;
readonly connectionError: string | null;
readonly environmentLabel: string | null;
readonly selectedThreadFeed: ReadonlyArray<ThreadFeedEntry>;
readonly activityRun: ThreadFeedLatestRun | null;
readonly activeWorkStartedAt: string | null;
readonly activePendingApproval: PendingApproval | null;
readonly respondingApprovalId: RuntimeRequestId | null;
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: RuntimeRequestId | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
readonly connectionStateLabel: EnvironmentConnectionPhase;
/** Message sync status for the selected thread (drives the composer status pill). */
readonly threadSyncStatus?: EnvironmentThreadStatus;
/** Progressive history controls for oversized mobile thread opens. */
readonly historyControls?: ThreadFeedHistoryControls;
readonly activeThreadBusy: boolean;
readonly canStopThread: boolean;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
readonly environmentId: EnvironmentId;
readonly projectWorkspaceRoot: string | null;
readonly threadCwd: string | null;
@@ -128,16 +121,16 @@ export interface ThreadDetailScreenProps {
readonly onUpdateThreadRuntimeMode: (runtimeMode: RuntimeMode) => void;
readonly onUpdateThreadInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onRespondToApproval: (
requestId: RuntimeRequestId,
requestId: ApprovalRequestId,
decision: ProviderApprovalDecision,
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: RuntimeRequestId,
question: ThreadUserInputQuestion,
requestId: ApprovalRequestId,
question: UserInputQuestion,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
requestId: RuntimeRequestId,
requestId: ApprovalRequestId,
questionId: string,
customAnswer: string,
) => void;
@@ -256,7 +249,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
}
}, []);
const windowHeight = useWindowDimensions().height;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + IOS_NAV_BAR_HEIGHT;
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
@@ -305,7 +298,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
// keyboard animations coherent. Collapse state is keyed by request id so a
// new request re-expands automatically.
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
useState<RuntimeRequestId | null>(null);
useState<ApprovalRequestId | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
const userInputCollapsed =
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
@@ -463,39 +456,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
selectedThreadKeyRef.current = selectedThreadKey;
}, [selectedThreadKey]);
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
const lastDispatchedVisitRef = useRef<string | null>(null);
const selectedThreadId = props.selectedThread.id;
const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
useEffect(() => {
// Records the server-side visited watermark while the thread is on
// screen (mirror of web ChatView), so the "Done" marker clears on every
// device. Field absent → the server predates visited tracking.
if (selectedThreadLastVisitedAt === undefined) return;
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
if (Number.isNaN(threadUpdatedAtMs)) return;
const lastVisitedAtMs = selectedThreadLastVisitedAt
? Date.parse(selectedThreadLastVisitedAt)
: NaN;
if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
// Dedupe per watermark — the effect re-runs before the command echo lands.
const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
if (lastDispatchedVisitRef.current === dispatchKey) return;
lastDispatchedVisitRef.current = dispatchKey;
void visitThread({
environmentId: props.environmentId,
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
});
}, [
props.environmentId,
selectedThreadId,
selectedThreadKey,
selectedThreadLastVisitedAt,
selectedThreadUpdatedAt,
visitThread,
]);
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
@@ -629,8 +589,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
feed={props.selectedThreadFeed}
contentPresentation={props.contentPresentation}
agentLabel={agentLabel}
threadTitle={props.selectedThread.title}
latestRun={props.activityRun}
latestTurn={props.selectedThread.latestTurn}
activeWorkStartedAt={props.activeWorkStartedAt}
listRef={listRef}
freeze={freeze}
@@ -639,18 +598,12 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
historyControls={props.historyControls}
topAccessory={
<ThreadRelationshipsBanner
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
onEndFollowEnabledChange={setEndFollowEnabled}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
</View>
) : (
@@ -715,11 +668,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
</Animated.View>
) : null}
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
<ThreadQueueControl
environmentId={props.environmentId}
threadId={props.selectedThread.id}
/>
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
@@ -778,8 +726,6 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
canStopThread={props.canStopThread}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
Loaded 100 of 1172 files, more files were not shown because too many files have changed in this diff. Show more