Compare commits

...
Author SHA1 Message Date
Julius Marminge 77544333e0 Improve mobile settings navigation and cached connection state
- Nest settings routes for form-sheet navigation
- Persist server config and VCS refs across web and mobile
- Add mobile header actions for empty connection state
2026-07-08 04:05:22 -07:00
Julius Marminge 10ca14a362 Tighten mobile navigation targets 2026-06-30 17:32:34 -07:00
Julius Marminge ee203ed518 Structure mobile navigation around native stack 2026-06-30 16:12:14 -07:00
Julius Marminge f6df16ab1e Replace Expo Router with native stack navigation 2026-06-30 11:41:13 -07:00
Julius Marminge a423e3c4b1 Move thread detail chrome to direct RNS 2026-06-30 09:46:59 -07:00
Julius Marminge c656e071e4 Wire iPad header search to thread sidebar 2026-06-30 08:44:41 -07:00
Julius Marminge 856fc61e65 Tune native mobile glass toolbar grouping 2026-06-30 08:26:38 -07:00
Julius Marminge 3158e1dc12 Group iPad detail header controls 2026-06-30 07:57:44 -07:00
Julius Marminge a930a44212 Polish native mobile Mail-style chrome 2026-06-30 07:39:55 -07:00
Julius Marminge 5bfd2161be Remove stale thread toolbar search slot 2026-06-30 04:58:51 -07:00
Julius Marminge 258a36a7f0 Flatten mobile not found link style 2026-06-30 04:50:22 -07:00
Julius Marminge a838270400 Use compact native search in iPad thread header 2026-06-30 04:40:23 -07:00
Julius Marminge 92404ecfd8 Use native new task sheet controls 2026-06-30 04:23:06 -07:00
Julius Marminge c77e6af72a Use native scroll edge effects on list headers 2026-06-30 04:11:46 -07:00
Julius Marminge dfbfc25a8f Centralize native header scroll edge effects 2026-06-30 04:05:42 -07:00
Julius Marminge 8fb62e1ba3 Use native glass header for file previews 2026-06-30 03:43:37 -07:00
Julius Marminge c70e6b5c34 Align inspector toolbar placement on iPad 2026-06-30 03:32:09 -07:00
Julius Marminge ffdacaf73d Use native Mail toolbar for file search 2026-06-30 03:14:16 -07:00
Julius Marminge 7cddaba1da Tune selected sidebar status pill contrast 2026-06-30 02:39:21 -07:00
Julius Marminge 035eb3b2e6 Centralize native Mail search toolbar config 2026-06-30 02:30:55 -07:00
Julius Marminge c1f87cc48b Show native search in iPad thread header 2026-06-30 02:15:56 -07:00
Julius Marminge c11d0c68e7 Use native header for git inspector 2026-06-30 02:08:45 -07:00
Julius Marminge 1b7051a5d3 Use native header search for file inspector 2026-06-30 01:59:32 -07:00
Julius Marminge 34379b6f5e Share archive row swipe behavior 2026-06-30 01:39:40 -07:00
Julius Marminge 27606a9c94 Use native iPad archive header search 2026-06-30 01:23:04 -07:00
Julius Marminge 2caf6dd1be Use Mail-style overflow controls on mobile 2026-06-30 01:10:37 -07:00
Julius Marminge af87ceced9 Add split sidebar control to terminal header 2026-06-30 00:59:41 -07:00
Julius Marminge 9083c716ea Hide thread search while inspector owns search 2026-06-30 00:47:06 -07:00
Julius Marminge b00deefb03 Match Mail sidebar selection on iPad 2026-06-30 00:37:24 -07:00
Julius Marminge f5d4d7b63c Stop forcing native glass debug route 2026-06-30 00:18:38 -07:00
Julius Marminge a0e0b6ef71 Add split home compose toolbar button 2026-06-30 00:01:16 -07:00
Julius Marminge 3e4b357a86 Add native sidebar status subtitle 2026-06-29 23:50:55 -07:00
Julius Marminge 0f3201e699 Use native edge chrome on file and review routes 2026-06-29 23:32:06 -07:00
Julius Marminge 2c00d79902 Use shared native scroll edge effect in thread surfaces 2026-06-29 23:16:01 -07:00
Julius Marminge 9e52f110e2 Use native glass header for terminal route 2026-06-29 23:05:17 -07:00
Julius Marminge 051160cfec Simplify iPhone thread native header 2026-06-29 22:51:23 -07:00
Julius Marminge fdac1fbcd4 Use Expo Router native home toolbar 2026-06-29 22:30:20 -07:00
Julius Marminge 036e481ec0 Fix native iOS thread header integration 2026-06-29 22:12:22 -07:00
Julius Marminge 29ffec87c0 Hide split detail native title 2026-06-29 19:57:07 -07:00
Julius Marminge 6c96dc7e92 Nudge iPad detail header controls inward 2026-06-29 19:02:21 -07:00
Julius Marminge 2f4fdfa03e Align iPad thread controls with Mail 2026-06-29 18:39:43 -07:00
Julius Marminge 89139e9394 Stabilize iPad thread header controls 2026-06-29 18:28:10 -07:00
Julius Marminge fcb6b03380 Align iPad detail header with Mail 2026-06-29 17:50:41 -07:00
Julius Marminge b5ef318748 Use native split thread header title 2026-06-29 17:40:20 -07:00
Julius Marminge 59af9dce68 Recover stale mobile thread routes 2026-06-29 17:05:45 -07:00
Julius Marminge a4472d0f49 Wire native iPad thread toolbar 2026-06-29 16:22:58 -07:00
Julius Marminge ce72ed4eb8 Restore native iPad thread search 2026-06-29 15:11:53 -07:00
Julius Marminge 5a1138cf39 Polish native phone chrome 2026-06-29 14:43:02 -07:00
Julius Marminge 618506f135 Group native iOS header controls 2026-06-29 14:16:34 -07:00
Julius Marminge 873a000567 Adopt native iOS glass navigation chrome 2026-06-29 13:10:36 -07:00
Julius Marminge b83af8a48e Reveal files inspector once 2026-06-27 12:54:20 -07:00
Julius Marminge 80208bc2c4 Stabilize inspector pane state 2026-06-27 12:44:54 -07:00
Julius Marminge c2aba434a1 Polish inspector routing behavior 2026-06-27 12:35:47 -07:00
Julius Marminge bf00c7e8a6 Fix sidebar selection and file return 2026-06-27 12:30:36 -07:00
Julius Marminge 43b9724418 Harden split inspector edge cases 2026-06-27 12:24:47 -07:00
Julius Marminge bcf070aa2c Fix file inspector route regressions 2026-06-27 12:21:31 -07:00
Julius Marminge 42a2275bbd Fix split inspector review followups 2026-06-27 12:17:54 -07:00
Julius Marminge 5efa2df4ab Address mobile review lifecycle issues 2026-06-27 12:12:33 -07:00
Julius Marminge e4ec3cfca7 Resolve remaining iPad review issues 2026-06-27 11:51:58 -07:00
Julius Marminge 75f0e90c03 Fix iPad header and input review issues 2026-06-27 11:27:13 -07:00
Julius Marminge ea8339ec90 Address iPad layout review feedback 2026-06-27 11:23:12 -07:00
Julius Marminge 7f81813feb Polish iPad mobile layout and native headers 2026-06-27 11:15:16 -07:00
Julius Marminge c4e63e0648 Fix EAS iOS CocoaPods UUID cache 2026-06-26 22:01:12 -07:00
Julius Marminge 4689c43c98 Refactor session handling and stream event processing 2026-06-26 18:43:31 -07:00
Julius Marminge 32e1983e61 Bump Clerk and Expo dependencies
- Update Clerk packages across web, desktop, relay, and mobile
- Refresh lockfile entries for related Expo and native packages
2026-06-26 17:55:40 -07:00
Julius Marminge babbf90197 Update Expo iOS tooling and native glass header 2026-06-26 17:25:24 -07:00
Julius Marminge 8351e7ca31 Refine mobile layout for iPad and native glass headers
- add thread selection context for split-view routing
- switch thread feeds to automatic content insets on iOS glass headers
- add native scroll-edge effect helper and app domain config
2026-06-26 17:08:26 -07:00
Julius Marmingeandcodex d353476417 Memoize thread navigation callbacks
- Stabilize thread selection routing in the adaptive workspace layout
- Extract and memoize thread sidebar rows to reduce unnecessary rerenders

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:26 -07:00
Julius Marmingeandcodex a896942bc7 Improve mobile thread navigation and diff selection
- Keep sidebar threads swipeable with archive/delete actions
- Hide archived threads from navigation groups
- Stabilize review diff visibility and optimistic file selection

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:26 -07:00
Julius Marmingeandcodex cf0f731bc8 Add split-view mobile navigation and native controls
- Adapt iPad/mobile layout for sidebar, inspector, and sheets
- Move review diff payloads off Fabric props and add native scrolling
- Add iOS header button module for consistent toolbar actions

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:18 -07:00
Julius Marmingeandcodex 80d2b26d94 Add split-view mobile workspace layout
- Enable adaptive sidebar navigation on wide mobile windows
- Keep compact single-pane behavior on phones
- Extract and test shared thread grouping and layout logic

Co-authored-by: codex <[email protected]>
2026-06-26 17:08:18 -07:00
Julius Marminge 6245c547c2 Fix native composer lag with revision-gated updates (#3574) 2026-06-26 16:55:44 -07:00
Julius Marminge 24abab789e Stabilize chat scroll anchoring after send (#3564) 2026-06-26 14:26:36 -07:00
52b04b947e fix(grok): Harden ACP resume with replay-idle load readiness (#3156)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-25 23:34:08 -07:00
Julius Marmingeandcodex e9ed70c5b9 [codex] Fix preview automation edge cases (#3561)
Co-authored-by: codex <[email protected]>
2026-06-25 20:08:27 -07:00
Julius Marmingeandcodex ffae5410e8 Route preview automation through live owner streams (#3548)
Co-authored-by: codex <[email protected]>
2026-06-25 19:06:44 -07:00
Julius MarmingeandJulius Marminge 31dfe3596e Fix Electron dev and packaged renderer startup (#3557)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-25 20:58:38 +00:00
Julius Marminge c2776c2336 Restore right panel inset when maximized (#3555) 2026-06-25 17:07:33 +00:00
Julius MarmingeandJulius Marminge 22f021ed69 [codex] Upgrade Legend List chat scrolling (#3545)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-24 15:39:17 -07:00
Wout StiensandCodex a4964b3b36 [codex] fix: show standalone element-pick context (#3527)
Co-authored-by: Codex <[email protected]>
2026-06-23 13:04:20 -07:00
c6c64918f8 Reduce ChatMarkdown settings rerenders (#3536)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-23 11:47:26 -07:00
Wout StiensandCodex 4abf8b46c5 [codex] fix: ignore stale shell reducer events (#3517)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:23 -07:00
Wout StiensandCodex 3083d712ee [codex] fix: clarify Cursor CLI setup error (#3519)
Co-authored-by: Codex <[email protected]>
2026-06-22 22:33:01 -07:00
Julius Marminge 6672a1d210 Bump Clerk packages and refresh lockfile (#3511) 2026-06-22 16:59:56 -07:00
92e54fb96c [codex] fix: guard DPoP fallback URL construction (#3503)
Co-authored-by: Codex <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 16:21:06 -07:00
Julius MarmingeandJulius Marminge 8cc9a6fa6b [codex] Restore T3 Connect account controls (#3492)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 15:58:54 -07:00
b2d17b7108 Add main sidebar toggle (#3497)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-06-22 14:00:30 -07:00
Abdul AzeezandJulius Marminge fb1034546f feat: add persistent word-wrap setting for chat code blocks and tables (#3480)
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 13:14:24 -07:00
f5f98cf0ae Stabilize composer provider state while typing (#3507)
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-06-22 12:52:13 -07:00
Julius Marmingeandcodex 37ac970e28 Persist mobile composer selectors across drafts (#3496)
Co-authored-by: codex <[email protected]>
2026-06-22 12:37:31 -07:00
Wout StiensandCodex 8919ae7c53 [codex] Reject unsupported remote pairing protocols (#3498)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:15:43 -07:00
Wout StiensandCodex c1e2408e1f [codex] fix: preserve localhost preview hosts (#3499)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:14:16 -07:00
Wout StiensandCodex 8b993bc9ff [codex] fix: restore pending input keyboard activation (#3501)
Co-authored-by: Codex <[email protected]>
2026-06-22 10:10:47 -07:00
Wout StiensandCodex ea52bb1dbd [codex] fix: guard trace ID clipboard copy (#3505)
Co-authored-by: Codex <[email protected]>
2026-06-22 09:46:15 -07:00
Illia Panasenko 28107e89c2 chore: remove AnnotatableFileDiff leftovers, rename file (#3488) 2026-06-21 20:31:26 -07:00
Julius Marminge 82a9bcc7f4 [codex] add session context to credential errors (#3349) 2026-06-20 20:45:17 -07:00
Julius Marminge 61f8d46fa2 [codex] Enforce Effect error handling conventions (#3380) 2026-06-20 20:43:41 -07:00
Julius Marminge 0debebafbb [codex] Structure thread archive blocked error (#3451) 2026-06-20 20:41:58 -07:00
Julius Marmingeandcodex 2a29de7502 [codex] Structure primary auth validation failures (#3471)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:12 -07:00
Julius Marmingeandcodex 8c1605b383 [codex] Structure OpenCode text generation failures (#3472)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:09 -07:00
Julius Marmingeandcodex 90074e359f [codex] Preserve desktop update state causes (#3473)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:07 -07:00
Julius Marmingeandcodex 6155f5cf64 [codex] Preserve VCS project config error causes (#3474)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:04 -07:00
Julius Marmingeandcodex e3970e755b [codex] Preserve APNs delivery failure context (#3475)
Co-authored-by: codex <[email protected]>
2026-06-20 20:20:01 -07:00
Julius Marmingeandcodex 3c246f56b4 [codex] Structure VCS process boundary errors (#3476)
Co-authored-by: codex <[email protected]>
2026-06-20 20:19:59 -07:00
Julius Marmingeandcodex cebbe6ff19 [codex] Preserve child process termination context (#3469)
Co-authored-by: codex <[email protected]>
2026-06-20 19:20:04 -07:00
Julius Marmingeandcodex e4a84a348e [codex] Structure release output failures (#3470)
Co-authored-by: codex <[email protected]>
2026-06-20 19:20:01 -07:00
Julius Marmingeandcodex 61e6d89d69 [codex] Structure GitHub CLI failures (#3456)
Co-authored-by: codex <[email protected]>
2026-06-20 19:14:35 -07:00
Julius Marmingeandcodex 1b2f39d018 [codex] Structure theme synchronization failures (#3466)
Co-authored-by: codex <[email protected]>
2026-06-20 19:09:05 -07:00
Julius Marmingeandcodex 8c2d33abde [codex] Structure release package updater failures (#3468)
Co-authored-by: codex <[email protected]>
2026-06-20 19:09:02 -07:00
Julius Marmingeandcodex 60dc4af916 [codex] Structure desktop build script failures (#3452)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:22 -07:00
Julius Marmingeandcodex d389cfd4e3 [codex] Structure Azure DevOps CLI failures (#3460)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:19 -07:00
Julius Marmingeandcodex 6fc79737c3 [codex] Structure mobile native static-check failures (#3464)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:16 -07:00
Julius Marmingeandcodex cdd03591ef [codex] Structure release metadata failures (#3467)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:13 -07:00
Julius Marmingeandcodex 2fbb0565d7 [codex] Structure workspace search cleanup failures (#3465)
Co-authored-by: codex <[email protected]>
2026-06-20 18:58:08 -07:00
Julius Marmingeandcodex a3dadc04bf [codex] Structure Bitbucket API errors (#3457)
Co-authored-by: codex <[email protected]>
2026-06-20 18:47:12 -07:00
Julius Marmingeandcodex 1a59277dc8 [codex] Structure GitLab CLI failures (#3458)
Co-authored-by: codex <[email protected]>
2026-06-20 18:41:25 -07:00
Julius Marmingeandcodex 6424197a19 [codex] Structure unroutable app-server messages (#3463)
Co-authored-by: codex <[email protected]>
2026-06-20 18:30:19 -07:00
Julius Marmingeandcodex 8d4a8b4f31 [codex] Structure preview capability errors (#3454)
Co-authored-by: codex <[email protected]>
2026-06-20 18:19:12 -07:00
Julius Marmingeandcodex 23ab75e84a [codex] Split project command failures (#3459)
Co-authored-by: codex <[email protected]>
2026-06-20 18:19:07 -07:00
Julius Marmingeandcodex 0488e47d9c [codex] Structure checkpoint diff failures (#3453)
Co-authored-by: codex <[email protected]>
2026-06-20 18:07:22 -07:00
Julius Marmingeandcodex 0eba548282 [codex] Model asset access failures with distinct errors (#3448)
Co-authored-by: codex <[email protected]>
2026-06-20 17:35:07 -07:00
Julius Marmingeandcodex 68c0dd3b70 [codex] Structure server CLI failures (#3450)
Co-authored-by: codex <[email protected]>
2026-06-20 17:35:02 -07:00
Julius Marmingeandcodex 4cd958445f [codex] Migrate desktop app errors to Schema (#3449)
Co-authored-by: codex <[email protected]>
2026-06-20 17:25:27 -07:00
Julius Marmingeandcodex 9f7861aadd [codex] Structure desktop update persistence errors (#3261)
Co-authored-by: codex <[email protected]>
2026-06-20 17:09:17 -07:00
Julius Marmingeandcodex 9243ead1c3 [codex] Preserve Linux icon resize fallback failures (#3447)
Co-authored-by: codex <[email protected]>
2026-06-20 17:09:11 -07:00
Julius Marmingeandcodex 803c2b7738 [codex] Preserve desktop backend output read failures (#3444)
Co-authored-by: codex <[email protected]>
2026-06-20 16:58:21 -07:00
Julius Marmingeandcodex 28e7c9ae17 [codex] Structure mobile waitlist enrollment failures (#3446)
Co-authored-by: codex <[email protected]>
2026-06-20 16:58:15 -07:00
Julius Marmingeandcodex a9460bb772 [codex] Structure pull request link failures (#3445)
Co-authored-by: codex <[email protected]>
2026-06-20 16:44:22 -07:00
Julius Marmingeandcodex 5edf7c56ba [codex] Preserve PR materialization failure chains (#3443)
Co-authored-by: codex <[email protected]>
2026-06-20 16:38:56 -07:00
Julius Marmingeandcodex 90dc76b11e Preserve asset access failure causes (#3342)
Co-authored-by: codex <[email protected]>
2026-06-20 16:15:22 -07:00
Julius Marmingeandcodex 57d25c934b [codex] Structure persistence error correlation (#3439)
Co-authored-by: codex <[email protected]>
2026-06-20 16:15:16 -07:00
Julius Marmingeandcodex a26f0dc89f [codex] structure source-control repository failures (#3336)
Co-authored-by: codex <[email protected]>
2026-06-20 15:56:46 -07:00
Julius Marmingeandcodex 6ff6c13fc8 [codex] structure desktop backend process errors (#3254)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:50 -07:00
Julius Marmingeandcodex 60c9ca0e33 [codex] Preserve checkpoint repository detection failures (#3360)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:44 -07:00
Julius Marmingeandcodex ad2cb1dd57 [codex] Diagnose desktop client settings read failures (#3432)
Co-authored-by: codex <[email protected]>
2026-06-20 15:55:38 -07:00
Julius Marmingeandcodex 674590e009 [codex] Fix terminal cwd error test construction (#3440)
Co-authored-by: codex <[email protected]>
2026-06-20 15:47:58 -07:00
Julius Marmingeandcodex f2cb14e774 [codex] Structure mobile relay token-store failures (#3309)
Co-authored-by: codex <[email protected]>
2026-06-20 15:31:33 -07:00
Julius Marmingeandcodex e042c25f56 [codex] Structure rotating log sink errors (#3279)
Co-authored-by: codex <[email protected]>
2026-06-20 15:24:38 -07:00
Julius Marmingeandcodex 90f1936fad [codex] Structure server runtime-state failures (#3319)
Co-authored-by: codex <[email protected]>
2026-06-20 15:15:05 -07:00
Julius Marmingeandcodex 42ff43915a [codex] Preserve mobile review highlighter failures (#3337)
Co-authored-by: codex <[email protected]>
2026-06-20 15:15:00 -07:00
Julius Marmingeandcodex 834e5db458 [codex] structure project CLI failures (#3339)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:55 -07:00
Julius Marmingeandcodex 8ce627ba91 [codex] Structure mobile thread outbox failures (#3341)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:51 -07:00
Julius Marmingeandcodex 9a78c6f2ba [codex] Structure web local storage failures (#3350)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:46 -07:00
Julius Marmingeandcodex aab72f10c1 [codex] Report markdown interaction failures (#3355)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:41 -07:00
Julius Marmingeandcodex a76b7bbfb5 Preserve PortScanner probe defects (#3282)
Co-authored-by: codex <[email protected]>
2026-06-20 15:14:02 -07:00
Julius Marmingeandcodex a51691a9b0 [codex] Structure server environment-label probe failures (#3321)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:53 -07:00
Julius Marmingeandcodex 97de7d7e15 [codex] Structure agent awareness registration errors (#3328)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:48 -07:00
Julius Marmingeandcodex d7718e81e0 [codex] Structure mobile notification navigation failures (#3359)
Co-authored-by: codex <[email protected]>
2026-06-20 15:13:04 -07:00
Julius Marmingeandcodex b88873508e [codex] Structure cross-client clipboard failures (#3361)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:59 -07:00
Julius Marmingeandcodex 58053d146b [codex] Structure terminal PTY operation failures (#3364)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:54 -07:00
Julius Marmingeandcodex 50767683b3 [codex] Preserve terminal preview link failure context (#3367)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:50 -07:00
Julius Marmingeandcodex d1339f3846 [codex] Structure client state key errors (#3374)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:45 -07:00
Julius Marmingeandcodex faccdd4ca9 [codex] Preserve desktop backend log failures (#3375)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:40 -07:00
Julius Marmingeandcodex dd48bfd98c [codex] Structure server settings failures (#3376)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:36 -07:00
Julius Marmingeandcodex 6d8d995621 [codex] Correlate protocol request failures (#3433)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:31 -07:00
Julius Marmingeandcodex b6c590af38 [codex] Fix desktop preview event delivery errors (#3435)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:27 -07:00
Julius Marmingeandcodex b51aef10c4 [codex] Preserve cloud disconnect diagnostics (#3437)
Co-authored-by: codex <[email protected]>
2026-06-20 15:12:22 -07:00
Julius Marmingeandcodex fc2cdeceb9 [codex] Structure preview automation boundary failures (#3436)
Co-authored-by: codex <[email protected]>
2026-06-20 13:50:19 -07:00
Julius Marmingeandcodex c637dfc454 [codex] enrich Git workflow errors (#3241)
Co-authored-by: codex <[email protected]>
2026-06-20 13:16:32 -07:00
Julius Marmingeandcodex 6e9b43cb84 Preserve trace file read causes (#3300)
Co-authored-by: codex <[email protected]>
2026-06-20 13:11:52 -07:00
Julius Marmingeandcodex be56fa43b0 [codex] Preserve workspace root stat failures (#3278)
Co-authored-by: codex <[email protected]>
2026-06-20 12:58:59 -07:00
Julius Marmingeandcodex eb5eb0d9fa [codex] Structure managed endpoint allocation failures (#3421)
Co-authored-by: codex <[email protected]>
2026-06-20 12:58:10 -07:00
Julius Marmingeandcodex 621616268a [codex] Sanitize text generation CLI errors (#3431)
Co-authored-by: codex <[email protected]>
2026-06-20 12:33:22 -07:00
Julius Marmingeandcodex 630df6b986 [codex] Enrich source-control errors (#3248)
Co-authored-by: codex <[email protected]>
2026-06-20 12:32:34 -07:00
Julius Marmingeandcodex 569b3e5959 [codex] Structure desktop SSH prompt presentation failures (#3429)
Co-authored-by: codex <[email protected]>
2026-06-20 12:31:49 -07:00
Julius Marmingeandcodex d7ff7e7333 [codex] Audit managed endpoint error context (#3245)
Co-authored-by: codex <[email protected]>
2026-06-20 12:30:03 -07:00
Julius Marmingeandcodex bd8e3ee008 Align text generation error catches (#3292)
Co-authored-by: codex <[email protected]>
2026-06-20 12:29:24 -07:00
Julius Marmingeandcodex c1d8a22f07 [codex] Structure desktop persisted credential errors (#3239)
Co-authored-by: codex <[email protected]>
2026-06-20 12:28:14 -07:00
Julius Marmingeandcodex 7b791895ad [codex] Structure relay auth persistence errors (#3250)
Co-authored-by: codex <[email protected]>
2026-06-20 12:27:28 -07:00
Julius Marmingeandcodex 4c16c66368 [codex] Structure ACP transport errors (#3251)
Co-authored-by: codex <[email protected]>
2026-06-20 12:25:16 -07:00
Julius Marmingeandcodex 4407a5a6b7 [codex] Structure Codex shadow home errors (#3262)
Co-authored-by: codex <[email protected]>
2026-06-20 12:24:32 -07:00
Julius Marmingeandcodex c7b375e9b0 [codex] Structure Electron window failures (#3276)
Co-authored-by: codex <[email protected]>
2026-06-20 12:23:46 -07:00
Julius Marmingeandcodex abc253d97d [codex] Preserve native SQLite failure context (#3428)
Co-authored-by: codex <[email protected]>
2026-06-20 12:12:41 -07:00
Julius Marmingeandcodex ce11e6facd [codex] Structure desktop browser session errors (#3273)
Co-authored-by: codex <[email protected]>
2026-06-20 12:10:51 -07:00
531 changed files with 45689 additions and 9833 deletions

No files matched your search

@@ -48,7 +48,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
- `Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
@@ -56,6 +58,9 @@ Review changed TypeScript and directly affected call sites for the conventions b
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
@@ -73,4 +78,6 @@ Review changed TypeScript and directly affected call sites for the conventions b
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code. If there are no findings, report exactly `All clear`.
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences 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.
+5
View File
@@ -0,0 +1,5 @@
{
"ios": {
"bundleIdentifier": "com.juliusmarminge.-t3toolsmonorepo"
}
}
+36 -14
View File
@@ -100,25 +100,41 @@ function shellSingleQuote(value) {
return `'${value.replaceAll("'", "'\\''")}'`;
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
const mainEntryPath = NodePath.join(desktopDir, "dist-electron", "main.cjs");
export function makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath,
desktopRoot,
environment,
}) {
const envEntries = [
["VITE_DEV_SERVER_URL", process.env.VITE_DEV_SERVER_URL],
["T3CODE_PORT", process.env.T3CODE_PORT],
["T3CODE_HOME", process.env.T3CODE_HOME],
["T3CODE_COMMIT_HASH", process.env.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", process.env.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", process.env.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["VITE_DEV_SERVER_URL", environment.VITE_DEV_SERVER_URL],
["T3CODE_PORT", environment.T3CODE_PORT],
["T3CODE_HOME", environment.T3CODE_HOME],
["T3CODE_COMMIT_HASH", environment.T3CODE_COMMIT_HASH],
["T3CODE_OTLP_TRACES_URL", environment.T3CODE_OTLP_TRACES_URL],
["T3CODE_OTLP_EXPORT_INTERVAL_MS", environment.T3CODE_OTLP_EXPORT_INTERVAL_MS],
["T3CODE_DESKTOP_APP_USER_MODEL_ID", APP_BUNDLE_ID],
].filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0);
return [
"#!/bin/sh",
...envEntries.map(
([name, value]) =>
`if [ -z "\${${name}:-}" ]; then export ${name}=${shellSingleQuote(value)}; fi`,
),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopRoot)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n");
}
function writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath) {
NodeFS.writeFileSync(
targetBinaryPath,
[
"#!/bin/sh",
...envEntries.map(([name, value]) => `export ${name}=${shellSingleQuote(value)}`),
`exec ${shellSingleQuote(electronBinaryPath)} --t3code-dev-root=${shellSingleQuote(desktopDir)} ${shellSingleQuote(mainEntryPath)} "$@"`,
"",
].join("\n"),
makeDevelopmentLauncherScript({
electronBinaryPath,
mainEntryPath: NodePath.join(desktopDir, "dist-electron", "main.cjs"),
desktopRoot: desktopDir,
environment: process.env,
}),
);
NodeFS.chmodSync(targetBinaryPath, 0o755);
}
@@ -286,6 +302,12 @@ function buildMacLauncher(electronBinaryPath) {
currentMetadata &&
JSON.stringify(currentMetadata) === JSON.stringify(expectedMetadata)
) {
if (isDevelopment) {
// The launcher also handles protocol activations outside the dev runner,
// so refresh its fallback environment on every launch. Never let a value
// captured by an older parent app override the live dev-runner environment.
writeDevelopmentLauncherScript(targetBinaryPath, electronBinaryPath);
}
registerMacLauncherBundle(targetAppBundlePath);
return targetBinaryPath;
}
@@ -0,0 +1,28 @@
import { assert, describe, it } from "vite-plus/test";
import { makeDevelopmentLauncherScript } from "./electron-launcher.mjs";
describe("electron development launcher", () => {
it("uses captured values only as fallbacks for a live runner environment", () => {
const script = makeDevelopmentLauncherScript({
electronBinaryPath: "/repo/node_modules/electron/Electron",
mainEntryPath: "/repo/apps/desktop/dist-electron/main.cjs",
desktopRoot: "/repo/apps/desktop",
environment: {
VITE_DEV_SERVER_URL: "http://127.0.0.1:8526",
T3CODE_PORT: "16566",
T3CODE_HOME: "/tmp/t3",
},
});
assert.include(
script,
"if [ -z \"${VITE_DEV_SERVER_URL:-}\" ]; then export VITE_DEV_SERVER_URL='http://127.0.0.1:8526'; fi",
);
assert.notInclude(script, "\nexport VITE_DEV_SERVER_URL=");
assert.include(
script,
"exec '/repo/node_modules/electron/Electron' --t3code-dev-root='/repo/apps/desktop' '/repo/apps/desktop/dist-electron/main.cjs' \"$@\"",
);
});
});
+13 -11
View File
@@ -1,8 +1,8 @@
import * as Cause from "effect/Cause";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as NetService from "@t3tools/shared/Net";
import * as Crypto from "effect/Crypto";
@@ -33,22 +33,24 @@ const makeDesktopRunId = Crypto.Crypto.pipe(
Effect.map((value) => value.replaceAll("-", "").slice(0, 12)),
);
class DesktopBackendPortUnavailableError extends Data.TaggedError(
export class DesktopBackendPortUnavailableError extends Schema.TaggedErrorClass<DesktopBackendPortUnavailableError>()(
"DesktopBackendPortUnavailableError",
)<{
readonly startPort: number;
readonly maxPort: number;
readonly hosts: readonly string[];
}> {
override get message() {
{
startPort: Schema.Int,
maxPort: Schema.Int,
hosts: Schema.Array(Schema.String),
},
) {
override get message(): string {
return `No desktop backend port is available on hosts ${this.hosts.join(", ")} between ${this.startPort} and ${this.maxPort}.`;
}
}
class DesktopDevelopmentBackendPortRequiredError extends Data.TaggedError(
export class DesktopDevelopmentBackendPortRequiredError extends Schema.TaggedErrorClass<DesktopDevelopmentBackendPortRequiredError>()(
"DesktopDevelopmentBackendPortRequiredError",
)<{}> {
override get message() {
{},
) {
override get message(): string {
return "T3CODE_PORT is required in desktop development.";
}
}
@@ -0,0 +1,30 @@
import { assert, describe, it } from "@effect/vitest";
import {
DesktopBackendPortUnavailableError,
DesktopDevelopmentBackendPortRequiredError,
} from "./DesktopApp.ts";
describe("DesktopApp errors", () => {
it("preserves unavailable backend port context", () => {
const error = new DesktopBackendPortUnavailableError({
startPort: 3_773,
maxPort: 65_535,
hosts: ["127.0.0.1", "0.0.0.0", "::"],
});
assert.equal(error.startPort, 3_773);
assert.equal(error.maxPort, 65_535);
assert.deepEqual(error.hosts, ["127.0.0.1", "0.0.0.0", "::"]);
assert.equal(
error.message,
"No desktop backend port is available on hosts 127.0.0.1, 0.0.0.0, :: between 3773 and 65535.",
);
});
it("reports the required development port", () => {
const error = new DesktopDevelopmentBackendPortRequiredError();
assert.equal(error.message, "T3CODE_PORT is required in desktop development.");
});
});
@@ -0,0 +1,122 @@
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 Logger from "effect/Logger";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as DesktopBackendOutputLog from "./DesktopBackendOutputLog.ts";
import * as DesktopConfig from "./DesktopConfig.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
const LOG_FILE_PATH = "/Users/alice/.t3/userdata/logs/server-child.log";
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/dist-electron",
homeDirectory: "/Users/alice",
platform: "darwin",
processArch: "arm64",
appVersion: "1.2.3",
appPath: "/Applications/T3 Code.app/Contents/Resources/app.asar",
isPackaged: true,
resourcesPath: "/Applications/T3 Code.app/Contents/Resources",
runningUnderArm64Translation: false,
}).pipe(Layer.provide(Layer.merge(Path.layer, DesktopConfig.layerTest({}))));
const withOutputLog = <A, E, R>(
effect: Effect.Effect<A, E, R | DesktopBackendOutputLog.DesktopBackendOutputLog>,
fileSystemLayer: Layer.Layer<FileSystem.FileSystem>,
messages: Array<ReadonlyArray<unknown>>,
) => {
const logger = Logger.make(({ message }) => {
messages.push(Array.isArray(message) ? message : [message]);
});
const outputLogLayer = DesktopBackendOutputLog.layer.pipe(
Layer.provide(Layer.mergeAll(fileSystemLayer, Path.layer, environmentLayer)),
Layer.provideMerge(Logger.layer([logger], { mergeWithExisting: false })),
);
return effect.pipe(Effect.provide(outputLogLayer));
};
const loggedError = (messages: ReadonlyArray<ReadonlyArray<unknown>>): unknown =>
messages.flat().find((value) => typeof value === "object" && value !== null && "error" in value)
?.error;
describe("DesktopBackendOutputLog", () => {
it.effect("logs setup failures with the log path and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const cause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "makeDirectory",
pathOrDescriptor: "/Users/alice/.t3/userdata/logs",
description: "private setup diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.fail(cause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogSetupError);
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to initialize the desktop backend output log at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private setup diagnostic");
}),
fileSystemLayer,
messages,
);
});
it.effect("logs record write failures with the operation and exact cause", () => {
const messages: Array<ReadonlyArray<unknown>> = [];
const missingCause = PlatformError.systemError({
_tag: "NotFound",
module: "FileSystem",
method: "stat",
pathOrDescriptor: LOG_FILE_PATH,
});
const writeCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "writeFile",
pathOrDescriptor: LOG_FILE_PATH,
description: "private write diagnostic",
});
const fileSystemLayer = FileSystem.layerNoop({
makeDirectory: () => Effect.void,
stat: () => Effect.fail(missingCause),
readDirectory: () => Effect.succeed([]),
writeFile: () => Effect.fail(writeCause),
});
return withOutputLog(
Effect.gen(function* () {
const outputLog = yield* DesktopBackendOutputLog.DesktopBackendOutputLog;
yield* outputLog.writeSessionBoundary({ phase: "START", details: "test" });
const error = loggedError(messages);
assert.instanceOf(error, DesktopBackendOutputLog.DesktopBackendOutputLogWriteError);
assert.equal(error.operation, "write-record");
assert.equal(error.logFilePath, LOG_FILE_PATH);
assert.strictEqual(error.cause, writeCause);
assert.equal(
error.message,
`Desktop backend output log operation "write-record" failed at ${LOG_FILE_PATH}.`,
);
assert.notInclude(error.message, "private write diagnostic");
}),
fileSystemLayer,
messages,
);
});
});
+151 -46
View File
@@ -19,8 +19,75 @@ export const DESKTOP_LOG_FILE_MAX_FILES = 10;
const DESKTOP_BACKEND_CHILD_LOG_FIBER_ID = "#backend-child";
interface RotatingLogFileWriter {
readonly writeBytes: (chunk: Uint8Array) => Effect.Effect<void>;
readonly writeText: (chunk: string) => Effect.Effect<void>;
readonly filePath: string;
readonly writeBytes: (
chunk: Uint8Array,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
readonly writeText: (
chunk: string,
) => Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError>;
}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
class DesktopLogFileWriterRecoveryError extends Schema.TaggedErrorClass<DesktopLogFileWriterRecoveryError>()(
"DesktopLogFileWriterRecoveryError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
recoveryCause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to refresh desktop backend output log size after a write failure at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogSetupError extends Schema.TaggedErrorClass<DesktopBackendOutputLogSetupError>()(
"DesktopBackendOutputLogSetupError",
{
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the desktop backend output log at ${this.logFilePath}.`;
}
}
export class DesktopBackendOutputLogWriteError extends Schema.TaggedErrorClass<DesktopBackendOutputLogWriteError>()(
"DesktopBackendOutputLogWriteError",
{
operation: Schema.Literals(["encode-record", "write-record"]),
logFilePath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend output log operation "${this.operation}" failed at ${this.logFilePath}.`;
}
}
export class DesktopBackendConsoleWriteError extends Schema.TaggedErrorClass<DesktopBackendConsoleWriteError>()(
"DesktopBackendConsoleWriteError",
{
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to mirror desktop backend output to ${this.streamName}.`;
}
}
export class DesktopBackendOutputLog extends Context.Service<
@@ -37,18 +104,6 @@ export class DesktopBackendOutputLog extends Context.Service<
}
>()("@t3tools/desktop/app/DesktopBackendOutputLog") {}
class DesktopLogFileWriterConfigurationError extends Schema.TaggedErrorClass<DesktopLogFileWriterConfigurationError>()(
"DesktopLogFileWriterConfigurationError",
{
option: Schema.Literals(["maxBytes", "maxFiles"]),
value: Schema.Number,
},
) {
override get message(): string {
return `${this.option} must be >= 1 (received ${this.value})`;
}
}
type DesktopLogFileWriterError =
| DesktopLogFileWriterConfigurationError
| PlatformError.PlatformError;
@@ -85,10 +140,13 @@ const sanitizeLogValue = (value: string): string => value.replace(/\s+/g, " ").t
const refreshFileSize = (
fileSystem: FileSystem.FileSystem,
filePath: string,
): Effect.Effect<number, never> =>
): Effect.Effect<number, PlatformError.PlatformError> =>
fileSystem.stat(filePath).pipe(
Effect.map((stat) => Number(stat.size)),
Effect.orElseSucceed(() => 0),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(0) : Effect.fail(error),
}),
);
const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(function* (input: {
@@ -126,41 +184,52 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
const currentSize = yield* Ref.make(yield* refreshFileSize(fileSystem, input.filePath));
const mutex = yield* Semaphore.make(1);
const recoverCurrentSize = (
cause: PlatformError.PlatformError,
): Effect.Effect<never, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.matchEffect({
onFailure: (recoveryCause) =>
Effect.fail(
new DesktopLogFileWriterRecoveryError({
logFilePath: input.filePath,
cause,
recoveryCause,
}),
),
onSuccess: (size) => Ref.set(currentSize, size).pipe(Effect.andThen(Effect.fail(cause))),
}),
);
const pruneOverflowBackups = Effect.gen(function* () {
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
const entries = yield* fileSystem.readDirectory(directory);
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
const suffix = Number(entry.slice(baseName.length + 1));
if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
yield* fileSystem.remove(path.join(directory, entry), { force: true });
}
});
const rotate = Effect.gen(function* () {
yield* fileSystem.remove(withSuffix(maxFiles), { force: true }).pipe(Effect.ignore);
yield* fileSystem.remove(withSuffix(maxFiles), { force: true });
for (let index = maxFiles - 1; index >= 1; index -= 1) {
const source = withSuffix(index);
const sourceExists = yield* fileSystem.exists(source).pipe(Effect.orElseSucceed(() => false));
const sourceExists = yield* fileSystem.exists(source);
if (sourceExists) {
yield* fileSystem.rename(source, withSuffix(index + 1));
}
}
const currentExists = yield* fileSystem
.exists(input.filePath)
.pipe(Effect.orElseSucceed(() => false));
const currentExists = yield* fileSystem.exists(input.filePath);
if (currentExists) {
yield* fileSystem.rename(input.filePath, withSuffix(1));
}
yield* Ref.set(currentSize, 0);
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
);
});
const writeBytes = (chunk: Uint8Array): Effect.Effect<void> => {
const writeBytes = (
chunk: Uint8Array,
): Effect.Effect<void, PlatformError.PlatformError | DesktopLogFileWriterRecoveryError> => {
if (chunk.byteLength === 0) return Effect.void;
return mutex.withPermits(1)(
@@ -178,11 +247,9 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
yield* rotate;
}
}).pipe(
Effect.catch(() =>
refreshFileSize(fileSystem, input.filePath).pipe(
Effect.flatMap((size) => Ref.set(currentSize, size)),
),
),
Effect.catchTags({
PlatformError: recoverCurrentSize,
}),
),
);
};
@@ -190,6 +257,7 @@ const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(functio
yield* pruneOverflowBackups;
return {
filePath: input.filePath,
writeBytes,
writeText: (chunk) => writeBytes(textEncoder.encode(chunk)),
} satisfies RotatingLogFileWriter;
@@ -199,10 +267,17 @@ const writeDevelopmentConsoleOutput = (
streamName: "stdout" | "stderr",
chunk: Uint8Array,
): Effect.Effect<void> =>
Effect.sync(() => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
}).pipe(Effect.ignore);
Effect.try({
try: () => {
const output = streamName === "stderr" ? process.stderr : process.stdout;
output.write(chunk);
},
catch: (cause) => new DesktopBackendConsoleWriteError({ streamName, cause }),
}).pipe(
Effect.catchTags({
DesktopBackendConsoleWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackendChildLogRecord")(
function* (
@@ -222,17 +297,47 @@ const writeBackendChildLogRecord = Effect.fn("desktop.observability.writeBackend
annotations: input.annotations,
spans: {},
fiberId: DESKTOP_BACKEND_CHILD_LOG_FIBER_ID,
});
yield* logFile.writeText(`${encoded}\n`);
}).pipe(Effect.ignore({ log: true }));
}).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "encode-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
yield* logFile.writeText(`${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopBackendOutputLogWriteError({
operation: "write-record",
logFilePath: logFile.filePath,
cause,
}),
),
);
}).pipe(
Effect.catchTags({
DesktopBackendOutputLogWriteError: (error) => Effect.logError(error.message, { error }),
}),
);
},
);
const make = Effect.gen(function* () {
export const make = Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const logFilePath = environment.path.join(environment.logDir, "server-child.log");
const writer = yield* makeRotatingLogFileWriter({
filePath: environment.path.join(environment.logDir, "server-child.log"),
}).pipe(Effect.option);
filePath: logFilePath,
}).pipe(
Effect.mapError((cause) => new DesktopBackendOutputLogSetupError({ logFilePath, cause })),
Effect.map(Option.some),
Effect.catchTags({
DesktopBackendOutputLogSetupError: (error) =>
Effect.logError(error.message, { error }).pipe(Effect.as(Option.none())),
}),
);
const service = Option.match(writer, {
onNone: () => DesktopBackendOutputLogNoop,
@@ -393,7 +393,21 @@ describe("DesktopConnectionCatalogStore", () => {
assert.isTrue(yield* store.set('{"schemaVersion":1,"targets":[]}'));
yield* Ref.set(failDecrypt, true);
const error = yield* store.get.pipe(Effect.flip);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageDecryptError);
assert.instanceOf(
error,
DesktopConnectionCatalogStore.DesktopConnectionCatalogStoreProtectionError,
);
assert.equal(error.operation, "decrypt-catalog");
assert.equal(error.catalogPath, `${baseDir}/userdata/connection-catalog.json`);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageDecryptError);
const decryptError = error.cause as ElectronSafeStorage.ElectronSafeStorageDecryptError;
assert.instanceOf(decryptError.cause, Error);
assert.equal(decryptError.cause.message, "invalid encrypted catalog");
assert.equal(
error.message,
`Desktop connection catalog protection failed during decrypt-catalog at ${baseDir}/userdata/connection-catalog.json.`,
);
assert.notEqual(error.message, decryptError.message);
yield* Ref.set(failDecrypt, false);
assert.deepStrictEqual(yield* store.get, Option.some('{"schemaVersion":1,"targets":[]}'));
}).pipe(Effect.provide(NodeServices.layer), Effect.scoped),
@@ -53,8 +53,6 @@ const DesktopConnectionCatalogStoreWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-catalog-file",
]);
type DesktopConnectionCatalogStoreWriteOperation =
typeof DesktopConnectionCatalogStoreWriteOperation.Type;
const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"read-legacy-registry",
@@ -62,8 +60,12 @@ const DesktopConnectionCatalogStoreMigrationOperation = Schema.Literals([
"encode-catalog",
"persist-catalog",
]);
type DesktopConnectionCatalogStoreMigrationOperation =
typeof DesktopConnectionCatalogStoreMigrationOperation.Type;
const DesktopConnectionCatalogStoreProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-catalog",
"decrypt-catalog",
]);
export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreWriteError>()(
"DesktopConnectionCatalogStoreWriteError",
@@ -78,17 +80,6 @@ export class DesktopConnectionCatalogStoreWriteError extends Schema.TaggedErrorC
}
}
const writeError = (
operation: DesktopConnectionCatalogStoreWriteOperation,
path: string,
cause: unknown,
): DesktopConnectionCatalogStoreWriteError =>
new DesktopConnectionCatalogStoreWriteError({
operation,
path,
cause,
});
export class DesktopConnectionCatalogStoreDecodeError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreDecodeError>()(
"DesktopConnectionCatalogStoreDecodeError",
{
@@ -142,18 +133,18 @@ export class DesktopConnectionCatalogStoreMigrationError extends Schema.TaggedEr
}
}
const migrationError = (
operation: DesktopConnectionCatalogStoreMigrationOperation,
catalogPath: string,
cause: unknown,
environmentId?: string,
): DesktopConnectionCatalogStoreMigrationError =>
new DesktopConnectionCatalogStoreMigrationError({
operation,
catalogPath,
...(environmentId === undefined ? {} : { environmentId }),
cause,
});
export class DesktopConnectionCatalogStoreProtectionError extends Schema.TaggedErrorClass<DesktopConnectionCatalogStoreProtectionError>()(
"DesktopConnectionCatalogStoreProtectionError",
{
operation: DesktopConnectionCatalogStoreProtectionOperation,
catalogPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop connection catalog protection failed during ${this.operation} at ${this.catalogPath}.`;
}
}
export class DesktopConnectionCatalogStore extends Context.Service<
DesktopConnectionCatalogStore,
@@ -164,13 +155,13 @@ export class DesktopConnectionCatalogStore extends Context.Service<
| DesktopConnectionCatalogStoreDocumentDecodeError
| DesktopConnectionCatalogStoreDecodeError
| DesktopConnectionCatalogStoreMigrationError
| ElectronSafeStorage.ElectronSafeStorageError
| DesktopConnectionCatalogStoreProtectionError
>;
readonly set: (
catalog: string,
) => Effect.Effect<
boolean,
DesktopConnectionCatalogStoreWriteError | ElectronSafeStorage.ElectronSafeStorageError
DesktopConnectionCatalogStoreWriteError | DesktopConnectionCatalogStoreProtectionError
>;
readonly clear: Effect.Effect<void>;
}
@@ -236,20 +227,46 @@ const writeDocument = Effect.fn("desktop.connectionCatalogStore.writeDocument")(
const directory = input.path.dirname(input.catalogPath);
const tempPath = `${input.catalogPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeEncryptedConnectionCatalogDocumentJson(input.document).pipe(
Effect.mapError((cause) => writeError("encode-document", input.catalogPath, cause)),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "encode-document",
path: input.catalogPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* Effect.gen(function* () {
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.catalogPath)
.pipe(
Effect.mapError((cause) => writeError("replace-catalog-file", input.catalogPath, cause)),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.catalogPath).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "replace-catalog-file",
path: input.catalogPath,
cause,
}),
),
);
}).pipe(
Effect.ensuring(
input.fileSystem.remove(tempPath, { force: true }).pipe(
@@ -330,13 +347,17 @@ const migrateSavedEnvironmentRecords = Effect.fn(
wsBaseUrl: record.wsBaseUrl,
}),
);
const token = yield* savedEnvironments
.getSecret(record.environmentId)
.pipe(
Effect.mapError((cause) =>
migrationError("read-legacy-secret", catalogPath, cause, record.environmentId),
),
);
const token = yield* savedEnvironments.getSecret(record.environmentId).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-secret",
catalogPath,
environmentId: record.environmentId,
cause,
}),
),
);
if (Option.isSome(token)) {
credentials.push({
connectionId: id,
@@ -362,13 +383,41 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
const catalogPath = path.join(environment.stateDir, "connection-catalog.json");
const encryptionAvailable = safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "check-encryption-availability",
catalogPath,
cause,
}),
),
);
const writeCatalog = Effect.fn("desktop.connectionCatalogStore.writeCatalog")(function* (
catalog: string,
) {
const encryptedCatalog = Encoding.encodeBase64(yield* safeStorage.encryptString(catalog));
const encryptedCatalog = Encoding.encodeBase64(
yield* safeStorage.encryptString(catalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "encrypt-catalog",
catalogPath,
cause,
}),
),
),
);
const suffix = (yield* crypto.randomUUIDv4.pipe(
Effect.mapError((cause) => writeError("create-temporary-file-name", catalogPath, cause)),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreWriteError({
operation: "create-temporary-file-name",
path: catalogPath,
cause,
}),
),
)).replace(/-/g, "");
yield* writeDocument({
fileSystem,
@@ -380,21 +429,42 @@ export const make = Effect.gen(function* () {
});
const migrateLegacyCatalog = Effect.gen(function* () {
if (!(yield* safeStorage.isEncryptionAvailable)) {
if (!(yield* encryptionAvailable)) {
return Option.none<string>();
}
const records = yield* savedEnvironments.getRegistry.pipe(
Effect.mapError((cause) => migrationError("read-legacy-registry", catalogPath, cause)),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "read-legacy-registry",
catalogPath,
cause,
}),
),
);
if (records.length === 0) {
return Option.none<string>();
}
const catalog = yield* migrateSavedEnvironmentRecords(records, savedEnvironments, catalogPath);
const encoded = yield* encodeRuntimeConnectionCatalogDocumentJson(catalog).pipe(
Effect.mapError((cause) => migrationError("encode-catalog", catalogPath, cause)),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "encode-catalog",
catalogPath,
cause,
}),
),
);
yield* writeCatalog(encoded).pipe(
Effect.mapError((cause) => migrationError("persist-catalog", catalogPath, cause)),
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreMigrationError({
operation: "persist-catalog",
catalogPath,
cause,
}),
),
);
return Option.some(encoded);
});
@@ -405,16 +475,27 @@ export const make = Effect.gen(function* () {
if (Option.isNone(document)) {
return yield* migrateLegacyCatalog;
}
if (!(yield* safeStorage.isEncryptionAvailable)) {
if (!(yield* encryptionAvailable)) {
return Option.none<string>();
}
const decrypted = yield* decodeSecretBytes(catalogPath, document.value.encryptedCatalog).pipe(
Effect.flatMap(safeStorage.decryptString),
Effect.flatMap((encryptedCatalog) =>
safeStorage.decryptString(encryptedCatalog).pipe(
Effect.mapError(
(cause) =>
new DesktopConnectionCatalogStoreProtectionError({
operation: "decrypt-catalog",
catalogPath,
cause,
}),
),
),
),
);
return Option.some(decrypted);
}).pipe(Effect.withSpan("desktop.connectionCatalogStore.get")),
set: Effect.fn("desktop.connectionCatalogStore.set")(function* (catalog) {
if (!(yield* safeStorage.isEncryptionAvailable)) {
if (!(yield* encryptionAvailable)) {
return false;
}
yield* writeCatalog(catalog);
@@ -3,12 +3,15 @@ import {
type DesktopBackendBootstrap as DesktopBackendBootstrapValue,
} from "@t3tools/contracts";
import { assert, describe, it } from "@effect/vitest";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
@@ -28,6 +31,7 @@ import * as DesktopWindow from "../window/DesktopWindow.ts";
const decodeDesktopBackendBootstrap = Schema.decodeEffect(
Schema.fromJsonString(DesktopBackendBootstrap),
);
const isBackendProcessError = Schema.is(DesktopBackendManager.BackendProcessError);
const baseConfig: DesktopBackendManager.DesktopBackendStartConfig = {
executablePath: "/electron",
@@ -55,9 +59,9 @@ const configWithObservability: DesktopBackendBootstrapValue = {
};
function makeProcess(options?: {
readonly stdout?: Stream.Stream<Uint8Array>;
readonly stderr?: Stream.Stream<Uint8Array>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode>;
readonly stdout?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly stderr?: Stream.Stream<Uint8Array, PlatformError.PlatformError>;
readonly exitCode?: Effect.Effect<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
readonly kill?: ChildProcessSpawner.ChildProcessHandle["kill"];
}): ChildProcessSpawner.ChildProcessHandle {
return ChildProcessSpawner.makeHandle({
@@ -145,6 +149,23 @@ function makeManagerLayer(input: {
}
describe("DesktopBackendManager", () => {
it("preserves the complete restart cause and schedule context", () => {
const cause = Cause.combine(
Cause.fail(new Error("start failed")),
Cause.die(new Error("restart defect")),
);
const error = new DesktopBackendManager.DesktopBackendRestartError({
reason: "backend exited with code 1",
delayMs: 500,
cause,
});
assert.strictEqual(error.cause, cause);
assert.equal(error.reason, "backend exited with code 1");
assert.equal(error.delayMs, 500);
assert.equal(error.message, "Desktop backend restart failed after a scheduled 500ms delay.");
});
it.effect("spawns the backend with fd3 bootstrap JSON and reports HTTP readiness", () =>
Effect.gen(function* () {
let spawnedCommand: ChildProcess.Command | undefined;
@@ -218,6 +239,243 @@ describe("DesktopBackendManager", () => {
}),
);
it.effect("preserves the readiness timeout cause and process context", () =>
Effect.gen(function* () {
const requested = yield* Deferred.make<HttpClientRequest.HttpClientRequest>();
const layer = Layer.merge(
TestClock.layer(),
httpClientLayer((request) =>
Deferred.succeed(requested, request).pipe(Effect.andThen(Effect.never)),
),
);
yield* Effect.gen(function* () {
const readiness = yield* DesktopBackendManager.waitForHttpReady({
executablePath: baseConfig.executablePath,
entryPath: baseConfig.entryPath,
cwd: baseConfig.cwd,
httpBaseUrl: baseConfig.httpBaseUrl,
timeout: Duration.millis(50),
}).pipe(Effect.flip, Effect.forkChild);
const request = yield* Deferred.await(requested);
assert.equal(request.url, "http://127.0.0.1:3773/.well-known/t3/environment");
yield* TestClock.adjust(Duration.millis(50));
const error = yield* Fiber.join(readiness);
assert.instanceOf(error, DesktopBackendManager.BackendReadinessTimeoutError);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.readinessUrl.href, "http://127.0.0.1:3773/.well-known/t3/environment");
assert.equal(error.timeoutMs, 50);
assert.isTrue(Cause.isTimeoutError(error.cause));
assert.equal(
error.message,
"Timed out after 50ms waiting for desktop backend readiness at http://127.0.0.1:3773/.well-known/t3/environment.",
);
}).pipe(Effect.provide(layer));
}),
);
it.effect("reports bootstrap encoding failures with stable process context", () =>
Effect.gen(function* () {
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.die("unexpected backend spawn")),
);
const error = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
bootstrap: {
...baseConfig.bootstrap,
port: 0,
},
}).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessBootstrapEncodeError") {
return assert.fail(`Expected bootstrap encode error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.isDefined(error.cause);
assert.equal(
error.message,
"Failed to encode the desktop backend bootstrap payload for /server/bin.mjs.",
);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves spawn failures without deriving their message from the cause", () =>
Effect.gen(function* () {
const spawnCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcessSpawner",
method: "spawn",
pathOrDescriptor: baseConfig.executablePath,
description: "low-level detail that must not become the public message",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.fail(spawnCause)),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessSpawnError") {
return assert.fail(`Expected backend spawn error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, spawnCause);
assert.equal(
error.message,
"Failed to spawn desktop backend entry /server/bin.mjs with /electron.",
);
assert.notInclude(error.message, spawnCause.message);
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("preserves exit-status failures without copying their detail into the message", () =>
Effect.gen(function* () {
const exitCause = PlatformError.systemError({
_tag: "PermissionDenied",
module: "ChildProcess",
method: "exitCode",
description: "exit-status-secret-sentinel",
});
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
exitCode: Effect.fail(exitCause),
}),
),
),
);
const error = yield* DesktopBackendManager.runBackendProcess(baseConfig).pipe(
Effect.flip,
Effect.scoped,
Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)),
);
if (error._tag !== "BackendProcessExitStatusError") {
return assert.fail(`Expected backend exit-status error, received ${error._tag}`);
}
assert.equal(error.pid, 123);
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.strictEqual(error.cause, exitCause);
assert.equal(error.message, "Failed to read the exit status of desktop backend process 123.");
assert.notInclude(error.message, "exit-status-secret-sentinel");
assert.isTrue(isBackendProcessError(error));
}),
);
it.effect("reports output stream failures with process and stream context", () =>
Effect.gen(function* () {
const outputCause = PlatformError.systemError({
_tag: "BadResource",
module: "ChildProcess",
method: "stdout",
description: "output-stream-secret-sentinel",
});
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.fail(outputCause),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputReadError") {
return assert.fail(`Expected output read error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.strictEqual(error.cause, outputCause);
assert.equal(error.message, "Failed to read stdout from desktop backend process 123.");
assert.notInclude(error.message, "output-stream-secret-sentinel");
}),
);
it.effect("reports output handler failures separately from stream read failures", () =>
Effect.gen(function* () {
const chunk = new TextEncoder().encode("backend output");
const outputCause = new Error("output-handler-secret-sentinel");
const reported = yield* Deferred.make<DesktopBackendManager.BackendProcessOutputError>();
const spawnerLayer = Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() =>
Effect.succeed(
makeProcess({
stdout: Stream.make(chunk),
exitCode: Deferred.await(reported).pipe(Effect.as(ChildProcessSpawner.ExitCode(0))),
}),
),
),
);
const exit = yield* DesktopBackendManager.runBackendProcess({
...baseConfig,
onOutput: () => Effect.fail(outputCause),
onOutputFailure: (error) => Deferred.succeed(reported, error).pipe(Effect.asVoid),
}).pipe(Effect.scoped, Effect.provide(Layer.merge(spawnerLayer, healthyHttpClientLayer)));
const error = yield* Deferred.await(reported);
assert.equal(exit.code.pipe(Option.getOrUndefined), 0);
if (error._tag !== "BackendProcessOutputHandlingError") {
return assert.fail(`Expected output handling error, received ${error._tag}`);
}
assert.equal(error.executablePath, "/electron");
assert.equal(error.entryPath, "/server/bin.mjs");
assert.equal(error.cwd, "/server");
assert.equal(error.httpBaseUrl.href, "http://127.0.0.1:3773/");
assert.equal(error.pid, 123);
assert.equal(error.streamName, "stdout");
assert.equal(error.chunkByteLength, chunk.byteLength);
assert.strictEqual(error.cause, outputCause);
assert.equal(
error.message,
`Failed to handle ${chunk.byteLength} bytes from stdout of desktop backend process 123.`,
);
assert.notInclude(error.message, "output-handler-secret-sentinel");
}),
);
it.effect("retries HTTP readiness before reporting the backend ready", () =>
Effect.gen(function* () {
const requestUrls: Array<string> = [];
+218 -65
View File
@@ -9,7 +9,6 @@ import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as Ref from "effect/Ref";
import * as Result from "effect/Result";
import * as Schedule from "effect/Schedule";
import * as Schema from "effect/Schema";
import * as Semaphore from "effect/Semaphore";
@@ -43,68 +42,145 @@ type BackendProcessRunRequirements = BackendProcessLayerServices | Scope.Scope;
export type BackendProcessOutputStream = "stdout" | "stderr";
export interface DesktopBackendStartConfig {
export interface BackendProcessContext {
readonly executablePath: string;
readonly entryPath: string;
readonly cwd: string;
readonly httpBaseUrl: URL;
}
export interface DesktopBackendStartConfig extends BackendProcessContext {
readonly env: Record<string, string | undefined>;
readonly bootstrap: DesktopBackendBootstrapValue;
readonly httpBaseUrl: URL;
readonly captureOutput: boolean;
}
interface BackendProcessExit {
readonly code: Option.Option<number>;
readonly reason: string;
readonly result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>;
}
export class BackendTimeoutError extends Schema.TaggedErrorClass<BackendTimeoutError>()(
"BackendTimeoutError",
const backendProcessContextSchema = {
executablePath: Schema.String,
entryPath: Schema.String,
cwd: Schema.String,
httpBaseUrl: Schema.URL,
};
export class BackendReadinessTimeoutError extends Schema.TaggedErrorClass<BackendReadinessTimeoutError>()(
"BackendReadinessTimeoutError",
{
url: Schema.URL,
...backendProcessContextSchema,
readinessUrl: Schema.URL,
timeoutMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Timed out waiting for backend readiness at ${this.url.href}.`;
return `Timed out after ${this.timeoutMs}ms waiting for desktop backend readiness at ${this.readinessUrl.href}.`;
}
}
class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
export class BackendProcessBootstrapEncodeError extends Schema.TaggedErrorClass<BackendProcessBootstrapEncodeError>()(
"BackendProcessBootstrapEncodeError",
{
detail: Schema.String,
...backendProcessContextSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to encode desktop backend bootstrap payload: ${this.detail}`;
return `Failed to encode the desktop backend bootstrap payload for ${this.entryPath}.`;
}
}
class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
export class BackendProcessSpawnError extends Schema.TaggedErrorClass<BackendProcessSpawnError>()(
"BackendProcessSpawnError",
{
detail: Schema.String,
...backendProcessContextSchema,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to spawn desktop backend process: ${this.detail}`;
return `Failed to spawn desktop backend entry ${this.entryPath} with ${this.executablePath}.`;
}
}
type BackendProcessError = BackendProcessBootstrapEncodeError | BackendProcessSpawnError;
export class BackendProcessOutputReadError extends Schema.TaggedErrorClass<BackendProcessOutputReadError>()(
"BackendProcessOutputReadError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read ${this.streamName} from desktop backend process ${this.pid}.`;
}
}
export class BackendProcessOutputHandlingError extends Schema.TaggedErrorClass<BackendProcessOutputHandlingError>()(
"BackendProcessOutputHandlingError",
{
...backendProcessContextSchema,
pid: Schema.Number,
streamName: Schema.Literals(["stdout", "stderr"]),
chunkByteLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle ${this.chunkByteLength} bytes from ${this.streamName} of desktop backend process ${this.pid}.`;
}
}
export type BackendProcessOutputError =
| BackendProcessOutputReadError
| BackendProcessOutputHandlingError;
export class BackendProcessExitStatusError extends Schema.TaggedErrorClass<BackendProcessExitStatusError>()(
"BackendProcessExitStatusError",
{
...backendProcessContextSchema,
pid: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to read the exit status of desktop backend process ${this.pid}.`;
}
}
export class DesktopBackendRestartError extends Schema.TaggedErrorClass<DesktopBackendRestartError>()(
"DesktopBackendRestartError",
{
reason: Schema.String,
delayMs: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop backend restart failed after a scheduled ${this.delayMs}ms delay.`;
}
}
export const BackendProcessError = Schema.Union([
BackendProcessBootstrapEncodeError,
BackendProcessSpawnError,
BackendProcessExitStatusError,
]);
export type BackendProcessError = typeof BackendProcessError.Type;
interface RunBackendProcessOptions extends DesktopBackendStartConfig {
readonly readinessTimeout?: Duration.Duration;
readonly onStarted?: (pid: number) => Effect.Effect<void>;
readonly onReady?: () => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendTimeoutError) => Effect.Effect<void>;
readonly onReadinessFailure?: (error: BackendReadinessTimeoutError) => Effect.Effect<void>;
readonly onOutput?: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void>;
) => Effect.Effect<void, Error>;
readonly onOutputFailure?: (error: BackendProcessOutputError) => Effect.Effect<void>;
}
export interface DesktopBackendSnapshot {
@@ -183,11 +259,10 @@ const closeRun = (
).pipe(Effect.ignore);
};
const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
baseUrl: URL,
timeout: Duration.Duration,
): Effect.fn.Return<void, BackendTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, baseUrl);
export const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(function* (
options: BackendProcessContext & { readonly timeout: Duration.Duration },
): Effect.fn.Return<void, BackendReadinessTimeoutError, HttpClient.HttpClient> {
const readinessUrl = new URL(BACKEND_READINESS_PATH, options.httpBaseUrl);
const client = (yield* HttpClient.HttpClient).pipe(
HttpClient.filterStatusOk,
HttpClient.transformResponse(Effect.timeout(DEFAULT_BACKEND_READINESS_REQUEST_TIMEOUT)),
@@ -196,43 +271,64 @@ const waitForHttpReady = Effect.fn("desktop.backendManager.waitForHttpReady")(fu
yield* client.get(readinessUrl).pipe(
Effect.asVoid,
Effect.timeout(timeout),
Effect.mapError(() => new BackendTimeoutError({ url: readinessUrl })),
Effect.timeout(options.timeout),
Effect.mapError(
(cause) =>
new BackendReadinessTimeoutError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
readinessUrl,
timeoutMs: Duration.toMillis(options.timeout),
cause,
}),
),
);
});
function describeProcessExit(
result: Result.Result<ChildProcessSpawner.ExitCode, PlatformError.PlatformError>,
): BackendProcessExit {
if (Result.isSuccess(result)) {
return {
code: Option.some(result.success),
reason: `code=${result.success}`,
result,
};
}
return {
code: Option.none(),
reason: result.failure.message,
result,
};
}
function drainBackendOutput(
context: BackendProcessContext & { readonly pid: number },
streamName: BackendProcessOutputStream,
stream: Stream.Stream<Uint8Array, PlatformError.PlatformError>,
onOutput: (streamName: BackendProcessOutputStream, chunk: Uint8Array) => Effect.Effect<void>,
onOutput: (
streamName: BackendProcessOutputStream,
chunk: Uint8Array,
) => Effect.Effect<void, Error>,
onOutputFailure: (error: BackendProcessOutputError) => Effect.Effect<void>,
): Effect.Effect<void> {
return stream.pipe(
Stream.runForEach((chunk) => onOutput(streamName, chunk)),
Effect.ignore,
Stream.mapError(
(cause) =>
new BackendProcessOutputReadError({
...context,
streamName,
cause,
}),
),
Stream.runForEach((chunk) =>
onOutput(streamName, chunk).pipe(
Effect.mapError(
(cause) =>
new BackendProcessOutputHandlingError({
...context,
streamName,
chunkByteLength: chunk.byteLength,
cause,
}),
),
),
),
Effect.catchTags({
BackendProcessOutputReadError: onOutputFailure,
BackendProcessOutputHandlingError: onOutputFailure,
}),
);
}
const encodeBootstrapJson = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
const runBackendProcess = Effect.fn("runBackendProcess")(function* (
export const runBackendProcess = Effect.fn("runBackendProcess")(function* (
options: RunBackendProcessOptions,
): Effect.fn.Return<BackendProcessExit, BackendProcessError, BackendProcessRunRequirements> {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -240,7 +336,10 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.mapError(
(cause) =>
new BackendProcessBootstrapEncodeError({
detail: cause.message,
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
@@ -273,7 +372,10 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
Effect.mapError(
(cause) =>
new BackendProcessSpawnError({
detail: cause.message,
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
cause,
}),
),
@@ -281,19 +383,60 @@ const runBackendProcess = Effect.fn("runBackendProcess")(function* (
yield* options.onStarted?.(handle.pid) ?? Effect.void;
if (options.captureOutput) {
yield* drainBackendOutput("stdout", handle.stdout, onOutput).pipe(Effect.forkScoped);
yield* drainBackendOutput("stderr", handle.stderr, onOutput).pipe(Effect.forkScoped);
const outputContext = {
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
};
const onOutputFailure = options.onOutputFailure ?? (() => Effect.void);
yield* drainBackendOutput(
outputContext,
"stdout",
handle.stdout,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
yield* drainBackendOutput(
outputContext,
"stderr",
handle.stderr,
onOutput,
onOutputFailure,
).pipe(Effect.forkScoped);
}
yield* waitForHttpReady(
options.httpBaseUrl,
options.readinessTimeout ?? DEFAULT_BACKEND_READINESS_TIMEOUT,
).pipe(
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.catch((error) => options.onReadinessFailure?.(error) ?? Effect.void),
Effect.catchTags({
BackendReadinessTimeoutError: (error) => options.onReadinessFailure?.(error) ?? Effect.void,
}),
Effect.forkScoped,
);
return describeProcessExit(yield* Effect.result(handle.exitCode));
const exitCode = yield* handle.exitCode.pipe(
Effect.mapError(
(cause) =>
new BackendProcessExitStatusError({
executablePath: options.executablePath,
entryPath: options.entryPath,
cwd: options.cwd,
httpBaseUrl: options.httpBaseUrl,
pid: Number(handle.pid),
cause,
}),
),
);
return {
code: Option.some(exitCode),
reason: `code=${exitCode}`,
} satisfies BackendProcessExit;
});
export const make = Effect.gen(function* () {
@@ -351,7 +494,7 @@ export const make = Effect.gen(function* () {
const config = yield* configuration.resolve.pipe(
Effect.tapError((error) =>
logBackendManagerError("failed to generate desktop backend configuration", {
cause: error.message,
cause: error,
}),
),
Effect.option,
@@ -489,22 +632,26 @@ export const make = Effect.gen(function* () {
yield* desktopWindow.handleBackendReady.pipe(
Effect.catch((error) =>
logBackendManagerError("failed to open main window after backend readiness", {
message: error.message,
cause: error,
}),
),
);
}),
onReadinessFailure: (error) =>
logBackendManagerWarning("backend readiness check failed during bootstrap", {
error: error.message,
error,
}),
onOutput: (streamName, chunk) => backendOutputLog.writeOutputChunk(streamName, chunk),
onOutputFailure: (error) => logBackendManagerError(error.message, { error }),
}).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
Effect.provideService(HttpClient.HttpClient, httpClient),
Scope.provide(runScope),
Effect.matchEffect({
onFailure: (error) => finalizeRun(error.message),
onFailure: (error) =>
logBackendManagerError(error.message, { error }).pipe(
Effect.andThen(finalizeRun(error.message)),
),
onSuccess: (exit) => finalizeRun(exit.reason),
}),
Effect.ensuring(Scope.close(runScope, Exit.void).pipe(Effect.ignore)),
@@ -559,11 +706,17 @@ export const make = Effect.gen(function* () {
}),
),
Effect.flatMap((shouldRestart) => (shouldRestart ? start : Effect.void)),
Effect.catchCause((cause) =>
logBackendManagerError("desktop backend restart fiber failed", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopBackendRestartError({
reason,
delayMs: Duration.toMillis(delay),
cause,
});
return logBackendManagerError(error.message, { error });
}),
),
parentScope,
);
@@ -43,7 +43,16 @@ describe("ElectronProtocol", () => {
assert.isDefined(handler);
const response = yield* Effect.promise(() =>
handler!(new Request("t3code-dev://app/api/health?verbose=1")),
handler!(
new Request("t3code-dev://app/api/health?verbose=1", {
headers: {
accept: "application/json",
origin: "t3code-dev://app",
referer: "t3code-dev://app/",
"sec-fetch-site": "same-origin",
},
}),
),
);
assert.equal(yield* Effect.promise(() => response.text()), "ok");
assert.include(
@@ -70,6 +79,11 @@ describe("ElectronProtocol", () => {
["t3code-dev"],
);
assert.equal(netFetchMock.mock.calls[0]?.[0], "http://127.0.0.1:3773/api/health?verbose=1");
const forwardedHeaders = new Headers(netFetchMock.mock.calls[0]?.[1]?.headers);
assert.equal(forwardedHeaders.get("accept"), "application/json");
assert.isNull(forwardedHeaders.get("origin"));
assert.isNull(forwardedHeaders.get("referer"));
assert.isNull(forwardedHeaders.get("sec-fetch-site"));
assert.deepEqual(unhandleMock.mock.calls, [["t3code-dev"]]);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
@@ -99,6 +113,34 @@ describe("ElectronProtocol", () => {
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("retries transient renderer target failures", () =>
Effect.gen(function* () {
let handler: ((request: Request) => Promise<Response>) | undefined;
handleMock.mockImplementation((_scheme, nextHandler) => {
handler = nextHandler;
});
netFetchMock
.mockRejectedValueOnce(new Error("connect ECONNREFUSED 127.0.0.1:5733"))
.mockResolvedValueOnce(new Response("ready"));
const response = yield* Effect.scoped(
Effect.gen(function* () {
const protocol = yield* ElectronProtocol.ElectronProtocol;
yield* protocol.registerDesktopProtocol({
scheme: "t3code-dev",
targetOrigin: new URL("http://127.0.0.1:5733/"),
backendOrigin: new URL("http://127.0.0.1:3773/"),
clerkFrontendApiHostname: undefined,
});
return yield* Effect.promise(() => handler!(new Request("t3code-dev://app/")));
}),
);
assert.equal(yield* Effect.promise(() => response.text()), "ready");
assert.equal(netFetchMock.mock.calls.length, 2);
}).pipe(Effect.provide(ElectronProtocol.layer)),
);
it.effect("preserves protocol registration failures", () =>
Effect.gen(function* () {
const cause = new Error("protocol registration failed");
+45 -2
View File
@@ -1,6 +1,7 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as NodeTimersPromises from "node:timers/promises";
import * as Ref from "effect/Ref";
import * as Schema from "effect/Schema";
import * as Scope from "effect/Scope";
@@ -114,18 +115,60 @@ async function proxyRequest(
}
const targetUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, targetOrigin);
const headers = new Headers(request.headers);
const headersToRemove: string[] = [];
for (const name of headers.keys()) {
if (
name === "host" ||
name === "origin" ||
name === "referer" ||
name === "connection" ||
name === "content-length" ||
name === "accept-encoding" ||
name === "upgrade-insecure-requests" ||
name.startsWith("sec-fetch-")
) {
headersToRemove.push(name);
}
}
for (const name of headersToRemove) {
headers.delete(name);
}
const init: RequestInit = {
method: request.method,
headers: request.headers,
headers,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
(init as RequestInit & { duplex: "half" }).duplex = "half";
}
const response = await Electron.net.fetch(targetUrl.toString(), init);
const response =
request.method === "GET" || request.method === "HEAD"
? await fetchWithTransientRetry(targetUrl.toString(), init)
: await Electron.net.fetch(targetUrl.toString(), init);
return withContentSecurityPolicy(response, contentSecurityPolicy);
}
const TRANSIENT_FETCH_RETRY_DELAYS_MS = [0, 50, 150] as const;
async function fetchWithTransientRetry(url: string, init: RequestInit): Promise<Response> {
let lastError: unknown;
for (const delayMs of TRANSIENT_FETCH_RETRY_DELAYS_MS) {
if (delayMs > 0) {
await NodeTimersPromises.setTimeout(delayMs);
}
try {
return await Electron.net.fetch(url, init);
} catch (error) {
lastError = error;
}
}
throw lastError;
}
export const make = Effect.gen(function* () {
const registered = yield* Ref.make(false);
+194 -10
View File
@@ -1,26 +1,39 @@
import { assert, describe, it } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import type * as Electron from "electron";
import { beforeEach, vi } from "vite-plus/test";
const { appFocusMock, getAllWindowsMock } = vi.hoisted(() => ({
appFocusMock: vi.fn(),
getAllWindowsMock: vi.fn(),
}));
const { appFocusMock, browserWindowMock, getAllWindowsMock, getFocusedWindowMock } = vi.hoisted(
() => ({
appFocusMock: vi.fn(),
browserWindowMock: vi.fn(function BrowserWindowMock() {}),
getAllWindowsMock: vi.fn(),
getFocusedWindowMock: vi.fn(),
}),
);
vi.mock("electron", () => ({
app: {
focus: appFocusMock,
},
BrowserWindow: {
BrowserWindow: Object.assign(browserWindowMock, {
getAllWindows: getAllWindowsMock,
},
getFocusedWindow: getFocusedWindowMock,
}),
}));
import * as ElectronWindow from "./ElectronWindow.ts";
function makeBrowserWindow(input: { readonly destroyed: boolean }) {
const TestLayer = ElectronWindow.layer.pipe(
Layer.provide(Layer.succeed(HostProcessPlatform, "linux")),
);
function makeBrowserWindow(input: { readonly id: number; readonly destroyed: boolean }) {
return {
id: input.id,
isDestroyed: vi.fn(() => input.destroyed),
} as unknown as Electron.BrowserWindow;
}
@@ -28,13 +41,78 @@ function makeBrowserWindow(input: { readonly destroyed: boolean }) {
describe("ElectronWindow", () => {
beforeEach(() => {
appFocusMock.mockReset();
browserWindowMock.mockReset();
getAllWindowsMock.mockReset();
getFocusedWindowMock.mockReset();
});
it.effect("preserves schema-safe creation context and the Electron cause", () =>
Effect.gen(function* () {
const cause = new Error("native BrowserWindow construction failed");
browserWindowMock.mockImplementationOnce(function BrowserWindowFailure() {
throw cause;
});
const options = {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
icon: {} as Electron.NativeImage,
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
spellcheck: true,
},
} satisfies Electron.BrowserWindowConstructorOptions;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const error = yield* electronWindow.create(options).pipe(Effect.flip);
assert.instanceOf(error, ElectronWindow.ElectronWindowCreateError);
assert.isTrue(ElectronWindow.isElectronWindowCreateError(error));
assert.deepEqual(error.options, {
title: "T3 Code",
width: 1100,
height: 780,
minWidth: 840,
minHeight: 620,
show: false,
modal: false,
frame: true,
transparent: false,
backgroundColor: "#101010",
webPreferences: {
preload: "/tmp/preload.js",
partition: "persist:t3code-preview-test",
sandbox: true,
contextIsolation: true,
nodeIntegration: false,
webviewTag: true,
},
});
assert.isFalse("icon" in error.options);
assert.isFalse("spellcheck" in error.options.webPreferences);
assert.strictEqual(error.cause, cause);
assert.equal(error.message, 'Failed to create Electron BrowserWindow "T3 Code" (1100x780).');
assert.notInclude(error.message, cause.message);
assert.deepEqual(browserWindowMock.mock.calls, [[options]]);
}).pipe(Effect.provide(TestLayer)),
);
it.effect("skips windows destroyed before appearance sync runs", () =>
Effect.gen(function* () {
const liveWindow = makeBrowserWindow({ destroyed: false });
const destroyedWindow = makeBrowserWindow({ destroyed: true });
const liveWindow = makeBrowserWindow({ id: 1, destroyed: false });
const destroyedWindow = makeBrowserWindow({ id: 2, destroyed: true });
getAllWindowsMock.mockReturnValue([destroyedWindow, liveWindow]);
const syncedWindows: Electron.BrowserWindow[] = [];
@@ -46,6 +124,112 @@ describe("ElectronWindow", () => {
);
assert.deepEqual(syncedWindows, [liveWindow]);
}).pipe(Effect.provide(ElectronWindow.layer)),
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves window enumeration failures as structured defects", () =>
Effect.gen(function* () {
const cause = new Error("window enumeration failed");
getAllWindowsMock.mockImplementationOnce(() => {
throw cause;
});
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.currentMainOrFirst);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "list-windows");
assert.equal(error.platform, "linux");
assert.isNull(error.windowId);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
assert.notInclude(error.message, cause.message);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves reveal failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window restore failed");
const window = {
id: 41,
isDestroyed: vi.fn(() => false),
isMinimized: vi.fn(() => true),
restore: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.reveal(window));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "reveal-window");
assert.equal(error.windowId, 41);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves message delivery failures with window and channel context", () =>
Effect.gen(function* () {
const cause = new Error("renderer send failed");
const window = {
id: 42,
isDestroyed: vi.fn(() => false),
webContents: {
send: vi.fn(() => {
throw cause;
}),
},
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.sendAll("desktop:update", { ready: true }));
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "send-window-message");
assert.equal(error.windowId, 42);
assert.equal(error.channel, "desktop:update");
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
it.effect("preserves destroy failures with the target window", () =>
Effect.gen(function* () {
const cause = new Error("window destroy failed");
const window = {
id: 43,
destroy: vi.fn(() => {
throw cause;
}),
} as unknown as Electron.BrowserWindow;
getAllWindowsMock.mockReturnValueOnce([window]);
const electronWindow = yield* ElectronWindow.ElectronWindow;
const exit = yield* Effect.exit(electronWindow.destroyAll);
assert.equal(exit._tag, "Failure");
if (exit._tag === "Failure") {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, ElectronWindow.ElectronWindowOperationError);
assert.equal(error.operation, "destroy-window");
assert.equal(error.windowId, 43);
assert.isNull(error.channel);
assert.strictEqual(error.cause, cause);
}
}).pipe(Effect.provide(TestLayer)),
);
});
+195 -48
View File
@@ -8,14 +8,69 @@ import * as Schema from "effect/Schema";
import * as Electron from "electron";
const ElectronWindowCreateOptions = Schema.Struct({
title: Schema.NullOr(Schema.String),
width: Schema.NullOr(Schema.Number),
height: Schema.NullOr(Schema.Number),
minWidth: Schema.NullOr(Schema.Number),
minHeight: Schema.NullOr(Schema.Number),
show: Schema.NullOr(Schema.Boolean),
modal: Schema.NullOr(Schema.Boolean),
frame: Schema.NullOr(Schema.Boolean),
transparent: Schema.NullOr(Schema.Boolean),
backgroundColor: Schema.NullOr(Schema.String),
webPreferences: Schema.Struct({
preload: Schema.NullOr(Schema.String),
partition: Schema.NullOr(Schema.String),
sandbox: Schema.NullOr(Schema.Boolean),
contextIsolation: Schema.NullOr(Schema.Boolean),
nodeIntegration: Schema.NullOr(Schema.Boolean),
webviewTag: Schema.NullOr(Schema.Boolean),
}),
});
const ElectronWindowOperation = Schema.Literals([
"list-windows",
"get-focused-window",
"inspect-window",
"reveal-window",
"send-window-message",
"destroy-window",
]);
export class ElectronWindowCreateError extends Schema.TaggedErrorClass<ElectronWindowCreateError>()(
"ElectronWindowCreateError",
{
options: ElectronWindowCreateOptions,
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Failed to create Electron BrowserWindow.";
const title = this.options.title === null ? "" : ` "${this.options.title}"`;
const dimensions =
this.options.width === null || this.options.height === null
? ""
: ` (${this.options.width}x${this.options.height})`;
return `Failed to create Electron BrowserWindow${title}${dimensions}.`;
}
}
export const isElectronWindowCreateError = Schema.is(ElectronWindowCreateError);
export class ElectronWindowOperationError extends Schema.TaggedErrorClass<ElectronWindowOperationError>()(
"ElectronWindowOperationError",
{
operation: ElectronWindowOperation,
platform: Schema.String,
windowId: Schema.NullOr(Schema.Number),
channel: Schema.NullOr(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
const window = this.windowId === null ? "" : ` for window ${this.windowId}`;
const channel = this.channel === null ? "" : ` on channel ${JSON.stringify(this.channel)}`;
return `Electron window operation ${JSON.stringify(this.operation)} failed${window}${channel} on ${this.platform}.`;
}
}
@@ -43,9 +98,38 @@ export const make = Effect.gen(function* () {
const platform = yield* HostProcessPlatform;
const mainWindowRef = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const liveMain = Ref.get(mainWindowRef).pipe(
Effect.map(Option.filter((value) => !value.isDestroyed())),
);
const listWindows = Effect.try({
try: () => Electron.BrowserWindow.getAllWindows(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "list-windows",
platform,
windowId: null,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const isWindowDestroyed = (window: Electron.BrowserWindow) =>
Effect.try({
try: () => window.isDestroyed(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "inspect-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
const liveMain = Effect.gen(function* () {
const main = yield* Ref.get(mainWindowRef);
if (Option.isNone(main) || (yield* isWindowDestroyed(main.value))) {
return Option.none<Electron.BrowserWindow>();
}
return main;
});
const currentMainOrFirst = Effect.gen(function* () {
const main = yield* liveMain;
@@ -53,27 +137,60 @@ export const make = Effect.gen(function* () {
return main;
}
return Option.fromNullishOr(Electron.BrowserWindow.getAllWindows()[0] ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
);
const first = Option.fromNullishOr((yield* listWindows)[0] ?? null);
if (Option.isNone(first) || (yield* isWindowDestroyed(first.value))) {
return Option.none<Electron.BrowserWindow>();
}
return first;
});
const focusedMainOrFirst = Effect.sync(() =>
Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null).pipe(
Option.filter((window) => !window.isDestroyed()),
),
).pipe(
Effect.flatMap((focused) =>
Option.isSome(focused) ? Effect.succeed(focused) : currentMainOrFirst,
),
);
const focusedMainOrFirst = Effect.gen(function* () {
const focused = yield* Effect.try({
try: () => Option.fromNullishOr(Electron.BrowserWindow.getFocusedWindow() ?? null),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "get-focused-window",
platform,
windowId: null,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
if (Option.isSome(focused) && !(yield* isWindowDestroyed(focused.value))) {
return focused;
}
return yield* currentMainOrFirst;
});
return ElectronWindow.of({
create: (options) =>
Effect.try({
create: (options) => {
const webPreferences = options.webPreferences;
const diagnosticOptions = {
title: options.title ?? null,
width: options.width ?? null,
height: options.height ?? null,
minWidth: options.minWidth ?? null,
minHeight: options.minHeight ?? null,
show: options.show ?? null,
modal: options.modal ?? null,
frame: options.frame ?? null,
transparent: options.transparent ?? null,
backgroundColor: options.backgroundColor ?? null,
webPreferences: {
preload: webPreferences?.preload ?? null,
partition: webPreferences?.partition ?? null,
sandbox: webPreferences?.sandbox ?? null,
contextIsolation: webPreferences?.contextIsolation ?? null,
nodeIntegration: webPreferences?.nodeIntegration ?? null,
webviewTag: webPreferences?.webviewTag ?? null,
},
} satisfies typeof ElectronWindowCreateOptions.Type;
return Effect.try({
try: () => new Electron.BrowserWindow(options),
catch: (cause) => new ElectronWindowCreateError({ cause }),
}),
catch: (cause) => new ElectronWindowCreateError({ options: diagnosticOptions, cause }),
});
},
main: liveMain,
currentMainOrFirst,
focusedMainOrFirst,
@@ -89,45 +206,75 @@ export const make = Effect.gen(function* () {
return Option.none();
}),
reveal: (window) =>
Effect.sync(() => {
if (window.isDestroyed()) {
return;
}
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
window.show();
}
if (platform === "darwin") {
Electron.app.focus({ steal: true });
}
window.focus();
}),
sendAll: (channel, ...args) =>
Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
Effect.try({
try: () => {
if (window.isDestroyed()) {
return;
}
if (window.isMinimized()) {
window.restore();
}
if (!window.isVisible()) {
window.show();
}
if (platform === "darwin") {
Electron.app.focus({ steal: true });
}
window.focus();
},
catch: (cause) =>
new ElectronWindowOperationError({
operation: "reveal-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie),
sendAll: (channel, ...args) =>
Effect.gen(function* () {
for (const window of yield* listWindows) {
if (yield* isWindowDestroyed(window)) {
continue;
}
window.webContents.send(channel, ...args);
yield* Effect.try({
try: () => window.webContents.send(channel, ...args),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "send-window-message",
platform,
windowId: window.id,
channel,
cause,
}),
}).pipe(Effect.orDie);
}
}),
destroyAll: Effect.sync(() => {
for (const window of Electron.BrowserWindow.getAllWindows()) {
window.destroy();
destroyAll: Effect.gen(function* () {
for (const window of yield* listWindows) {
yield* Effect.try({
try: () => window.destroy(),
catch: (cause) =>
new ElectronWindowOperationError({
operation: "destroy-window",
platform,
windowId: window.id,
channel: null,
cause,
}),
}).pipe(Effect.orDie);
}
}),
syncAllAppearance: Effect.fn("desktop.electron.window.syncAllAppearance")(function* <E, R>(
sync: (window: Electron.BrowserWindow) => Effect.Effect<void, E, R>,
) {
const windows = Electron.BrowserWindow.getAllWindows();
const windows = yield* listWindows;
for (const window of windows) {
if (window.isDestroyed()) {
if (yield* isWindowDestroyed(window)) {
continue;
}
yield* sync(window);
+11 -18
View File
@@ -19,37 +19,30 @@ import {
PreviewAutomationSnapshot,
PreviewAutomationStatus,
} from "@t3tools/contracts";
import { BrowserWindow } from "electron";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as NodeURL from "node:url";
import * as ElectronWindow from "../../electron/ElectronWindow.ts";
import * as PreviewManager from "../../preview/Manager.ts";
import { PREVIEW_WEBVIEW_PREFERENCES } from "../../preview/WebviewPreferences.ts";
import * as IpcChannels from "../channels.ts";
import * as DesktopIpc from "../DesktopIpc.ts";
const broadcast = (channel: string, ...args: ReadonlyArray<unknown>): void => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(channel, ...args);
}
}
};
export const installPreviewEventForwarding = Effect.fn(
"desktop.ipc.preview.installEventForwarding",
)(function* () {
const electronWindow = yield* ElectronWindow.ElectronWindow;
const manager = yield* PreviewManager.PreviewManager;
yield* manager.subscribeStateChanges((tabId, state) => {
broadcast(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state);
});
yield* manager.subscribeRecordingFrames((frame) => {
broadcast(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame);
});
yield* manager.subscribePointerEvents((event) => {
broadcast(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event);
});
yield* manager.subscribeStateChanges((tabId, state) =>
electronWindow.sendAll(IpcChannels.PREVIEW_STATE_CHANGE_CHANNEL, tabId, state),
);
yield* manager.subscribeRecordingFrames((frame) =>
electronWindow.sendAll(IpcChannels.PREVIEW_RECORDING_FRAME_CHANNEL, frame),
);
yield* manager.subscribePointerEvents((event) =>
electronWindow.sendAll(IpcChannels.PREVIEW_POINTER_EVENT_CHANNEL, event),
);
});
export const createTab = DesktopIpc.makeIpcMethod({
@@ -1,7 +1,9 @@
import { assert, describe, it } from "@effect/vitest";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import { beforeEach, vi } from "vite-plus/test";
const { fromPartition, sessions } = vi.hoisted(() => ({
@@ -59,6 +61,64 @@ describe("BrowserSession", () => {
}).pipe(Effect.provide(layer)),
);
it.effect("preserves partition scope and the platform failure chain", () => {
const nativeCause = new Error("native digest failed");
const platformCause = PlatformError.systemError({
_tag: "Unknown",
module: "Crypto",
method: "digest",
cause: nativeCause,
});
const failingCryptoLayer = Layer.succeed(
Crypto.Crypto,
Crypto.make({
randomBytes: (size) => new Uint8Array(size),
digest: () => Effect.fail(platformCause),
}),
);
return Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
const error = yield* browserSessions.getPartition("environment-a").pipe(Effect.flip);
assert.instanceOf(error, BrowserSession.BrowserSessionPartitionDerivationError);
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
assert.isTrue(BrowserSession.isBrowserSessionError(error));
assert.equal(error.scope, "environment-a");
assert.strictEqual(error.cause, platformCause);
assert.strictEqual(error.cause.reason.cause, nativeCause);
assert.equal(
error.message,
"Failed to derive a desktop preview browser partition for scope environment-a.",
);
assert.notInclude(error.message, nativeCause.message);
}).pipe(Effect.provide(BrowserSession.layer.pipe(Layer.provide(failingCryptoLayer))));
});
it.effect("preserves session scope, partition, and the Electron failure", () =>
Effect.gen(function* () {
const cause = new Error("Electron session failed");
fromPartition.mockImplementationOnce(() => {
throw cause;
});
const browserSessions = yield* BrowserSession.BrowserSession;
const partition = yield* browserSessions.getPartition("environment-b");
const error = yield* browserSessions.getSession("environment-b").pipe(Effect.flip);
assert.instanceOf(error, BrowserSession.BrowserSessionCreationError);
assert.isTrue(BrowserSession.isBrowserSessionGetSessionError(error));
assert.isTrue(BrowserSession.isBrowserSessionError(error));
assert.equal(error.scope, "environment-b");
assert.equal(error.partition, partition);
assert.strictEqual(error.cause, cause);
assert.equal(
error.message,
`Failed to create a desktop preview browser session for scope environment-b (partition ${partition}).`,
);
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(layer)),
);
it.effect("clears storage and cache for every created session", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
@@ -80,4 +140,52 @@ describe("BrowserSession", () => {
}
}).pipe(Effect.provide(layer)),
);
it.effect("correlates clear failures while still attempting every session", () =>
Effect.gen(function* () {
const browserSessions = yield* BrowserSession.BrowserSession;
yield* browserSessions.getSession("scope-a");
yield* browserSessions.getSession("scope-b");
const firstPartition = yield* browserSessions.getPartition("scope-a");
const secondPartition = yield* browserSessions.getPartition("scope-b");
const firstSession = sessions.get(firstPartition);
const secondSession = sessions.get(secondPartition);
assert.isDefined(firstSession);
assert.isDefined(secondSession);
const storageCause = new Error("storage clear failed");
secondSession.clearStorageData.mockImplementationOnce(() => Promise.reject(storageCause));
const storageError = yield* browserSessions.clearCookies().pipe(Effect.flip);
assert.instanceOf(storageError, BrowserSession.BrowserSessionStorageClearError);
assert.isTrue(BrowserSession.isBrowserSessionError(storageError));
assert.equal(storageError.partition, secondPartition);
assert.strictEqual(storageError.cause, storageCause);
assert.equal(
storageError.message,
`Failed to clear desktop preview browser storage for partition ${secondPartition}.`,
);
assert.notInclude(storageError.message, storageCause.message);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearStorageData.mock.calls.length, 1);
}
const cacheCause = new Error("cache clear failed");
firstSession.clearCache.mockImplementationOnce(() => Promise.reject(cacheCause));
const cacheError = yield* browserSessions.clearCache().pipe(Effect.flip);
assert.instanceOf(cacheError, BrowserSession.BrowserSessionCacheClearError);
assert.isTrue(BrowserSession.isBrowserSessionError(cacheError));
assert.equal(cacheError.partition, firstPartition);
assert.strictEqual(cacheError.cause, cacheCause);
assert.equal(
cacheError.message,
`Failed to clear the desktop preview browser cache for partition ${firstPartition}.`,
);
assert.notInclude(cacheError.message, cacheCause.message);
for (const browserSession of sessions.values()) {
assert.strictEqual(browserSession.clearCache.mock.calls.length, 1);
}
}).pipe(Effect.provide(layer)),
);
});
+91 -18
View File
@@ -5,31 +5,87 @@ import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
import * as Encoding from "effect/Encoding";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import * as SynchronizedRef from "effect/SynchronizedRef";
const PREVIEW_PARTITION_PREFIX = "persist:t3code-preview-";
export class BrowserSessionError extends Schema.TaggedErrorClass<BrowserSessionError>()(
"BrowserSessionError",
export class BrowserSessionPartitionDerivationError extends Schema.TaggedErrorClass<BrowserSessionPartitionDerivationError>()(
"BrowserSessionPartitionDerivationError",
{
operation: Schema.Literals(["getPartition", "getSession", "clearCookies", "clearCache"]),
scope: Schema.String,
cause: Schema.instanceOf(PlatformError.PlatformError),
},
) {
override get message(): string {
return `Failed to derive a desktop preview browser partition for scope ${this.scope}.`;
}
}
export class BrowserSessionCreationError extends Schema.TaggedErrorClass<BrowserSessionCreationError>()(
"BrowserSessionCreationError",
{
scope: Schema.String,
partition: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop preview browser session operation failed: ${this.operation}`;
return `Failed to create a desktop preview browser session for scope ${this.scope} (partition ${this.partition}).`;
}
}
export class BrowserSessionStorageClearError extends Schema.TaggedErrorClass<BrowserSessionStorageClearError>()(
"BrowserSessionStorageClearError",
{
partition: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clear desktop preview browser storage for partition ${this.partition}.`;
}
}
export class BrowserSessionCacheClearError extends Schema.TaggedErrorClass<BrowserSessionCacheClearError>()(
"BrowserSessionCacheClearError",
{
partition: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to clear the desktop preview browser cache for partition ${this.partition}.`;
}
}
export const BrowserSessionGetSessionError = Schema.Union([
BrowserSessionPartitionDerivationError,
BrowserSessionCreationError,
]);
export type BrowserSessionGetSessionError = typeof BrowserSessionGetSessionError.Type;
export const isBrowserSessionGetSessionError = Schema.is(BrowserSessionGetSessionError);
export const BrowserSessionError = Schema.Union([
BrowserSessionPartitionDerivationError,
BrowserSessionCreationError,
BrowserSessionStorageClearError,
BrowserSessionCacheClearError,
]);
export type BrowserSessionError = typeof BrowserSessionError.Type;
export const isBrowserSessionError = Schema.is(BrowserSessionError);
export class BrowserSession extends Context.Service<
BrowserSession,
{
readonly getPartition: (scope?: string) => Effect.Effect<string, BrowserSessionError>;
readonly getPartition: (
scope?: string,
) => Effect.Effect<string, BrowserSessionPartitionDerivationError>;
readonly isPartition: (partition: string) => boolean;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionError>;
readonly getSession: (scope?: string) => Effect.Effect<Session, BrowserSessionGetSessionError>;
readonly clearCookies: () => Effect.Effect<void, BrowserSessionStorageClearError>;
readonly clearCache: () => Effect.Effect<void, BrowserSessionCacheClearError>;
}
>()("@t3tools/desktop/preview/BrowserSession") {}
@@ -38,11 +94,15 @@ export const make = Effect.gen(function* BrowserSessionMake() {
const sessionsRef = yield* SynchronizedRef.make<ReadonlyMap<string, Session>>(new Map());
const getPartition = Effect.fn("BrowserSession.getPartition")(function* (scope = "shared") {
const digest = yield* crypto
.digest("SHA-256", new TextEncoder().encode(scope))
.pipe(
Effect.mapError((cause) => new BrowserSessionError({ operation: "getPartition", cause })),
);
const digest = yield* crypto.digest("SHA-256", new TextEncoder().encode(scope)).pipe(
Effect.mapError(
(cause) =>
new BrowserSessionPartitionDerivationError({
scope,
cause,
}),
),
);
return `${PREVIEW_PARTITION_PREFIX}${Encoding.encodeHex(digest).slice(0, 20)}`;
});
@@ -67,7 +127,12 @@ export const make = Effect.gen(function* BrowserSessionMake() {
next.set(partition, browserSession);
return [browserSession, next] as const;
},
catch: (cause) => new BrowserSessionError({ operation: "getSession", cause }),
catch: (cause) =>
new BrowserSessionCreationError({
scope,
partition,
cause,
}),
});
});
});
@@ -79,13 +144,17 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCookies: Effect.fn("BrowserSession.clearCookies")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.values()].map((browserSession) =>
[...sessions.entries()].map(([partition, browserSession]) =>
Effect.tryPromise({
try: () =>
browserSession.clearStorageData({
storages: ["cookies", "localstorage", "indexdb", "websql", "serviceworkers"],
}),
catch: (cause) => new BrowserSessionError({ operation: "clearCookies", cause }),
catch: (cause) =>
new BrowserSessionStorageClearError({
partition,
cause,
}),
}),
),
{ concurrency: "unbounded", discard: true },
@@ -94,10 +163,14 @@ export const make = Effect.gen(function* BrowserSessionMake() {
clearCache: Effect.fn("BrowserSession.clearCache")(function* () {
const sessions = yield* SynchronizedRef.get(sessionsRef);
yield* Effect.all(
[...sessions.values()].map((browserSession) =>
[...sessions.entries()].map(([partition, browserSession]) =>
Effect.tryPromise({
try: () => browserSession.clearCache(),
catch: (cause) => new BrowserSessionError({ operation: "clearCache", cause }),
catch: (cause) =>
new BrowserSessionCacheClearError({
partition,
cause,
}),
}),
),
{ concurrency: "unbounded", discard: true },
+460 -11
View File
@@ -1,10 +1,12 @@
import { it as effectIt } from "@effect/vitest";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Schema from "effect/Schema";
@@ -13,19 +15,29 @@ import { TestClock } from "effect/testing";
import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as ElectronWindow from "../electron/ElectronWindow.ts";
import * as BrowserSession from "./BrowserSession.ts";
import * as PreviewManager from "./Manager.ts";
const { createFromPath, fromId, mkdir, showItemInFolder, webviewSend, writeFile, writeImage } =
vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
const {
createFromPath,
fromId,
getFocusedWebContents,
mkdir,
showItemInFolder,
webviewSend,
writeFile,
writeImage,
} = vi.hoisted(() => ({
createFromPath: vi.fn((): { readonly isEmpty: () => boolean } => ({ isEmpty: () => false })),
fromId: vi.fn(() => null),
getFocusedWebContents: vi.fn(() => null),
mkdir: vi.fn((_path: string) => undefined),
showItemInFolder: vi.fn(),
webviewSend: vi.fn(),
writeFile: vi.fn((_path: string, _data: Uint8Array) => undefined),
writeImage: vi.fn(),
}));
vi.mock("electron", () => ({
clipboard: {
@@ -42,6 +54,7 @@ vi.mock("electron", () => ({
},
webContents: {
fromId,
getFocusedWebContents,
},
}));
@@ -79,6 +92,7 @@ const layer = PreviewManager.layer.pipe(
Layer.provideMerge(environmentLayer),
Layer.provideMerge(fileSystemLayer),
Layer.provideMerge(Path.layer),
Layer.provideMerge(Layer.succeed(HostProcessPlatform, "linux")),
);
const encodePreviewManagerError = Schema.encodeSync(PreviewManager.PreviewManagerError);
@@ -95,6 +109,8 @@ const withManager = <A>(
describe("PreviewManager", () => {
beforeEach(() => {
fromId.mockClear();
getFocusedWebContents.mockReset();
getFocusedWebContents.mockReturnValue(null);
mkdir.mockClear();
writeFile.mockClear();
showItemInFolder.mockClear();
@@ -130,6 +146,72 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("isolates failed state listeners and continues delivery", () => {
const loggedErrors: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
for (const value of Array.isArray(message) ? message : [message]) {
if (typeof value === "object" && value !== null && "cause" in value) {
loggedErrors.push(Cause.squash(value.cause as Cause.Cause<never>));
}
}
});
const deliveryError = new ElectronWindow.ElectronWindowOperationError({
operation: "send-window-message",
platform: "darwin",
windowId: 42,
channel: "preview:state-change",
cause: new Error("renderer unavailable"),
});
const delivered = vi.fn();
return withManager((manager) =>
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.die(deliveryError));
yield* manager.subscribeStateChanges((tabId, state) =>
Effect.sync(() => {
delivered(tabId, state);
}),
);
const state = yield* manager.createTab("tab_listener_failure");
expect(delivered).toHaveBeenCalledOnce();
expect(delivered).toHaveBeenCalledWith("tab_listener_failure", state);
expect(loggedErrors).toHaveLength(1);
expect(loggedErrors[0]).toBeInstanceOf(ElectronWindow.ElectronWindowOperationError);
expect(loggedErrors[0]).toMatchObject({
operation: "send-window-message",
windowId: 42,
channel: "preview:state-change",
});
}),
).pipe(
Effect.provide(
Logger.layer([logger], {
mergeWithExisting: false,
}),
),
);
});
effectIt.effect("does not swallow state listener interruption", () =>
withManager((manager) =>
Effect.gen(function* () {
const exit = yield* Effect.scoped(
Effect.gen(function* () {
yield* manager.subscribeStateChanges(() => Effect.interrupt);
return yield* Effect.exit(manager.createTab("tab_interrupted_listener"));
}),
);
expect(Exit.isFailure(exit)).toBe(true);
if (Exit.isFailure(exit)) {
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
}
}),
),
);
effectIt.effect("queues navigation until the webview registers", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -182,6 +264,197 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("mirrors Electron's effective zoom across registration and navigation", () =>
withManager((manager) =>
Effect.gen(function* () {
let effectiveZoom = 0.9;
let zoomReadable = true;
let url = "https://example.com";
const listeners = new Map<string, (...args: unknown[]) => void>();
const setZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => {
if (!zoomReadable) throw new Error("zoom unavailable");
return effectiveZoom;
},
setZoomFactor,
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
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_zoom");
yield* manager.registerWebview("tab_zoom", 42);
expect(states.at(-1)?.zoomFactor).toBe(0.9);
expect(setZoomFactor).not.toHaveBeenCalled();
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";
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(states.at(-1)?.navStatus).toEqual({
kind: "Success",
url,
title: "Example",
});
expect(states.at(-1)?.zoomFactor).toBe(1.25);
const replacementSetZoomFactor = vi.fn();
fromId.mockReturnValue({
id: 43,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "Example",
isLoading: () => false,
getZoomFactor: () => 1,
setZoomFactor: replacementSetZoomFactor,
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.registerWebview("tab_zoom", 43);
expect(replacementSetZoomFactor).toHaveBeenCalledWith(1.25);
expect(states.at(-1)?.zoomFactor).toBe(1.25);
}),
),
);
effectIt.effect("keeps a main-frame load failure visible until a retry starts", () =>
withManager((manager) =>
Effect.gen(function* () {
const url = "http://localhost:5733/";
let loading = false;
const listeners = new Map<string, (...args: unknown[]) => void>();
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => url,
getTitle: () => "localhost:5733",
isLoading: () => loading,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn((event: string, listener: (...args: unknown[]) => void) => {
listeners.set(event, listener);
}),
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 statuses: PreviewManager.PreviewNavStatus[] = [];
yield* manager.subscribeStateChanges((_tabId, state) =>
Effect.sync(() => {
statuses.push(state.navStatus);
}),
);
yield* manager.createTab("tab_failed");
yield* manager.registerWebview("tab_failed", 42);
listeners.get("did-fail-load")?.(
{},
-105,
"ERR_NAME_NOT_RESOLVED",
"https://missing-frame.example/",
false,
);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
listeners.get("did-stop-loading")?.();
listeners.get("page-title-updated")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)).toEqual({
kind: "LoadFailed",
url,
title: "localhost:5733",
code: -102,
description: "ERR_CONNECTION_REFUSED",
});
loading = true;
listeners.get("did-start-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Loading");
loading = false;
listeners.get("did-stop-loading")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
listeners.get("did-fail-load")?.({}, -102, "ERR_CONNECTION_REFUSED", url, true);
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("LoadFailed");
listeners.get("did-navigate")?.();
yield* Effect.yieldNow;
expect(statuses.at(-1)?.kind).toBe("Success");
}),
),
);
effectIt.effect("captures a PNG screenshot into browser artifacts", () =>
withManager((manager) =>
Effect.gen(function* () {
@@ -411,7 +684,11 @@ describe("PreviewManager", () => {
},
} as never);
yield* manager.subscribePointerEvents((event) => activity.push(event.phase));
yield* manager.subscribePointerEvents((event) =>
Effect.sync(() => {
activity.push(event.phase);
}),
);
yield* manager.createTab("tab_1");
yield* manager.registerWebview("tab_1", 42);
const click = yield* manager
@@ -439,6 +716,178 @@ describe("PreviewManager", () => {
),
);
effectIt.effect("types in background webviews and enables native key input", () =>
withManager((manager) =>
Effect.gen(function* () {
let failKeyDown = false;
let humanInput: ((_event: unknown, signal: unknown) => void) | undefined;
const sendCommand = vi.fn(async (method: string, params?: Record<string, unknown>) => {
if (
failKeyDown &&
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
throw new Error("key dispatch failed");
}
if (
method === "Input.dispatchKeyEvent" &&
(params?.["type"] === "keyDown" || params?.["type"] === "rawKeyDown")
) {
humanInput?.(
{},
{
kind: "key",
key: params["key"],
code: params["code"] ?? "Digit1",
},
);
}
return method === "Runtime.evaluate" ? { result: { value: { ok: true } } } : undefined;
});
const restoreFocus = vi.fn();
const focus = vi.fn();
getFocusedWebContents.mockReturnValue({
id: 7,
isDestroyed: () => false,
focus: restoreFocus,
} as never);
fromId.mockReturnValue({
id: 42,
isDestroyed: () => false,
getType: () => "webview",
getURL: () => "https://example.com",
getTitle: () => "Example",
isLoading: () => false,
isDevToolsOpened: () => false,
focus,
getZoomFactor: () => 1,
setZoomFactor: vi.fn(),
on: vi.fn(),
off: vi.fn(),
ipc: {
on: vi.fn((channel: string, listener: typeof humanInput) => {
if (channel === "preview:human-input") humanInput = listener;
}),
off: vi.fn(),
},
send: webviewSend,
navigationHistory: { canGoBack: () => false, canGoForward: () => false },
setWindowOpenHandler: vi.fn(),
debugger: {
isAttached: () => false,
attach: vi.fn(),
sendCommand,
on: vi.fn(),
off: vi.fn(),
},
} as never);
yield* manager.createTab("tab_input");
yield* manager.registerWebview("tab_input", 42);
yield* manager.automationType("tab_input", { text: "hello", clear: true });
yield* manager.automationType("tab_input", { text: "", clear: true });
yield* manager.automationPress("tab_input", { key: "x" });
const calls = sendCommand.mock.calls;
const methods = calls.map(([method]) => method);
const enableIndex = methods.indexOf("Input.setIgnoreInputEvents");
const focusOnIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === true,
);
const keyDownIndex = calls.findIndex(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyDown",
);
const keyUpIndex = calls.findIndex(
([method, params]) => method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
);
const focusOffIndex = calls.findIndex(
([method, params]) =>
method === "Emulation.setFocusEmulationEnabled" && params?.["enabled"] === false,
);
const typeEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('document.execCommand("insertText"'),
);
expect(typeEvaluation).toBeDefined();
const clearOnlyEvaluation = sendCommand.mock.calls.find(
([method, params]) =>
method === "Runtime.evaluate" &&
typeof params === "object" &&
params !== null &&
"expression" in params &&
typeof params.expression === "string" &&
params.expression.includes('const text = ""') &&
params.expression.includes("Object.getOwnPropertyDescriptor"),
);
expect(clearOnlyEvaluation).toBeDefined();
expect(methods).not.toContain("Input.insertText");
expect(enableIndex).toBeGreaterThanOrEqual(0);
expect(focus).toHaveBeenCalledOnce();
expect(restoreFocus).toHaveBeenCalledOnce();
expect(methods).toContain("Page.bringToFront");
expect(enableIndex).toBeLessThan(focusOnIndex);
expect(focusOnIndex).toBeLessThan(keyDownIndex);
expect(keyDownIndex).toBeLessThan(keyUpIndex);
expect(keyUpIndex).toBeLessThan(focusOffIndex);
expect(
calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
expect(sendCommand).toHaveBeenCalledWith("Input.setIgnoreInputEvents", { ignore: false });
sendCommand.mockClear();
failKeyDown = true;
const failedPress = yield* Effect.exit(manager.automationPress("tab_input", { key: "y" }));
expect(Exit.isFailure(failedPress)).toBe(true);
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyUp",
key: "y",
code: "KeyY",
modifiers: 0,
windowsVirtualKeyCode: 89,
location: 0,
isKeypad: false,
});
expect(sendCommand).toHaveBeenCalledWith("Emulation.setFocusEmulationEnabled", {
enabled: false,
});
expect(restoreFocus).toHaveBeenCalledTimes(2);
expect(
sendCommand.mock.calls.filter(
([method, params]) =>
method === "Input.dispatchKeyEvent" && params?.["type"] === "keyUp",
),
).toHaveLength(1);
sendCommand.mockClear();
failKeyDown = false;
yield* manager.automationPress("tab_input", { key: "!" });
expect(sendCommand).toHaveBeenCalledWith("Input.dispatchKeyEvent", {
type: "keyDown",
key: "!",
code: "Digit1",
modifiers: 0,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
text: "!",
unmodifiedText: "!",
});
expect(restoreFocus).toHaveBeenCalledTimes(3);
}),
),
);
effectIt.effect("still interrupts agent control for a different human pointer event", () =>
withManager((manager) =>
Effect.gen(function* () {
+260 -80
View File
@@ -25,6 +25,7 @@ import type {
PreviewAutomationTypeInput,
PreviewAutomationWaitForInput,
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { normalizePreviewUrl } from "@t3tools/shared/preview";
import {
type BrowserWindow,
@@ -62,6 +63,7 @@ import {
} from "./GuestProtocol.ts";
import { isPreviewAnnotationPayload } from "./PickedElementPayload.ts";
import { playwrightInjectedRuntimeInstallExpression } from "./PlaywrightInjectedRuntime.ts";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
export type PreviewNavStatus =
| { kind: "Idle" }
@@ -281,8 +283,8 @@ const nextZoomLevel = (current: number, direction: "in" | "out"): number => {
return ZOOM_LEVELS[Math.max(step - 1, 0)] ?? current;
};
type Listener = (tabId: string, state: PreviewTabState) => void;
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => void;
type Listener = (tabId: string, state: PreviewTabState) => Effect.Effect<void>;
type RecordingFrameListener = (frame: DesktopPreviewRecordingFrame) => Effect.Effect<void>;
type PreviewInputSignal =
| { readonly kind: "pointer"; readonly x: number; readonly y: number; readonly button: number }
@@ -313,7 +315,7 @@ interface BrowserDiagnostics {
readonly requests: ReadonlyMap<string, { url: string; method: string }>;
}
type PointerEventListener = (event: DesktopPreviewPointerEvent) => void;
type PointerEventListener = (event: DesktopPreviewPointerEvent) => Effect.Effect<void>;
interface ExpectedAgentInput {
readonly signal: PreviewInputSignal;
@@ -378,6 +380,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
artifactDirectory: string,
) {
const fileSystem = yield* FileSystem.FileSystem;
const hostPlatform = yield* HostProcessPlatform;
const path = yield* Path.Path;
const parentScope = yield* Scope.Scope;
const context = yield* Effect.context<never>();
@@ -442,11 +445,28 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return copy;
};
const deliverEvent = (
eventKind: "state-change" | "recording-frame" | "pointer-event",
tabId: string,
delivery: () => Effect.Effect<void>,
) =>
Effect.suspend(delivery).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("Desktop preview event listener failed.", {
eventKind,
tabId,
cause,
}),
),
);
const emit = Effect.fn("PreviewManager.emit")(function* (tabId: string, state: PreviewTabState) {
const listeners = yield* Ref.get(listenersRef);
yield* Effect.forEach(
listeners,
(listener) => Effect.sync(() => listener(tabId, state)).pipe(Effect.ignore),
(listener) => deliverEvent("state-change", tabId, () => listener(tabId, state)),
{ discard: true },
);
});
@@ -739,7 +759,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
};
yield* Effect.forEach(
listeners,
(listener) => Effect.sync(() => listener(frame)).pipe(Effect.ignore),
(listener) =>
deliverEvent("recording-frame", frame.tabId, () => listener(frame)),
{ discard: true },
);
}
@@ -836,11 +857,24 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
commandParams?: Record<string, unknown>,
) => Effect.Effect<unknown, PreviewManagerError>;
const prepareAutomationInput = Effect.fn("PreviewManager.prepareAutomationInput")(function* (
send: SendCommand,
enableRuntime: boolean,
) {
yield* Effect.all(
[
...(enableRuntime ? [send("Runtime.enable")] : []),
send("Input.setIgnoreInputEvents", { ignore: false }),
],
{ concurrency: 2, discard: true },
);
});
const withControlSession = Effect.fn("PreviewManager.withControlSession")(function* <A>(
tabId: string,
wc: Electron.WebContents,
action: string,
use: (send: SendCommand) => Effect.Effect<A, PreviewManagerError>,
use: (send: SendCommand, sendCleanup: SendCommand) => Effect.Effect<A, PreviewManagerError>,
) {
const sequence = yield* nextCounter(actionSequenceRef);
const startedAt = yield* currentIso;
@@ -881,7 +915,22 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
return result;
},
);
return yield* use(send);
// Cleanup commands must still run after human input invalidates the action's
// control epoch. Otherwise a partially dispatched input can leave Chromium
// with a held key or focus emulation enabled for subsequent actions.
const sendCleanup: SendCommand = Effect.fn("PreviewManager.sendCleanupCommand")(
function* (method, commandParams) {
return yield* attemptPromise(
{
operation: `${action}.cleanup.${method}`,
tabId,
webContentsId: wc.id,
},
() => wc.debugger.sendCommand(method, commandParams),
);
},
);
return yield* use(send, sendCleanup);
});
const finalize = Effect.fn("PreviewManager.finalizeControlAction")(function* (
exit: Exit.Exit<A, PreviewManagerError>,
@@ -1073,22 +1122,62 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
wc: Electron.WebContents,
) {
const scope = yield* Scope.fork(parentScope, "sequential");
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* () {
const syncState = Effect.fn("PreviewManager.syncWebContentsState")(function* (
preserveLoadFailure: boolean,
) {
if (wc.isDestroyed()) return;
yield* update(tabId, {
navStatus: computeNavStatus(wc),
canGoBack: wc.navigationHistory.canGoBack(),
canGoForward: wc.navigationHistory.canGoForward(),
const zoomFactor = yield* attempt(
{ operation: "syncWebContentsState.getZoomFactor", tabId, webContentsId: wc.id },
() => wc.getZoomFactor(),
).pipe(Effect.option);
const computedNavStatus = computeNavStatus(wc);
const canGoBack = wc.navigationHistory.canGoBack();
const canGoForward = wc.navigationHistory.canGoForward();
const updatedAt = yield* currentIso;
const next = yield* SynchronizedRef.modify(tabsRef, (tabs) => {
const current = tabs.get(tabId);
if (!current) return [Option.none<PreviewTabState>(), tabs] as const;
// Electron emits did-stop-loading after did-fail-load. At that point the
// failed guest is no longer "loading", but it has not successfully
// navigated anywhere. Keep the failure until a new load actually starts.
const navStatus =
preserveLoadFailure &&
current.navStatus.kind === "LoadFailed" &&
computedNavStatus.kind === "Success"
? current.navStatus
: computedNavStatus;
const state: PreviewTabState = {
...current,
navStatus,
canGoBack,
canGoForward,
...(Option.isSome(zoomFactor) ? { zoomFactor: zoomFactor.value } : {}),
updatedAt,
};
return [
Option.some(state),
replaceMap(tabs, (copy) => {
copy.set(tabId, state);
}),
] as const;
});
if (Option.isSome(next)) yield* emit(tabId, next.value);
});
const sync = () => runFork(syncState());
const failed = (_event: Event, code: number, description: string): void => {
if (code === -3) return;
const sync = () => runFork(syncState(true));
const syncNavigation = () => runFork(syncState(false));
const failed = (
_event: Event,
code: number,
description: string,
validatedUrl: string,
isMainFrame: boolean,
): void => {
if (code === -3 || !isMainFrame) return;
runFork(
update(tabId, {
navStatus: {
kind: "LoadFailed",
url: wc.getURL(),
url: validatedUrl || wc.getURL(),
title: wc.getTitle(),
code,
description,
@@ -1143,8 +1232,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
yield* Scope.addFinalizer(
scope,
attempt({ operation: "detachListeners", tabId, webContentsId: wc.id }, () => {
wc.off("did-navigate", sync);
wc.off("did-navigate-in-page", sync);
wc.off("did-navigate", syncNavigation);
wc.off("did-navigate-in-page", syncNavigation);
wc.off("page-title-updated", sync);
wc.off("did-start-loading", sync);
wc.off("did-stop-loading", sync);
@@ -1155,8 +1244,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
const install = Effect.fn("PreviewManager.installWebContentsListeners")(function* () {
yield* attempt({ operation: "attachListeners", tabId, webContentsId: wc.id }, () => {
wc.on("did-navigate", sync);
wc.on("did-navigate-in-page", sync);
wc.on("did-navigate", syncNavigation);
wc.on("did-navigate-in-page", syncNavigation);
wc.on("page-title-updated", sync);
wc.on("did-start-loading", sync);
wc.on("did-stop-loading", sync);
@@ -1262,21 +1351,40 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const attached = yield* Ref.get(attachedRef);
const annotationTheme = yield* Ref.get(annotationThemeRef);
if (tab.webContentsId === webContentsId && attached.has(webContentsId)) {
const zoomFactor = yield* attempt(
{ operation: "registerWebview.getZoomFactor", tabId, webContentsId },
() => wc.getZoomFactor(),
);
yield* update(tabId, { zoomFactor });
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
return;
}
if (tab.webContentsId != null && tab.webContentsId !== webContentsId) {
const replacedWebContentsId =
tab.webContentsId != null && tab.webContentsId !== webContentsId ? tab.webContentsId : null;
if (replacedWebContentsId !== null) {
yield* Effect.all(
[
detachControlSession(tab.webContentsId),
detachListeners(tab.webContentsId),
detachControlSession(replacedWebContentsId),
detachListeners(replacedWebContentsId),
cancelPickElement(tabId),
],
{ concurrency: 3, discard: true },
);
}
const zoomFactor =
replacedWebContentsId !== null
? yield* attempt(
{ operation: "registerWebview.restoreZoomFactor", tabId, webContentsId },
() => {
wc.setZoomFactor(tab.zoomFactor);
return tab.zoomFactor;
},
)
: yield* attempt({ operation: "registerWebview.getZoomFactor", tabId, webContentsId }, () =>
wc.getZoomFactor(),
);
yield* attachListeners(tabId, wc);
runFork(ensureControlSession(wc).pipe(Effect.ignore));
const registeredAt = yield* currentIso;
@@ -1295,6 +1403,7 @@ 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 [
@@ -1312,11 +1421,6 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
}
const { state: registered, pendingUrl } = registration.value;
yield* emit(tabId, registered);
if (Math.abs(registered.zoomFactor - DEFAULT_ZOOM_FACTOR) > ZOOM_EPSILON) {
yield* attempt({ operation: "registerWebview.restoreZoom", tabId, webContentsId }, () =>
wc.setZoomFactor(registered.zoomFactor),
).pipe(Effect.ignore);
}
yield* attempt({ operation: "registerWebview.sendTheme", tabId, webContentsId }, () =>
wc.send(ANNOTATION_THEME_CHANNEL, annotationTheme),
);
@@ -1918,7 +2022,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const listeners = yield* Ref.get(pointerEventListenersRef);
yield* Effect.forEach(
listeners,
(listener) => Effect.sync(() => listener(event)).pipe(Effect.ignore),
(listener) => deliverEvent("pointer-event", event.tabId, () => listener(event)),
{ discard: true },
);
});
@@ -1928,10 +2032,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationClickInput,
send: SendCommand,
) {
yield* Effect.all(
[send("Runtime.enable"), send("Input.setIgnoreInputEvents", { ignore: false })],
{ concurrency: 2, discard: true },
);
yield* prepareAutomationInput(send, true);
const point = yield* resolveClickPoint(tabId, send, input);
const viewport = yield* evaluateWithDebugger<{ width: number; height: number }>(
tabId,
@@ -1993,7 +2094,7 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
);
});
const focusAutomationTarget = Effect.fn("PreviewManager.focusAutomationTarget")(function* (
const typeIntoAutomationTarget = Effect.fn("PreviewManager.typeIntoAutomationTarget")(function* (
tabId: string,
send: SendCommand,
input: PreviewAutomationTypeInput,
@@ -2003,8 +2104,15 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const locatorJson = locator
? yield* encodeJson({ operation: "automationType.encodeLocator", tabId }, locator)
: null;
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
const result = yield* evaluateWithDebugger<
{ ok: true } | { invalidSelector: true; message: string } | { notFound: true }
| { ok: true }
| { invalidSelector: true; message: string }
| { notEditable: true }
| { notFound: true }
>(
tabId,
send,
@@ -2012,12 +2120,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
try {
const element = ${locatorJson ? `(() => { const injected = globalThis.__t3PlaywrightInjected; return injected.querySelector(injected.parseSelector(${locatorJson}), document, true); })()` : "document.activeElement"};
if (!element) return { notFound: true };
const textControl =
element instanceof HTMLTextAreaElement ||
(element instanceof HTMLInputElement &&
!new Set(["button", "checkbox", "color", "file", "hidden", "image", "radio", "range", "reset", "submit"]).has(element.type));
const editable = textControl || element.isContentEditable;
if (!editable || element.disabled || element.readOnly) return { notEditable: true };
element.focus();
if (${input.clear ?? false}) {
if ("value" in element) element.value = "";
else if (element.isContentEditable) element.textContent = "";
element.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "deleteContentBackward" }));
if (document.activeElement !== element) return { notEditable: true };
const clear = ${input.clear ?? false};
if (clear) {
if (textControl) {
element.select();
} else {
const range = document.createRange();
range.selectNodeContents(element);
const selection = document.getSelection();
selection?.removeAllRanges();
selection?.addRange(range);
}
}
const text = ${textJson};
let inserted = true;
if (text.length > 0) {
inserted = document.execCommand("insertText", false, text);
} else if (clear) {
document.execCommand("delete", false);
const cleared = textControl
? element.value.length === 0
: (element.textContent ?? "").length === 0;
if (!cleared) {
if (textControl) {
const prototype = element instanceof HTMLTextAreaElement
? HTMLTextAreaElement.prototype
: HTMLInputElement.prototype;
const valueSetter = Object.getOwnPropertyDescriptor(prototype, "value")?.set;
if (valueSetter) valueSetter.call(element, "");
else element.value = "";
} else {
element.replaceChildren();
}
element.dispatchEvent(new InputEvent("input", {
bubbles: true,
inputType: "deleteContentBackward",
}));
}
}
if (!inserted) return { notEditable: true };
element.dispatchEvent(new Event("change", { bubbles: true }));
return { ok: true };
} catch (error) {
return { invalidSelector: true, message: String(error) };
@@ -2041,6 +2191,12 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
...automationSelectorDiagnostics(input),
});
}
if ("notEditable" in result) {
return yield* new PreviewAutomationTargetNotEditableError({
tabId,
...automationSelectorDiagnostics(input),
});
}
});
const performAutomationType = Effect.fn("PreviewManager.performAutomationType")(function* (
@@ -2048,23 +2204,10 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationTypeInput,
send: SendCommand,
) {
yield* send("Runtime.enable");
yield* focusAutomationTarget(tabId, send, input);
yield* send("Input.insertText", { text: input.text });
const textJson = yield* encodeJson(
{ operation: "automationType.encodeText", tabId },
input.text,
);
yield* evaluateWithDebugger(
tabId,
send,
`(() => {
const element = document.activeElement;
element?.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: ${textJson} }));
element?.dispatchEvent(new Event("change", { bubbles: true }));
})()`,
false,
);
// CDP Input.insertText silently drops text until Electron has activated a hidden
// guest WebContents with a pointer event. Editing in the page runtime keeps
// background automation deterministic without stealing foreground app focus.
yield* typeIntoAutomationTarget(tabId, send, input);
});
const automationType = Effect.fn("PreviewManager.automationType")(function* (
@@ -2079,32 +2222,54 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
const performAutomationPress = Effect.fn("PreviewManager.performAutomationPress")(function* (
tabId: string,
wc: Electron.WebContents,
input: PreviewAutomationPressInput,
send: SendCommand,
sendCleanup: SendCommand,
) {
const modifiers = (input.modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
yield* prepareAutomationInput(send, false);
const keySequence = makePreviewAutomationKeySequence(input, {
isMac: hostPlatform === "darwin",
});
const previouslyFocused = yield* attempt(
{ operation: "automationPress.getFocusedWebContents", tabId, webContentsId: wc.id },
() => webContents.getFocusedWebContents(),
);
let keyDownAttempted = false;
const releaseInput = Effect.gen(function* () {
if (keyDownAttempted) {
yield* sendCleanup("Input.dispatchKeyEvent", keySequence.keyUp).pipe(Effect.ignore);
}
}, 0);
const key = input.key;
const text = key.length === 1 ? key : undefined;
const params = {
key,
code: key.length === 1 ? `Key${key.toUpperCase()}` : key,
modifiers,
...(text ? { text, unmodifiedText: text } : {}),
};
yield* expectAgentInput(tabId, { kind: "key", key, code: params.code });
yield* send("Input.dispatchKeyEvent", { type: "keyDown", ...params });
yield* send("Input.dispatchKeyEvent", { type: "keyUp", ...params });
yield* sendCleanup("Emulation.setFocusEmulationEnabled", { enabled: false }).pipe(
Effect.ignore,
);
if (previouslyFocused && previouslyFocused.id !== wc.id && !previouslyFocused.isDestroyed()) {
yield* attempt(
{
operation: "automationPress.restoreFocusedWebContents",
tabId,
webContentsId: previouslyFocused.id,
},
() => previouslyFocused.focus(),
).pipe(Effect.ignore);
}
});
// Focus the guest WebContents itself, not its containing BrowserWindow. This
// activates native keyboard behavior for hidden/background previews without
// changing which thread is mounted in the UI. Restore the previous renderer
// after dispatch so automation never leaves the app's input focus behind.
yield* Effect.gen(function* () {
yield* attempt(
{ operation: "automationPress.focusWebContents", tabId, webContentsId: wc.id },
() => wc.focus(),
);
yield* send("Page.bringToFront");
yield* send("Emulation.setFocusEmulationEnabled", { enabled: true });
yield* expectAgentInput(tabId, keySequence.signal);
keyDownAttempted = true;
yield* send("Input.dispatchKeyEvent", keySequence.keyDown);
}).pipe(Effect.ensuring(releaseInput));
});
const automationPress = Effect.fn("PreviewManager.automationPress")(function* (
@@ -2112,8 +2277,8 @@ const makeNativeOperations = Effect.fn("PreviewManager.makeOperations")(function
input: PreviewAutomationPressInput,
) {
const wc = yield* requireWebContents(tabId);
yield* withControlSession(tabId, wc, "press", (send) =>
performAutomationPress(tabId, input, send),
yield* withControlSession(tabId, wc, "press", (send, sendCleanup) =>
performAutomationPress(tabId, wc, input, send, sendCleanup),
);
});
@@ -2511,6 +2676,20 @@ export class PreviewAutomationTargetNotFoundError extends Schema.TaggedErrorClas
}
}
export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
"PreviewAutomationTargetNotEditableError",
{
tabId: Schema.String,
selectorKind: PreviewAutomationSelectorKind,
selectorLength: Schema.optionalKey(Schema.Number),
},
) {
override get message(): string {
const target = previewAutomationTargetLabel(this.selectorKind, this.selectorLength);
return `Preview automation type found ${target}, but it is not editable in tab ${this.tabId}`;
}
}
export class PreviewAutomationCoordinatesOutsideViewportError extends Schema.TaggedErrorClass<PreviewAutomationCoordinatesOutsideViewportError>()(
"PreviewAutomationCoordinatesOutsideViewportError",
{
@@ -2613,6 +2792,7 @@ export const PreviewManagerError = Schema.Union([
PreviewAutomationDebuggerAttachedError,
PreviewAutomationEvaluationError,
PreviewAutomationTargetNotFoundError,
PreviewAutomationTargetNotEditableError,
PreviewAutomationCoordinatesOutsideViewportError,
PreviewAutomationInvalidSelectorError,
PreviewAutomationResultTooLargeError,
@@ -0,0 +1,97 @@
import { describe, expect, it } from "vite-plus/test";
import { makePreviewAutomationKeySequence } from "./PreviewKeyboard.ts";
describe("preview keyboard packets", () => {
it("includes the Chromium virtual key code and Enter text", () => {
expect(makePreviewAutomationKeySequence({ key: "Enter" })).toEqual({
keyDown: {
type: "keyDown",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
text: "\r",
unmodifiedText: "\r",
},
keyUp: {
type: "keyUp",
key: "Enter",
code: "Enter",
modifiers: 0,
windowsVirtualKeyCode: 13,
location: 0,
isKeypad: false,
},
signal: { kind: "key", key: "Enter", code: "Enter" },
});
});
it("dispatches printable keys as text key-down events", () => {
const sequence = makePreviewAutomationKeySequence({ key: "z" });
expect(sequence.keyDown).toMatchObject({
type: "keyDown",
key: "z",
code: "KeyZ",
windowsVirtualKeyCode: 90,
text: "z",
});
expect(sequence.keyUp).not.toHaveProperty("text");
});
it("suppresses text and uses raw key-down for shortcuts", () => {
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }, { isMac: true }).keyDown,
).toEqual({
type: "rawKeyDown",
key: "a",
code: "KeyA",
modifiers: 4,
windowsVirtualKeyCode: 65,
location: 0,
isKeypad: false,
commands: ["selectAll"],
});
});
it("maps common macOS editing shortcuts without changing other platforms", () => {
expect(
makePreviewAutomationKeySequence({ key: "z", modifiers: ["Shift", "Meta"] }, { isMac: true })
.keyDown.commands,
).toEqual(["redo"]);
expect(
makePreviewAutomationKeySequence({ key: "a", modifiers: ["Meta"] }).keyDown,
).not.toHaveProperty("commands");
});
it("resolves shifted printable keys to their browser values", () => {
const sequence = makePreviewAutomationKeySequence({ key: "1", modifiers: ["Shift"] });
expect(sequence.keyDown).toMatchObject({
key: "!",
code: "Digit1",
modifiers: 8,
windowsVirtualKeyCode: 49,
text: "!",
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
it("keeps shifted key values while suppressing text for modified chords", () => {
const sequence = makePreviewAutomationKeySequence({
key: "1",
modifiers: ["Control", "Shift"],
});
expect(sequence.keyDown).toEqual({
type: "rawKeyDown",
key: "!",
code: "Digit1",
modifiers: 10,
windowsVirtualKeyCode: 49,
location: 0,
isKeypad: false,
});
expect(sequence.signal).toEqual({ kind: "key", key: "!", code: "Digit1" });
});
});
+203
View File
@@ -0,0 +1,203 @@
import type { PreviewAutomationPressInput } from "@t3tools/contracts";
interface KeyDefinition {
readonly code: string;
readonly key: string;
readonly keyCode: number;
readonly text?: string;
readonly location?: number;
readonly shiftedKey?: string;
}
export interface PreviewAutomationKeyEvent {
readonly [key: string]: unknown;
readonly type: "keyDown" | "rawKeyDown" | "keyUp";
readonly key: string;
readonly code: string;
readonly modifiers: number;
readonly windowsVirtualKeyCode: number;
readonly location: number;
readonly isKeypad: boolean;
readonly text?: string;
readonly unmodifiedText?: string;
readonly commands?: ReadonlyArray<string>;
}
export interface PreviewAutomationKeySequence {
readonly keyDown: PreviewAutomationKeyEvent;
readonly keyUp: PreviewAutomationKeyEvent;
readonly signal: {
readonly kind: "key";
readonly key: string;
readonly code: string;
};
}
const NAMED_KEYS: Readonly<Record<string, KeyDefinition>> = {
Escape: { code: "Escape", key: "Escape", keyCode: 27 },
Backspace: { code: "Backspace", key: "Backspace", keyCode: 8 },
Tab: { code: "Tab", key: "Tab", keyCode: 9 },
Enter: { code: "Enter", key: "Enter", keyCode: 13, text: "\r" },
Shift: { code: "ShiftLeft", key: "Shift", keyCode: 16, location: 1 },
Control: { code: "ControlLeft", key: "Control", keyCode: 17, location: 1 },
Alt: { code: "AltLeft", key: "Alt", keyCode: 18, location: 1 },
Meta: { code: "MetaLeft", key: "Meta", keyCode: 91, location: 1 },
CapsLock: { code: "CapsLock", key: "CapsLock", keyCode: 20 },
Space: { code: "Space", key: " ", keyCode: 32, text: " " },
PageUp: { code: "PageUp", key: "PageUp", keyCode: 33 },
PageDown: { code: "PageDown", key: "PageDown", keyCode: 34 },
End: { code: "End", key: "End", keyCode: 35 },
Home: { code: "Home", key: "Home", keyCode: 36 },
ArrowLeft: { code: "ArrowLeft", key: "ArrowLeft", keyCode: 37 },
ArrowUp: { code: "ArrowUp", key: "ArrowUp", keyCode: 38 },
ArrowRight: { code: "ArrowRight", key: "ArrowRight", keyCode: 39 },
ArrowDown: { code: "ArrowDown", key: "ArrowDown", keyCode: 40 },
Insert: { code: "Insert", key: "Insert", keyCode: 45 },
Delete: { code: "Delete", key: "Delete", keyCode: 46 },
};
const PRINTABLE_KEYS: ReadonlyArray<KeyDefinition> = [
{ code: "Backquote", key: "`", shiftedKey: "~", keyCode: 192 },
{ code: "Digit1", key: "1", shiftedKey: "!", keyCode: 49 },
{ code: "Digit2", key: "2", shiftedKey: "@", keyCode: 50 },
{ code: "Digit3", key: "3", shiftedKey: "#", keyCode: 51 },
{ code: "Digit4", key: "4", shiftedKey: "$", keyCode: 52 },
{ code: "Digit5", key: "5", shiftedKey: "%", keyCode: 53 },
{ code: "Digit6", key: "6", shiftedKey: "^", keyCode: 54 },
{ code: "Digit7", key: "7", shiftedKey: "&", keyCode: 55 },
{ code: "Digit8", key: "8", shiftedKey: "*", keyCode: 56 },
{ code: "Digit9", key: "9", shiftedKey: "(", keyCode: 57 },
{ code: "Digit0", key: "0", shiftedKey: ")", keyCode: 48 },
{ code: "Minus", key: "-", shiftedKey: "_", keyCode: 189 },
{ code: "Equal", key: "=", shiftedKey: "+", keyCode: 187 },
{ code: "Backslash", key: "\\", shiftedKey: "|", keyCode: 220 },
{ code: "BracketLeft", key: "[", shiftedKey: "{", keyCode: 219 },
{ code: "BracketRight", key: "]", shiftedKey: "}", keyCode: 221 },
{ code: "Semicolon", key: ";", shiftedKey: ":", keyCode: 186 },
{ code: "Quote", key: "'", shiftedKey: '"', keyCode: 222 },
{ code: "Comma", key: ",", shiftedKey: "<", keyCode: 188 },
{ code: "Period", key: ".", shiftedKey: ">", keyCode: 190 },
{ code: "Slash", key: "/", shiftedKey: "?", keyCode: 191 },
];
/**
* Chromium does not infer macOS editing commands from synthetic Meta chords.
* Keep the common browser editing/navigation shortcuts explicit so dispatched
* key events behave like their physical-key equivalents.
*/
const MAC_EDITING_COMMANDS: Readonly<Record<string, string>> = {
"Meta+Backspace": "deleteToBeginningOfLine",
"Meta+ArrowUp": "moveToBeginningOfDocument",
"Meta+ArrowDown": "moveToEndOfDocument",
"Meta+ArrowLeft": "moveToLeftEndOfLine",
"Meta+ArrowRight": "moveToRightEndOfLine",
"Shift+Meta+ArrowUp": "moveToBeginningOfDocumentAndModifySelection",
"Shift+Meta+ArrowDown": "moveToEndOfDocumentAndModifySelection",
"Shift+Meta+ArrowLeft": "moveToLeftEndOfLineAndModifySelection",
"Shift+Meta+ArrowRight": "moveToRightEndOfLineAndModifySelection",
"Meta+KeyA": "selectAll",
"Meta+KeyC": "copy",
"Meta+KeyX": "cut",
"Meta+KeyV": "paste",
"Meta+KeyZ": "undo",
"Shift+Meta+KeyZ": "redo",
};
const SHORTCUT_MODIFIER_ORDER = ["Shift", "Control", "Alt", "Meta"] as const;
const macEditingCommands = (
code: string,
modifiers: PreviewAutomationPressInput["modifiers"],
): ReadonlyArray<string> => {
const shortcut = [
...SHORTCUT_MODIFIER_ORDER.filter((modifier) => modifiers?.includes(modifier)),
code,
].join("+");
const command = MAC_EDITING_COMMANDS[shortcut];
return command ? [command] : [];
};
const modifierMask = (modifiers: PreviewAutomationPressInput["modifiers"]): number =>
(modifiers ?? []).reduce((value, modifier) => {
switch (modifier) {
case "Alt":
return value | 1;
case "Control":
return value | 2;
case "Meta":
return value | 4;
case "Shift":
return value | 8;
}
}, 0);
function resolveKeyDefinition(input: PreviewAutomationPressInput): KeyDefinition {
const named = NAMED_KEYS[input.key];
if (named) return named;
const functionKey = /^F([1-9]|1[0-2])$/.exec(input.key);
if (functionKey) {
const number = Number(functionKey[1]);
return { code: input.key, key: input.key, keyCode: 111 + number };
}
if (/^[a-z]$/i.test(input.key)) {
const upper = input.key.toUpperCase();
const shifted = input.modifiers?.includes("Shift") ?? false;
const key = shifted || input.key === upper ? upper : input.key;
return { code: `Key${upper}`, key, keyCode: upper.charCodeAt(0), text: key };
}
const printable = PRINTABLE_KEYS.find(
(definition) => definition.key === input.key || definition.shiftedKey === input.key,
);
if (printable) {
const shifted = input.modifiers?.includes("Shift") ?? false;
const key =
printable.shiftedKey && (shifted || input.key === printable.shiftedKey)
? printable.shiftedKey
: printable.key;
return { ...printable, key, text: key };
}
return {
code: input.key.length > 1 ? input.key : "",
key: input.key,
keyCode: 0,
...(input.key.length === 1 ? { text: input.key } : {}),
};
}
/**
* Build Chromium CDP key packets using the same required fields and down-event
* choice as Playwright's pinned Chromium keyboard implementation.
*/
export function makePreviewAutomationKeySequence(
input: PreviewAutomationPressInput,
options?: { readonly isMac?: boolean },
): PreviewAutomationKeySequence {
const definition = resolveKeyDefinition(input);
const modifiers = modifierMask(input.modifiers);
const suppressText = input.modifiers?.some((modifier) => modifier !== "Shift") ?? false;
const text = suppressText ? "" : (definition.text ?? "");
const location = definition.location ?? 0;
const commands = options?.isMac ? macEditingCommands(definition.code, input.modifiers) : [];
const shared = {
key: definition.key,
code: definition.code,
modifiers,
windowsVirtualKeyCode: definition.keyCode,
location,
isKeypad: location === 3,
};
return {
keyDown: {
type: text ? "keyDown" : "rawKeyDown",
...shared,
...(text ? { text, unmodifiedText: text } : {}),
...(commands.length > 0 ? { commands } : {}),
},
keyUp: { type: "keyUp", ...shared },
signal: { kind: "key", key: definition.key, code: definition.code },
};
}
+47 -20
View File
@@ -83,12 +83,6 @@ export class DesktopSettingsWriteError extends Schema.TaggedErrorClass<DesktopSe
}
}
const writeError = (
operation: DesktopSettingsWriteOperation,
path: string,
cause: unknown,
): DesktopSettingsWriteError => new DesktopSettingsWriteError({ operation, path, cause });
export class DesktopAppSettings extends Context.Service<
DesktopAppSettings,
{
@@ -244,18 +238,46 @@ const writeSettings = Effect.fn("desktop.settings.writeSettings")(function* (inp
const tempPath = `${input.settingsPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeDesktopSettingsJson(
toDesktopSettingsDocument(input.settings, input.defaultSettings),
).pipe(Effect.mapError((cause) => writeError("encode-document", input.settingsPath, cause)));
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.settingsPath)
.pipe(
Effect.mapError((cause) => writeError("replace-settings-file", input.settingsPath, cause)),
);
).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "encode-document",
path: input.settingsPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.settingsPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "replace-settings-file",
path: input.settingsPath,
cause,
}),
),
);
});
export const make = Effect.gen(function* () {
@@ -276,8 +298,13 @@ export const make = Effect.gen(function* () {
return crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.desktopSettingsPath, cause),
Effect.mapError(
(cause) =>
new DesktopSettingsWriteError({
operation: "create-temporary-file-name",
path: environment.desktopSettingsPath,
cause,
}),
),
Effect.flatMap((suffix) =>
writeSettings({
@@ -0,0 +1,129 @@
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 Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as PlatformError from "effect/PlatformError";
import * as References from "effect/References";
import * as DesktopConfig from "../app/DesktopConfig.ts";
import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
interface LogRecord {
readonly message: unknown;
readonly annotations: Readonly<Record<string, unknown>>;
}
const baseDir = "/virtual-home";
function makeLayer(fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) {
const environmentLayer = DesktopEnvironment.layer({
dirname: "/repo/apps/desktop/src",
homeDirectory: baseDir,
platform: "darwin",
processArch: "x64",
appVersion: "1.2.3",
appPath: "/repo",
isPackaged: true,
resourcesPath: "/missing/resources",
runningUnderArm64Translation: false,
}).pipe(
Layer.provide(
Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({ T3CODE_HOME: baseDir })),
),
);
return DesktopClientSettings.layer.pipe(
Layer.provideMerge(Layer.mergeAll(environmentLayer, NodeServices.layer, fileSystemLayer)),
);
}
const readWithLogs = (fileSystemLayer: Layer.Layer<FileSystem.FileSystem>) => {
const records: Array<LogRecord> = [];
const logger = Logger.make(({ fiber, message }) => {
records.push({
message,
annotations: { ...fiber.getRef(References.CurrentLogAnnotations) },
});
});
return Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const settings = yield* DesktopClientSettings.DesktopClientSettings;
return {
result: yield* settings.get,
settingsPath: environment.clientSettingsPath,
records,
};
}).pipe(
Effect.provide(
Layer.mergeAll(
makeLayer(fileSystemLayer),
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
};
describe("DesktopClientSettings diagnostics", () => {
it.effect("treats a missing settings file as expected without warning", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(FileSystem.layerNoop({}));
assert.isTrue(Option.isNone(result.result));
assert.deepEqual(result.records, []);
}),
);
it.effect("logs non-missing filesystem failures with the settings path", () => {
const permissionError = PlatformError.systemError({
_tag: "PermissionDenied",
module: "FileSystem",
method: "readFileString",
pathOrDescriptor: `${baseDir}/userdata/client-settings.json`,
});
return Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.fail(permissionError),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
assert.deepEqual(result.records[0]?.message, [
"Could not read desktop client settings.",
permissionError,
]);
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
});
});
it.effect("logs malformed settings documents with the settings path", () =>
Effect.gen(function* () {
const result = yield* readWithLogs(
FileSystem.layerNoop({
readFileString: () => Effect.succeed("{not-json"),
}),
);
assert.isTrue(Option.isNone(result.result));
assert.equal(result.records.length, 1);
const message = result.records[0]?.message;
if (!Array.isArray(message)) {
return assert.fail("expected structured warning arguments");
}
assert.equal(message[0], "Could not decode desktop client settings.");
const schemaError = message[1];
if (schemaError === null || typeof schemaError !== "object") {
return assert.fail("expected the schema error in the warning");
}
assert.equal("_tag" in schemaError ? schemaError._tag : undefined, "SchemaError");
assert.equal(result.records[0]?.annotations.settingsPath, result.settingsPath);
}),
);
});
@@ -18,7 +18,6 @@ const clientSettings: ClientSettings = {
confirmThreadDelete: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
diffWordWrap: true,
favorites: [],
providerModelPreferences: {},
sidebarProjectGroupingMode: "repository_path",
@@ -29,6 +28,7 @@ const clientSettings: ClientSettings = {
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
timestampFormat: "24-hour",
wordWrap: true,
};
const decodeClientSettingsJson = Schema.decodeEffect(Schema.fromJsonString(ClientSettingsSchema));
@@ -67,14 +67,29 @@ const readClientSettings = (
settingsPath: string,
): Effect.Effect<Option.Option<ClientSettings>> =>
fileSystem.readFileString(settingsPath).pipe(
Effect.option,
Effect.map(Option.some),
Effect.catchTags({
PlatformError: (cause) =>
cause.reason._tag === "NotFound"
? Effect.succeed(Option.none<string>())
: Effect.logWarning("Could not read desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<string>()),
),
}),
Effect.flatMap(
Option.match({
onNone: () => Effect.succeed(Option.none<ClientSettings>()),
onSome: (raw) =>
decodeClientSettingsJson(raw).pipe(
Effect.map((settings) => Option.some(settings)),
Effect.orElseSucceed(() => Option.none<ClientSettings>()),
Effect.catchTags({
SchemaError: (cause) =>
Effect.logWarning("Could not decode desktop client settings.", cause).pipe(
Effect.annotateLogs({ settingsPath }),
Effect.as(Option.none<ClientSettings>()),
),
}),
),
}),
),
@@ -271,10 +271,11 @@ describe("DesktopSavedEnvironments", () => {
),
);
it.effect("surfaces typed safe storage availability failures", () => {
it.effect("adds saved-environment context to safe storage availability failures", () => {
const cause = new Error("safe storage unavailable");
return withSavedEnvironments(
Effect.gen(function* () {
const environment = yield* DesktopEnvironment.DesktopEnvironment;
const savedEnvironments = yield* DesktopSavedEnvironments.DesktopSavedEnvironments;
yield* savedEnvironments.setRegistry([savedRegistryRecord]);
@@ -285,8 +286,22 @@ describe("DesktopSavedEnvironments", () => {
})
.pipe(Effect.flip);
assert.instanceOf(error, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
assert.equal(error.cause, cause);
assert.instanceOf(
error,
DesktopSavedEnvironments.DesktopSavedEnvironmentSecretProtectionError,
);
assert.equal(error.operation, "check-encryption-availability");
assert.equal(error.environmentId, savedRegistryRecord.environmentId);
assert.equal(error.registryPath, environment.savedEnvironmentRegistryPath);
assert.instanceOf(error.cause, ElectronSafeStorage.ElectronSafeStorageAvailabilityError);
const availabilityError =
error.cause as ElectronSafeStorage.ElectronSafeStorageAvailabilityError;
assert.strictEqual(availabilityError.cause, cause);
assert.equal(
error.message,
`Desktop saved-environment secret protection failed during check-encryption-availability for environment ${savedRegistryRecord.environmentId} at ${environment.savedEnvironmentRegistryPath}.`,
);
assert.notEqual(error.message, availabilityError.message);
}),
{ availabilityError: cause },
);
@@ -77,7 +77,12 @@ const DesktopSavedEnvironmentsWriteOperation = Schema.Literals([
"write-temporary-file",
"replace-registry-file",
]);
type DesktopSavedEnvironmentsWriteOperation = typeof DesktopSavedEnvironmentsWriteOperation.Type;
const DesktopSavedEnvironmentSecretProtectionOperation = Schema.Literals([
"check-encryption-availability",
"encrypt-secret",
"decrypt-secret",
]);
export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsWriteError>()(
"DesktopSavedEnvironmentsWriteError",
@@ -92,17 +97,6 @@ export class DesktopSavedEnvironmentsWriteError extends Schema.TaggedErrorClass<
}
}
const writeError = (
operation: DesktopSavedEnvironmentsWriteOperation,
path: string,
cause: unknown,
): DesktopSavedEnvironmentsWriteError =>
new DesktopSavedEnvironmentsWriteError({
operation,
path,
cause,
});
export class DesktopSavedEnvironmentsReadError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentsReadError>()(
"DesktopSavedEnvironmentsReadError",
{
@@ -141,6 +135,20 @@ export class DesktopSavedEnvironmentSecretDecodeError extends Schema.TaggedError
}
}
export class DesktopSavedEnvironmentSecretProtectionError extends Schema.TaggedErrorClass<DesktopSavedEnvironmentSecretProtectionError>()(
"DesktopSavedEnvironmentSecretProtectionError",
{
operation: DesktopSavedEnvironmentSecretProtectionOperation,
environmentId: Schema.String,
registryPath: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop saved-environment secret protection failed during ${this.operation} for environment ${this.environmentId} at ${this.registryPath}.`;
}
}
export type DesktopSavedEnvironmentsReadRegistryError =
| DesktopSavedEnvironmentsReadError
| DesktopSavedEnvironmentsDocumentDecodeError;
@@ -152,11 +160,11 @@ export type DesktopSavedEnvironmentsMutationError =
export type DesktopSavedEnvironmentsGetSecretError =
| DesktopSavedEnvironmentsReadRegistryError
| DesktopSavedEnvironmentSecretDecodeError
| ElectronSafeStorage.ElectronSafeStorageError;
| DesktopSavedEnvironmentSecretProtectionError;
export type DesktopSavedEnvironmentsSetSecretError =
| DesktopSavedEnvironmentsMutationError
| ElectronSafeStorage.ElectronSafeStorageError;
| DesktopSavedEnvironmentSecretProtectionError;
export class DesktopSavedEnvironments extends Context.Service<
DesktopSavedEnvironments,
@@ -276,19 +284,45 @@ const writeRegistryDocument = Effect.fn("desktop.savedEnvironments.writeRegistry
const directory = input.path.dirname(input.registryPath);
const tempPath = `${input.registryPath}.${process.pid}.${input.suffix}.tmp`;
const encoded = yield* encodeSavedEnvironmentRegistryDocumentJson(input.document).pipe(
Effect.mapError((cause) => writeError("encode-registry", input.registryPath, cause)),
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "encode-registry",
path: input.registryPath,
cause,
}),
),
);
yield* input.fileSystem.makeDirectory(directory, { recursive: true }).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "create-directory",
path: directory,
cause,
}),
),
);
yield* input.fileSystem.writeFileString(tempPath, `${encoded}\n`).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "write-temporary-file",
path: tempPath,
cause,
}),
),
);
yield* input.fileSystem.rename(tempPath, input.registryPath).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "replace-registry-file",
path: input.registryPath,
cause,
}),
),
);
yield* input.fileSystem
.makeDirectory(directory, { recursive: true })
.pipe(Effect.mapError((cause) => writeError("create-directory", directory, cause)));
yield* input.fileSystem
.writeFileString(tempPath, `${encoded}\n`)
.pipe(Effect.mapError((cause) => writeError("write-temporary-file", tempPath, cause)));
yield* input.fileSystem
.rename(tempPath, input.registryPath)
.pipe(
Effect.mapError((cause) => writeError("replace-registry-file", input.registryPath, cause)),
);
},
);
@@ -341,8 +375,13 @@ export const make = Effect.gen(function* () {
const writeDocument = (document: SavedEnvironmentRegistryDocument) =>
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => uuid.replace(/-/g, "")),
Effect.mapError((cause) =>
writeError("create-temporary-file-name", environment.savedEnvironmentRegistryPath, cause),
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentsWriteError({
operation: "create-temporary-file-name",
path: environment.savedEnvironmentRegistryPath,
cause,
}),
),
Effect.flatMap((suffix) =>
writeRegistryDocument({
@@ -396,7 +435,21 @@ export const make = Effect.gen(function* () {
document.records.find((record) => record.environmentId === environmentId)
?.encryptedBearerToken,
);
if (Option.isNone(encoded) || !(yield* safeStorage.isEncryptionAvailable)) {
if (Option.isNone(encoded)) {
return Option.none<string>();
}
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "check-encryption-availability",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
);
if (!encryptionAvailable) {
return Option.none<string>();
}
@@ -405,7 +458,19 @@ export const make = Effect.gen(function* () {
environment.savedEnvironmentRegistryPath,
encoded.value,
);
return Option.some(yield* safeStorage.decryptString(secretBytes));
return Option.some(
yield* safeStorage.decryptString(secretBytes).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "decrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
}),
setSecret: Effect.fn("desktop.savedEnvironments.setSecret")(function* (input) {
const { environmentId, secret } = input;
@@ -415,11 +480,34 @@ export const make = Effect.gen(function* () {
environment.savedEnvironmentRegistryPath,
);
if (!(yield* safeStorage.isEncryptionAvailable)) {
const encryptionAvailable = yield* safeStorage.isEncryptionAvailable.pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "check-encryption-availability",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
);
if (!encryptionAvailable) {
return false;
}
const encryptedBearerToken = Encoding.encodeBase64(yield* safeStorage.encryptString(secret));
const encryptedBearerToken = Encoding.encodeBase64(
yield* safeStorage.encryptString(secret).pipe(
Effect.mapError(
(cause) =>
new DesktopSavedEnvironmentSecretProtectionError({
operation: "encrypt-secret",
environmentId,
registryPath: environment.savedEnvironmentRegistryPath,
cause,
}),
),
),
);
let found = false;
const nextDocument: SavedEnvironmentRegistryDocument = {
version: document.version,
@@ -23,6 +23,7 @@ describe("sshEnvironment", () => {
const cause = new DesktopSshPasswordPrompts.DesktopSshPromptPresentationError({
requestId: "prompt-1",
destination: "devbox",
operation: "send-prompt-request",
cause: new Error("renderer send failed"),
});
@@ -17,7 +17,13 @@ interface SentMessage {
readonly args: readonly unknown[];
}
function makeTestWindow() {
function makeTestWindow(
options: {
readonly isDestroyedError?: unknown;
readonly isMinimizedError?: unknown;
readonly sendError?: unknown;
} = {},
) {
const listeners = new Map<string, Set<() => void>>();
const sentMessages: SentMessage[] = [];
let destroyed = false;
@@ -26,8 +32,18 @@ function makeTestWindow() {
let focused = false;
const window = {
isDestroyed: () => destroyed,
isMinimized: () => minimized,
isDestroyed: () => {
if (options.isDestroyedError !== undefined) {
throw options.isDestroyedError;
}
return destroyed;
},
isMinimized: () => {
if (options.isMinimizedError !== undefined) {
throw options.isMinimizedError;
}
return minimized;
},
restore: () => {
restored = true;
minimized = false;
@@ -45,7 +61,11 @@ function makeTestWindow() {
},
webContents: {
send: (channel: string, ...args: readonly unknown[]) => {
sentMessages.push({ channel, args });
const message = { channel, args };
sentMessages.push(message);
if (options.sendError !== undefined) {
throw options.sendError;
}
},
},
};
@@ -55,6 +75,7 @@ function makeTestWindow() {
sentMessages,
isRestored: () => restored,
isFocused: () => focused,
closedListenerCount: () => listeners.get("closed")?.size ?? 0,
close: () => {
destroyed = true;
const closedListeners = [...(listeners.get("closed") ?? [])];
@@ -107,6 +128,7 @@ describe("DesktopSshPasswordPrompts", () => {
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
yield* Effect.yieldNow;
assert.equal(testWindow.sentMessages.length, 1);
const sent = testWindow.sentMessages[0];
@@ -143,4 +165,85 @@ describe("DesktopSshPasswordPrompts", () => {
assert.equal(error.destination, "devbox");
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("cleans up a prompt that fails during renderer delivery", () => {
const cause = new Error("renderer unavailable");
const testWindow = makeTestWindow({ sendError: cause });
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const error = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
assert.equal(error.operation, "send-prompt-request");
assert.equal(error.destination, "devbox");
const requestId = error.requestId;
if (requestId === null) {
assert.fail("renderer delivery failures must retain their request id");
}
assert.equal(testWindow.closedListenerCount(), 0);
const resolveError = yield* prompts
.resolve({ requestId, password: "secret" })
.pipe(Effect.flip);
assert.instanceOf(resolveError, DesktopSshPasswordPrompts.DesktopSshPromptExpiredError);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("keeps a submitted password when a later presentation step fails", () => {
const testWindow = makeTestWindow({
isMinimizedError: new Error("failed to read minimized state"),
});
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const requestFiber = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.forkScoped);
yield* Effect.yieldNow;
const sent = testWindow.sentMessages[0];
assert.ok(sent);
const request = sent.args[0] as { readonly requestId: string };
yield* prompts.resolve({ requestId: request.requestId, password: "secret" });
const password = yield* Fiber.join(requestFiber);
assert.equal(password, "secret");
assert.equal(testWindow.isFocused(), false);
assert.equal(testWindow.closedListenerCount(), 0);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
it.effect("classifies a failed initial window availability check", () => {
const testWindow = makeTestWindow({ isDestroyedError: new Error("window unavailable") });
return Effect.gen(function* () {
const prompts = yield* DesktopSshPasswordPrompts.DesktopSshPasswordPrompts;
const error = yield* prompts
.request({
destination: "devbox",
username: "julius",
prompt: "Enter the SSH password.",
attempt: 1,
})
.pipe(Effect.flip);
assert.instanceOf(error, DesktopSshPasswordPrompts.DesktopSshPromptPresentationError);
assert.equal(error.operation, "check-window-before-request");
assert.equal(error.requestId, null);
assert.deepEqual(testWindow.sentMessages, []);
}).pipe(Effect.provide(makeLayer(testWindow.window)), Effect.scoped);
});
});
+123 -35
View File
@@ -20,7 +20,26 @@ const DEFAULT_SSH_PASSWORD_PROMPT_TIMEOUT_MS = 3 * 60 * 1000;
type DesktopSshPasswordPromptResolutionInput =
typeof DesktopSshPasswordPromptResolutionInputSchema.Type;
const WINDOW_UNAVAILABLE_MESSAGE = "T3 Code window is not available for SSH authentication.";
const DesktopSshPromptWindowAvailabilityStage = Schema.Literals([
"before-request",
"before-presentation",
"after-send",
"after-restore",
]);
const DesktopSshPromptPresentationOperation = Schema.Literals([
"check-window-before-request",
"check-window-before-presentation",
"register-window-close-listener",
"send-prompt-request",
"check-window-after-send",
"check-window-minimized",
"restore-window",
"check-window-after-restore",
"focus-window",
"remove-window-close-listener",
]);
type DesktopSshPromptPresentationOperation = typeof DesktopSshPromptPresentationOperation.Type;
export class DesktopSshPromptRequestIdGenerationError extends Schema.TaggedErrorClass<DesktopSshPromptRequestIdGenerationError>()(
"DesktopSshPromptRequestIdGenerationError",
@@ -38,20 +57,22 @@ export class DesktopSshPromptWindowUnavailableError extends Schema.TaggedErrorCl
"DesktopSshPromptWindowUnavailableError",
{
destination: Schema.String,
requestId: Schema.NullOr(Schema.String),
stage: DesktopSshPromptWindowAvailabilityStage,
},
) {
override get message(): string {
return WINDOW_UNAVAILABLE_MESSAGE;
const request = this.requestId === null ? "before a request id was assigned" : this.requestId;
return `T3 Code window is unavailable during ${this.stage} for SSH authentication to ${this.destination} (request: ${request}).`;
}
}
const isDesktopSshPromptWindowUnavailableError = Schema.is(DesktopSshPromptWindowUnavailableError);
export class DesktopSshPromptPresentationError extends Schema.TaggedErrorClass<DesktopSshPromptPresentationError>()(
"DesktopSshPromptPresentationError",
{
requestId: Schema.String,
requestId: Schema.NullOr(Schema.String),
destination: Schema.String,
operation: DesktopSshPromptPresentationOperation,
cause: Schema.Defect(),
},
) {
@@ -263,9 +284,29 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
"desktop.sshPasswordPrompts.request",
)(function* (input) {
const window = yield* electronWindow.main;
if (Option.isNone(window) || window.value.isDestroyed()) {
if (Option.isNone(window)) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId: null,
stage: "before-request",
});
}
const unavailableBeforeRequest = yield* Effect.try({
try: () => window.value.isDestroyed(),
catch: (cause) =>
new DesktopSshPromptPresentationError({
requestId: null,
destination: input.destination,
operation: "check-window-before-request",
cause,
}),
});
if (unavailableBeforeRequest) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId: null,
stage: "before-request",
});
}
@@ -319,11 +360,25 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
),
);
};
const cleanup = Effect.sync(() => {
const runPresentationOperation = <A>(
operation: DesktopSshPromptPresentationOperation,
evaluate: () => A,
) =>
Effect.try({
try: evaluate,
catch: (cause) =>
new DesktopSshPromptPresentationError({
requestId,
destination: input.destination,
operation,
cause,
}),
});
const cleanup = runPresentationOperation("remove-window-close-listener", () => {
if (!window.value.isDestroyed()) {
window.value.removeListener("closed", cancelOnWindowClosed);
}
}).pipe(Effect.andThen(removePending(pendingRef, requestId)), Effect.asVoid);
}).pipe(Effect.orDie, Effect.ensuring(removePending(pendingRef, requestId)), Effect.asVoid);
const waitForPassword = Deferred.await(deferred).pipe(
Effect.timeoutOption(Duration.millis(passwordPromptTimeoutMs)),
Effect.flatMap(
@@ -339,40 +394,73 @@ export const make = Effect.fn("desktop.sshPasswordPrompts.make")(function* (
}),
),
);
const preferSubmittedPassword = (error: DesktopSshPasswordPromptRequestError) =>
Deferred.poll(deferred).pipe(
Effect.flatMap(
Option.match({
onSome: (completion) => completion,
onNone: () =>
Ref.get(pendingRef).pipe(
Effect.flatMap((entries) =>
entries.has(requestId) ? Effect.fail(error) : Deferred.await(deferred),
),
),
}),
),
);
return yield* Effect.try({
try: () => {
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
return yield* Effect.gen(function* () {
const unavailableBeforePresentation = yield* runPresentationOperation(
"check-window-before-presentation",
() => window.value.isDestroyed(),
);
if (unavailableBeforePresentation) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "before-presentation",
});
}
yield* runPresentationOperation("register-window-close-listener", () =>
window.value.once("closed", cancelOnWindowClosed),
);
return yield* Effect.gen(function* () {
yield* runPresentationOperation("send-prompt-request", () =>
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest),
);
yield* Effect.yieldNow;
const unavailableAfterSend = yield* runPresentationOperation(
"check-window-after-send",
() => window.value.isDestroyed(),
);
if (unavailableAfterSend) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-send",
});
}
window.value.once("closed", cancelOnWindowClosed);
window.value.webContents.send(SSH_PASSWORD_PROMPT_CHANNEL, promptRequest);
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
const minimized = yield* runPresentationOperation("check-window-minimized", () =>
window.value.isMinimized(),
);
if (minimized) {
yield* runPresentationOperation("restore-window", () => window.value.restore());
}
const unavailableAfterRestore = yield* runPresentationOperation(
"check-window-after-restore",
() => window.value.isDestroyed(),
);
if (unavailableAfterRestore) {
return yield* new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
requestId,
stage: "after-restore",
});
}
if (window.value.isMinimized()) {
window.value.restore();
}
if (window.value.isDestroyed()) {
throw new DesktopSshPromptWindowUnavailableError({
destination: input.destination,
});
}
window.value.focus();
},
catch: (cause) =>
isDesktopSshPromptWindowUnavailableError(cause)
? cause
: new DesktopSshPromptPresentationError({
requestId,
destination: input.destination,
cause,
}),
}).pipe(Effect.andThen(waitForPassword), Effect.ensuring(cleanup));
yield* runPresentationOperation("focus-window", () => window.value.focus());
return yield* waitForPassword;
}).pipe(Effect.catch(preferSubmittedPassword));
}).pipe(Effect.ensuring(cleanup));
});
return DesktopSshPasswordPrompts.of({
+259 -3
View File
@@ -7,7 +7,10 @@ import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Logger from "effect/Logger";
import * as Option from "effect/Option";
import * as References from "effect/References";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import * as DesktopBackendManager from "../backend/DesktopBackendManager.ts";
@@ -24,6 +27,9 @@ interface UpdatesHarnessOptions {
void,
ElectronUpdater.ElectronUpdaterCheckForUpdatesError
>;
readonly setUpdateChannelError?: DesktopAppSettings.DesktopSettingsWriteError;
readonly setDisableDifferentialDownload?: Effect.Effect<void>;
readonly stopBackend?: Effect.Effect<void>;
readonly env?: Record<string, string | undefined>;
}
@@ -67,7 +73,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
Effect.sync(() => {
allowDowngrade = value;
}),
setDisableDifferentialDownload: () => Effect.void,
setDisableDifferentialDownload: () => options.setDisableDifferentialDownload ?? Effect.void,
checkForUpdates: Effect.sync(() => {
checkCount += 1;
}).pipe(Effect.andThen(options.checkForUpdates ?? Effect.void)),
@@ -103,7 +109,7 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
const backendLayer = Layer.succeed(DesktopBackendManager.DesktopBackendManager, {
start: Effect.void,
stop: () => Effect.void,
stop: () => options.stopBackend ?? Effect.void,
currentConfig: Effect.succeed(Option.none()),
snapshot: Effect.succeed({
desiredRunning: false,
@@ -138,12 +144,23 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
),
);
const setUpdateChannelError = options.setUpdateChannelError;
const settingsLayer = setUpdateChannelError
? Layer.succeed(DesktopAppSettings.DesktopAppSettings, {
get: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
load: Effect.succeed(DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS),
setServerExposureMode: () => Effect.die("unexpected server exposure update"),
setTailscaleServe: () => Effect.die("unexpected Tailscale Serve update"),
setUpdateChannel: () => Effect.fail(setUpdateChannelError),
} satisfies DesktopAppSettings.DesktopAppSettings["Service"])
: DesktopAppSettings.layer;
const layer = DesktopUpdates.layer.pipe(
Layer.provideMerge(updaterLayer),
Layer.provideMerge(windowLayer),
Layer.provideMerge(backendLayer),
Layer.provideMerge(DesktopState.layer),
Layer.provideMerge(DesktopAppSettings.layer),
Layer.provideMerge(settingsLayer),
Layer.provideMerge(
DesktopConfig.layerTest({
T3CODE_HOME: `/tmp/t3-desktop-updates-test-${process.pid}`,
@@ -175,6 +192,45 @@ function makeHarness(options: UpdatesHarnessOptions = {}) {
}
describe("DesktopUpdates", () => {
it("preserves complete causes for update poller and event failures", () => {
const cause = Cause.combine(
Cause.fail(new Error("updater failed")),
Cause.die(new Error("updater defect")),
);
const pollerError = new DesktopUpdates.DesktopUpdatePollerError({
poller: "startup",
cause,
});
const eventError = new DesktopUpdates.DesktopUpdateEventHandlingError({
event: "download-progress",
cause,
});
const reportedError = new DesktopUpdates.DesktopUpdaterReportedError({
operation: "download",
cause,
});
const unexpectedActionError = new DesktopUpdates.DesktopUpdateUnexpectedActionError({
action: "install",
cause,
});
assert.strictEqual(pollerError.cause, cause);
assert.equal(pollerError.poller, "startup");
assert.equal(pollerError.message, "Desktop update startup poller failed.");
assert.strictEqual(eventError.cause, cause);
assert.equal(eventError.event, "download-progress");
assert.equal(eventError.message, "Failed to handle desktop update download-progress event.");
assert.strictEqual(reportedError.cause, cause);
assert.equal(reportedError.operation, "download");
assert.equal(reportedError.message, "Desktop updater download operation reported an error.");
assert.strictEqual(unexpectedActionError.cause, cause);
assert.equal(unexpectedActionError.action, "install");
assert.equal(
unexpectedActionError.message,
"Desktop update install action failed unexpectedly.",
);
});
it.effect("configures the updater and runs startup checks on the test clock", () => {
const harness = makeHarness();
@@ -222,6 +278,178 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("keeps raw updater event failures out of update state", () => {
const harness = makeHarness();
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("error", cause);
yield* flushCallbacks;
const state = yield* updates.getState;
assert.equal(state.status, "error");
assert.equal(state.message, "Desktop updater background operation reported an error.");
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("logs bounded updater failure context without exposing the cause", () => {
const cause = new Error(
"request failed for https://user:[email protected]/update?token=secret",
);
const updaterError = new ElectronUpdater.ElectronUpdaterCheckForUpdatesError({
channel: null,
cause,
});
const harness = makeHarness({ checkForUpdates: Effect.fail(updaterError) });
const loggedAnnotations: Array<Record<string, unknown>> = [];
const logger = Logger.make(({ fiber }) => {
const annotations = fiber.getRef(References.CurrentLogAnnotations);
if (annotations.errorTag === "ElectronUpdaterCheckForUpdatesError") {
loggedAnnotations.push(annotations);
}
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
yield* updates.check("manual");
const state = yield* updates.getState;
const loggedAnnotation = loggedAnnotations.at(-1);
assert.isDefined(loggedAnnotation);
assert.equal(loggedAnnotation.errorTag, "ElectronUpdaterCheckForUpdatesError");
assert.isNull(loggedAnnotation.channel);
assert.notProperty(loggedAnnotation, "error");
assert.notInclude(Object.values(loggedAnnotation).map(String).join(" "), "secret");
assert.equal(
state.message,
"Electron updater failed to check for updates on channel default.",
);
assert.notInclude(state.message ?? "", "secret");
}),
).pipe(
Effect.provide(
Layer.mergeAll(
TestClock.layer(),
harness.layer,
Logger.layer([logger], { mergeWithExisting: false }),
),
),
);
});
it.effect("recovers download state after an unexpected setup failure", () => {
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
return disableDifferentialCalls === 1
? Effect.void
: Effect.die(new Error("download setup failed"));
}),
});
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.download;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
const failedState = yield* updates.getState;
assert.equal(failedState.status, "available");
assert.equal(failedState.errorContext, "download");
assert.equal(failedState.message, "Desktop update download action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("restores download state and permits retry after interruption", () =>
Effect.gen(function* () {
const actionStarted = yield* Deferred.make<void>();
let disableDifferentialCalls = 0;
const harness = makeHarness({
setDisableDifferentialDownload: Effect.suspend(() => {
disableDifferentialCalls += 1;
if (disableDifferentialCalls === 1) {
return Effect.void;
}
if (disableDifferentialCalls === 2) {
return Deferred.succeed(actionStarted, undefined).pipe(Effect.andThen(Effect.never));
}
return Effect.void;
}),
});
yield* Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-available", { version: "1.2.4" });
yield* flushCallbacks;
const downloadFiber = yield* updates.download.pipe(Effect.forkScoped);
yield* Deferred.await(actionStarted);
yield* Fiber.interrupt(downloadFiber);
const interruptedState = yield* updates.getState;
assert.equal(interruptedState.status, "available");
assert.isNull(interruptedState.message);
const retry = yield* updates.download;
assert.isTrue(retry.accepted);
assert.isTrue(retry.completed);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("clears quitting state after an unexpected install setup failure", () => {
const harness = makeHarness({
stopBackend: Effect.die(new Error("backend stop failed")),
});
return Effect.scoped(
Effect.gen(function* () {
const desktopState = yield* DesktopState.DesktopState;
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
harness.emit("update-downloaded", { version: "1.2.4" });
yield* flushCallbacks;
const result = yield* updates.install;
assert.isTrue(result.accepted);
assert.isFalse(result.completed);
assert.isFalse(yield* Ref.get(desktopState.quitting));
const failedState = yield* updates.getState;
assert.equal(failedState.status, "downloaded");
assert.equal(failedState.errorContext, "install");
assert.equal(failedState.message, "Desktop update install action failed unexpectedly.");
const changedState = yield* updates.setChannel("nightly");
assert.equal(changedState.channel, "nightly");
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
it.effect("persists channel changes through the settings service", () => {
const harness = makeHarness();
@@ -284,6 +512,7 @@ describe("DesktopUpdates", () => {
const error = Cause.squash(exit.cause);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateActionInProgressError);
assert.equal(error.action, "check");
assert.equal(error.requestedChannel, "nightly");
}
yield* Deferred.succeed(releaseCheck, undefined);
@@ -292,4 +521,31 @@ describe("DesktopUpdates", () => {
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}),
);
it.effect("preserves settings failure context when an update channel cannot be persisted", () => {
const diskFailure = new Error("disk exploded");
const settingsFailure = new DesktopAppSettings.DesktopSettingsWriteError({
operation: "replace-settings-file",
path: "/tmp/settings.json",
cause: diskFailure,
});
const harness = makeHarness({ setUpdateChannelError: settingsFailure });
return Effect.scoped(
Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
yield* updates.configure;
const error = yield* updates.setChannel("nightly").pipe(Effect.flip);
assert.instanceOf(error, DesktopUpdates.DesktopUpdateChannelPersistenceError);
assert.isTrue(DesktopUpdates.isDesktopUpdateSetChannelError(error));
assert.equal(error.channel, "nightly");
assert.strictEqual(error.cause, settingsFailure);
assert.strictEqual(error.cause.cause, diskFailure);
assert.equal(error.message, "Failed to persist the nightly desktop update channel.");
assert.notInclude(error.message, diskFailure.message);
}),
).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
});
});
+218 -57
View File
@@ -1,9 +1,10 @@
import type {
DesktopRuntimeInfo,
DesktopUpdateActionResult,
DesktopUpdateChannel,
DesktopUpdateCheckResult,
DesktopUpdateState,
import {
DesktopUpdateChannelSchema,
type DesktopRuntimeInfo,
type DesktopUpdateActionResult,
type DesktopUpdateChannel,
type DesktopUpdateCheckResult,
type DesktopUpdateState,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
@@ -63,30 +64,82 @@ export class DesktopUpdateActionInProgressError extends Schema.TaggedErrorClass<
"DesktopUpdateActionInProgressError",
{
action: Schema.Literals(["check", "download", "install"]),
requestedChannel: DesktopUpdateChannelSchema,
},
) {
override get message(): string {
return `Cannot change update tracks while an update ${this.action} action is in progress.`;
return `Cannot change the desktop update channel to ${this.requestedChannel} while an update ${this.action} action is in progress.`;
}
}
export class DesktopUpdatePersistenceError extends Schema.TaggedErrorClass<DesktopUpdatePersistenceError>()(
"DesktopUpdatePersistenceError",
export class DesktopUpdateChannelPersistenceError extends Schema.TaggedErrorClass<DesktopUpdateChannelPersistenceError>()(
"DesktopUpdateChannelPersistenceError",
{
channel: DesktopUpdateChannelSchema,
cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
},
) {
override get message(): string {
return `Failed to persist the ${this.channel} desktop update channel.`;
}
}
export class DesktopUpdatePollerError extends Schema.TaggedErrorClass<DesktopUpdatePollerError>()(
"DesktopUpdatePollerError",
{
poller: Schema.Literals(["startup", "poll"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
const detail = this.cause instanceof Error ? this.cause.message : String(this.cause);
return `Failed to persist desktop update settings: ${detail}`;
return `Desktop update ${this.poller} poller failed.`;
}
}
export class DesktopUpdateEventHandlingError extends Schema.TaggedErrorClass<DesktopUpdateEventHandlingError>()(
"DesktopUpdateEventHandlingError",
{
event: Schema.Literals(["update-available", "download-progress", "update-downloaded"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to handle desktop update ${this.event} event.`;
}
}
export class DesktopUpdaterReportedError extends Schema.TaggedErrorClass<DesktopUpdaterReportedError>()(
"DesktopUpdaterReportedError",
{
operation: Schema.Literals(["check", "download", "install", "background"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop updater ${this.operation} operation reported an error.`;
}
}
export class DesktopUpdateUnexpectedActionError extends Schema.TaggedErrorClass<DesktopUpdateUnexpectedActionError>()(
"DesktopUpdateUnexpectedActionError",
{
action: Schema.Literals(["download", "install"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Desktop update ${this.action} action failed unexpectedly.`;
}
}
export type DesktopUpdateConfigureError = never;
export type DesktopUpdateSetChannelError =
| DesktopUpdateActionInProgressError
| DesktopUpdatePersistenceError;
export const DesktopUpdateSetChannelError = Schema.Union([
DesktopUpdateActionInProgressError,
DesktopUpdateChannelPersistenceError,
]);
export type DesktopUpdateSetChannelError = typeof DesktopUpdateSetChannelError.Type;
export const isDesktopUpdateSetChannelError = Schema.is(DesktopUpdateSetChannelError);
export class DesktopUpdates extends Context.Service<
DesktopUpdates,
@@ -308,16 +361,21 @@ export const make = Effect.gen(function* () {
return yield* electronUpdater.checkForUpdates.pipe(
Effect.as(true),
Effect.catch(
Effect.fn("desktop.updates.handleCheckForUpdatesFailure")(function* (error) {
Effect.catchTags({
ElectronUpdaterCheckForUpdatesError: Effect.fn(
"desktop.updates.handleCheckForUpdatesFailure",
)(function* (error) {
const failedAt = yield* currentIsoTimestamp;
yield* updateState((current) =>
reduceDesktopUpdateStateOnCheckFailure(current, error.message, failedAt),
);
yield* logUpdaterError("failed to check for updates", { message: error.message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return true;
}),
),
}),
Effect.ensuring(Ref.set(updateCheckInFlightRef, false)),
);
});
@@ -342,19 +400,50 @@ export const make = Effect.gen(function* () {
yield* electronUpdater.downloadUpdate;
return { accepted: true, completed: true };
}).pipe(
Effect.catch(
Effect.fn("desktop.updates.handleDownloadFailure")(function* (error) {
Effect.catchTags({
ElectronUpdaterDownloadUpdateError: Effect.fn("desktop.updates.handleDownloadFailure")(
function* (error) {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() =>
updateState((current) => (current.status === "downloading" ? state : current)).pipe(
Effect.asVoid,
),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
const error = new DesktopUpdateUnexpectedActionError({ action: "download", cause });
return Effect.gen(function* () {
yield* updateState((current) =>
reduceDesktopUpdateStateOnDownloadFailure(current, error.message),
);
yield* logUpdaterError("failed to download update", { message: error.message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
return { accepted: true, completed: false };
}),
),
});
}),
Effect.ensuring(Ref.set(updateDownloadInFlightRef, false)),
);
}).pipe(Effect.withSpan("desktop.updates.downloadAvailableUpdate"));
const resetInstallAction = Effect.all(
[Ref.set(updateInstallInFlightRef, false), Ref.set(desktopState.quitting, false)],
{ discard: true },
);
const installDownloadedUpdate = Effect.gen(function* () {
const state = yield* Ref.get(updateStateRef);
if (
@@ -377,14 +466,38 @@ export const make = Effect.gen(function* () {
});
return { accepted: true, completed: false };
}).pipe(
Effect.catch(
Effect.fn("desktop.updates.handleInstallFailure")(function* (error) {
yield* Ref.set(updateInstallInFlightRef, false);
Effect.catchTags({
ElectronUpdaterQuitAndInstallError: Effect.fn("desktop.updates.handleInstallFailure")(
function* (error) {
yield* resetInstallAction;
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
channel: error.channel,
isSilent: error.isSilent,
isForceRunAfter: error.isForceRunAfter,
});
return { accepted: true, completed: false };
},
),
}),
Effect.onInterrupt(() => resetInstallAction),
Effect.catchCause((cause) =>
Effect.gen(function* () {
if (Cause.hasInterruptsOnly(cause)) {
return yield* Effect.failCause(cause);
}
yield* resetInstallAction;
const error = new DesktopUpdateUnexpectedActionError({ action: "install", cause });
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* Ref.set(desktopState.quitting, false);
yield* logUpdaterError("failed to install update", { message: error.message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
action: error.action,
});
return { accepted: true, completed: false };
}),
),
@@ -394,17 +507,31 @@ export const make = Effect.gen(function* () {
const startUpdatePollers: Effect.Effect<void, never, Scope.Scope> = Effect.gen(function* () {
yield* Effect.sleep(AUTO_UPDATE_STARTUP_DELAY).pipe(
Effect.andThen(checkForUpdates("startup")),
Effect.catchCause((cause) =>
logUpdaterError("startup update check failed", { cause: Cause.pretty(cause) }),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "startup", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.forkScoped,
);
yield* Effect.sleep(AUTO_UPDATE_POLL_INTERVAL).pipe(
Effect.andThen(checkForUpdates("poll")),
Effect.forever,
Effect.catchCause((cause) =>
logUpdaterError("poll update check failed", { cause: Cause.pretty(cause) }),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdatePollerError({ poller: "poll", cause });
return logUpdaterError(error.message, {
errorTag: error._tag,
poller: error.poller,
});
}),
Effect.forkScoped,
);
}).pipe(Effect.withSpan("desktop.updates.startPollers"));
@@ -435,11 +562,16 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update available", { version: info.version });
}),
),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-available event", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-available", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
);
});
@@ -452,14 +584,23 @@ export const make = Effect.gen(function* () {
}).pipe(Effect.withSpan("desktop.updates.handleUpdateNotAvailable"));
const handleUpdaterError = Effect.fn("desktop.updates.handleUpdaterError")(function* (
error: unknown,
cause: unknown,
) {
const message = error instanceof Error ? error.message : String(error);
const activeAction = yield* activeUpdateAction;
const error = new DesktopUpdaterReportedError({
operation: Option.getOrElse(activeAction, () => "background" as const),
cause,
});
if (yield* Ref.get(updateInstallInFlightRef)) {
yield* Ref.set(updateInstallInFlightRef, false);
yield* Ref.set(desktopState.quitting, false);
yield* updateState((current) => reduceDesktopUpdateStateOnInstallFailure(current, message));
yield* logUpdaterError("updater error", { message });
yield* updateState((current) =>
reduceDesktopUpdateStateOnInstallFailure(current, error.message),
);
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
return;
}
@@ -469,7 +610,7 @@ export const make = Effect.gen(function* () {
yield* updateState((current) => ({
...current,
status: "error",
message,
message: error.message,
checkedAt,
downloadPercent: null,
errorContext,
@@ -477,7 +618,10 @@ export const make = Effect.gen(function* () {
}));
}
yield* logUpdaterError("updater error", { message });
yield* logUpdaterError(error.message, {
errorTag: error._tag,
operation: error.operation,
});
});
const handleDownloadProgress = Effect.fn("desktop.updates.handleDownloadProgress")(function* (
@@ -499,11 +643,16 @@ export const make = Effect.gen(function* () {
}
}),
),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed download-progress event", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "download-progress", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
);
});
@@ -518,11 +667,16 @@ export const make = Effect.gen(function* () {
yield* logUpdaterInfo("update downloaded", { version: info.version });
}),
),
Effect.catchCause((cause) =>
logUpdaterWarning("ignored malformed update-downloaded event", {
cause: Cause.pretty(cause),
}),
),
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.void;
}
const error = new DesktopUpdateEventHandlingError({ event: "update-downloaded", cause });
return logUpdaterWarning(error.message, {
errorTag: error._tag,
event: error.event,
});
}),
);
});
@@ -598,7 +752,10 @@ export const make = Effect.gen(function* () {
yield* Effect.annotateCurrentSpan({ channel: nextChannel });
const activeAction = yield* activeUpdateAction;
if (Option.isSome(activeAction)) {
return yield* new DesktopUpdateActionInProgressError({ action: activeAction.value });
return yield* new DesktopUpdateActionInProgressError({
action: activeAction.value,
requestedChannel: nextChannel,
});
}
const state = yield* Ref.get(updateStateRef);
@@ -608,7 +765,11 @@ export const make = Effect.gen(function* () {
yield* desktopSettings
.setUpdateChannel(nextChannel)
.pipe(Effect.mapError((cause) => new DesktopUpdatePersistenceError({ cause })));
.pipe(
Effect.mapError(
(cause) => new DesktopUpdateChannelPersistenceError({ channel: nextChannel, cause }),
),
);
const enabled = yield* shouldEnableAutoUpdates;
yield* setState(createBaseUpdateState(nextChannel, enabled, environment));
@@ -4,6 +4,7 @@ import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
import * as TestClock from "effect/testing/TestClock";
import type * as Electron from "electron";
import { vi } from "vite-plus/test";
@@ -47,12 +48,14 @@ function makeFakeBrowserWindow() {
const webContentsListeners = new Map<string, (...args: readonly unknown[]) => void>();
const webContents = {
copyImageAt: vi.fn(),
getURL: vi.fn(() => "t3code-dev://app/"),
isLoadingMainFrame: vi.fn(() => false),
on: vi.fn((eventName: string, listener: (...args: readonly unknown[]) => void) => {
webContentsListeners.set(eventName, listener);
}),
once: vi.fn(),
openDevTools: vi.fn(),
reload: vi.fn(),
replaceMisspelling: vi.fn(),
send: vi.fn(),
setWindowOpenHandler: vi.fn(),
@@ -79,6 +82,7 @@ function makeFakeBrowserWindow() {
window: window as unknown as Electron.BrowserWindow,
loadURL: window.loadURL,
openDevTools: webContents.openDevTools,
reload: webContents.reload,
setAutoHideCursor: window.setAutoHideCursor,
webContentsListeners,
};
@@ -237,6 +241,73 @@ describe("DesktopWindow", () => {
}),
);
it.effect("recovers when the development renderer is temporarily unreachable", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
const createCount = yield* Ref.make(0);
const mainWindow = yield* Ref.make<Option.Option<Electron.BrowserWindow>>(Option.none());
const layer = makeTestLayer({
window: fakeWindow.window,
createCount,
mainWindow,
});
yield* Effect.gen(function* () {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.handleBackendReady;
const didFailLoad = fakeWindow.webContentsListeners.get("did-fail-load");
const didFinishLoad = fakeWindow.webContentsListeners.get("did-finish-load");
if (!didFailLoad || !didFinishLoad) {
return yield* Effect.die("renderer load listeners were not registered");
}
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
assert.equal(fakeWindow.loadURL.mock.calls.length, 1);
yield* TestClock.adjust(100);
assert.deepEqual(fakeWindow.loadURL.mock.calls, [
["t3code-dev://app/"],
["t3code-dev://app/"],
]);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
didFailLoad({}, -9, "ERR_UNEXPECTED", "t3code-dev://app/", true);
didFinishLoad();
yield* TestClock.adjust(250);
assert.equal(fakeWindow.loadURL.mock.calls.length, 2);
assert.equal(fakeWindow.reload.mock.calls.length, 0);
}).pipe(Effect.provide(layer));
}),
);
it("retries only transient failures for the development renderer", () => {
assert.isTrue(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -3,
isMainFrame: true,
validatedUrl: "t3code-dev://app/",
}),
);
assert.isFalse(
DesktopWindow.isRetryableDevelopmentRendererLoadFailure({
applicationUrl: "t3code-dev://app/",
errorCode: -102,
isMainFrame: true,
validatedUrl: "https://example.com/",
}),
);
});
it.effect("opens safe off-origin renderer navigations in the system browser", () =>
Effect.gen(function* () {
const fakeWindow = makeFakeBrowserWindow();
+95 -3
View File
@@ -1,5 +1,6 @@
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Ref from "effect/Ref";
@@ -22,6 +23,16 @@ const TITLEBAR_HEIGHT = 40;
const TITLEBAR_COLOR = "#01000000"; // #00000000 does not work correctly on Linux
const TITLEBAR_LIGHT_SYMBOL_COLOR = "#1f2937";
const TITLEBAR_DARK_SYMBOL_COLOR = "#f8fafc";
const DEVELOPMENT_LOAD_RETRY_DELAYS_MS = [100, 250, 500, 1_000, 2_000] as const;
const DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES = new Set([
-2, // ERR_FAILED
-7, // ERR_TIMED_OUT
-9, // ERR_UNEXPECTED (custom protocol handler rejected)
-102, // ERR_CONNECTION_REFUSED
-105, // ERR_NAME_NOT_RESOLVED
-106, // ERR_INTERNET_DISCONNECTED
-118, // ERR_CONNECTION_TIMED_OUT
]);
type WindowTitleBarOptions = Pick<
Electron.BrowserWindowConstructorOptions,
@@ -86,6 +97,22 @@ export function isSameOriginRendererNavigation(input: {
}
}
export function isRetryableDevelopmentRendererLoadFailure(input: {
readonly applicationUrl: string;
readonly errorCode: number;
readonly isMainFrame: boolean;
readonly validatedUrl: string;
}): boolean {
return (
input.isMainFrame &&
DEVELOPMENT_RETRYABLE_LOAD_ERROR_CODES.has(input.errorCode) &&
isSameOriginRendererNavigation({
applicationUrl: input.applicationUrl,
navigationUrl: input.validatedUrl,
})
);
}
function getWindowTitleBarOptions(
shouldUseDarkColors: boolean,
platform: NodeJS.Platform,
@@ -152,6 +179,7 @@ export const make = Effect.gen(function* () {
const previewManager = yield* PreviewManager.PreviewManager;
const state = yield* DesktopState.DesktopState;
const context = yield* Effect.context<DesktopWindowRuntimeServices>();
const runFork = Effect.runForkWith(context);
const runPromise = Effect.runPromiseWith(context);
const createWindow = Effect.fn("desktop.window.createWindow")(function* (): Effect.fn.Return<
@@ -277,7 +305,61 @@ export const make = Effect.gen(function* () {
event.preventDefault();
window.setTitle(environment.displayName);
});
let developmentLoadRetryIndex = 0;
let developmentLoadRetryFiber: Fiber.Fiber<void, never> | undefined;
const clearDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber === undefined) {
return;
}
const retryFiber = developmentLoadRetryFiber;
developmentLoadRetryFiber = undefined;
runFork(Fiber.interrupt(retryFiber));
};
const loadApplication = () => {
if (window.isDestroyed()) {
return;
}
void window.loadURL(applicationUrl).catch(() => undefined);
};
const scheduleDevelopmentLoadRetry = () => {
if (developmentLoadRetryFiber !== undefined || window.isDestroyed()) {
return undefined;
}
const retryIndex = Math.min(
developmentLoadRetryIndex,
DEVELOPMENT_LOAD_RETRY_DELAYS_MS.length - 1,
);
const retryInMs = DEVELOPMENT_LOAD_RETRY_DELAYS_MS[retryIndex] ?? 2_000;
developmentLoadRetryIndex += 1;
developmentLoadRetryFiber = runFork(
Effect.sleep(retryInMs).pipe(
Effect.andThen(
Effect.sync(() => {
developmentLoadRetryFiber = undefined;
if (!window.isDestroyed()) {
loadApplication();
}
}),
),
),
);
return retryInMs;
};
window.webContents.on("did-finish-load", () => {
if (
environment.isDevelopment &&
!isSameOriginRendererNavigation({
applicationUrl,
navigationUrl: window.webContents.getURL(),
})
) {
return;
}
clearDevelopmentLoadRetry();
developmentLoadRetryIndex = 0;
window.setTitle(environment.displayName);
});
window.webContents.on(
@@ -286,11 +368,22 @@ export const make = Effect.gen(function* () {
if (!isMainFrame) {
return;
}
const retryInMs =
environment.isDevelopment &&
isRetryableDevelopmentRendererLoadFailure({
applicationUrl,
errorCode,
isMainFrame,
validatedUrl: validatedURL,
})
? scheduleDevelopmentLoadRetry()
: undefined;
void runPromise(
logWindowWarning("main window failed to load", {
errorCode,
errorDescription,
url: validatedURL,
...(retryInMs === undefined ? {} : { retryInMs }),
}),
);
},
@@ -312,14 +405,13 @@ export const make = Effect.gen(function* () {
void runPromise(electronWindow.reveal(window));
});
loadApplication();
if (environment.isDevelopment) {
void window.loadURL(applicationUrl);
window.webContents.openDevTools({ mode: "detach" });
} else {
void window.loadURL(applicationUrl);
}
window.on("closed", () => {
clearDevelopmentLoadRetry();
void runPromise(electronWindow.clearMain(Option.some(window)));
});
+1 -1
View File
@@ -10,7 +10,7 @@
"typecheck": "astro check"
},
"dependencies": {
"astro": "^6.0.4"
"astro": "^7.0.3"
},
"devDependencies": {
"@astrojs/check": "^0.9.7",
+1
View File
@@ -1,6 +1,7 @@
included:
- ios/T3Code
- modules/t3-composer-editor/ios
- modules/t3-native-controls/ios
- modules/t3-terminal/ios
- modules/t3-review-diff/ios
+10 -1
View File
@@ -17,6 +17,7 @@ const VARIANT_CONFIG: Record<
readonly iosIcon: string;
readonly iosBundleIdentifier: string;
readonly androidPackage: string;
readonly relyingParty?: string;
}
> = {
development: {
@@ -25,6 +26,7 @@ const VARIANT_CONFIG: Record<
iosIcon: "./assets/icon-composer-dev.icon",
iosBundleIdentifier: "com.t3tools.t3code.dev",
androidPackage: "com.t3tools.t3code.dev",
relyingParty: "clerk.t3.codes",
},
preview: {
appName: "T3 Code Preview",
@@ -32,6 +34,7 @@ const VARIANT_CONFIG: Record<
iosIcon: "./assets/icon-composer-prod.icon",
iosBundleIdentifier: "com.t3tools.t3code.preview",
androidPackage: "com.t3tools.t3code.preview",
relyingParty: "clerk.t3.codes",
},
production: {
appName: "T3 Code",
@@ -39,6 +42,7 @@ const VARIANT_CONFIG: Record<
iosIcon: "./assets/icon-composer-prod.icon",
iosBundleIdentifier: "com.t3tools.t3code",
androidPackage: "com.t3tools.t3code",
relyingParty: "clerk.t3.codes",
},
};
@@ -77,6 +81,10 @@ const config: ExpoConfig = {
icon: variant.iosIcon,
supportsTablet: true,
bundleIdentifier: variant.iosBundleIdentifier,
associatedDomains: [
`applinks:${variant.relyingParty}`,
`webcredentials:${variant.relyingParty}`,
],
infoPlist: {
NSAppTransportSecurity: {
NSAllowsArbitraryLoads: true,
@@ -101,7 +109,6 @@ const config: ExpoConfig = {
favicon: "./assets/favicon.png",
},
plugins: [
"expo-router",
"expo-font",
"expo-secure-store",
["@clerk/expo", { theme: "./clerk-theme.json" }],
@@ -139,6 +146,7 @@ const config: ExpoConfig = {
},
},
],
"./plugins/withIosCocoaPodsUuidCache.cjs",
[
"expo-widgets",
{
@@ -155,6 +163,7 @@ const config: ExpoConfig = {
],
},
],
"./plugins/withIosSceneLifecycle.cjs",
"./plugins/withAndroidCleartextTraffic.cjs",
],
extra: {
+5 -1
View File
@@ -1,2 +1,6 @@
import "react-native-gesture-handler";
import "expo-router/entry";
import { registerRootComponent } from "expo";
import App from "./src/App";
registerRootComponent(App);
@@ -5,14 +5,8 @@ public class T3ComposerEditorModule: Module {
Name("T3ComposerEditor")
View(T3ComposerEditorView.self) {
Prop("value") { (view: T3ComposerEditorView, value: String) in
view.setValue(value)
}
Prop("tokensJson") { (view: T3ComposerEditorView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("selectionJson") { (view: T3ComposerEditorView, selectionJson: String) in
view.setSelectionJson(selectionJson)
Prop("controlledDocumentJson") { (view: T3ComposerEditorView, documentJson: String) in
view.setControlledDocumentJson(documentJson)
}
Prop("themeJson") { (view: T3ComposerEditorView, themeJson: String) in
view.setThemeJson(themeJson)
@@ -53,6 +47,7 @@ public class T3ComposerEditorModule: Module {
"onComposerSelectionChange",
"onComposerFocus",
"onComposerBlur",
"onComposerSubmit",
"onComposerPasteImages",
"onComposerContentSizeChange"
)
@@ -15,6 +15,14 @@ private struct ComposerSelectionPayload: Decodable {
let end: Int
}
private struct ComposerControlledDocumentPayload: Decodable {
let value: String
let selection: ComposerSelectionPayload?
let tokensJson: String
let mostRecentEventCount: Int
let isNativeEcho: Bool
}
private struct ComposerThemePayload: Decodable {
let text: String
let placeholder: String
@@ -55,6 +63,24 @@ private final class ComposerTextView: UITextView {
var onPasteImages: (([String]) -> Void)?
var onAttributedMutation: (() -> Void)?
var onSubmit: (() -> Void)?
override var keyCommands: [UIKeyCommand]? {
var commands = super.keyCommands ?? []
let submit = UIKeyCommand(
input: "\r",
modifierFlags: .command,
action: #selector(submitMessage(_:))
)
submit.discoverabilityTitle = "Send Message"
submit.wantsPriorityOverSystemBehavior = true
commands.append(submit)
return commands
}
@objc private func submitMessage(_ sender: UIKeyCommand) {
onSubmit?()
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == #selector(paste(_:)) {
@@ -281,6 +307,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
private var shouldAutoFocus = false
private var didAutoFocus = false
private var isApplyingControlledValue = false
private var nativeEventCount = 0
private var lastContentSize = CGSize.zero
private var iconImages: [String: UIImage] = [:]
private var pendingIconUris = Set<String>()
@@ -290,6 +317,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
let onComposerSelectionChange = EventDispatcher()
let onComposerFocus = EventDispatcher()
let onComposerBlur = EventDispatcher()
let onComposerSubmit = EventDispatcher()
let onComposerPasteImages = EventDispatcher()
let onComposerContentSizeChange = EventDispatcher()
@@ -311,6 +339,9 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
textView.onAttributedMutation = { [weak self] in
self?.emitTextChange()
}
textView.onSubmit = { [weak self] in
self?.onComposerSubmit([:])
}
addSubview(textView)
placeholderLabel.numberOfLines = 0
@@ -350,32 +381,28 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
}
}
func setValue(_ value: String) {
self.value = value
applyControlledDocument(force: tokensNeedRebuild)
if tokensMatchCurrentValue() {
tokensNeedRebuild = false
}
}
func setTokensJson(_ tokensJson: String) {
guard self.tokensJson != tokensJson else {
func setControlledDocumentJson(_ documentJson: String) {
guard let document = decode(ComposerControlledDocumentPayload.self, from: documentJson),
document.mostRecentEventCount >= nativeEventCount else {
return
}
self.tokensJson = tokensJson
tokens = decode([ComposerTokenPayload].self, from: tokensJson) ?? []
tokensNeedRebuild = true
applyControlledDocument(force: true)
if document.isNativeEcho && textView.serializedText() != document.value {
return
}
if tokensJson != document.tokensJson {
tokensJson = document.tokensJson
tokens = decode([ComposerTokenPayload].self, from: document.tokensJson) ?? []
tokensNeedRebuild = true
}
value = document.value
requestedSelection = document.selection
applyControlledDocument(force: tokensNeedRebuild)
applyRequestedSelection()
if tokensMatchCurrentValue() {
tokensNeedRebuild = false
}
}
func setSelectionJson(_ selectionJson: String) {
requestedSelection = decode(ComposerSelectionPayload.self, from: selectionJson)
applyRequestedSelection()
}
func setThemeJson(_ themeJson: String) {
guard let nextTheme = decode(ComposerThemePayload.self, from: themeJson) else {
return
@@ -700,18 +727,23 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
}
value = textView.serializedText()
let selection = sourceSelection()
nativeEventCount += 1
onComposerChange([
"value": value,
"selection": ["start": selection.start, "end": selection.end],
"eventCount": nativeEventCount,
])
updatePlaceholderVisibility()
emitContentSizeIfNeeded()
}
private func emitSelection() {
let currentValue = textView.serializedText()
let selection = sourceSelection()
onComposerSelectionChange([
"value": currentValue,
"selection": ["start": selection.start, "end": selection.end],
"eventCount": nativeEventCount,
])
}
@@ -752,6 +784,7 @@ public final class T3ComposerEditorView: ExpoView, UITextViewDelegate {
isApplyingControlledValue = true
textView.selectedRange = nextRange
isApplyingControlledValue = false
self.requestedSelection = nil
}
private func updatePlaceholderVisibility() {
@@ -0,0 +1,6 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["T3NativeControlsModule", "T3KeyboardCommandsModule"]
}
}
@@ -0,0 +1,62 @@
import ExpoModulesCore
import UIKit
public final class T3HeaderButtonView: ExpoView {
private static let size: CGFloat = 44
private static let symbolSize: CGFloat = 18
private let button = UIButton(type: .system)
private var systemImage = "circle"
let onTriggered = EventDispatcher()
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
isAccessibilityElement = false
button.frame = bounds
button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
button.addTarget(self, action: #selector(handlePress), for: .primaryActionTriggered)
addSubview(button)
applyConfiguration()
}
public override var intrinsicContentSize: CGSize {
CGSize(width: Self.size, height: Self.size)
}
public func setLabel(_ label: String) {
button.accessibilityLabel = label
}
public func setSystemImage(_ systemImage: String) {
guard self.systemImage != systemImage else {
return
}
self.systemImage = systemImage
applyConfiguration()
}
private func applyConfiguration() {
var configuration: UIButton.Configuration
if #available(iOS 26.0, *) {
configuration = .glass()
configuration.cornerStyle = .capsule
} else {
configuration = .plain()
}
configuration.baseForegroundColor = .label
configuration.contentInsets = .zero
configuration.image = UIImage(systemName: systemImage)
configuration.preferredSymbolConfigurationForImage = UIImage.SymbolConfiguration(
pointSize: Self.symbolSize,
weight: .regular
)
button.configuration = configuration
}
@objc private func handlePress() {
onTriggered()
}
}
@@ -0,0 +1,131 @@
import ExpoModulesCore
import UIKit
public final class T3KeyboardCommandsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3KeyboardCommands")
View(T3KeyboardCommandsView.self) {
Prop("enabledCommands") { (view: T3KeyboardCommandsView, commands: [String]) in
view.setEnabledCommands(commands)
}
Events("onCommand")
}
}
}
public final class T3KeyboardCommandsView: ExpoView {
let onCommand = EventDispatcher()
private var enabledCommands = Set<String>()
public override var canBecomeFirstResponder: Bool { true }
public override var keyCommands: [UIKeyCommand]? {
[
enabledCommand("newTask", input: "n", modifiers: .command, action: #selector(newTask), title: "New Task"),
enabledCommand("focusSearch", input: "f", modifiers: .command, action: #selector(focusSearch), title: "Find"),
enabledCommand("focusSearch", input: "k", modifiers: .command, action: #selector(focusSearch), title: "Focus Search"),
enabledCommand("back", input: "[", modifiers: .command, action: #selector(goBack), title: "Back"),
enabledCommand("files", input: "f", modifiers: [.command, .shift], action: #selector(openFiles), title: "Open Files"),
enabledCommand("terminal", input: "t", modifiers: [.command, .shift], action: #selector(openTerminal), title: "Open Terminal"),
enabledCommand("review", input: "r", modifiers: [.command, .shift], action: #selector(openReview), title: "Open Review"),
enabledCommand("toggleSidebar", input: "\\", modifiers: .command, action: #selector(handleToggleSidebar), title: "Toggle Sidebar"),
].compactMap { $0 }
}
func setEnabledCommands(_ commands: [String]) {
enabledCommands = Set(commands)
if isFirstResponder {
resignFirstResponder()
}
reclaimFirstResponderIfAvailable()
}
private func enabledCommand(
_ identifier: String,
input: String,
modifiers: UIKeyModifierFlags,
action: Selector,
title: String
) -> UIKeyCommand? {
guard enabledCommands.contains(identifier) else { return nil }
return command(input, modifiers: modifiers, action: action, title: title)
}
public required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UITextView.textDidEndEditingNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UITextField.textDidEndEditingNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(reclaimFirstResponderIfAvailable),
name: UIApplication.didBecomeActiveNotification,
object: nil
)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public override func didMoveToWindow() {
super.didMoveToWindow()
reclaimFirstResponderIfAvailable()
}
public override func layoutSubviews() {
super.layoutSubviews()
reclaimFirstResponderIfAvailable()
}
private func command(
_ input: String,
modifiers: UIKeyModifierFlags,
action: Selector,
title: String
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
command.discoverabilityTitle = title
command.wantsPriorityOverSystemBehavior = true
return command
}
@objc private func newTask() { emit("newTask") }
@objc private func focusSearch() { emit("focusSearch") }
@objc private func goBack() { emit("back") }
@objc private func openFiles() { emit("files") }
@objc private func openTerminal() { emit("terminal") }
@objc private func openReview() { emit("review") }
@objc private func handleToggleSidebar() { emit("toggleSidebar") }
private func emit(_ command: String) {
onCommand(["command": command])
}
@objc private func reclaimFirstResponderIfAvailable() {
DispatchQueue.main.async { [weak self] in
guard let self, self.window?.t3FirstResponder == nil else { return }
self.becomeFirstResponder()
}
}
}
private extension UIView {
var t3FirstResponder: UIResponder? {
if isFirstResponder { return self }
for subview in subviews {
if let responder = subview.t3FirstResponder { return responder }
}
return nil
}
}
@@ -0,0 +1,19 @@
Pod::Spec.new do |s|
s.name = 'T3NativeControls'
s.version = '1.0.0'
s.summary = 'Native UIKit controls for T3 Code mobile.'
s.description = 'UIKit-backed controls that match native iOS navigation chrome.'
s.author = 'T3 Tools'
s.homepage = 'https://t3tools.com'
s.platforms = {
:ios => '18.0',
}
s.source = { :path => '.' }
s.static_framework = true
s.dependency 'ExpoModulesCore'
s.pod_target_xcconfig = {
'DEFINES_MODULE' => 'YES',
}
s.source_files = '**/*.{h,m,mm,swift,hpp,cpp}'
end
@@ -0,0 +1,18 @@
import ExpoModulesCore
public final class T3NativeControlsModule: Module {
public func definition() -> ModuleDefinition {
Name("T3NativeControls")
View(T3HeaderButtonView.self) {
Prop("label") { (view: T3HeaderButtonView, label: String) in
view.setLabel(label)
}
Prop("systemImage") { (view: T3HeaderButtonView, systemImage: String) in
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
@@ -5,22 +5,14 @@ public class T3ReviewDiffModule: Module {
Name("T3ReviewDiffSurface")
View(T3ReviewDiffView.self) {
Prop("rowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
Prop("tokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
Prop("tokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
Prop("tokensResetKey") { (view: T3ReviewDiffView, tokensResetKey: String) in
view.setTokensResetKey(tokensResetKey)
}
Prop("contentResetKey") { (view: T3ReviewDiffView, contentResetKey: String) in
view.setContentResetKey(contentResetKey)
}
Prop("collapsedFileIdsJson") { (view: T3ReviewDiffView, collapsedFileIdsJson: String) in
view.setCollapsedFileIdsJson(collapsedFileIdsJson)
}
@@ -61,7 +53,37 @@ public class T3ReviewDiffModule: Module {
view.setInitialRowIndex(initialRowIndex)
}
Events("onDebug", "onToggleFile", "onToggleViewedFile", "onPressLine", "onToggleComment")
Events(
"onDebug",
"onVisibleFileChange",
"onToggleFile",
"onToggleViewedFile",
"onPressLine",
"onToggleComment"
)
AsyncFunction("scrollToFile") { (view: T3ReviewDiffView, fileId: String, animated: Bool) in
view.scrollToFile(fileId, animated: animated)
}
AsyncFunction("scrollToTop") { (view: T3ReviewDiffView, animated: Bool) in
view.scrollToTop(animated: animated)
}
// Large, frequently changing JSON values cannot be regular Fabric props. Expo's
// prop adapter compares strings on the main thread before invoking a setter, which
// makes a syntax-token patch capable of blocking a frame by itself.
AsyncFunction("setRowsJson") { (view: T3ReviewDiffView, rowsJson: String) in
view.setRowsJson(rowsJson)
}
AsyncFunction("setTokensJson") { (view: T3ReviewDiffView, tokensJson: String) in
view.setTokensJson(tokensJson)
}
AsyncFunction("setTokensPatchJson") { (view: T3ReviewDiffView, tokensPatchJson: String) in
view.setTokensPatchJson(tokensPatchJson)
}
}
}
}
@@ -1,7 +1,7 @@
import ExpoModulesCore
import UIKit
private struct ReviewDiffNativeRow: Decodable {
private struct ReviewDiffNativeRow: Decodable, Sendable {
let kind: String
let id: String
let fileId: String?
@@ -21,18 +21,18 @@ private struct ReviewDiffNativeRow: Decodable {
let commentSectionTitle: String?
}
private struct ReviewDiffNativeWordDiffRange: Decodable {
private struct ReviewDiffNativeWordDiffRange: Decodable, Sendable {
let start: Int
let end: Int
}
private struct ReviewDiffNativeToken: Decodable {
private struct ReviewDiffNativeToken: Decodable, Sendable {
let content: String
let color: String?
let fontStyle: Int?
}
private struct ReviewDiffNativeTokenPatch: Decodable {
private struct ReviewDiffNativeTokenPatch: Decodable, Sendable {
let resetKey: String?
let chunkIndex: Int?
let tokensByRowId: [String: [ReviewDiffNativeToken]]?
@@ -312,6 +312,10 @@ private struct ReviewDiffNativeStyle {
}
public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private let payloadDecodeQueue = DispatchQueue(
label: "com.t3tools.review-diff.payload-decode",
qos: .userInitiated
)
private let scrollView = UIScrollView()
private let contentView = ReviewDiffContentView()
private var rows: [ReviewDiffNativeRow] = []
@@ -323,10 +327,18 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
private var lastMetricsDebugKey = ""
private var lastVisibleRangeDebugKey = ""
private var tokensResetKey = ""
private var contentResetKey = ""
private var initialRowIndex: Int?
private var hasAppliedInitialRowIndex = false
private var lastVisibleFileId: String?
private var pendingScrollFileId: String?
private var pendingScrollAnimated = false
private var isProgrammaticScrollActive = false
private var rowsDecodeGeneration = 0
private var tokensDecodeGeneration = 0
let onDebug = EventDispatcher()
let onVisibleFileChange = EventDispatcher()
let onToggleFile = EventDispatcher()
let onToggleViewedFile = EventDispatcher()
let onPressLine = EventDispatcher()
@@ -379,6 +391,13 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
updateViewportFrame()
}
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
// A direct gesture takes ownership from any interrupted programmatic jump.
// Resume visible-file events immediately so the inspector follows the finger.
isProgrammaticScrollActive = false
contentView.isVerticalScrollActive = true
}
public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard !decelerate else {
return
@@ -396,77 +415,125 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
}
func setRowsJson(_ rowsJson: String) {
guard let data = rowsJson.data(using: .utf8) else {
return
}
rowsDecodeGeneration += 1
let generation = rowsDecodeGeneration
do {
rows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
contentView.rows = rows
hasAppliedInitialRowIndex = false
emitDebug("rows-decoded", [
"rows": rows.count,
"firstKind": rows.first?.kind ?? "none",
])
updateContentMetrics()
} catch {
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
updateContentMetrics()
emitDebug("rows-decode-failed", [
"error": error.localizedDescription,
])
payloadDecodeQueue.async { [weak self] in
guard let data = rowsJson.data(using: .utf8) else {
return
}
do {
let decodedRows = try JSONDecoder().decode([ReviewDiffNativeRow].self, from: data)
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.rowsDecodeGeneration else {
return
}
self.rows = decodedRows
self.contentView.rows = decodedRows
self.hasAppliedInitialRowIndex = false
self.lastVisibleFileId = nil
self.emitDebug("rows-decoded", [
"rows": decodedRows.count,
"firstKind": decodedRows.first?.kind ?? "none",
])
self.updateContentMetrics()
self.applyPendingScrollIfNeeded()
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.rowsDecodeGeneration else {
return
}
self.rows = []
self.contentView.rows = []
self.hasAppliedInitialRowIndex = false
self.lastVisibleFileId = nil
self.pendingScrollFileId = nil
self.updateContentMetrics()
self.emitDebug("rows-decode-failed", ["error": message])
}
}
}
}
func setTokensJson(_ tokensJson: String) {
guard let data = tokensJson.data(using: .utf8) else {
return
}
tokensDecodeGeneration += 1
let generation = tokensDecodeGeneration
do {
contentView.tokensByRowId = try JSONDecoder().decode(
[String: [ReviewDiffNativeToken]].self,
from: data
)
} catch {
contentView.tokensByRowId = [:]
emitDebug("tokens-decode-failed", [
"error": error.localizedDescription,
])
payloadDecodeQueue.async { [weak self] in
guard let data = tokensJson.data(using: .utf8) else {
return
}
do {
let decodedTokens = try JSONDecoder().decode(
[String: [ReviewDiffNativeToken]].self,
from: data
)
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.tokensDecodeGeneration else {
return
}
self.contentView.tokensByRowId = decodedTokens
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
guard let self, generation == self.tokensDecodeGeneration else {
return
}
self.contentView.tokensByRowId = [:]
self.emitDebug("tokens-decode-failed", ["error": message])
}
}
}
}
func setTokensPatchJson(_ tokensPatchJson: String) {
guard let data = tokensPatchJson.data(using: .utf8) else {
return
}
let contentResetKey = self.contentResetKey
do {
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
if let resetKey = patch.resetKey, resetKey != tokensResetKey {
tokensResetKey = resetKey
contentView.tokensByRowId = [:]
}
let tokensByRowId = patch.tokensByRowId ?? [:]
if tokensByRowId.isEmpty {
payloadDecodeQueue.async { [weak self] in
guard let data = tokensPatchJson.data(using: .utf8) else {
return
}
contentView.mergeTokensByRowId(tokensByRowId)
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
emitDebug("tokens-patch-decoded", [
"chunkIndex": chunkIndex,
"rows": tokensByRowId.count,
"totalRows": contentView.tokensByRowId.count,
])
do {
let patch = try JSONDecoder().decode(ReviewDiffNativeTokenPatch.self, from: data)
DispatchQueue.main.async { [weak self] in
guard let self else {
return
}
guard contentResetKey == self.contentResetKey else {
return
}
// A highlighter request from the previous file can finish after the view has
// already reset. Never let that stale patch roll the native token state back.
if let resetKey = patch.resetKey, resetKey != self.tokensResetKey {
return
}
let tokensByRowId = patch.tokensByRowId ?? [:]
if tokensByRowId.isEmpty {
return
}
self.contentView.mergeTokensByRowId(tokensByRowId)
if let chunkIndex = patch.chunkIndex, chunkIndex < 5 || chunkIndex.isMultiple(of: 10) {
self.emitDebug("tokens-patch-decoded", [
"chunkIndex": chunkIndex,
"rows": tokensByRowId.count,
"totalRows": self.contentView.tokensByRowId.count,
])
}
}
} catch {
let message = error.localizedDescription
DispatchQueue.main.async { [weak self] in
self?.emitDebug("tokens-patch-decode-failed", ["error": message])
}
}
} catch {
emitDebug("tokens-patch-decode-failed", [
"error": error.localizedDescription,
])
}
}
@@ -482,6 +549,27 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
])
}
func setContentResetKey(_ contentResetKey: String) {
guard contentResetKey != self.contentResetKey else {
return
}
self.contentResetKey = contentResetKey
rowsDecodeGeneration += 1
tokensDecodeGeneration += 1
contentView.tokensByRowId = [:]
rows = []
contentView.rows = []
hasAppliedInitialRowIndex = false
pendingScrollFileId = nil
isProgrammaticScrollActive = false
scrollView.setContentOffset(.zero, animated: false)
updateContentMetrics()
updateViewportFrame()
lastVisibleFileId = nil
applyInitialRowIndexIfNeeded()
}
func setCollapsedFileIdsJson(_ collapsedFileIdsJson: String) {
let nextCollapsedFileIds = decodeFileIdSet(collapsedFileIdsJson)
let changedFileIds = contentView.collapsedFileIds.symmetricDifference(nextCollapsedFileIds)
@@ -573,6 +661,8 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
contentView.invalidateVisibleViewport()
contentView.setNeedsDisplay()
applyInitialRowIndexIfNeeded()
applyPendingScrollIfNeeded()
emitVisibleFileIfNeeded()
let debugKey = "\(rows.count):\(Int(bounds.width)):\(Int(bounds.height)):\(Int(height))"
if debugKey != lastMetricsDebugKey {
@@ -596,11 +686,41 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
}
private func finishVerticalScroll() {
isProgrammaticScrollActive = false
contentView.isVerticalScrollActive = false
updateViewportFrame()
emitVisibleRange(reason: "scroll-end")
}
private func emitVisibleFileIfNeeded() {
// Keep the explicit destination selected while UIKit animates through the files
// between the old and new offsets. Emitting every intermediate header forces a
// React render per crossing and makes the navigator visibly flash.
guard !isProgrammaticScrollActive else {
return
}
// The top of the combined diff is the explicit "All files" destination.
// Treat it as a first-class selection instead of immediately resolving the
// first file header and undoing the navigator's optimistic selection.
if scrollView.contentOffset.y <= 0.5 {
guard lastVisibleFileId != nil else {
return
}
lastVisibleFileId = nil
onVisibleFileChange(["fileId": NSNull()])
return
}
guard let fileId = contentView.visibleFileId(atVerticalOffset: scrollView.contentOffset.y),
fileId != lastVisibleFileId else {
return
}
lastVisibleFileId = fileId
onVisibleFileChange(["fileId": fileId])
}
private func emitVisibleRange(reason: String) {
guard let range = contentView.currentVisibleRowRange() else {
return
@@ -670,6 +790,18 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
applyInitialRowIndexIfNeeded()
}
func scrollToFile(_ fileId: String, animated: Bool) {
pendingScrollFileId = fileId
pendingScrollAnimated = animated
applyPendingScrollIfNeeded()
}
func scrollToTop(animated: Bool) {
pendingScrollFileId = nil
pendingScrollAnimated = false
setVerticalContentOffset(0, animated: animated)
}
private func applyStyle() {
contentView.style = ReviewDiffNativeStyle
.resolve(stylePayload)
@@ -686,6 +818,38 @@ public final class T3ReviewDiffView: ExpoView, UIScrollViewDelegate {
)
contentView.verticalOffset = scrollView.contentOffset.y
contentView.invalidateVisibleViewport()
emitVisibleFileIfNeeded()
}
private func applyPendingScrollIfNeeded() {
guard let fileId = pendingScrollFileId,
bounds.height > 0 else {
return
}
guard let headerOffset = contentView.fileHeaderOffset(forFileId: fileId) else {
if !rows.isEmpty {
pendingScrollFileId = nil
}
return
}
let animated = pendingScrollAnimated
pendingScrollFileId = nil
pendingScrollAnimated = false
setVerticalContentOffset(headerOffset, animated: animated)
}
private func setVerticalContentOffset(_ targetOffset: CGFloat, animated: Bool) {
let maxOffset = max(scrollView.contentSize.height - scrollView.bounds.height, 0)
let clampedOffset = min(max(targetOffset, 0), maxOffset)
let shouldAnimate = animated && abs(scrollView.contentOffset.y - clampedOffset) > 0.5
isProgrammaticScrollActive = shouldAnimate
contentView.isVerticalScrollActive = shouldAnimate
scrollView.setContentOffset(CGPoint(x: 0, y: clampedOffset), animated: shouldAnimate)
if !shouldAnimate {
updateViewportFrame()
}
}
private func applyInitialRowIndexIfNeeded() {
@@ -1255,6 +1419,32 @@ private final class ReviewDiffContentView: UIView, UIGestureRecognizerDelegate {
return rowOffsets[rowIndex]
}
func visibleFileId(atVerticalOffset verticalOffset: CGFloat) -> String? {
guard let firstHeaderRowIndex = fileHeaderRowIndices.first else {
return nil
}
var lowerBound = 0
var upperBound = fileHeaderRowIndices.count
while lowerBound < upperBound {
let midpoint = (lowerBound + upperBound) / 2
let rowIndex = fileHeaderRowIndices[midpoint]
if rowOffsets[rowIndex] <= verticalOffset + 0.5 {
lowerBound = midpoint + 1
} else {
upperBound = midpoint
}
}
let rowIndex = lowerBound > 0
? fileHeaderRowIndices[lowerBound - 1]
: firstHeaderRowIndex
guard rows.indices.contains(rowIndex) else {
return nil
}
return resolvedFileId(for: rows[rowIndex])
}
private func fileHeaderRowIndex(forFileId fileId: String) -> Int? {
fileHeaderRowIndices.first { rowIndex in
rows.indices.contains(rowIndex) && resolvedFileId(for: rows[rowIndex]) == fileId
@@ -17,6 +17,10 @@ public class T3TerminalModule: Module {
view.fontSize = CGFloat(fontSize)
}
Prop("focusRequest") { (view: T3TerminalView, focusRequest: Double) in
view.focusRequest = focusRequest
}
Prop("appearanceScheme") { (view: T3TerminalView, appearanceScheme: String) in
view.appearanceScheme = appearanceScheme
}
@@ -24,11 +24,37 @@ private enum GhosttyRuntime {
private final class TerminalInputField: UITextField {
var onDeleteBackward: (() -> Void)?
var onInsert: ((String) -> Void)?
override var keyCommands: [UIKeyCommand]? {
[
command(input: "\t", modifiers: UIKeyModifierFlags(), action: #selector(handleTab)),
command(input: "\t", modifiers: .shift, action: #selector(handleBackTab)),
]
}
override func deleteBackward() {
onDeleteBackward?()
super.deleteBackward()
}
private func command(
input: String,
modifiers: UIKeyModifierFlags,
action: Selector
) -> UIKeyCommand {
let command = UIKeyCommand(input: input, modifierFlags: modifiers, action: action)
command.wantsPriorityOverSystemBehavior = true
return command
}
@objc private func handleTab() {
onInsert?("\t")
}
@objc private func handleBackTab() {
onInsert?("\u{1B}[Z")
}
}
private enum TerminalAppearanceScheme: String {
@@ -108,6 +134,15 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
}
}
var focusRequest: Double = 0 {
didSet {
guard oldValue != focusRequest else { return }
DispatchQueue.main.async { [weak self] in
self?.requestKeyboardFocus()
}
}
}
var appearanceScheme: String = TerminalAppearanceScheme.dark.rawValue {
didSet {
guard oldValue != appearanceScheme else { return }
@@ -167,6 +202,9 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
inputField.onDeleteBackward = { [weak self] in
self?.emitInput("\u{7F}")
}
inputField.onInsert = { [weak self] data in
self?.emitInput(data)
}
focusTapGesture.addTarget(self, action: #selector(handleViewportTap))
terminalViewport.addGestureRecognizer(focusTapGesture)
+23 -20
View File
@@ -43,12 +43,16 @@
"@clerk/expo": "catalog:",
"@effect/atom-react": "catalog:",
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/ui": "~56.0.8",
"@legendapp/list": "3.0.0-beta.44",
"@expo/metro-runtime": "~56.0.15",
"@expo/ui": "~56.0.18",
"@legendapp/list": "3.2.0",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@react-native-menu/menu": "^2.0.0",
"@react-navigation/elements": "2.9.26",
"@react-navigation/native": "7.3.4",
"@react-navigation/native-stack": "7.17.6",
"@shikijs/core": "4.2.0",
"@shikijs/engine-javascript": "4.2.0",
"@shikijs/langs": "4.2.0",
@@ -62,31 +66,30 @@
"clsx": "^2.1.1",
"diff": "8.0.3",
"effect": "catalog:",
"expo": "^56.0.0",
"expo-asset": "~56.0.15",
"expo-auth-session": "~56.0.12",
"expo-build-properties": "~56.0.15",
"expo-camera": "~56.0.7",
"expo-clipboard": "~56.0.3",
"expo-constants": "~56.0.16",
"expo": "~56.0.12",
"expo-asset": "~56.0.17",
"expo-auth-session": "~56.0.14",
"expo-build-properties": "~56.0.19",
"expo-camera": "~56.0.8",
"expo-clipboard": "~56.0.4",
"expo-constants": "~56.0.18",
"expo-crypto": "~56.0.4",
"expo-dev-client": "~56.0.16",
"expo-file-system": "~56.0.7",
"expo-font": "~56.0.5",
"expo-dev-client": "~56.0.20",
"expo-file-system": "~56.0.8",
"expo-font": "~56.0.7",
"expo-glass-effect": "~56.0.4",
"expo-haptics": "~56.0.3",
"expo-image-picker": "~56.0.14",
"expo-linking": "~56.0.12",
"expo-image-picker": "~56.0.18",
"expo-linking": "~56.0.14",
"expo-network": "~56.0.5",
"expo-notifications": "~56.0.14",
"expo-notifications": "~56.0.18",
"expo-paste-input": "^0.1.15",
"expo-router": "~56.2.7",
"expo-secure-store": "~56.0.4",
"expo-splash-screen": "~56.0.10",
"expo-symbols": "~56.0.5",
"expo-updates": "~56.0.17",
"expo-symbols": "~56.0.6",
"expo-updates": "~56.0.19",
"expo-web-browser": "~56.0.5",
"expo-widgets": "~56.0.15",
"expo-widgets": "~56.0.19",
"punycode": "^2.3.1",
"react": "19.2.3",
"react-dom": "19.2.3",
@@ -95,7 +98,7 @@
"react-native-image-viewing": "^0.2.2",
"react-native-keyboard-controller": "1.21.6",
"react-native-nitro-markdown": "^0.5.0",
"react-native-nitro-modules": "^0.35.4",
"react-native-nitro-modules": "0.35.9",
"react-native-reanimated": "4.3.1",
"react-native-safe-area-context": "~5.7.0",
"react-native-screens": "4.25.2",
@@ -0,0 +1,52 @@
const fs = require("node:fs");
const path = require("node:path");
const { withDangerousMod } = require("expo/config-plugins");
const MARKER = "# t3code: repair cached CocoaPods UUID allocation before SPM integration";
const UUID_REPAIR = `${MARKER}
pods_project = installer.pods_project
existing_uuids = pods_project.objects.map(&:uuid)
uuid_prefix = pods_project.instance_variable_get(:@uuid_prefix)[0, 6]
sequential_uuid = /\\A#{Regexp.escape(uuid_prefix)}([0-9A-F]{7})0\\z/
highest_index = existing_uuids.filter_map do |uuid|
match = sequential_uuid.match(uuid)
match && match[1].to_i(16)
end.max || -1
# Pod::Project generates sequential UUIDs without collision checks because CocoaPods
# normally creates the project in this process. EAS can restore Pods.xcodeproj from
# cache, leaving the allocator behind the loaded objects. React Native's SPM support
# then reuses an existing UUID and silently corrupts the project graph.
next_index = highest_index + 1
pods_project.instance_variable_set(:@generated_uuids, Array.new(next_index))
pods_project.instance_variable_set(:@available_uuids, [])
pods_project.generate_available_uuid_list(1_000)
Pod::UI.puts "T3Code: reset CocoaPods UUID allocator at #{next_index} (#{existing_uuids.length} existing objects)"
`;
module.exports = function withIosCocoaPodsUuidCache(config) {
return withDangerousMod(config, [
"ios",
(nextConfig) => {
const podfilePath = path.join(nextConfig.modRequest.platformProjectRoot, "Podfile");
const podfile = fs.readFileSync(podfilePath, "utf8");
if (podfile.includes(MARKER)) {
return nextConfig;
}
const postInstallStart = "post_install do |installer|\n";
if (!podfile.includes(postInstallStart)) {
throw new Error("Unable to repair CocoaPods UUID allocation: post_install is missing.");
}
fs.writeFileSync(
podfilePath,
podfile.replace(postInstallStart, `${postInstallStart}${UUID_REPAIR}`),
"utf8",
);
return nextConfig;
},
]);
};
@@ -0,0 +1,99 @@
const { withAppDelegate, withInfoPlist } = require("expo/config-plugins");
const SCENE_DELEGATE = `
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(
_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions
) {
guard
let windowScene = scene as? UIWindowScene,
let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
let appWindow: UIWindow
if let existingWindow = appDelegate.window {
appWindow = existingWindow
} else {
appWindow = UIWindow(windowScene: windowScene)
appDelegate.window = appWindow
appDelegate.reactNativeFactory?.startReactNative(
withModuleName: "main",
in: appWindow,
launchOptions: nil)
}
window = appWindow
appWindow.windowScene = windowScene
appWindow.makeKeyAndVisible()
if let url = connectionOptions.urlContexts.first?.url {
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
}
if let userActivity = connectionOptions.userActivities.first {
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in })
}
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard
let url = URLContexts.first?.url,
let appDelegate = UIApplication.shared.delegate as? AppDelegate
else {
return
}
_ = appDelegate.application(UIApplication.shared, open: url, options: [:])
}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
_ = appDelegate.application(
UIApplication.shared,
continue: userActivity,
restorationHandler: { _ in })
}
}`;
module.exports = function withIosSceneLifecycle(config) {
config = withInfoPlist(config, (nextConfig) => {
nextConfig.modResults.UIApplicationSceneManifest = {
UIApplicationSupportsMultipleScenes: false,
UISceneConfigurations: {
UIWindowSceneSessionRoleApplication: [
{
UISceneConfigurationName: "Default Configuration",
UISceneDelegateClassName: "$(PRODUCT_MODULE_NAME).SceneDelegate",
},
],
},
};
return nextConfig;
});
return withAppDelegate(config, (nextConfig) => {
if (nextConfig.modResults.language !== "swift") {
throw new Error("The iOS scene lifecycle plugin requires a Swift AppDelegate.");
}
if (!nextConfig.modResults.contents.includes("class SceneDelegate:")) {
nextConfig.modResults.contents += SCENE_DELEGATE;
}
return nextConfig;
});
};
+46
View File
@@ -0,0 +1,46 @@
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { RegistryContext } from "@effect/atom-react";
import { LoadingScreen } from "./components/LoadingScreen";
import { CloudAuthProvider } from "./features/cloud/CloudAuthProvider";
import { AppNavigationProvider } from "./navigation/app-navigation";
import { RootNavigator } from "./navigation/RootNavigator";
import { appAtomRegistry } from "./state/atom-registry";
import "../global.css";
export default function App() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
<AppNavigationProvider>
{fontsLoaded ? (
<RootNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</AppNavigationProvider>
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</CloudAuthProvider>
</RegistryContext.Provider>
);
}
-149
View File
@@ -1,149 +0,0 @@
import "../../global.css";
import {
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
useFonts,
} from "@expo-google-fonts/dm-sans";
import { usePathname } from "expo-router";
import Stack from "expo-router/stack";
import { useCallback } from "react";
import { StatusBar, useColorScheme } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { useResolveClassNames } from "uniwind";
import { LoadingScreen } from "../components/LoadingScreen";
import { useWorkspaceState } from "../state/workspace";
import { useThreadOutboxDrain } from "../state/use-thread-outbox-drain";
import { RegistryContext } from "@effect/atom-react";
import { appAtomRegistry } from "../state/atom-registry";
import { CloudAuthProvider } from "../features/cloud/CloudAuthProvider";
import {
ClerkSettingsSheetDetentProvider,
useClerkSettingsSheetDetent,
} from "../features/cloud/ClerkSettingsSheetDetent";
import { useAgentNotificationNavigation } from "../features/agent-awareness/notificationNavigation";
import { useThemeColor } from "../lib/useThemeColor";
function AppNavigator() {
const pathname = usePathname();
const expandedSettingsRouteIsActive =
pathname === "/settings/archive" || pathname === "/settings/auth";
return (
<ClerkSettingsSheetDetentProvider initiallyExpanded={expandedSettingsRouteIsActive}>
<AppNavigatorContent />
</ClerkSettingsSheetDetentProvider>
);
}
function AppNavigatorContent() {
const { state } = useWorkspaceState();
const { collapse, isExpanded } = useClerkSettingsSheetDetent();
const colorScheme = useColorScheme();
const statusBarBg = useThemeColor("--color-status-bar");
const sheetStyle = useResolveClassNames("bg-sheet");
useAgentNotificationNavigation();
useThreadOutboxDrain();
const handleSettingsTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
}
},
[collapse],
);
const newTaskScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.92],
sheetGrabberVisible: true,
};
const connectionSheetScreenOptions = {
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.55, 0.7],
sheetGrabberVisible: true,
};
const settingsSheetScreenOptions = {
...connectionSheetScreenOptions,
sheetAllowedDetents: isExpanded ? [0.92] : [0.7],
};
if (state.isLoadingConnections) {
return <LoadingScreen message="Loading remote workspace…" />;
}
return (
<>
<StatusBar
barStyle={colorScheme === "dark" ? "light-content" : "dark-content"}
backgroundColor={String(statusBarBg)}
translucent
/>
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
}}
/>
<Stack.Screen
name="settings"
listeners={{ transitionEnd: handleSettingsTransitionEnd }}
options={settingsSheetScreenOptions}
/>
<Stack.Screen name="connections" options={connectionSheetScreenOptions} />
<Stack.Screen name="new" options={newTaskScreenOptions} />
<Stack.Screen
name="threads/[environmentId]/[threadId]"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "transparent" },
gestureEnabled: true,
headerShown: false,
}}
/>
</Stack>
</>
);
}
export default function RootLayout() {
const [fontsLoaded] = useFonts({
DMSans_400Regular,
DMSans_500Medium,
DMSans_700Bold,
});
return (
<RegistryContext.Provider value={appAtomRegistry}>
<CloudAuthProvider>
<GestureHandlerRootView style={{ flex: 1 }}>
<KeyboardProvider statusBarTranslucent>
<SafeAreaProvider>
{fontsLoaded ? (
<AppNavigator />
) : (
<LoadingScreen message="Loading remote workspace…" />
)}
</SafeAreaProvider>
</KeyboardProvider>
</GestureHandlerRootView>
</CloudAuthProvider>
</RegistryContext.Provider>
);
}
@@ -1,29 +0,0 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function ConnectionsLayout() {
const contentStyle = useResolveClassNames("bg-sheet");
const connSheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
return (
<Stack
screenOptions={{
contentStyle,
headerStyle: { backgroundColor: connSheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
headerShadowVisible: false,
headerBackButtonDisplayMode: "minimal",
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen name="new" options={{ animation: "slide_from_right" }} />
</Stack>
);
}
-50
View File
@@ -1,50 +0,0 @@
import Stack from "expo-router/stack";
import { useResolveClassNames } from "uniwind";
import { NewTaskFlowProvider } from "../../features/threads/new-task-flow-provider";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function NewTaskLayout() {
const sheetStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
return (
<NewTaskFlowProvider>
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerLargeTitle: false,
headerShadowVisible: false,
headerStyle: { backgroundColor: sheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
}}
>
<Stack.Screen name="index" options={{ animation: "none", title: "Choose project" }} />
<Stack.Screen
name="add-project/index"
options={{ animation: "slide_from_right", title: "New project" }}
/>
<Stack.Screen
name="add-project/repository"
options={{ animation: "slide_from_right", title: "Repository" }}
/>
<Stack.Screen
name="add-project/destination"
options={{ animation: "slide_from_right", title: "Clone destination" }}
/>
<Stack.Screen
name="add-project/local"
options={{ animation: "slide_from_right", title: "Local folder" }}
/>
<Stack.Screen name="draft" options={{ animation: "slide_from_right", title: "New task" }} />
</Stack>
</NewTaskFlowProvider>
);
}
-62
View File
@@ -1,62 +0,0 @@
import Stack from "expo-router/stack";
import { useCallback } from "react";
import { useResolveClassNames } from "uniwind";
import { useClerkSettingsSheetDetent } from "../../features/cloud/ClerkSettingsSheetDetent";
import { useThemeColor } from "../../lib/useThemeColor";
export const unstable_settings = {
anchor: "index",
};
export default function SettingsLayout() {
const { collapse } = useClerkSettingsSheetDetent();
const contentStyle = useResolveClassNames("bg-sheet");
const sheetBg = useThemeColor("--color-sheet");
const headerTint = useThemeColor("--color-foreground");
const handleExpandedRouteTransitionEnd = useCallback(
(event: { data: { closing: boolean } }) => {
if (event.data.closing) {
collapse();
}
},
[collapse],
);
return (
<Stack
screenOptions={{
contentStyle,
headerBackButtonDisplayMode: "minimal",
headerShadowVisible: false,
headerStyle: { backgroundColor: sheetBg },
headerTintColor: headerTint,
headerTitleStyle: { fontFamily: "DMSans_700Bold" },
}}
>
<Stack.Screen name="index" options={{ animation: "none", title: "Settings" }} />
<Stack.Screen
name="environments"
options={{ animation: "slide_from_right", title: "Environments" }}
/>
<Stack.Screen
name="environment-new"
options={{ animation: "slide_from_right", title: "Add Environment" }}
/>
<Stack.Screen
name="waitlist"
options={{ animation: "slide_from_right", title: "Join the waitlist" }}
/>
<Stack.Screen
name="archive"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Archived Threads" }}
/>
<Stack.Screen
name="auth"
listeners={{ transitionEnd: handleExpandedRouteTransitionEnd }}
options={{ animation: "slide_from_right", title: "Sign in" }}
/>
</Stack>
);
}
-3
View File
@@ -1,3 +0,0 @@
import { ArchivedThreadsRouteScreen } from "../../features/archive/ArchivedThreadsRouteScreen";
export default ArchivedThreadsRouteScreen;
@@ -1 +0,0 @@
export { default } from "../connections/new";
@@ -1,107 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export default function ThreadLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack screenOptions={{ headerShown: false }}>
<Stack.Screen
name="index"
options={{
contentStyle: { backgroundColor: "transparent" },
headerShown: true,
headerTransparent: true,
headerShadowVisible: false,
headerTitle: "",
}}
/>
<Stack.Screen
name="git"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.85],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="git-confirm"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.4],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files changed",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/index"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "Files",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="files/[...path]"
options={{
animation: "slide_from_right",
contentStyle: sheetStyle,
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerTitle: "File",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review-comment"
options={{
contentStyle: sheetStyle,
gestureEnabled: true,
headerShown: false,
presentation: "formSheet" as const,
sheetAllowedDetents: [0.72, 0.92],
sheetGrabberVisible: true,
}}
/>
<Stack.Screen
name="terminal"
options={{
animation: "slide_from_right",
contentStyle: { backgroundColor: "#050505" },
headerBackButtonDisplayMode: "minimal",
headerShown: true,
headerShadowVisible: false,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { ThreadFileScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFileRoute() {
return <ThreadFileScreen />;
}
@@ -1,5 +0,0 @@
import { ThreadFilesTreeScreen } from "../../../../../features/files/ThreadFilesRouteScreen";
export default function ThreadFilesIndexRoute() {
return <ThreadFilesTreeScreen />;
}
@@ -1,5 +0,0 @@
import { GitConfirmSheet } from "../../../../features/threads/git/GitConfirmSheet";
export default function GitConfirmRoute() {
return <GitConfirmSheet />;
}
@@ -1,58 +0,0 @@
import Stack from "expo-router/stack";
import { StyleSheet } from "react-native";
import { useResolveClassNames } from "uniwind";
export const unstable_settings = {
anchor: "index",
};
export default function GitSheetLayout() {
const sheetStyle = StyleSheet.flatten(useResolveClassNames("bg-sheet"));
const headerBg = {
backgroundColor: (sheetStyle as { backgroundColor?: string })?.backgroundColor,
};
return (
<Stack
screenOptions={{
contentStyle: sheetStyle,
headerShown: false,
}}
>
<Stack.Screen name="index" options={{ animation: "none" }} />
<Stack.Screen
name="commit"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Commit changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="branches"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Branches & worktrees",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
<Stack.Screen
name="review"
options={{
animation: "slide_from_right",
headerShown: true,
headerTitle: "Review changes",
headerBackTitle: "",
headerShadowVisible: false,
headerStyle: headerBg,
}}
/>
</Stack>
);
}
@@ -1,5 +0,0 @@
import { GitBranchesSheet } from "../../../../../features/threads/git/GitBranchesSheet";
export default function GitBranchesRoute() {
return <GitBranchesSheet />;
}
@@ -1,5 +0,0 @@
import { GitCommitSheet } from "../../../../../features/threads/git/GitCommitSheet";
export default function GitCommitRoute() {
return <GitCommitSheet />;
}
@@ -1,5 +0,0 @@
import { GitOverviewSheet } from "../../../../../features/threads/git/GitOverviewSheet";
export default function GitRoute() {
return <GitOverviewSheet />;
}
@@ -1,18 +0,0 @@
import { Redirect, useLocalSearchParams } from "expo-router";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
export default function ReviewRoute() {
const { environmentId, threadId } = useLocalSearchParams<{
environmentId: EnvironmentId;
threadId: ThreadId;
}>();
return (
<Redirect
href={{
pathname: "/threads/[environmentId]/[threadId]/review",
params: { environmentId, threadId },
}}
/>
);
}
@@ -1,5 +0,0 @@
import { ThreadRouteScreen } from "../../../../features/threads/ThreadRouteScreen";
export default function ThreadRoute() {
return <ThreadRouteScreen />;
}
@@ -1,5 +0,0 @@
import { ReviewCommentComposerSheet } from "../../../../features/review/ReviewCommentComposerSheet";
export default function ReviewCommentRoute() {
return <ReviewCommentComposerSheet />;
}
@@ -1,10 +0,0 @@
import { ReviewHighlighterProvider } from "../../../../features/review/ReviewHighlighterProvider";
import { ReviewSheet } from "../../../../features/review/ReviewSheet";
export default function ReviewRoute() {
return (
<ReviewHighlighterProvider>
<ReviewSheet />
</ReviewHighlighterProvider>
);
}
@@ -1,5 +0,0 @@
import { ThreadTerminalRouteScreen } from "../../../../features/terminal/ThreadTerminalRouteScreen";
export default function ThreadTerminalRoute() {
return <ThreadTerminalRouteScreen />;
}
+195 -12
View File
@@ -18,7 +18,9 @@ import {
EnvironmentId,
OrchestrationThread,
OrchestrationShellSnapshot,
ServerConfig,
ThreadId,
VcsListRefsResult,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -34,6 +36,10 @@ const SHELL_SNAPSHOT_CACHE_DIRECTORY = "connection-shell-snapshots";
const LEGACY_SHELL_SNAPSHOT_CACHE_DIRECTORY = "shell-snapshots";
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
const THREAD_SNAPSHOT_CACHE_DIRECTORY = "connection-thread-snapshots";
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
const SERVER_CONFIG_CACHE_DIRECTORY = "connection-server-configs";
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
const VCS_REFS_CACHE_DIRECTORY = "connection-vcs-refs";
const StoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION),
@@ -48,6 +54,19 @@ const StoredThreadSnapshot = Schema.Struct({
thread: OrchestrationThread,
});
const StoredServerConfig = Schema.Struct({
schemaVersion: Schema.Literal(SERVER_CONFIG_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
config: ServerConfig,
});
const StoredVcsRefs = Schema.Struct({
schemaVersion: Schema.Literal(VCS_REFS_CACHE_SCHEMA_VERSION),
environmentId: EnvironmentId,
cwd: Schema.String,
refs: VcsListRefsResult,
});
const LegacyStoredShellSnapshot = Schema.Struct({
schemaVersion: Schema.Literal(1),
environmentId: EnvironmentId,
@@ -55,6 +74,16 @@ const LegacyStoredShellSnapshot = Schema.Struct({
snapshot: OrchestrationShellSnapshot,
});
const decodeStoredShellSnapshot = Schema.decodeUnknownResult(StoredShellSnapshot);
const encodeStoredShellSnapshot = Schema.encodeUnknownResult(StoredShellSnapshot);
const decodeStoredThreadSnapshot = Schema.decodeUnknownResult(StoredThreadSnapshot);
const encodeStoredThreadSnapshot = Schema.encodeUnknownResult(StoredThreadSnapshot);
const decodeStoredServerConfig = Schema.decodeUnknownResult(StoredServerConfig);
const encodeStoredServerConfig = Schema.encodeUnknownResult(StoredServerConfig);
const decodeStoredVcsRefs = Schema.decodeUnknownResult(StoredVcsRefs);
const encodeStoredVcsRefs = Schema.encodeUnknownResult(StoredVcsRefs);
const decodeLegacyStoredShellSnapshot = Schema.decodeUnknownResult(LegacyStoredShellSnapshot);
function catalogError(operation: string, cause: unknown) {
return new ConnectionTransientError({
reason: "remote-unavailable",
@@ -69,6 +98,10 @@ function shellPersistenceError(
| "load-thread"
| "save-thread"
| "remove-thread"
| "load-server-config"
| "save-server-config"
| "load-vcs-refs"
| "save-vcs-refs"
| "clear-environment",
cause: unknown,
) {
@@ -82,6 +115,14 @@ function threadSnapshotFileName(threadId: ThreadId): string {
return `${encodeURIComponent(threadId)}.json`;
}
function environmentCacheFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
}
function vcsRefsFileName(cwd: string): string {
return `${encodeURIComponent(cwd)}.json`;
}
const threadSnapshotDirectory = Effect.fn("mobile.connectionStorage.threadSnapshotDirectory")(
function* (
environmentId: EnvironmentId,
@@ -146,9 +187,54 @@ const secureCatalogStorage: SecureCatalogStorage = {
};
function shellSnapshotFileName(environmentId: EnvironmentId): string {
return `${encodeURIComponent(environmentId)}.json`;
return environmentCacheFileName(environmentId);
}
const serverConfigFile = Effect.fn("mobile.connectionStorage.serverConfigFile")(function* (
environmentId: EnvironmentId,
operation: "load-server-config" | "save-server-config" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, File, Paths } = await import("expo-file-system");
const directory = new Directory(Paths.document, SERVER_CONFIG_CACHE_DIRECTORY);
directory.create({ idempotent: true, intermediates: true });
return new File(directory, environmentCacheFileName(environmentId));
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const vcsRefsDirectory = Effect.fn("mobile.connectionStorage.vcsRefsDirectory")(function* (
environmentId: EnvironmentId,
operation: "load-vcs-refs" | "save-vcs-refs" | "clear-environment",
) {
return yield* Effect.tryPromise({
try: async () => {
const { Directory, Paths } = await import("expo-file-system");
const directory = new Directory(
Paths.document,
VCS_REFS_CACHE_DIRECTORY,
encodeURIComponent(environmentId),
);
if (operation !== "clear-environment") {
directory.create({ idempotent: true, intermediates: true });
}
return directory;
},
catch: (cause) => shellPersistenceError(operation, cause),
});
});
const vcsRefsFile = Effect.fn("mobile.connectionStorage.vcsRefsFile")(function* (
environmentId: EnvironmentId,
cwd: string,
operation: "load-vcs-refs" | "save-vcs-refs",
) {
const { File } = yield* Effect.promise(() => import("expo-file-system"));
return new File(yield* vcsRefsDirectory(environmentId, operation), vcsRefsFileName(cwd));
});
const shellSnapshotFileInDirectory = Effect.fn(
"mobile.connectionStorage.shellSnapshotFileInDirectory",
)(function* (
@@ -289,9 +375,9 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredShellSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
const stored = yield* Effect.fromResult(decodeStoredShellSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-shell", cause)),
);
return stored.environmentId === environmentId
? Option.some(stored.snapshot)
: Option.none();
@@ -310,7 +396,7 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("load-shell", cause),
});
const legacyStored = yield* Effect.fromResult(
Schema.decodeUnknownResult(LegacyStoredShellSnapshot)(legacyParsed),
decodeLegacyStoredShellSnapshot(legacyParsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-shell", cause)));
return legacyStored.environmentId === environmentId
? Option.some(legacyStored.snapshot)
@@ -324,9 +410,9 @@ export const connectionStorageLayer = Layer.effectContext(
environmentId,
snapshot,
} as const;
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredShellSnapshot)(stored),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-shell", cause)));
const encoded = yield* Effect.fromResult(encodeStoredShellSnapshot(stored)).pipe(
Effect.mapError((cause) => shellPersistenceError("save-shell", cause)),
);
yield* Effect.try({
try: () => {
if (!file.exists) {
@@ -337,6 +423,47 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("save-shell", cause),
});
}),
loadServerConfig: (environmentId) =>
Effect.gen(function* () {
const file = yield* serverConfigFile(environmentId, "load-server-config");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-server-config", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-server-config", cause),
});
const stored = yield* Effect.fromResult(decodeStoredServerConfig(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-server-config", cause)),
);
return stored.environmentId === environmentId
? Option.some(stored.config)
: Option.none();
}),
saveServerConfig: (environmentId, config) =>
Effect.gen(function* () {
const file = yield* serverConfigFile(environmentId, "save-server-config");
const encoded = yield* Effect.fromResult(
encodeStoredServerConfig({
schemaVersion: SERVER_CONFIG_CACHE_SCHEMA_VERSION,
environmentId,
config,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-server-config", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-server-config", cause),
});
}),
loadThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "load-thread");
@@ -351,9 +478,9 @@ export const connectionStorageLayer = Layer.effectContext(
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-thread", cause),
});
const stored = yield* Effect.fromResult(
Schema.decodeUnknownResult(StoredThreadSnapshot)(parsed),
).pipe(Effect.mapError((cause) => shellPersistenceError("load-thread", cause)));
const stored = yield* Effect.fromResult(decodeStoredThreadSnapshot(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-thread", cause)),
);
return stored.environmentId === environmentId && stored.threadId === threadId
? Option.some(stored.thread)
: Option.none();
@@ -362,7 +489,7 @@ export const connectionStorageLayer = Layer.effectContext(
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, thread.id, "save-thread");
const encoded = yield* Effect.fromResult(
Schema.encodeUnknownResult(StoredThreadSnapshot)({
encodeStoredThreadSnapshot({
schemaVersion: THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION,
environmentId,
threadId: thread.id,
@@ -379,6 +506,48 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("save-thread", cause),
});
}),
loadVcsRefs: (environmentId, cwd) =>
Effect.gen(function* () {
const file = yield* vcsRefsFile(environmentId, cwd, "load-vcs-refs");
if (!file.exists) {
return Option.none();
}
const raw = yield* Effect.tryPromise({
try: () => file.text(),
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
});
const parsed = yield* Effect.try({
try: () => JSON.parse(raw) as unknown,
catch: (cause) => shellPersistenceError("load-vcs-refs", cause),
});
const stored = yield* Effect.fromResult(decodeStoredVcsRefs(parsed)).pipe(
Effect.mapError((cause) => shellPersistenceError("load-vcs-refs", cause)),
);
return stored.environmentId === environmentId && stored.cwd === cwd
? Option.some(stored.refs)
: Option.none();
}),
saveVcsRefs: (environmentId, cwd, refs) =>
Effect.gen(function* () {
const file = yield* vcsRefsFile(environmentId, cwd, "save-vcs-refs");
const encoded = yield* Effect.fromResult(
encodeStoredVcsRefs({
schemaVersion: VCS_REFS_CACHE_SCHEMA_VERSION,
environmentId,
cwd,
refs,
}),
).pipe(Effect.mapError((cause) => shellPersistenceError("save-vcs-refs", cause)));
yield* Effect.try({
try: () => {
if (!file.exists) {
file.create({ intermediates: true, overwrite: true });
}
file.write(JSON.stringify(encoded));
},
catch: (cause) => shellPersistenceError("save-vcs-refs", cause),
});
}),
removeThread: (environmentId, threadId) =>
Effect.gen(function* () {
const file = yield* threadSnapshotFile(environmentId, threadId, "remove-thread");
@@ -408,6 +577,13 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const configFile = yield* serverConfigFile(environmentId, "clear-environment");
if (configFile.exists) {
yield* Effect.try({
try: () => configFile.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const threadDirectory = yield* threadSnapshotDirectory(
environmentId,
"clear-environment",
@@ -418,6 +594,13 @@ export const connectionStorageLayer = Layer.effectContext(
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
const refsDirectory = yield* vcsRefsDirectory(environmentId, "clear-environment");
if (refsDirectory.exists) {
yield* Effect.try({
try: () => refsDirectory.delete(),
catch: (cause) => shellPersistenceError("clear-environment", cause),
});
}
}),
});
@@ -1,4 +1,7 @@
import { describe, expect, it } from "vite-plus/test";
import type { NotificationResponse } from "expo-notifications";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
import {
extractAgentNotificationDeepLink,
@@ -18,6 +21,76 @@ function responseWithData(data: Record<string, unknown>, identifier = "notificat
};
}
afterEach(() => {
vi.restoreAllMocks();
});
describe("consumeLastAgentNotificationResponse", () => {
it("reports which initial-response operation failed", async () => {
const cause = new Error("notification lookup unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.reject(cause),
clearLastResponse: () => Promise.resolve(),
handleResponse: vi.fn(),
});
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "read",
}),
);
});
it("routes a response before reporting a clear failure", async () => {
const cause = new Error("notification clear unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const response = responseWithData({}, "notification-clear") as NotificationResponse;
const handleResponse = vi.fn();
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.resolve(response),
clearLastResponse: () => Promise.reject(cause),
handleResponse,
});
expect(handleResponse).toHaveBeenCalledWith(response);
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "clear",
notificationId: "notification-clear",
}),
);
});
it("reports routing failures before clearing the response", async () => {
const cause = new Error("notification routing unavailable");
const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
const response = responseWithData({}, "notification-route") as NotificationResponse;
const clearLastResponse = vi.fn(() => Promise.resolve());
await consumeLastAgentNotificationResponse({
getLastResponse: () => Promise.resolve(response),
clearLastResponse,
handleResponse: () => {
throw cause;
},
});
expect(clearLastResponse).not.toHaveBeenCalled();
expect(consoleError).toHaveBeenCalledWith(
expect.objectContaining({
_tag: "NotificationNavigationError",
operation: "route",
notificationId: "notification-route",
}),
);
});
});
describe("extractAgentNotificationDeepLink", () => {
it("uses explicit deep links from APNs payload data", () => {
expect(
@@ -1,11 +1,12 @@
import { useEffect, useRef } from "react";
import * as Notifications from "expo-notifications";
import { useRouter } from "expo-router";
import { useAppNavigation } from "../../navigation/native-stack-header";
import { routeAgentNotificationResponseOnce } from "./notificationPayload";
import { consumeLastAgentNotificationResponse } from "./notificationResponseConsumer";
export function useAgentNotificationNavigation(): void {
const router = useRouter();
const navigation = useAppNavigation();
const handledResponseIds = useRef(new Set<string>());
useEffect(() => {
@@ -13,23 +14,19 @@ export function useAgentNotificationNavigation(): void {
routeAgentNotificationResponseOnce({
handledResponseIds: handledResponseIds.current,
response,
navigate: (deepLink) => router.push(deepLink as never),
navigate: (deepLink) => navigation.push(deepLink as never),
});
};
const subscription = Notifications.addNotificationResponseReceivedListener(handleResponse);
void Notifications.getLastNotificationResponseAsync()
.then((response) => {
if (response) {
handleResponse(response);
return Notifications.clearLastNotificationResponseAsync();
}
return undefined;
})
.catch(() => undefined);
void consumeLastAgentNotificationResponse({
getLastResponse: () => Notifications.getLastNotificationResponseAsync(),
clearLastResponse: () => Notifications.clearLastNotificationResponseAsync(),
handleResponse,
});
return () => {
subscription.remove();
};
}, [router]);
}, [navigation]);
}
@@ -0,0 +1,58 @@
import type { NotificationResponse } from "expo-notifications";
import * as Schema from "effect/Schema";
export class NotificationNavigationError extends Schema.TaggedErrorClass<NotificationNavigationError>()(
"NotificationNavigationError",
{
operation: Schema.Literals(["read", "route", "clear"]),
notificationId: Schema.optional(Schema.String),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to ${this.operation} the last notification response.`;
}
}
export async function consumeLastAgentNotificationResponse(input: {
readonly getLastResponse: () => Promise<NotificationResponse | null>;
readonly clearLastResponse: () => Promise<void>;
readonly handleResponse: (response: NotificationResponse) => void;
}): Promise<void> {
let response: NotificationResponse | null;
try {
response = await input.getLastResponse();
} catch (cause) {
console.error(new NotificationNavigationError({ operation: "read", cause }));
return;
}
if (!response) {
return;
}
try {
input.handleResponse(response);
} catch (cause) {
console.error(
new NotificationNavigationError({
operation: "route",
notificationId: response.notification.request.identifier,
cause,
}),
);
return;
}
try {
await input.clearLastResponse();
} catch (cause) {
console.error(
new NotificationNavigationError({
operation: "clear",
notificationId: response.notification.request.identifier,
cause,
}),
);
}
}
@@ -18,6 +18,7 @@ import { cryptoLayer } from "../cloud/dpop";
import { managedRelayClientLayer } from "../cloud/managedRelayLayer";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
import {
AgentAwarenessOperationError,
__resetAgentAwarenessRemoteRegistrationForTest,
refreshActiveLiveActivityRemoteRegistration,
refreshAgentAwarenessRegistration,
@@ -267,6 +268,28 @@ describe("makeRelayDeviceRegistrationRequest", () => {
}).pipe(Effect.provide(relayTestLayer));
});
it.effect("preserves Live Activity push-token lookup failures", () => {
const cause = new Error("native token lookup failed");
const activity = {
getPushToken: vi.fn(() => Promise.reject(cause)),
addPushTokenListener: vi.fn(),
};
return Effect.gen(function* () {
const error = yield* Effect.flip(
registerLiveActivityPushToken({ activity: activity as never }),
);
expect(error).toBeInstanceOf(AgentAwarenessOperationError);
expect(error).toMatchObject({
_tag: "AgentAwarenessOperationError",
operation: "read-live-activity-push-token",
cause,
message: "Agent awareness operation read-live-activity-push-token failed.",
});
}).pipe(Effect.provide(relayTestLayer));
});
it.effect(
"reports Live Activity token registration as skipped when relay auth is unavailable",
() => {
@@ -2,6 +2,7 @@ import { addPushToStartTokenListener, type LiveActivity } from "expo-widgets";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import { Platform } from "react-native";
import type { EnvironmentId } from "@t3tools/contracts";
import {
@@ -28,6 +29,33 @@ import { resolveCloudPublicConfig } from "../cloud/publicConfig";
import { makeRelayDeviceRegistrationRequest } from "./registrationPayload";
const REMOTE_ACTIVITY_REGISTRATION_RETRY_MS = 15_000;
const AgentAwarenessOperation = Schema.Literals([
"read-notification-permissions",
"read-native-push-token",
"read-device-registration-relay-token",
"read-device-unregistration-relay-token",
"read-live-activity-registration-relay-token",
"load-device-registration-identifier",
"load-device-registration-preferences",
"load-device-unregistration-identifier",
"read-live-activity-push-token",
"load-live-activity-registration-identifier",
"list-active-live-activities",
]);
export class AgentAwarenessOperationError extends Schema.TaggedErrorClass<AgentAwarenessOperationError>()(
"AgentAwarenessOperationError",
{
operation: AgentAwarenessOperation,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Agent awareness operation ${this.operation} failed.`;
}
}
const environmentConnections = new Map<EnvironmentId, SavedRemoteConnection>();
const activityPushTokenListeners = new WeakSet<LiveActivity<AgentActivityProps>>();
let pushToStartSubscription: { remove: () => void } | null = null;
@@ -137,14 +165,22 @@ function nativePushTokenRegistration(observedPushToken?: string) {
}
const permissions = yield* Effect.tryPromise({
try: () => Notifications.getPermissionsAsync(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-notification-permissions",
cause,
}),
});
if (!permissions.granted) {
return { notificationsEnabled: false, pushToken: null };
}
const token = yield* Effect.tryPromise({
try: () => Notifications.getDevicePushTokenAsync(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-native-push-token",
cause,
}),
}).pipe(
Effect.tapError((error) =>
Effect.sync(() => {
@@ -161,16 +197,19 @@ function nativePushTokenRegistration(observedPushToken?: string) {
});
}
const relayToken = Effect.gen(function* () {
const provider = relayTokenProvider;
if (!provider) {
return null;
}
return yield* Effect.tryPromise({
try: provider,
catch: (error) => error,
const relayToken = (
operation: "read-device-registration-relay-token" | "read-live-activity-registration-relay-token",
) =>
Effect.gen(function* () {
const provider = relayTokenProvider;
if (!provider) {
return null;
}
return yield* Effect.tryPromise({
try: provider,
catch: (cause) => new AgentAwarenessOperationError({ operation, cause }),
});
});
});
function registerDeviceWithRelay(
body: RelayDeviceRegistrationRequest,
@@ -185,7 +224,7 @@ function registerDeviceWithRelay(
return;
}
if (!readRelayConfig()) return;
const token = yield* relayToken;
const token = yield* relayToken("read-device-registration-relay-token");
if (expectedGeneration !== deviceRegistrationGeneration) {
logRegistrationDebug("device registration cancelled after auth lookup", {
expectedGeneration,
@@ -220,7 +259,11 @@ function unregisterDeviceWithRelay(input: {
if (!readRelayConfig()) return;
const token = yield* Effect.tryPromise({
try: input.tokenProvider,
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-device-unregistration-relay-token",
cause,
}),
});
if (!token) {
logRegistrationDebug("relay device unregistration skipped; user is not signed in");
@@ -240,7 +283,7 @@ function registerLiveActivityWithRelay(
): Effect.Effect<boolean, unknown, ManagedRelay.ManagedRelayClient> {
return Effect.gen(function* () {
if (!readRelayConfig()) return false;
const token = yield* relayToken;
const token = yield* relayToken("read-live-activity-registration-relay-token");
if (!token) {
logRegistrationDebug("relay live activity registration skipped; user is not signed in");
return false;
@@ -381,11 +424,19 @@ function registerDevice(
const [deviceId, preferences] = yield* Effect.all([
Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-registration-identifier",
cause,
}),
}),
Effect.tryPromise({
try: () => loadPreferences(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-registration-preferences",
cause,
}),
}),
]);
const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken);
@@ -519,7 +570,11 @@ export function unregisterAgentAwarenessDeviceForCurrentUser(
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadAgentAwarenessDeviceId(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-device-unregistration-identifier",
cause,
}),
});
if (!deviceId) {
return;
@@ -544,7 +599,11 @@ export function registerLiveActivityPushToken(input: {
const activityPushToken = yield* Effect.tryPromise({
try: () => input.activity.getPushToken(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "read-live-activity-push-token",
cause,
}),
});
if (!activityPushToken) {
if (activityPushTokenListeners.has(input.activity)) {
@@ -592,7 +651,11 @@ function registerLiveActivityPushTokenValue(input: {
return Effect.gen(function* () {
const deviceId = yield* Effect.tryPromise({
try: () => loadOrCreateAgentAwarenessDeviceId(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "load-live-activity-registration-identifier",
cause,
}),
});
const registered = yield* registerLiveActivityWithRelay({
deviceId,
@@ -633,7 +696,11 @@ export function refreshActiveLiveActivityRemoteRegistration(): Effect.Effect<
const activities = yield* Effect.try({
try: () => AgentActivity.getInstances(),
catch: (error) => error,
catch: (cause) =>
new AgentAwarenessOperationError({
operation: "list-active-live-activities",
cause,
}),
}).pipe(
Effect.catch((error) =>
Effect.sync(() => {
@@ -1,7 +1,7 @@
import type { EnvironmentId } from "@t3tools/contracts";
import * as Arr from "effect/Array";
import * as Order from "effect/Order";
import { useFocusEffect } from "expo-router";
import { useFocusEffect } from "../../navigation/native-stack-header";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -4,35 +4,37 @@ import type {
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId } from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import * as Haptics from "expo-haptics";
import { Stack } from "expo-router";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
import { SymbolView } from "expo-symbols";
import { useCallback, useRef } from "react";
import { useCallback, useMemo, useRef, type ComponentProps } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
RefreshControl,
ScrollView,
useWindowDimensions,
View,
} from "react-native";
import ReanimatedSwipeable, {
type SwipeableMethods,
} from "react-native-gesture-handler/ReanimatedSwipeable";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import type { SwipeableMethods } from "react-native-gesture-handler/ReanimatedSwipeable";
import { AppText as Text } from "../../components/AppText";
import { ControlPillMenu } from "../../components/ControlPill";
import { EmptyState } from "../../components/EmptyState";
import { ProjectFavicon } from "../../components/ProjectFavicon";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { relativeTime } from "../../lib/time";
import { useThemeColor } from "../../lib/useThemeColor";
import {
THREAD_SWIPE_ACTIONS_WIDTH,
THREAD_SWIPE_SPRING,
ThreadSwipeActions,
} from "../home/thread-swipe-actions";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import type { ArchivedThreadGroup, ArchivedThreadSortOrder } from "./archivedThreadList";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
export interface ArchivedThreadsHeaderEnvironment {
readonly environmentId: EnvironmentId;
readonly label: string;
@@ -57,79 +59,168 @@ function ArchivedThreadsHeader(props: {
readonly selectedEnvironmentId: EnvironmentId | null;
readonly sortOrder: ArchivedThreadSortOrder;
readonly onEnvironmentChange: (environmentId: EnvironmentId | null) => void;
readonly onRefresh: () => void;
readonly onSearchQueryChange: (query: string) => void;
readonly onSortOrderChange: (sortOrder: ArchivedThreadSortOrder) => void;
}) {
const { width } = useWindowDimensions();
const hasCustomFilter = props.selectedEnvironmentId !== null || props.sortOrder !== "newest";
const usesNativeChrome = Platform.OS === "ios";
const usesCompactMailToolbar = Platform.OS === "ios" && width < 700;
const archiveFilterMenu = {
title: "Archived thread options",
items: [
{
type: "submenu" as const,
title: "Environment",
items: [
{
type: "action" as const,
title: "All environments",
state: props.selectedEnvironmentId === null ? ("on" as const) : ("off" as const),
onPress: () => props.onEnvironmentChange(null),
},
...props.environments.map((environment) => ({
type: "action" as const,
title: environment.label,
state:
props.selectedEnvironmentId === environment.environmentId
? ("on" as const)
: ("off" as const),
onPress: () => props.onEnvironmentChange(environment.environmentId),
})),
],
},
{
type: "submenu" as const,
title: "Sort by archived date",
items: [
{
type: "action" as const,
title: "Newest first",
state: props.sortOrder === "newest" ? ("on" as const) : ("off" as const),
onPress: () => props.onSortOrderChange("newest"),
},
{
type: "action" as const,
title: "Oldest first",
state: props.sortOrder === "oldest" ? ("on" as const) : ("off" as const),
onPress: () => props.onSortOrderChange("oldest"),
},
],
},
],
};
return (
<>
<Stack.Screen
<NativeStackScreenOptions
options={{
title: "Archived Threads",
headerSearchBarOptions: {
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
placement: "stacked",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
headerTransparent: usesNativeChrome,
headerStyle: usesNativeChrome ? { backgroundColor: "transparent" } : undefined,
headerShadowVisible: usesNativeChrome ? false : undefined,
scrollEdgeEffects: usesNativeChrome ? HEADER_SCROLL_EDGE_EFFECTS : undefined,
unstable_navigationItemStyle: usesNativeChrome ? "editor" : undefined,
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
composeButtonId: "archived-refresh",
composeSystemImageName: "arrow.clockwise",
filterMenu: archiveFilterMenu,
filterButtonId: "archived-filter",
filterSystemImageName: hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease",
onComposePress: props.onRefresh,
onSearchTextChange: props.onSearchQueryChange,
placeholder: "Search",
searchTextChangeId: "archived-search-text",
}),
]
: undefined,
headerSearchBarOptions: usesCompactMailToolbar
? undefined
: {
...(usesNativeChrome
? {
allowToolbarIntegration: true,
placement: "integratedButton" as const,
}
: {
placement: "stacked" as const,
}),
autoCapitalize: "none",
hideNavigationBar: false,
obscureBackground: false,
placeholder: "Search archived threads",
onChangeText: (event) => {
props.onSearchQueryChange(event.nativeEvent.text);
},
onCancelButtonPress: () => {
props.onSearchQueryChange("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<Stack.Toolbar.Menu title="Environment">
<Stack.Toolbar.Label>Environment</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>All environments</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
{props.environments.map((environment) => (
<Stack.Toolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
{usesCompactMailToolbar ? null : (
<NativeHeaderToolbar placement="right">
{usesNativeChrome ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh archived threads"
icon="arrow.clockwise"
onPress={props.onRefresh}
separateBackground
/>
) : null}
<NativeHeaderToolbar.Menu
accessibilityLabel="Filter and sort archived threads"
icon={
hasCustomFilter
? "line.3.horizontal.decrease.circle.fill"
: "line.3.horizontal.decrease.circle"
}
separateBackground
title="Archived thread options"
>
<NativeHeaderToolbar.Menu title="Environment">
<NativeHeaderToolbar.Label>Environment</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.selectedEnvironmentId === null}
onPress={() => props.onEnvironmentChange(null)}
>
<Stack.Toolbar.Label>{environment.label}</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
))}
</Stack.Toolbar.Menu>
<NativeHeaderToolbar.Label>All environments</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
{props.environments.map((environment) => (
<NativeHeaderToolbar.MenuAction
key={environment.environmentId}
isOn={props.selectedEnvironmentId === environment.environmentId}
onPress={() => props.onEnvironmentChange(environment.environmentId)}
>
<NativeHeaderToolbar.Label>{environment.label}</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
))}
</NativeHeaderToolbar.Menu>
<Stack.Toolbar.Menu title="Sort by archived date">
<Stack.Toolbar.Label>Sort by archived date</Stack.Toolbar.Label>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<Stack.Toolbar.Label>Newest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
<Stack.Toolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<Stack.Toolbar.Label>Oldest first</Stack.Toolbar.Label>
</Stack.Toolbar.MenuAction>
</Stack.Toolbar.Menu>
</Stack.Toolbar.Menu>
</Stack.Toolbar>
<NativeHeaderToolbar.Menu title="Sort by archived date">
<NativeHeaderToolbar.Label>Sort by archived date</NativeHeaderToolbar.Label>
<NativeHeaderToolbar.MenuAction
isOn={props.sortOrder === "newest"}
onPress={() => props.onSortOrderChange("newest")}
>
<NativeHeaderToolbar.Label>Newest first</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
<NativeHeaderToolbar.MenuAction
isOn={props.sortOrder === "oldest"}
onPress={() => props.onSortOrderChange("oldest")}
>
<NativeHeaderToolbar.Label>Oldest first</NativeHeaderToolbar.Label>
</NativeHeaderToolbar.MenuAction>
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar.Menu>
</NativeHeaderToolbar>
)}
</>
);
}
@@ -168,26 +259,20 @@ function ArchivedThreadRow(props: {
readonly onDelete: () => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
typeof ThreadSwipeable
>["simultaneousWithExternalGesture"];
readonly onUnarchive: () => void;
readonly thread: EnvironmentThreadShell;
}) {
const swipeableRef = useRef<SwipeableMethods | null>(null);
const fullSwipeArmedRef = useRef(false);
const { width: windowWidth } = useWindowDimensions();
const cardColor = useThemeColor("--color-card");
const iconColor = useThemeColor("--color-icon-subtle");
const separatorColor = useThemeColor("--color-separator");
const fullSwipeThreshold = Math.max(THREAD_SWIPE_ACTIONS_WIDTH + 44, (windowWidth - 32) * 0.58);
const timestamp = relativeTime(props.thread.archivedAt ?? props.thread.updatedAt);
const subtitle = [props.environmentLabel, props.thread.branch].filter((part): part is string =>
Boolean(part),
);
const handleFullSwipeArmedChange = useCallback((armed: boolean) => {
if (armed && !fullSwipeArmedRef.current && process.env.EXPO_OS === "ios") {
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
}
fullSwipeArmedRef.current = armed;
}, []);
const handleMenuAction = useCallback(
(event: { nativeEvent: { event: string } }) => {
if (event.nativeEvent.event === "unarchive") {
@@ -200,114 +285,80 @@ function ArchivedThreadRow(props: {
);
return (
<ReanimatedSwipeable
ref={swipeableRef}
animationOptions={THREAD_SWIPE_SPRING}
childrenContainerStyle={{ backgroundColor: cardColor }}
containerStyle={{ backgroundColor: cardColor }}
dragOffsetFromRightEdge={8}
enableTrackpadTwoFingerGesture
friction={1}
onSwipeableClose={() => {
fullSwipeArmedRef.current = false;
if (swipeableRef.current) {
props.onSwipeableClose(swipeableRef.current);
}
<ThreadSwipeable
backgroundColor={cardColor}
fullSwipeWidth={windowWidth - 32}
onDelete={props.onDelete}
onSwipeableClose={props.onSwipeableClose}
onSwipeableWillOpen={props.onSwipeableWillOpen}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
onSwipeableOpenStartDrag={() => {
if (swipeableRef.current) {
props.onSwipeableWillOpen(swipeableRef.current);
}
}}
onSwipeableWillOpen={() => {
const methods = swipeableRef.current;
if (!methods) return;
props.onSwipeableWillOpen(methods);
if (fullSwipeArmedRef.current) {
fullSwipeArmedRef.current = false;
methods.close();
props.onDelete();
}
}}
overshootFriction={1}
overshootRight
renderRightActions={(_progress, translation, methods) => (
<ThreadSwipeActions
backgroundColor={cardColor}
fullSwipeThreshold={fullSwipeThreshold}
onDelete={props.onDelete}
onFullSwipeArmedChange={handleFullSwipeArmedChange}
primaryAction={{
accessibilityLabel: `Unarchive ${props.thread.title}`,
icon: "arrow.uturn.backward",
label: "Unarchive",
onPress: props.onUnarchive,
}}
swipeableMethods={methods}
threadTitle={props.thread.title}
translation={translation}
/>
)}
rightThreshold={THREAD_SWIPE_ACTIONS_WIDTH * 0.42}
simultaneousWithExternalGesture={props.simultaneousSwipeGesture}
threadTitle={props.thread.title}
>
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
>
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
{() => (
<View
className="flex-row items-center gap-3 bg-card px-4 py-3"
style={{
borderBottomColor: separatorColor,
borderBottomWidth: props.isLast ? 0 : 1,
}}
>
<View className="h-[34px] w-[34px] items-center justify-center rounded-[11px] bg-subtle">
<SymbolView name="archivebox.fill" size={15} tintColor={iconColor} type="monochrome" />
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<View className="min-w-0 flex-1 gap-1">
<View className="flex-row items-center gap-2">
<Text
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
className="min-w-0 flex-1 text-base font-t3-bold leading-[20px] text-foreground"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
{props.thread.title}
</Text>
<Text
className="text-xs text-foreground-tertiary"
style={{ fontVariant: ["tabular-nums"] }}
>
{timestamp}
</Text>
</View>
) : null}
</View>
{subtitle.length > 0 ? (
<View className="flex-row items-center gap-1.5">
<SymbolView
name="arrow.triangle.branch"
size={10}
tintColor={iconColor}
type="monochrome"
/>
<Text
className="min-w-0 flex-1 text-2xs text-foreground-tertiary"
numberOfLines={1}
style={{ fontFamily: "monospace" }}
>
{subtitle.join(" · ")}
</Text>
</View>
) : null}
</View>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
</ReanimatedSwipeable>
<ControlPillMenu actions={THREAD_ACTIONS} onPressAction={handleMenuAction}>
<Pressable
accessibilityLabel={`Actions for ${props.thread.title}`}
accessibilityRole="button"
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
hitSlop={6}
>
<SymbolView name="ellipsis" size={16} tintColor={iconColor} type="monochrome" />
</Pressable>
</ControlPillMenu>
</View>
)}
</ThreadSwipeable>
);
}
@@ -341,6 +392,7 @@ export function ArchivedThreadsScreen(props: {
readonly onUnarchiveThread: (thread: EnvironmentThreadShell) => void;
}) {
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const archiveScrollGesture = useMemo(() => Gesture.Native(), []);
const refreshTint = useThemeColor("--color-icon");
const handleSwipeableWillOpen = useCallback((methods: SwipeableMethods) => {
if (openSwipeableRef.current && openSwipeableRef.current !== methods) {
@@ -361,76 +413,85 @@ export function ArchivedThreadsScreen(props: {
<ArchivedThreadsHeader
environments={props.environments}
onEnvironmentChange={props.onEnvironmentChange}
onRefresh={props.onRefresh}
onSearchQueryChange={props.onSearchQueryChange}
onSortOrderChange={props.onSortOrderChange}
selectedEnvironmentId={props.selectedEnvironmentId}
sortOrder={props.sortOrder}
/>
<ScrollView
className="flex-1"
contentContainerStyle={{ gap: 20, paddingBottom: 32, paddingHorizontal: 16, paddingTop: 8 }}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
showsVerticalScrollIndicator={false}
>
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
<GestureDetector gesture={archiveScrollGesture}>
<ScrollView
className="flex-1"
contentContainerStyle={{
gap: 20,
paddingBottom: 32,
paddingHorizontal: 16,
paddingTop: 8,
}}
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
onScrollBeginDrag={() => openSwipeableRef.current?.close()}
refreshControl={
<RefreshControl
onRefresh={props.onRefresh}
refreshing={props.isLoading && !isInitialLoad}
tintColor={String(refreshTint)}
/>
}
showsVerticalScrollIndicator={false}
>
{props.error ? <ArchiveError message={props.error} onRetry={props.onRefresh} /> : null}
{isInitialLoad ? (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
</View>
) : props.groups.length === 0 ? (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
) : (
props.groups.map((group) => {
const environmentLabel =
props.environments.find(
(environment) => environment.environmentId === group.project.environmentId,
)?.label ?? null;
{isInitialLoad ? (
<View className="items-center py-16">
<ActivityIndicator color={refreshTint} />
<Text className="mt-3 text-sm text-foreground-muted">Loading archive…</Text>
</View>
) : props.groups.length === 0 ? (
<EmptyState
detail={
isFiltered
? "Try another search or environment."
: "Threads you archive will appear here."
}
title={isFiltered ? "No matching threads" : "No archived threads"}
/>
) : (
props.groups.map((group) => {
const environmentLabel =
props.environments.find(
(environment) => environment.environmentId === group.project.environmentId,
)?.label ?? null;
return (
<View key={group.key} collapsable={false}>
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{group.threads.map((thread, index) => (
<ArchivedThreadRow
key={`${thread.environmentId}:${thread.id}`}
environmentLabel={environmentLabel}
isLast={index === group.threads.length - 1}
onDelete={() => props.onDeleteThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => props.onUnarchiveThread(thread)}
thread={thread}
/>
))}
return (
<View key={group.key} collapsable={false}>
<ProjectGroupLabel environmentLabel={environmentLabel} project={group.project} />
<View
className="overflow-hidden rounded-[20px] bg-card"
style={{ borderCurve: "continuous" }}
>
{group.threads.map((thread, index) => (
<ArchivedThreadRow
key={`${thread.environmentId}:${thread.id}`}
environmentLabel={environmentLabel}
isLast={index === group.threads.length - 1}
onDelete={() => props.onDeleteThread(thread)}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
onUnarchive={() => props.onUnarchiveThread(thread)}
simultaneousSwipeGesture={archiveScrollGesture}
thread={thread}
/>
))}
</View>
</View>
</View>
);
})
)}
</ScrollView>
);
})
)}
</ScrollView>
</GestureDetector>
</View>
);
}
@@ -4,6 +4,7 @@ import { useState } from "react";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { CloudWaitlistJoinRejectedError, joinCloudWaitlist } from "./cloudWaitlistJoin";
export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }) {
const { errors, fetchStatus, waitlist } = useWaitlist();
@@ -21,12 +22,14 @@ export function CloudWaitlistEnrollment(props: { readonly onSignIn: () => void }
setRequestError(null);
try {
const { error } = await waitlist.join({ emailAddress: normalizedEmailAddress });
if (error) {
setRequestError("Could not join the waitlist. Check your email address and try again.");
}
} catch {
setRequestError("Could not join the waitlist. Check your connection and try again.");
await joinCloudWaitlist(waitlist, normalizedEmailAddress);
} catch (error) {
console.error(error);
setRequestError(
error instanceof CloudWaitlistJoinRejectedError
? "Could not join the waitlist. Check your email address and try again."
: "Could not join the waitlist. Check your connection and try again.",
);
}
};
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
CloudWaitlistJoinRejectedError,
CloudWaitlistJoinRequestError,
joinCloudWaitlist,
} from "./cloudWaitlistJoin";
describe("joinCloudWaitlist", () => {
it("submits the provided email address", async () => {
const join = vi.fn().mockResolvedValue({ error: null });
await joinCloudWaitlist({ join }, "[email protected]");
expect(join).toHaveBeenCalledExactlyOnceWith({ emailAddress: "[email protected]" });
});
it("preserves Clerk rejection details without exposing the email address", async () => {
const cause = Object.assign(new Error("The enrollment was rejected."), {
code: "form_identifier_invalid",
});
const join = vi.fn().mockResolvedValue({ error: cause });
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRejectedError);
expect(failure).toMatchObject({
code: "form_identifier_invalid",
cause,
});
expect(String(failure)).not.toContain("[email protected]");
});
it("distinguishes request failures from rejected enrollments", async () => {
const cause = new Error("network unavailable");
const join = vi.fn().mockRejectedValue(cause);
const failure = await joinCloudWaitlist({ join }, "[email protected]").catch(
(error: unknown) => error,
);
expect(failure).toBeInstanceOf(CloudWaitlistJoinRequestError);
expect(failure).toMatchObject({ cause });
expect(failure).not.toBeInstanceOf(CloudWaitlistJoinRejectedError);
});
});
@@ -0,0 +1,46 @@
import * as Schema from "effect/Schema";
interface CloudWaitlistJoiner {
readonly join: (input: { emailAddress: string }) => Promise<{
readonly error: { readonly code: string } | null;
}>;
}
export class CloudWaitlistJoinRejectedError extends Schema.TaggedErrorClass<CloudWaitlistJoinRejectedError>()(
"CloudWaitlistJoinRejectedError",
{
code: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Cloud waitlist enrollment was rejected with code "${this.code}".`;
}
}
export class CloudWaitlistJoinRequestError extends Schema.TaggedErrorClass<CloudWaitlistJoinRequestError>()(
"CloudWaitlistJoinRequestError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Cloud waitlist enrollment request failed.";
}
}
export async function joinCloudWaitlist(
waitlist: CloudWaitlistJoiner,
emailAddress: string,
): Promise<void> {
const result = await waitlist.join({ emailAddress }).catch((cause) => {
throw new CloudWaitlistJoinRequestError({ cause });
});
if (result.error) {
throw new CloudWaitlistJoinRejectedError({
code: result.error.code,
cause: result.error,
});
}
}
@@ -1,5 +1,7 @@
import { expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Logger from "effect/Logger";
import * as SecureStore from "expo-secure-store";
import { vi } from "vite-plus/test";
const secureStore = vi.hoisted(() => new Map<string, string>());
@@ -16,7 +18,10 @@ vi.mock("expo-secure-store", () => ({
}),
}));
import { managedRelayAccessTokenStore } from "./managedRelayTokenStore";
import {
ManagedRelayTokenStoreError,
managedRelayAccessTokenStore,
} from "./managedRelayTokenStore";
it.effect("round-trips and clears persisted managed relay access tokens", () =>
Effect.gen(function* () {
@@ -49,3 +54,32 @@ it.effect("falls back to an empty cache when persisted data is invalid", () =>
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
}),
);
it.effect("logs structured storage failures before falling back to an empty cache", () => {
const messages: Array<unknown> = [];
const logger = Logger.make(({ message }) => {
messages.push(message);
});
const cause = new Error("secure store unavailable");
vi.mocked(SecureStore.getItemAsync).mockRejectedValueOnce(cause);
return Effect.gen(function* () {
expect(yield* managedRelayAccessTokenStore.load).toEqual([]);
const message = messages.find(
(candidate) =>
Array.isArray(candidate) && candidate[0] === "Managed relay token store operation failed.",
);
expect(message).toBeDefined();
const context = (message as ReadonlyArray<unknown>)[1] as {
readonly cause: ManagedRelayTokenStoreError;
};
expect(context.cause).toBeInstanceOf(ManagedRelayTokenStoreError);
expect(context.cause).toMatchObject({
operation: "read",
storageKey: "t3code.cloud.relay-access-tokens",
cause,
});
expect(context.cause.message).not.toContain(cause.message);
}).pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: false })));
});
@@ -1,5 +1,4 @@
import { ManagedRelay } from "@t3tools/client-runtime/relay";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import * as SecureStore from "expo-secure-store";
@@ -31,36 +30,50 @@ const decodeManagedRelayAccessTokenCache = Schema.decodeUnknownEffect(
);
const encodeManagedRelayAccessTokenCache = Schema.encodeEffect(ManagedRelayAccessTokenCacheSchema);
export class ManagedRelayTokenStoreError extends Data.TaggedError("ManagedRelayTokenStoreError")<{
readonly message: string;
readonly cause: unknown;
}> {}
export class ManagedRelayTokenStoreError extends Schema.TaggedErrorClass<ManagedRelayTokenStoreError>()(
"ManagedRelayTokenStoreError",
{
operation: Schema.Literals(["read", "decode", "encode", "write", "clear"]),
storageKey: Schema.String,
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Managed relay token store operation "${this.operation}" failed for key "${this.storageKey}".`;
}
}
const storeError =
(message: string) =>
(cause: unknown): ManagedRelayTokenStoreError =>
new ManagedRelayTokenStoreError({ message, cause });
function logStoreFailure(operation: string) {
return (error: ManagedRelayTokenStoreError) =>
Effect.logWarning(`Managed relay token store ${operation} failed.`).pipe(
Effect.annotateLogs({
errorTag: error._tag,
message: error.message,
}),
);
function logStoreFailure(error: ManagedRelayTokenStoreError) {
return Effect.logWarning("Managed relay token store operation failed.", {
errorTag: error._tag,
operation: error.operation,
storageKey: error.storageKey,
cause: error,
});
}
const loadManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.getItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: storeError("Could not read persisted relay access tokens."),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "read",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
}).pipe(
Effect.flatMap((encoded) =>
encoded === null
? Effect.succeed<ReadonlyArray<ManagedRelay.ManagedRelayAccessTokenCacheEntry>>([])
: decodeManagedRelayAccessTokenCache(encoded).pipe(
Effect.map((cache) => cache.entries),
Effect.mapError(storeError("Persisted relay access tokens are invalid.")),
Effect.mapError(
(cause) =>
new ManagedRelayTokenStoreError({
operation: "decode",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
),
),
),
);
@@ -72,34 +85,48 @@ const saveManagedRelayAccessTokens = (
version: MANAGED_RELAY_TOKEN_CACHE_VERSION,
entries,
}).pipe(
Effect.mapError(storeError("Could not encode relay access tokens.")),
Effect.mapError(
(cause) =>
new ManagedRelayTokenStoreError({
operation: "encode",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
),
Effect.flatMap((encoded) =>
Effect.tryPromise({
try: () => SecureStore.setItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY, encoded),
catch: storeError("Could not persist relay access tokens."),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "write",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
}),
),
);
const clearManagedRelayAccessTokens = Effect.tryPromise({
try: () => SecureStore.deleteItemAsync(MANAGED_RELAY_TOKEN_CACHE_KEY),
catch: storeError("Could not clear persisted relay access tokens."),
catch: (cause) =>
new ManagedRelayTokenStoreError({
operation: "clear",
storageKey: MANAGED_RELAY_TOKEN_CACHE_KEY,
cause,
}),
});
export const managedRelayAccessTokenStore: ManagedRelay.ManagedRelayAccessTokenStore = {
load: loadManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure("load")),
Effect.tapError(logStoreFailure),
Effect.orElseSucceed(() => []),
Effect.withSpan("mobile.managedRelayTokenStore.load"),
),
save: Effect.fn("mobile.managedRelayTokenStore.save")((entries) =>
saveManagedRelayAccessTokens(entries).pipe(
Effect.tapError(logStoreFailure("save")),
Effect.ignore,
),
saveManagedRelayAccessTokens(entries).pipe(Effect.tapError(logStoreFailure), Effect.ignore),
),
clear: clearManagedRelayAccessTokens.pipe(
Effect.tapError(logStoreFailure("clear")),
Effect.tapError(logStoreFailure),
Effect.ignore,
Effect.withSpan("mobile.managedRelayTokenStore.clear"),
),
@@ -101,7 +101,7 @@ export function ConnectionEnvironmentRow(props: {
className="underline"
onLongPress={(event) => {
event.stopPropagation();
copyTextWithHaptic(statusTraceId);
copyTextWithHaptic(statusTraceId, { target: "connection-trace-id" });
}}
onPress={(event) => {
event.stopPropagation();
@@ -85,7 +85,11 @@ export function EnvironmentConnectionNotice(props: {
accessibilityHint="Copies the trace ID"
accessibilityRole="button"
className="underline decoration-dotted"
onPress={() => copyTextWithHaptic(props.connection.traceId!)}
onPress={() =>
copyTextWithHaptic(props.connection.traceId!, {
target: "connection-trace-id",
})
}
>
{props.connection.traceId}
</Text>
@@ -8,6 +8,7 @@ import jsxLanguage from "@shikijs/langs/jsx";
import tsxLanguage from "@shikijs/langs/tsx";
import typescriptLanguage from "@shikijs/langs/typescript";
import yamlLanguage from "@shikijs/langs/yaml";
import * as Schema from "effect/Schema";
import type { NativeReviewDiffFile, NativeReviewDiffLanguage } from "./nativeReviewDiffTypes";
import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewDiffSurface";
@@ -15,6 +16,32 @@ import type { NativeReviewDiffRow, NativeReviewDiffToken } from "./nativeReviewD
export type NativeReviewDiffHighlightScheme = "light" | "dark";
export type NativeReviewDiffHighlightEngine = "native" | "javascript";
export class NativeReviewDiffHighlighterUnavailableError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterUnavailableError>()(
"NativeReviewDiffHighlighterUnavailableError",
{},
) {
override get message(): string {
return "The native review diff highlighter is unavailable in this build.";
}
}
export const isNativeReviewDiffHighlighterUnavailableError = Schema.is(
NativeReviewDiffHighlighterUnavailableError,
);
export class NativeReviewDiffHighlighterInitializationError extends Schema.TaggedErrorClass<NativeReviewDiffHighlighterInitializationError>()(
"NativeReviewDiffHighlighterInitializationError",
{
requestedEngine: Schema.Literals(["native", "javascript"]),
attemptedEngine: Schema.Literals(["native", "javascript"]),
cause: Schema.Defect(),
},
) {
override get message(): string {
return `Failed to initialize the ${this.attemptedEngine} review diff highlighter requested as ${this.requestedEngine}.`;
}
}
export interface NativeReviewDiffHighlighterHandle {
readonly engine: NativeReviewDiffHighlightEngine;
readonly tokenize: (
@@ -197,7 +224,7 @@ function normalizeTokens(
async function createNativeReviewDiffHighlighter(): Promise<NativeReviewDiffHighlighterHandle> {
const nativeEngineModule = await import("react-native-shiki-engine");
if (!nativeEngineModule.isNativeEngineAvailable()) {
throw new Error("Native Shiki engine is not available in this build.");
throw new NativeReviewDiffHighlighterUnavailableError();
}
const highlighter = await createHighlighterCore({
@@ -229,18 +256,52 @@ export async function getNativeReviewDiffHighlighter(
engine: NativeReviewDiffHighlightEngine = "native",
): Promise<NativeReviewDiffHighlighterHandle> {
if (engine === "javascript") {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
try {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return await javascriptHighlighterPromise;
} catch (cause) {
javascriptHighlighterPromise = null;
throw new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "javascript",
cause,
});
}
}
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter().catch((error: unknown) => {
console.warn("[debug-native-diff] native highlighter unavailable", {
error: error instanceof Error ? error.message : String(error),
nativeHighlighterPromise ??= createNativeReviewDiffHighlighter()
.catch(async (cause: unknown) => {
const nativeError = isNativeReviewDiffHighlighterUnavailableError(cause)
? cause
: new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "native",
cause,
});
console.warn("[debug-native-diff] native highlighter unavailable", {
error: nativeError,
});
try {
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return await javascriptHighlighterPromise;
} catch (fallbackCause) {
javascriptHighlighterPromise = null;
throw new NativeReviewDiffHighlighterInitializationError({
requestedEngine: engine,
attemptedEngine: "javascript",
cause: new AggregateError(
[nativeError, fallbackCause],
"Native and JavaScript review diff highlighter initialization failed.",
{ cause: nativeError },
),
});
}
})
.catch((error) => {
nativeHighlighterPromise = null;
throw error;
});
javascriptHighlighterPromise ??= createJavascriptReviewDiffHighlighter();
return javascriptHighlighterPromise;
});
return nativeHighlighterPromise;
return await nativeHighlighterPromise;
}
function isHighlightableLineRow(row: NativeReviewDiffRow): row is NativeReviewDiffLineRow {
@@ -33,11 +33,14 @@ describe("resolveNativeReviewDiffView", () => {
expect(expoMocks.requireNativeView).not.toHaveBeenCalled();
});
it("returns the native review diff view when the view config is installed", async () => {
it("returns the payload bridge when the native review diff view is installed", async () => {
setExpoViewConfigAvailable();
expoMocks.requireNativeView.mockReturnValue(nativeView);
const { resolveNativeReviewDiffView } = await import("./nativeReviewDiffSurface");
expect(resolveNativeReviewDiffView()).toBe(nativeView);
const resolvedView = resolveNativeReviewDiffView();
expect(resolvedView).not.toBeNull();
expect(resolvedView).not.toBe(nativeView);
expect(resolveNativeReviewDiffView()).toBe(resolvedView);
expect(expoMocks.requireNativeView).toHaveBeenCalledWith("T3ReviewDiffSurface");
});
@@ -78,3 +81,20 @@ describe("resolveNativeReviewDiffView", () => {
expect(consoleError).toHaveBeenCalledTimes(1);
});
});
describe("isPendingNativeViewRegistration", () => {
it("recognizes registration races for the installed native view name", async () => {
const { isPendingNativeViewRegistration } = await import("./nativeReviewDiffSurface");
expect(
isPendingNativeViewRegistration(
new Error("Unable to find the 'T3ReviewDiffSurface' view for this native tag"),
),
).toBe(true);
expect(
isPendingNativeViewRegistration(
new Error("Unable to find the 'T3ReviewDiffView' view for this native tag"),
),
).toBe(false);
});
});
@@ -1,10 +1,18 @@
import type { ComponentType } from "react";
import {
createElement,
useEffect,
useImperativeHandle,
useRef,
type ComponentType,
type Ref,
} from "react";
import type { NativeSyntheticEvent, ViewProps } from "react-native";
import { requireNativeView } from "expo";
import { NativeViewResolutionError } from "../../native/nativeViewResolutionError";
const NATIVE_REVIEW_DIFF_MODULE_NAME = "T3ReviewDiffSurface";
const NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES = 60;
interface ExpoGlobalWithViewConfig {
readonly expo?: {
@@ -103,6 +111,7 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly tokensJson?: string;
readonly tokensPatchJson?: string;
readonly tokensResetKey?: string;
readonly contentResetKey?: string;
readonly collapsedFileIdsJson?: string;
readonly viewedFileIdsJson?: string;
readonly selectedRowIdsJson?: string;
@@ -113,7 +122,11 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly rowHeight: number;
readonly contentWidth: number;
readonly initialRowIndex?: number;
readonly nativeViewRef?: Ref<NativeReviewDiffViewHandle>;
readonly onDebug?: (event: NativeSyntheticEvent<Record<string, unknown>>) => void;
readonly onVisibleFileChange?: (
event: NativeSyntheticEvent<{ readonly fileId?: string | null }>,
) => void;
readonly onToggleFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onToggleViewedFile?: (event: NativeSyntheticEvent<{ readonly fileId?: string }>) => void;
readonly onPressLine?: (
@@ -129,18 +142,130 @@ export interface NativeReviewDiffViewProps extends ViewProps {
readonly onToggleComment?: (event: NativeSyntheticEvent<{ readonly commentId?: string }>) => void;
}
let cachedNativeReviewDiffView: ComponentType<NativeReviewDiffViewProps> | undefined;
export interface NativeReviewDiffViewHandle {
readonly scrollToFile: (fileId: string, animated?: boolean) => Promise<void>;
readonly scrollToTop: (animated?: boolean) => Promise<void>;
}
interface NativeReviewDiffViewRef {
readonly setRowsJson: (rowsJson: string) => Promise<void>;
readonly setTokensJson: (tokensJson: string) => Promise<void>;
readonly setTokensPatchJson: (tokensPatchJson: string) => Promise<void>;
readonly scrollToFile: (fileId: string, animated: boolean) => Promise<void>;
readonly scrollToTop: (animated: boolean) => Promise<void>;
}
type NativeReviewDiffRawViewProps = Omit<
NativeReviewDiffViewProps,
"nativeViewRef" | "rowsJson" | "tokensJson" | "tokensPatchJson"
> & {
readonly ref?: Ref<NativeReviewDiffViewRef>;
};
let cachedNativeReviewDiffRawView: ComponentType<NativeReviewDiffRawViewProps> | undefined;
let nativeReviewDiffViewResolutionFailed = false;
type NativeReviewDiffPayloadMethod = "setRowsJson" | "setTokensJson" | "setTokensPatchJson";
export function isPendingNativeViewRegistration(error: unknown): boolean {
return (
error instanceof Error &&
error.message.includes(`Unable to find the '${NATIVE_REVIEW_DIFF_MODULE_NAME}' view`)
);
}
function useNativeReviewDiffPayload(
nativeRef: React.RefObject<NativeReviewDiffViewRef | null>,
method: NativeReviewDiffPayloadMethod,
payload: string | undefined,
) {
useEffect(() => {
if (payload === undefined) {
return;
}
let cancelled = false;
let frame: number | null = null;
let attempts = 0;
const dispatch = () => {
if (cancelled) {
return;
}
const view = nativeRef.current;
const command = view?.[method];
if (!view || !command) {
if (attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES) {
attempts += 1;
frame = requestAnimationFrame(dispatch);
}
return;
}
void command.call(view, payload).catch((error: unknown) => {
if (
!cancelled &&
attempts < NATIVE_REVIEW_DIFF_PAYLOAD_RETRY_FRAMES &&
isPendingNativeViewRegistration(error)
) {
attempts += 1;
frame = requestAnimationFrame(dispatch);
return;
}
console.error(`[native-review-diff] ${method} failed`, error);
});
};
// Fabric attaches the React ref before Expo registers the native tag used by
// view functions. Starting on the next frame avoids racing that registration.
frame = requestAnimationFrame(dispatch);
return () => {
cancelled = true;
if (frame !== null) {
cancelAnimationFrame(frame);
}
};
}, [method, nativeRef, payload]);
}
function getExpoViewConfig(moduleName: string) {
return (globalThis as typeof globalThis & ExpoGlobalWithViewConfig).expo?.getViewConfig?.(
moduleName,
);
}
function NativeReviewDiffView(props: NativeReviewDiffViewProps) {
const { nativeViewRef, rowsJson, tokensJson, tokensPatchJson, ...nativeProps } = props;
const nativeRef = useRef<NativeReviewDiffViewRef>(null);
useNativeReviewDiffPayload(nativeRef, "setRowsJson", rowsJson);
useNativeReviewDiffPayload(nativeRef, "setTokensJson", tokensJson);
useNativeReviewDiffPayload(nativeRef, "setTokensPatchJson", tokensPatchJson);
useImperativeHandle(
nativeViewRef,
() => ({
scrollToFile: async (fileId, animated = true) => {
await nativeRef.current?.scrollToFile(fileId, animated);
},
scrollToTop: async (animated = true) => {
await nativeRef.current?.scrollToTop(animated);
},
}),
[],
);
const RawNativeView = cachedNativeReviewDiffRawView;
if (!RawNativeView) {
return null;
}
return createElement(RawNativeView, { ...nativeProps, ref: nativeRef });
}
export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffViewProps> | null {
if (cachedNativeReviewDiffView) {
return cachedNativeReviewDiffView;
if (cachedNativeReviewDiffRawView) {
return NativeReviewDiffView;
}
if (nativeReviewDiffViewResolutionFailed) {
@@ -152,7 +277,7 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
}
try {
cachedNativeReviewDiffView = requireNativeView<NativeReviewDiffViewProps>(
cachedNativeReviewDiffRawView = requireNativeView<NativeReviewDiffRawViewProps>(
NATIVE_REVIEW_DIFF_MODULE_NAME,
);
} catch (cause) {
@@ -166,5 +291,5 @@ export function resolveNativeReviewDiffView(): ComponentType<NativeReviewDiffVie
return null;
}
return cachedNativeReviewDiffView ?? null;
return cachedNativeReviewDiffRawView ? NativeReviewDiffView : null;
}
@@ -1,6 +1,6 @@
import type { ProjectEntry } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { memo, useCallback, useEffect, useMemo, useState } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { ActivityIndicator, FlatList, Pressable, RefreshControl, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
@@ -11,9 +11,25 @@ import {
buildFileTree,
defaultExpandedTreePaths,
flattenFileTree,
type FileTreeNode,
type VisibleFileTreeNode,
} from "./fileTree";
const fileTreeCache = new WeakMap<ReadonlyArray<ProjectEntry>, ReadonlyArray<FileTreeNode>>();
const FILE_TREE_INITIAL_RENDER_COUNT = 20;
const FILE_TREE_RENDER_BATCH_SIZE = 12;
const OPTIMISTIC_SELECTION_TIMEOUT_MS = 1_000;
function cachedFileTree(entries: ReadonlyArray<ProjectEntry>): ReadonlyArray<FileTreeNode> {
const cached = fileTreeCache.get(entries);
if (cached !== undefined) {
return cached;
}
const tree = buildFileTree(entries);
fileTreeCache.set(entries, tree);
return tree;
}
function ancestorPaths(path: string): ReadonlyArray<string> {
const parts = path.split("/").filter(Boolean);
const ancestors: string[] = [];
@@ -25,19 +41,24 @@ function ancestorPaths(path: string): ReadonlyArray<string> {
const FileTreeRow = memo(function FileTreeRow(props: {
readonly item: VisibleFileTreeNode;
readonly selectedPath: string | null;
readonly selected: boolean;
readonly expanded: boolean;
readonly iconColor: string;
readonly onPressDirectory: (path: string) => void;
readonly onPreviewFile?: (path: string) => void;
readonly onPressFile: (path: string) => void;
}) {
const { node, depth } = props.item;
const selected = node.kind === "file" && node.path === props.selectedPath;
return (
<Pressable
accessibilityRole="button"
accessibilityLabel={node.path}
onPressIn={() => {
if (node.kind === "file") {
props.onPreviewFile?.(node.path);
}
}}
onPress={() => {
if (node.kind === "directory") {
props.onPressDirectory(node.path);
@@ -47,7 +68,7 @@ const FileTreeRow = memo(function FileTreeRow(props: {
}}
className={cn(
"mx-2 min-h-[42px] flex-row items-center gap-2 rounded-[12px] px-2 active:bg-subtle",
selected && "bg-subtle-strong",
props.selected && "bg-subtle-strong",
)}
style={{ paddingLeft: 8 + depth * 18 }}
>
@@ -65,7 +86,9 @@ const FileTreeRow = memo(function FileTreeRow(props: {
<Text
className={cn(
"min-w-0 flex-1 text-sm leading-[19px]",
selected ? "font-t3-bold text-foreground" : "font-t3-medium text-foreground-secondary",
props.selected
? "font-t3-bold text-foreground"
: "font-t3-medium text-foreground-secondary",
)}
numberOfLines={1}
>
@@ -86,13 +109,26 @@ export function FileTreeBrowser(props: {
readonly isPending: boolean;
readonly searchQuery: string;
readonly selectedPath: string | null;
readonly onPreviewFile?: (path: string) => void;
readonly onRefresh: () => void;
readonly onSelectFile: (path: string) => void;
}) {
const [expandedPaths, setExpandedPaths] = useState<ReadonlySet<string>>(() => new Set());
const [pendingSelection, setPendingSelection] = useState<{
readonly path: string;
readonly selectedPathAtPress: string | null;
} | null>(null);
const iconColor = String(useThemeColor("--color-icon-muted"));
const { onPreviewFile, onSelectFile, selectedPath: controlledSelectedPath } = props;
const controlledSelectedPathRef = useRef(controlledSelectedPath);
const pendingSelectionTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
controlledSelectedPathRef.current = controlledSelectedPath;
const tree = useMemo(() => buildFileTree(props.entries), [props.entries]);
const selectedPath =
pendingSelection?.selectedPathAtPress === controlledSelectedPath
? pendingSelection.path
: controlledSelectedPath;
const tree = useMemo(() => cachedFileTree(props.entries), [props.entries]);
const defaultExpanded = useMemo(() => defaultExpandedTreePaths(tree), [tree]);
const visibleNodes = useMemo(
() =>
@@ -114,17 +150,30 @@ export function FileTreeBrowser(props: {
}, [defaultExpanded]);
useEffect(() => {
if (!props.selectedPath) {
if (!controlledSelectedPath) {
return;
}
setExpandedPaths((current) => {
const ancestors = ancestorPaths(controlledSelectedPath);
if (ancestors.every((ancestor) => current.has(ancestor))) {
return current;
}
const next = new Set(current);
for (const ancestor of ancestorPaths(props.selectedPath ?? "")) {
for (const ancestor of ancestors) {
next.add(ancestor);
}
return next;
});
}, [props.selectedPath]);
}, [controlledSelectedPath]);
useEffect(
() => () => {
if (pendingSelectionTimeoutRef.current !== null) {
clearTimeout(pendingSelectionTimeoutRef.current);
}
},
[],
);
const toggleDirectory = useCallback((path: string) => {
setExpandedPaths((current) => {
@@ -137,6 +186,37 @@ export function FileTreeBrowser(props: {
return next;
});
}, []);
const handleSelectFile = useCallback(
(path: string) => {
if (pendingSelectionTimeoutRef.current !== null) {
clearTimeout(pendingSelectionTimeoutRef.current);
}
setPendingSelection({
path,
selectedPathAtPress: controlledSelectedPathRef.current,
});
pendingSelectionTimeoutRef.current = setTimeout(() => {
pendingSelectionTimeoutRef.current = null;
setPendingSelection((current) => (current?.path === path ? null : current));
}, OPTIMISTIC_SELECTION_TIMEOUT_MS);
onSelectFile(path);
},
[onSelectFile],
);
const renderItem = useCallback(
({ item }: { readonly item: VisibleFileTreeNode }) => (
<FileTreeRow
item={item}
selected={item.node.kind === "file" && item.node.path === selectedPath}
expanded={expandedPaths.has(item.node.path)}
iconColor={iconColor}
onPressDirectory={toggleDirectory}
onPreviewFile={onPreviewFile}
onPressFile={handleSelectFile}
/>
),
[expandedPaths, handleSelectFile, iconColor, onPreviewFile, selectedPath, toggleDirectory],
);
return (
<View className="flex-1 bg-sheet">
@@ -152,20 +232,15 @@ export function FileTreeBrowser(props: {
contentInsetAdjustmentBehavior="automatic"
keyboardDismissMode="on-drag"
keyboardShouldPersistTaps="handled"
initialNumToRender={FILE_TREE_INITIAL_RENDER_COUNT}
maxToRenderPerBatch={FILE_TREE_RENDER_BATCH_SIZE}
updateCellsBatchingPeriod={16}
windowSize={5}
contentContainerStyle={{ paddingVertical: 8 }}
refreshControl={
<RefreshControl refreshing={props.isPending} onRefresh={props.onRefresh} />
}
renderItem={({ item }) => (
<FileTreeRow
item={item}
selectedPath={props.selectedPath}
expanded={expandedPaths.has(item.node.path)}
iconColor={iconColor}
onPressDirectory={toggleDirectory}
onPressFile={props.onSelectFile}
/>
)}
renderItem={renderItem}
ListEmptyComponent={
<View className="px-4 py-5">
{props.isPending ? (
@@ -20,13 +20,13 @@ import type { ReviewHighlightedToken } from "../review/shikiReviewHighlighter";
import { cn } from "../../lib/cn";
import { MOBILE_CODE_SURFACE } from "../../lib/typography";
import {
buildNativeSourceRows,
buildNativeSourceTokens,
NATIVE_SOURCE_CONTENT_WIDTH,
NATIVE_SOURCE_ROW_HEIGHT,
NATIVE_SOURCE_STYLE,
nativeSourceRowId,
} from "./nativeSourceFileAdapter";
import { prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
const SOURCE_LINE_HEIGHT = MOBILE_CODE_SURFACE.rowHeight;
@@ -41,10 +41,6 @@ interface SourceFileSurfaceProps {
type SourceHighlightStatus = "highlighting" | "ready" | "error";
function splitSourceLines(contents: string): ReadonlyArray<string> {
return contents.replace(/\r\n?/g, "\n").split("\n");
}
const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
readonly index: number;
readonly line: string;
@@ -119,11 +115,8 @@ const HighlightedSourceLine = memo(function HighlightedSourceLine(props: {
function useSourceFileModel(props: SourceFileSurfaceProps) {
const colorScheme = useColorScheme();
const theme: "dark" | "light" = colorScheme === "dark" ? "dark" : "light";
const normalizedContents = useMemo(
() => props.contents.replace(/\r\n?/g, "\n"),
[props.contents],
);
const lines = useMemo(() => splitSourceLines(normalizedContents), [normalizedContents]);
const document = useMemo(() => prepareSourceFileDocument(props.contents), [props.contents]);
const { contents: normalizedContents, lines, rowsJson } = document;
const targetIndex =
props.initialLine !== null && props.initialLine !== undefined && props.initialLine > 0
? Math.min(Math.floor(props.initialLine) - 1, Math.max(0, lines.length - 1))
@@ -140,7 +133,7 @@ function useSourceFileModel(props: SourceFileSurfaceProps) {
? "ready"
: "highlighting";
return { lines, status, targetIndex, theme, tokens };
return { lines, rowsJson, status, targetIndex, theme, tokens };
}
function SourceHighlightStatusView(props: { readonly status: SourceHighlightStatus }) {
@@ -163,8 +156,7 @@ function NativeSourceFileSurface(
},
) {
const { NativeView } = props;
const { lines, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const rowsJson = useMemo(() => JSON.stringify(buildNativeSourceRows(lines)), [lines]);
const { rowsJson, status, targetIndex, theme, tokens } = useSourceFileModel(props);
const tokensJson = useMemo(() => JSON.stringify(buildNativeSourceTokens(tokens)), [tokens]);
const selectedRowIdsJson = useMemo(
() => JSON.stringify(targetIndex === null ? [] : [nativeSourceRowId(targetIndex)]),
@@ -176,11 +168,11 @@ function NativeSourceFileSurface(
<View className="relative flex-1 bg-card">
<SourceHighlightStatusView status={status} />
<NativeView
key={props.path}
collapsable={false}
testID="source-native-code-view"
style={{ flex: 1 }}
appearanceScheme={theme}
contentResetKey={props.path}
contentWidth={NATIVE_SOURCE_CONTENT_WIDTH}
initialRowIndex={targetIndex ?? -1}
rowHeight={NATIVE_SOURCE_ROW_HEIGHT}
@@ -1,8 +1,19 @@
import Stack from "expo-router/stack";
import {
NativeHeaderToolbar,
NativeStackScreenOptions,
} from "../../navigation/native-stack-header";
import { SymbolView } from "expo-symbols";
import { useLocalSearchParams, useRouter } from "expo-router";
import { useCallback, useMemo, useRef, useState } from "react";
import { ActivityIndicator, Pressable, ScrollView, Text as RNText, View } from "react-native";
import { useRouteParams, useAppNavigation } from "../../navigation/native-stack-header";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ActivityIndicator,
Platform,
Pressable,
ScrollView,
Text as RNText,
useColorScheme,
View,
} from "react-native";
import Svg, { Defs, LinearGradient, Rect, Stop } from "react-native-svg";
import {
EnvironmentId,
@@ -16,18 +27,30 @@ import { CopyTextButton } from "../../components/CopyTextButton";
import { EmptyState } from "../../components/EmptyState";
import { LoadingScreen } from "../../components/LoadingScreen";
import { cn } from "../../lib/cn";
import { resolveFileSelectionNavigationAction } from "../../lib/adaptive-navigation";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { tryOpenExternalUrl } from "../../lib/openExternalUrl";
import { buildThreadFilesNavigation } from "../../lib/routes";
import { buildThreadFilesNavigation, threadNavigation } from "../../lib/routes";
import { MOBILE_TYPOGRAPHY } from "../../lib/typography";
import { useThemeColor } from "../../lib/useThemeColor";
import { useThreadSelection } from "../../state/use-thread-selection";
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useEnvironmentQuery } from "../../state/query";
import { projectEnvironment } from "../../state/projects";
import { AdaptiveInspectorLayout } from "../layout/adaptive-inspector-layout";
import {
useAdaptiveWorkspaceLayout,
useAdaptiveWorkspacePaneRole,
} from "../layout/AdaptiveWorkspaceLayout";
import { createNativeMailSearchToolbarItem } from "../layout/native-mail-search-toolbar";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
import { ReviewHighlighterProvider } from "../review/ReviewHighlighterProvider";
import { ThreadRouteScreen } from "../threads/ThreadRouteScreen";
import { FileMarkdownPreview } from "./FileMarkdownPreview";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
import { SourceFileSurface } from "./SourceFileSurface";
import { ThreadFileNavigatorPane } from "./thread-file-navigator-pane";
import { WorkspaceFileImagePreview } from "./WorkspaceFileImagePreview";
import { WorkspaceFileWebPreview } from "./WorkspaceFileWebPreview";
import {
@@ -41,6 +64,7 @@ import {
import { useWorkspaceFileAssetUrl } from "./workspaceFileAssetUrl";
type FileViewMode = "preview" | "source";
const HEADER_SCROLL_EDGE_EFFECTS = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
function firstRouteParam(value: string | string[] | undefined): string | null {
if (Array.isArray(value)) {
@@ -334,7 +358,7 @@ function FileContent(props: {
}
function useThreadFilesWorkspace() {
const params = useLocalSearchParams<{
const params = useRouteParams<{
environmentId?: string | string[];
threadId?: string | string[];
}>();
@@ -364,7 +388,7 @@ function useThreadFilesWorkspace() {
function FilesUnavailable() {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<NativeStackScreenOptions options={{ title: "Files" }} />
<EmptyState
title="Files unavailable"
detail="This thread does not have an active workspace path."
@@ -443,11 +467,17 @@ function FilesToolbarBottomFade() {
}
export function ThreadFilesTreeScreen() {
const router = useRouter();
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useAppNavigation();
const { fileInspector, layout, panes, showAuxiliaryPane, togglePrimarySidebar } =
useAdaptiveWorkspaceLayout();
const [searchQuery, setSearchQuery] = useState("");
const colorScheme = useColorScheme();
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
const { cwd, environmentId, projectName, selectedThread, threadId } = useThreadFilesWorkspace();
const revealedInspectorRef = useRef(false);
const entriesQuery = useEnvironmentQuery(
environmentId !== null && cwd !== null
environmentId !== null && cwd !== null && !fileInspector.supported
? projectEnvironment.listEntries({
environmentId,
input: { cwd },
@@ -455,18 +485,81 @@ export function ThreadFilesTreeScreen() {
: null,
);
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handleReturnToThread = useCallback(() => {
if (navigation.canGoBack()) {
navigation.back();
return;
}
if (environmentId !== null && threadId !== null) {
navigation.replace(threadNavigation({ environmentId, threadId }));
}
}, [environmentId, navigation, threadId]);
const handleSelectFile = useCallback(
(path: string) => {
if (environmentId === null || threadId === null) {
return;
}
router.push(buildThreadFilesNavigation({ environmentId, threadId }, path));
const destination = buildThreadFilesNavigation({ environmentId, threadId }, path);
const navigationAction = resolveFileSelectionNavigationAction({
hasPersistentFileInspector: fileInspector.supported,
});
if (navigationAction === "replace") {
navigation.replace(destination);
return;
}
navigation.push(destination);
},
[environmentId, router, threadId],
[environmentId, fileInspector.supported, navigation, threadId],
);
const renderInspector = useCallback(
(headerInset: number) =>
environmentId !== null && cwd !== null ? (
<ThreadFileNavigatorPane
cwd={cwd}
environmentId={environmentId}
headerInset={headerInset}
projectName={projectName}
selectedPath={null}
onSelectFile={handleSelectFile}
/>
) : null,
[cwd, environmentId, handleSelectFile, projectName],
);
const handlePreviewFile = useCallback(
(relativePath: string) => {
if (environmentId === null || cwd === null) {
return;
}
preloadWorkspaceFileContents({
cwd,
environmentId,
relativePath,
theme: highlightTheme,
});
},
[cwd, environmentId, highlightTheme],
);
const renderHeaderTitle = useCallback(
() => <FilesHeaderTitle projectName={projectName} />,
[projectName],
);
useEffect(() => {
if (fileInspector.supported && cwd !== null && !revealedInspectorRef.current) {
revealedInspectorRef.current = true;
showAuxiliaryPane("inspector");
}
}, [cwd, fileInspector.supported, showAuxiliaryPane]);
if (selectedThread === null || environmentId === null || threadId === null) {
if (fileInspector.supported) {
return (
<ThreadRouteScreen
onReturnToThread={handleReturnToThread}
renderInspector={renderInspector}
/>
);
}
return <LoadingScreen message="Opening files..." messagePlacement="above-spinner" />;
}
@@ -474,46 +567,90 @@ export function ThreadFilesTreeScreen() {
return <FilesUnavailable />;
}
if (fileInspector.supported) {
return (
<ThreadRouteScreen
onReturnToThread={handleReturnToThread}
renderInspector={renderInspector}
/>
);
}
const usesCompactMailToolbar = Platform.OS === "ios" && !layout.usesSplitView;
return (
<View className="flex-1 bg-sheet">
<Stack.Screen
<NativeStackScreenOptions
options={{
title: "Files",
headerShown: true,
headerTransparent: true,
headerStyle: { backgroundColor: "transparent" },
headerShadowVisible: false,
headerTitle: () => <FilesHeaderTitle projectName={projectName} />,
headerSearchBarOptions: {
allowToolbarIntegration: true,
autoCapitalize: "none",
hideNavigationBar: false,
placeholder: "Search files",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
},
headerTitle: renderHeaderTitle,
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
unstable_headerToolbarItems: usesCompactMailToolbar
? () => [
createNativeMailSearchToolbarItem({
composeButtonId: "files-refresh",
composeSystemImageName: "arrow.clockwise",
onComposePress: entriesQuery.refresh,
onSearchTextChange: setSearchQuery,
placeholder: "Search files",
searchTextChangeId: "files-search-text",
}),
]
: undefined,
headerSearchBarOptions: usesCompactMailToolbar
? undefined
: {
allowToolbarIntegration: true,
autoCapitalize: "none",
hideNavigationBar: false,
placeholder: "Search files",
onChangeText: (event) => {
setSearchQuery(event.nativeEvent.text);
},
onCancelButtonPress: () => {
setSearchQuery("");
},
},
}}
/>
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
accessibilityLabel="Refresh files"
icon="arrow.clockwise"
onPress={entriesQuery.refresh}
/>
</Stack.Toolbar>
<Stack.Toolbar placement="bottom">
<Stack.Toolbar.SearchBarSlot />
</Stack.Toolbar>
{layout.usesSplitView ? (
<NativeHeaderToolbar placement="left">
<NativeHeaderToolbar.Button
accessibilityLabel={panes.primarySidebarVisible ? "Maximize files" : "Show threads"}
icon={
panes.primarySidebarVisible ? "arrow.up.left.and.arrow.down.right" : "sidebar.left"
}
onPress={togglePrimarySidebar}
separateBackground
/>
</NativeHeaderToolbar>
) : null}
{!usesCompactMailToolbar ? (
<NativeHeaderToolbar placement="right">
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh files"
icon="arrow.clockwise"
onPress={entriesQuery.refresh}
/>
</NativeHeaderToolbar>
) : null}
{usesCompactMailToolbar ? null : (
<NativeHeaderToolbar placement="bottom">
<NativeHeaderToolbar.SearchBarSlot />
</NativeHeaderToolbar>
)}
<FileTreeBrowser
entries={entriesData?.entries ?? []}
error={entriesQuery.error}
isPending={entriesQuery.isPending}
searchQuery={searchQuery}
selectedPath={null}
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
onSelectFile={handleSelectFile}
/>
@@ -523,7 +660,11 @@ export function ThreadFilesTreeScreen() {
}
export function ThreadFileScreen() {
const params = useLocalSearchParams<{
useAdaptiveWorkspacePaneRole("inspector");
const navigation = useAppNavigation();
const { fileInspector, panes, toggleAuxiliaryPane } = useAdaptiveWorkspaceLayout();
const iconColor = useThemeColor("--color-icon");
const params = useRouteParams<{
line?: string | string[];
path?: string | string[];
}>();
@@ -568,6 +709,33 @@ export function ThreadFileScreen() {
);
const fileData = fileQuery.data as ProjectReadFileResult | null;
const handleSelectFile = useCallback(
(path: string) => {
// We are already on the catch-all file route. Updating its params keeps
// the current native screen mounted while replacing the selected file in
// place, avoiding an RNSScreen snapshot/unmount for every tree click.
navigation.setParams({
line: undefined,
path: path.split("/").filter(Boolean),
});
},
[navigation],
);
const renderInspector = useCallback(
(headerInset: number) =>
fileInspector.supported && environmentId !== null && cwd !== null ? (
<ThreadFileNavigatorPane
cwd={cwd}
environmentId={environmentId}
headerInset={headerInset}
projectName={projectName}
selectedPath={relativePath}
onSelectFile={handleSelectFile}
/>
) : undefined,
[cwd, environmentId, fileInspector.supported, handleSelectFile, projectName, relativePath],
);
if (selectedThread === null || environmentId === null || threadId === null) {
return <LoadingScreen message="Opening file..." messagePlacement="above-spinner" />;
}
@@ -579,7 +747,7 @@ export function ThreadFileScreen() {
if (relativePath === null) {
return (
<View className="flex-1 items-center justify-center bg-sheet px-6">
<Stack.Screen options={{ title: "Files" }} />
<NativeStackScreenOptions options={{ title: "Files" }} />
<EmptyState title="File unavailable" detail="This file path is invalid." />
</View>
);
@@ -588,9 +756,42 @@ export function ThreadFileScreen() {
return (
<ReviewHighlighterProvider>
<View className="flex-1 bg-sheet">
<Stack.Screen options={{ title: basename(relativePath) }} />
<Stack.Toolbar placement="right">
<Stack.Toolbar.Button
<NativeStackScreenOptions
options={{
headerTitle: basename(relativePath),
headerTransparent: true,
headerShadowVisible: false,
headerStyle: { backgroundColor: "transparent" },
headerTintColor: iconColor,
scrollEdgeEffects: HEADER_SCROLL_EDGE_EFFECTS,
title: basename(relativePath),
unstable_navigationItemStyle: Platform.OS === "ios" ? "editor" : undefined,
}}
/>
<WorkspaceSidebarToolbar>
{fileInspector.supported ? (
<NativeHeaderToolbar.Button
accessibilityLabel="Return to chat"
icon="chevron.left"
onPress={() => {
navigation.replace(threadNavigation({ environmentId, threadId }));
}}
/>
) : null}
</WorkspaceSidebarToolbar>
<NativeHeaderToolbar placement="right">
{fileInspector.supported ? (
<NativeHeaderToolbar.Button
accessibilityLabel={
panes.auxiliaryPaneVisible ? "Hide file navigator" : "Show file navigator"
}
icon="sidebar.right"
onPress={toggleAuxiliaryPane}
separateBackground
/>
) : null}
<NativeHeaderToolbar.Button
accessibilityLabel="Refresh file"
icon="arrow.clockwise"
onPress={() => {
if (resolvedActiveMode === "preview" && (isBrowserFile || isImageFile)) {
@@ -600,26 +801,30 @@ export function ThreadFileScreen() {
fileQuery.refresh();
}}
/>
</Stack.Toolbar>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
}}
/>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
/>
</NativeHeaderToolbar>
<AdaptiveInspectorLayout
renderInspector={fileInspector.supported ? () => renderInspector(0) : undefined}
>
<FilePreviewHeader
activeMode={resolvedActiveMode}
showModeSelector={canPreview && !isImageFile}
externalPreviewUri={isBrowserFile ? assetPreviewUri : undefined}
projectName={projectName}
relativePath={relativePath}
onSetMode={(mode) => {
setModeOverride({ path: relativePath, mode });
}}
/>
<FileContent
activeMode={resolvedActiveMode}
previewUri={previewUri}
fileContents={fileData?.contents ?? null}
fileError={fileQuery.error}
initialLine={targetLine}
relativePath={relativePath}
truncated={fileData?.truncated ?? false}
/>
</AdaptiveInspectorLayout>
</View>
</ReviewHighlighterProvider>
);
@@ -0,0 +1,74 @@
import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
import { isBrowserPreviewFile, isImagePreviewFile } from "./filePath";
import { prepareSourceFileDocument } from "./source-file-document";
import { sourceHighlightAtom } from "./sourceHighlightingState";
import type { ReviewDiffTheme } from "../review/shikiReviewHighlighter";
const inFlightPreloads = new Map<string, Promise<void>>();
const MAX_HIGHLIGHT_PRELOAD_CHARACTERS = 256 * 1024;
function preloadKey(input: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly relativePath: string;
}): string {
return JSON.stringify([input.environmentId, input.cwd, input.relativePath]);
}
export function preloadWorkspaceFileContents(input: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly relativePath: string;
readonly theme: ReviewDiffTheme;
}): void {
if (isBrowserPreviewFile(input.relativePath) || isImagePreviewFile(input.relativePath)) {
return;
}
const key = preloadKey(input);
if (inFlightPreloads.has(key)) {
return;
}
const preload = executeAtomQuery(
appAtomRegistry,
projectEnvironment.readFile({
environmentId: input.environmentId,
input: { cwd: input.cwd, relativePath: input.relativePath },
}),
{
label: "workspace file preload",
reportDefect: false,
reportFailure: false,
},
)
.then(async (result) => {
if (result._tag === "Success") {
const document = prepareSourceFileDocument(result.value.contents);
if (document.contents.length <= MAX_HIGHLIGHT_PRELOAD_CHARACTERS) {
await executeAtomQuery(
appAtomRegistry,
sourceHighlightAtom({
path: input.relativePath,
contents: document.contents,
theme: input.theme,
}),
{
label: "workspace source highlight preload",
reportDefect: false,
reportFailure: false,
},
);
}
}
})
.finally(() => {
inFlightPreloads.delete(key);
});
inFlightPreloads.set(key, preload);
}
@@ -0,0 +1,16 @@
import { describe, expect, it } from "vite-plus/test";
import { prepareSourceFileDocument } from "./source-file-document";
describe("prepareSourceFileDocument", () => {
it("normalizes and serializes source rows once for repeated consumers", () => {
const first = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r");
const second = prepareSourceFileDocument("const value = 1;\r\n\tvalue;\r");
const rows = JSON.parse(first.rowsJson) as ReadonlyArray<{ readonly content: string }>;
expect(first.contents).toBe("const value = 1;\n\tvalue;\n");
expect(first.lines).toEqual(["const value = 1;", "\tvalue;", ""]);
expect(rows.map((row) => row.content)).toEqual(["const value = 1;", " value;", ""]);
expect(second).toBe(first);
});
});
@@ -0,0 +1,54 @@
import { buildNativeSourceRows } from "./nativeSourceFileAdapter";
const MAX_CACHED_DOCUMENTS = 8;
const MAX_CACHED_CHARACTERS = 4 * 1024 * 1024;
export interface SourceFileDocument {
readonly contents: string;
readonly lines: ReadonlyArray<string>;
readonly rowsJson: string;
}
const documentCache = new Map<string, SourceFileDocument>();
let cachedCharacterCount = 0;
function removeOldestCachedDocument(): void {
const oldestKey = documentCache.keys().next().value;
if (typeof oldestKey !== "string") {
return;
}
const document = documentCache.get(oldestKey);
documentCache.delete(oldestKey);
cachedCharacterCount -= (document?.contents.length ?? 0) + (document?.rowsJson.length ?? 0);
}
export function prepareSourceFileDocument(contents: string): SourceFileDocument {
const cached = documentCache.get(contents);
if (cached !== undefined) {
documentCache.delete(contents);
documentCache.set(contents, cached);
return cached;
}
const normalizedContents = contents.replace(/\r\n?/g, "\n");
const lines = normalizedContents.split("\n");
const document = {
contents: normalizedContents,
lines,
rowsJson: JSON.stringify(buildNativeSourceRows(lines)),
} satisfies SourceFileDocument;
const characterCount = document.contents.length + document.rowsJson.length;
if (characterCount <= MAX_CACHED_CHARACTERS) {
while (
documentCache.size >= MAX_CACHED_DOCUMENTS ||
cachedCharacterCount + characterCount > MAX_CACHED_CHARACTERS
) {
removeOldestCachedDocument();
}
documentCache.set(contents, document);
cachedCharacterCount += characterCount;
}
return document;
}
@@ -88,7 +88,7 @@ describe("sourceHighlightingState", () => {
expect(AsyncResult.isSuccess(registry.get(atom))).toBe(true);
});
firstUnmount();
await new Promise((resolve) => setTimeout(resolve, 25));
await new Promise((resolve) => setTimeout(resolve, 100));
const secondUnmount = registry.mount(atom);
await vi.waitFor(() => {
@@ -0,0 +1,175 @@
import type { EnvironmentId, ProjectListEntriesResult } from "@t3tools/contracts";
import { SymbolView } from "expo-symbols";
import { useCallback, useMemo, useState, type ComponentProps } from "react";
import { Platform, Pressable, useColorScheme, View, type NativeSyntheticEvent } from "react-native";
import {
Screen,
ScreenStack,
ScreenStackHeaderConfig,
ScreenStackHeaderSearchBarView,
SearchBar,
} from "react-native-screens";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { nativeHeaderScrollEdgeEffects } from "../../lib/native-scroll-edge-effect";
import { useThemeColor } from "../../lib/useThemeColor";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import { FileTreeBrowser } from "./FileTreeBrowser";
import { preloadWorkspaceFileContents } from "./preload-workspace-file";
export function ThreadFileNavigatorPane(props: {
readonly cwd: string;
readonly environmentId: EnvironmentId;
readonly headerInset: number;
readonly projectName: string;
readonly selectedPath: string | null;
readonly onSelectFile: (path: string) => void;
}) {
const [searchQuery, setSearchQuery] = useState("");
const colorScheme = useColorScheme();
const highlightTheme = colorScheme === "dark" ? "dark" : "light";
const iconColor = String(useThemeColor("--color-icon-muted"));
const foregroundColor = String(useThemeColor("--color-foreground"));
const sheetColor = String(useThemeColor("--color-sheet"));
const headerScrollEdgeEffects = nativeHeaderScrollEdgeEffects(Platform.OS, Platform.Version);
const entriesQuery = useEnvironmentQuery(
projectEnvironment.listEntries({
environmentId: props.environmentId,
input: { cwd: props.cwd },
}),
);
const entriesData = entriesQuery.data as ProjectListEntriesResult | null;
const handlePreviewFile = useCallback(
(relativePath: string) => {
preloadWorkspaceFileContents({
cwd: props.cwd,
environmentId: props.environmentId,
relativePath,
theme: highlightTheme,
});
},
[highlightTheme, props.cwd, props.environmentId],
);
const nativeHeaderRightBarButtonItems = useMemo(
() =>
[
{
accessibilityLabel: "Refresh files",
icon: { name: "arrow.clockwise", type: "sfSymbol" as const },
identifier: "thread-file-navigator-refresh",
onPress: entriesQuery.refresh,
sharesBackground: false,
tintColor: foregroundColor,
type: "button" as const,
width: 44,
},
] as ComponentProps<typeof ScreenStackHeaderConfig>["headerRightBarButtonItems"],
[entriesQuery.refresh, foregroundColor],
);
const fileTree = (
<FileTreeBrowser
entries={entriesData?.entries ?? []}
error={entriesQuery.error}
isPending={entriesQuery.isPending}
searchQuery={searchQuery}
selectedPath={props.selectedPath}
onPreviewFile={handlePreviewFile}
onRefresh={entriesQuery.refresh}
onSelectFile={props.onSelectFile}
/>
);
if (Platform.OS === "ios") {
return (
<View className="flex-1 border-l border-border bg-sheet">
<ScreenStack style={{ flex: 1 }}>
<Screen
activityState={2}
enabled
isNativeStack
screenId="thread-file-navigator-native"
scrollEdgeEffects={headerScrollEdgeEffects}
style={{ backgroundColor: sheetColor, flex: 1 }}
>
{fileTree}
<ScreenStackHeaderConfig
backgroundColor="rgba(0,0,0,0)"
color={foregroundColor}
headerRightBarButtonItems={nativeHeaderRightBarButtonItems}
hideBackButton
hideShadow={false}
navigationItemStyle="editor"
subtitle={props.projectName}
title="Files"
titleColor={foregroundColor}
titleFontSize={17}
titleFontWeight="700"
translucent
>
<ScreenStackHeaderSearchBarView>
<SearchBar
allowToolbarIntegration
autoCapitalize="none"
barTintColor={sheetColor}
hideNavigationBar={false}
hideWhenScrolling={false}
obscureBackground={false}
onCancelButtonPress={() => {
setSearchQuery("");
}}
onChangeText={(event: NativeSyntheticEvent<{ readonly text?: string }>) => {
setSearchQuery(event.nativeEvent.text ?? "");
}}
placement="integratedButton"
placeholder="Search files"
textColor={foregroundColor}
tintColor={foregroundColor}
/>
</ScreenStackHeaderSearchBarView>
</ScreenStackHeaderConfig>
</Screen>
</ScreenStack>
</View>
);
}
return (
<View className="flex-1 border-l border-border bg-sheet">
<View className="border-b border-border" style={{ paddingTop: props.headerInset }}>
<View className="h-12 flex-row items-center gap-2 px-3">
<View className="min-w-0 flex-1">
<Text className="text-sm font-t3-bold text-foreground">Files</Text>
<Text className="text-xs text-foreground-muted" numberOfLines={1}>
{props.projectName}
</Text>
</View>
<Pressable
accessibilityRole="button"
accessibilityLabel="Refresh files"
hitSlop={8}
className="h-8 w-8 items-center justify-center rounded-full active:bg-subtle"
onPress={entriesQuery.refresh}
>
<SymbolView name="arrow.clockwise" size={14} tintColor={iconColor} type="monochrome" />
</Pressable>
</View>
<View className="flex-row items-center gap-2 border-t border-border px-3 py-2">
<SymbolView name="magnifyingglass" size={15} tintColor={iconColor} type="monochrome" />
<TextInput
accessibilityLabel="Search files"
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="while-editing"
className="min-h-10 flex-1 rounded-xl py-2 text-sm"
placeholder="Search files"
value={searchQuery}
onChangeText={setSearchQuery}
/>
</View>
</View>
{fileTree}
</View>
);
}
Loaded 100 of 531 files, more files were not shown because too many files have changed in this diff. Show more