Compare commits

..
Author SHA1 Message Date
Theo Browne 19b837ee9c feat(server): sync thread read status across clients 2026-08-13 16:23:03 -07:00
Theo Browne db1507e986 feat: allow disabling auto-settle on merge (#5880) 2026-08-13 16:18:15 -07:00
Rakshith Bhat 96bfa67b3d fix(web): align the snoozed thread wake icon (#6215) 2026-08-13 18:14:24 -04:00
Taylor Bombay 5ff3a03ada fix(web): align sidebar wordmark label (#6086) 2026-08-13 18:14:13 -04:00
t3-code[bot]andmaria 23d45d914e fix(web): restore default stage artwork colors (#6535)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-13 18:04:24 -04:00
Paul van DykandClaude Opus 5 bad1143b02 fix(mobile): show a real settings cog in the Android sidebar header (#6520)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-13 20:41:17 +00:00
Adamulek123andJulius Marminge 92d4a2e996 fix(web): scope pull request errors to their environment (#6490)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 20:40:21 +00:00
Utkarsh Patil 2fab18e289 fix(web): show unlinked icon when viewport aspect ratio is unlocked (#6509) 2026-08-13 16:03:48 -04:00
1b16ed663f fix(web): avoid Clerk close button overlap (#6442)
Co-authored-by: t3-code[bot] <236186684+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-13 15:08:28 -04:00
SimoneandSimone 83ad26c3a3 fix(mobile): prevent invalid HTML entities from crashing markdown (#6495)
Co-authored-by: Simone <[email protected]>
2026-08-13 15:08:13 -04:00
Chris Deeming fd51561b4e fix(mobile): extend blockquotes across wrapped lines (#6482) 2026-08-13 20:00:03 +02:00
Julius Marminge 9e201941aa Remove rebase requirement before opening PR (#6479) 2026-08-13 15:04:42 +00:00
t3-code[bot]andJulius Marminge 2ab188f1c0 fix: ignore pull request actions in latency tracker (#6476)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-13 14:51:31 +00:00
maria 9513e62e24 Add bil0000 to VOUCHED contributors list (#6462) 2026-08-13 14:26:36 +00:00
Bilal Bakr 97db94c9bf fix(web): keep pull request panel within viewport (#6451) 2026-08-13 08:45:33 -04:00
Exotic 5015d7cf9f fix(web): keep turn minimap stable as composer grows (#6414) 2026-08-13 15:30:37 +05:30
Nick Anisimov df19f6cfe3 fix(server): align Codex collaboration prompts (#6432) 2026-08-13 10:31:53 +02:00
Dominic RoyandClaude Fable 5 6bc6cb6be4 fix(web): keep diff file lists scrollable past expanded files (#6423)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 20:11:53 -07:00
Theo BrowneandClaude Fable 5 1e59b4c400 fix(web): keep the typed prompt when a draft changes repo (#6393)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-12 16:26:27 -07:00
t3-code[bot]andUtkarsh Patil 33f9705926 fix(web): make reset zoom hover visible (#6385)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 19:13:35 -04:00
Dominic Roy da6253b3dd web/settings: fix source control scan on relay environments (#6230) 2026-08-12 16:13:06 -07:00
GianmarcoandCursor ac1264e2ca feat(web): project favicon and workspace icons in command subtitles (#6330)
Co-authored-by: Cursor <[email protected]>
2026-08-12 17:32:58 -04:00
Theo Browne 2eb099fdc8 fix(web): cmd+click sidebar PR numbers open in the browser (#6378) 2026-08-12 14:28:37 -07:00
Bilal BakrandJulius Marminge b28f9bf0a1 feat(web): pull request surfaces — filters & qualifiers, all-server listing, update branch, reactions, in-place editing, smarter diffs (#6039)
Co-authored-by: Julius Marminge <[email protected]>
2026-08-12 22:58:36 +02:00
d0b8d6306b feat(connect): deregister account environments from any client (#4844)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-12 22:46:23 +02:00
Exotic 9666b87516 fix(web): preserve appearance mode when changing themes (#6343) 2026-08-12 16:43:40 -04:00
Alex e3a9c2518d test(mobile): seed snoozed showcase threads (#5155) 2026-08-12 16:43:18 -04:00
Julius Marminge 18918d1c4d Fix mobile command popover glass rendering (#6370) 2026-08-12 22:21:45 +02:00
t3-code[bot]andmaria 8d24b5131f fix(web): open modified PR clicks in browser (#6278)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-12 14:32:44 -04:00
Exotic 770946d026 fix(web): render tooltips above dropdowns (#6241) 2026-08-12 14:32:20 -04:00
8601797233 fix(web): align update toast release notes link (#6322)
Co-authored-by: t3-code[bot] <219304759+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
Co-authored-by: Exotic <[email protected]>
2026-08-12 14:32:10 -04:00
Exotic b73232bdd3 feat(web): reset sidebar width on double click (#6320) 2026-08-12 10:07:39 -04:00
Wout Stiens f131228a59 fix(web): theme Clerk surfaces (#6300) 2026-08-12 19:36:04 +05:30
t3-code[bot]andWout Stiens e321667b10 fix(web): prevent changed files header overlap (#6314)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-12 08:56:13 -04:00
Julius Marminge 849bac8946 fix(connect): preserve CLI OAuth parameters through browser sign-in (#6285) 2026-08-12 12:58:34 +02:00
t3-code[bot]andUtkarsh Patil 6fd088af9f fix(web): align mobile onboarding header (#6293)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 16:07:44 +05:30
Wout Stiens b54bfc9312 feat(web): a better right panel empty state (#6258) 2026-08-12 15:28:46 +05:30
Nick Anisimovandshivam e1378a1f4d fix(mobile): keep ordered lists inside user bubbles (#6154)
Co-authored-by: shivam <[email protected]>
2026-08-12 14:39:51 +05:30
t3-code[bot]andmaria 5a84614809 fix(web): align the composer model picker (#6252)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-11 22:38:45 -04:00
maria 63e6faef62 chore: add dara to vouched (#6259) 2026-08-11 21:51:00 -04:00
Chris Deeming d37a9b09b8 feat(mobile): add thread title regeneration (#6253) 2026-08-11 21:43:05 -04:00
Exotic 560d4a4560 fix(web): keep sidebar wordmark visible at minimum width (#6246) 2026-08-11 19:57:10 -04:00
maria 52e5a75a87 feat(web): compact sidebar footer actions (#6210) 2026-08-11 18:53:40 -04:00
Exotic c196f422ed fix(web): clean up composer resize animation (#6209) 2026-08-11 23:21:44 +02:00
f0b57ca231 feat(web): add Open VSX theme search (#5654)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-11 20:06:05 +00:00
t3-code[bot] 2db08457f2 fix(web): use upload icon for disabled push action (#6207) 2026-08-11 20:25:24 +02:00
Wout Stiens 083fa4ab24 feat(web): use OKLCH for theme palettes (#6036) 2026-08-11 20:00:17 +02:00
Exotic 35172010b1 fix(web): use a clearer pull action icon (#6194) 2026-08-11 16:39:59 +00:00
Mina Yacoub 57b1052679 fix(web): thread error banner dismiss survives reconnect and rerenders (#6123) 2026-08-11 12:27:55 -04:00
1e355a2a34 fix(web): render dropdowns above toasts (#6165)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-11 12:27:02 -04:00
Utkarsh Patilandshivam 44621c345f feat(web): add back buttons for the pull requests and usage pages in the sidebar footer (#6031)
Co-authored-by: shivam <[email protected]>
2026-08-11 12:26:24 -04:00
Arham AminandClaude Opus 4.8 220e573b14 fix(shared): detect Azure DevOps SSH remotes (ssh.dev.azure.com) (#6187)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 16:14:02 +00:00
Arham AminandClaude Opus 4.8 6befe42eb0 fix(shared): normalize a bare Windows drive root the same as C:\ / C:/ (#6189)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 15:52:23 +00:00
Julius Marmingeandcodex b30a9bc414 feat(web): make environment artwork theme aware (#6183)
Co-authored-by: codex <[email protected]>
2026-08-11 17:46:52 +02:00
Wout Stiens ac4780f451 fix(web): restore typography font sizes to defaults (#6172) 2026-08-11 17:21:58 +02:00
Julius Marmingeandcodex 3da7f9c5c3 fix(mobile): guard App Store release versions (#6177)
Co-authored-by: codex <[email protected]>
2026-08-11 15:06:54 +00:00
Julius Marminge c842c6f5b9 Add hourly past-24-hour usage view (#6170) 2026-08-11 16:47:13 +02:00
6676f9c83b fix(mobile): stabilize thread composer and interactions (#5986)
Co-authored-by: codex <[email protected]>
Co-authored-by: Thuong Tin <[email protected]>
Co-authored-by: Kapish14 <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-11 14:05:03 +00:00
Utkarsh Patilandshivam 65b005f1e4 feat(web): add Copy Thread ID to the sidebar and chat header thread context menu (#5574)
Co-authored-by: shivam <[email protected]>
2026-08-11 18:32:02 +05:30
Utkarsh Patilandshivam 752acbf654 feat: add ability to create a new thread in the current project with shift+click and show shortcut in tooltip (#5994)
Co-authored-by: shivam <[email protected]>
2026-08-11 18:26:53 +05:30
Guilherme Vieira f5fce74169 fix(pull-requests): route self-hosted GitLab remotes (#6061) 2026-08-11 13:11:19 +02:00
t3-code[bot] 9c7622dac3 fix(server): handle unborn HEAD in VCS status (#5944)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-10 23:34:18 -04:00
yassiEmp c14bcca103 fix(server): advertise 256-color TERM on Windows terminals (#5693) 2026-08-10 23:33:58 -04:00
bkntr 1fa315ea93 fix(server): skip Linux libc detection on Windows/macOS (#5354) 2026-08-10 23:33:18 -04:00
Taras f9730979c1 perf(web): skip base64 for oversized image candidates (#5220) 2026-08-10 23:33:08 -04:00
AlexandIllia Panasenko 59d0c922e9 fix(web): persist sidebar shelf collapse state (#5136)
Co-authored-by: Illia Panasenko <[email protected]>
2026-08-10 23:32:22 -04:00
Arham AminandClaude Opus 4.8 2ea51bd31f fix(server): OpenCode model parsing drops models with a slash in the JSON body (#5072)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-10 23:31:31 -04:00
Pavlo TrinkoandClaude Fable 5 e5c82d79a0 fix(mobile): keep chat composer above the Android gesture bar (#5988)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-10 20:31:00 -04:00
Jono Kemball 9afef94a61 feat: add three-hour snooze option (#5914) 2026-08-11 00:03:26 +02:00
Utkarsh Patil a7b0366cbe fix(web): account for Windows window controls in PR page header (#6049) 2026-08-10 22:10:00 +02:00
Julius Marminge 428d9f9f67 Allow Android tablets to rotate (#5613) 2026-08-10 21:18:13 +02:00
t3-code[bot] 1b120f352f fix(ci): extend release publish timeout (#6034) 2026-08-10 21:01:09 +02:00
Chris Deeming 0a7c662d39 fix(web): improve built-in theme contrast (#6000) 2026-08-10 12:06:55 -04:00
Utkarsh Patil b91a000a17 feat(web): add duplicate action to the T3 Code default theme (#6013) 2026-08-10 18:02:27 +02:00
Tylerandtsouth89 8de0aa24d9 perf(desktop): probe the Windows shell environment concurrently (#5878)
Co-authored-by: tsouth89 <[email protected]>
2026-08-10 11:53:10 -04:00
cad2c93616 feat: multi-provider pull requests page with in-app reviews (#4849)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: maria <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-10 17:47:02 +02:00
t3-code[bot] 78f462c4e1 chore(release): prepare v0.0.33 2026-08-10 12:00:11 +00:00
Julius Marmingeandcodex 3b72d17cbc fix(mobile): parse EAS fingerprint JSON (#5991)
Co-authored-by: codex <[email protected]>
2026-08-10 11:35:40 +00:00
d440442db6 fix(mobile): stop Android user bubbles with code blocks from overlapping (#5659)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-10 12:36:08 +02:00
Mina Yacoub 67ef189d8b fix(mobile): detect PowerShell cmdlet errors in work log rows (#5726) 2026-08-10 12:34:28 +02:00
Utkarsh Patil fbcae59ef5 fix(web): use import/export-appropriate icons for theme buttons (#5964) 2026-08-10 15:48:54 +05:30
Wout Stiens 9821bca1ce fix(web): use themed confirmation dialogs (#5624) 2026-08-10 02:23:27 -04:00
Chris Deeming 3d74474f6c fix(web): update pills use readable theme foregrounds (#5938) 2026-08-09 23:26:45 -04:00
Carter Smith f0e2975180 fix(web): align project name with headline (#5864) 2026-08-09 23:22:48 -04:00
Theo BrowneandClaude Opus 5 d43210050b fix(web): trait menu closes after you pick a level (#5879)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-09 23:22:28 -04:00
SimoneandSimone ef051bdb87 fix(web): enable restore defaults after theme mix changes (#5928)
Co-authored-by: Simone <[email protected]>
2026-08-09 23:21:56 -04:00
Tristan Knight 0ca9fb3fb5 fix(web): show worktree icon in sidebar v2 (#5909) 2026-08-09 23:21:39 -04:00
Ellie Gummere cbd55d6374 fix(web): correct model picker trigger padding (#5935) 2026-08-10 04:32:13 +02:00
Julius Marminge 96906805f1 Add settings and usage breadcrumbs (#5929) 2026-08-10 02:12:19 +00:00
Julius Marminge 73b2e8fdd4 Automate production mobile EAS releases (#5609) 2026-08-10 04:11:22 +02:00
Julius Marmingeandcodex 5da45337f7 Preserve back navigation when opening settings (#5930)
Co-authored-by: codex <[email protected]>
2026-08-10 01:55:32 +00:00
Julius Marminge f21d5e444e Move project settings to contextual project routes (#5923) 2026-08-10 02:57:39 +02:00
t3-code[bot] 9a1472d955 fix(web): match usage titlebar text styling (#5897)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-09 20:14:15 -04:00
Theo Browne 2abe66800c fix(server): sandbox user-provided SVGs (#5916) 2026-08-09 16:51:43 -07:00
Theo BrowneandClaude Fable 5 0d38866dcf fix(server): usage no longer double-counts forked Codex sessions (#5887)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-09 15:56:17 -07:00
Julius MarmingeandClaude Fable 5 f993fa1c5f fix(mobile): long-pressing a thread row no longer navigates into the thread (#5901)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-10 00:29:31 +02:00
Utkarsh Patil 83d769f02d fix(web): match settings search shortcut styling to command palette's (#5841) 2026-08-09 17:48:10 -04:00
Arham AminandClaude Opus 4.8 c8ad4b8135 fix(shell): add ~/.local/bin to the Windows CLI resolver so native-installed providers are found (#5074)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-09 14:45:08 -07:00
t3-code[bot] bd18d8d6d1 fix(web): unify usage page chrome (#5823) 2026-08-09 23:26:26 +02:00
nathangerday 659986ce38 fix(web): thread title button no longer eats the drag area (#5857) 2026-08-09 17:22:52 -04:00
062b4618c2 fix(shared): bound the file-link label so bracket runs stop rescanning (#5782)
Co-authored-by: tsouth89 <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-09 14:16:12 -07:00
Matt Urenovich deb901d638 fix(server): favicon resolution no longer pins the event loop (#5538) 2026-08-09 21:10:49 +00:00
Utkarsh Patil 02f4ce5667 fix(web): match create theme and import theme buttons to the standard outline style (#5860) 2026-08-09 14:04:34 -04:00
Robert Soriano 285cf5947b fix(web): preserve desktop route during Clerk auth (#5770) 2026-08-09 17:33:03 +00:00
Julius Marminge 1a003e383a Add cross-platform mobile usage dashboard (#5743) 2026-08-09 12:10:27 +02:00
Theo BrowneandClaude Fable 5 963ebf5bd7 ci: label-gated hosted-web preview deploys (#5465)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-09 00:30:27 -07:00
Theo BrowneandClaude Opus 5 ba9c9ae81d fix(server): one greedy agent process no longer takes down the whole server (#5788)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 22:13:26 -07:00
Theo Browne 076e9048dc feat(web): project icons can be chosen manually (#5775) 2026-08-08 22:13:16 -07:00
Theo BrowneandClaude Fable 5 05eb051184 feat(web): keep unsent drafts one click away in the sidebar (#5777)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 20:29:21 -07:00
Theo BrowneandClaude Fable 5 ddaa6afef5 feat(server): vp run migrate-dev-db seeds worktree dev dbs with real data (#5773)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:51:18 -07:00
Theo BrowneandClaude Opus 5 6f69b4407f fix(web): sidebar rows show the branch again, not a truncated plan step (#5776)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 19:45:21 -07:00
Theo BrowneandClaude Fable 5 6dbffa022d feat: pick worktree or current checkout per project (#5766)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:44:58 -07:00
Theo BrowneandClaude Fable 5 5bb8c03664 fix(server): settle no longer leaves monitors and dev servers running (#5774)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:44:15 -07:00
Theo BrowneandClaude Fable 5 886195ec1e fix(web): usage totals no longer jump while devices report in (#5772)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 19:05:16 -07:00
Theo BrowneandClaude Fable 5 288d8e3457 feat(web): overhaul project settings into a real settings page (#5768)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:50:03 -07:00
Theo BrowneandClaude Fable 5 5208bdeb0d fix(web): pinned reorder no longer reshuffles while writes land (#5767)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:46:27 -07:00
Theo BrowneandClaude Fable 5 a6c9b41f90 feat(server): agents can now open the images you paste into chat (#5757)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 18:43:53 -07:00
Theo BrowneandClaude Fable 5 70c423a5e4 fix(web): usage page loses the cost quality panel, gains a back button (#5756)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 21:31:20 -04:00
Theo Browne 89c320df0b fix(server): stop Codex threads with queued follow-ups (#5762) 2026-08-08 17:52:06 -07:00
Theo Browne 7b2cf4374f chore: vouch saphid (#5763) 2026-08-08 20:44:28 -04:00
Theo Browne 49964e38c0 chore: vouch gfsaaser24 (#5761) 2026-08-09 00:32:10 +00:00
e70cdb478d fix(server): stop Claude resume handshakes from completing turns that never ran (#5710)
Co-authored-by: t3-turbo-simulation <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 17:24:42 -07:00
naMqe be01b287b9 fix(web): add missing cursor-pointer styling to dropdowns and interactive buttons (#5716) 2026-08-08 20:02:57 -04:00
Theo BrowneandClaude Fable 5 c2f8cb7ca1 feat(web): show how many subagents are running at a glance (#5745)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 16:20:06 -07:00
Leonel Rivas 89ee692bf0 fix(web): persist diff view mode (#5731) 2026-08-08 17:02:51 -04:00
Theo BrowneandClaude Opus 5 a20923ce46 fix(web): usage chart no longer makes Claude look like the bigger spender (#5697)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 05:43:03 -07:00
Theo BrowneandClaude Opus 5 8101cd0449 feat(usage): usage page reading provider transcripts across environments (#5684)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-08 03:59:04 -07:00
Theo BrowneandClaude Fable 5 30164cb1ba feat(mobile): one sheet for model and thread settings (#5625)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 03:51:20 -07:00
Theo BrowneandClaude Fable 5 0640410726 fix(desktop): zoom shortcuts no longer die when the preview browser has focus (#5691)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-08 02:24:38 -07:00
Theo BrowneandClaude Fable 5 2c7267ad43 fix(server): stop the reaper from silently killing live background subagents (#5677)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 21:42:14 -07:00
Chris Deeming daf8ee0b2f fix(web): inherit terminal size in simple typography (#5628) 2026-08-07 23:31:47 -04:00
t3-code[bot] ed886fe181 fix(web): delay transient reconnect warnings (#5670)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 23:17:18 -04:00
Theo BrowneandClaude Opus 5 4eaf5ef8bb fix(server): stop PR status lookups amplifying GitHub rate limits (#5673)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 18:09:46 -07:00
Theo BrowneandClaude Fable 5 0de9540739 feat: sidebar v2 is now the default sidebar (#5672)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 18:06:10 -07:00
Theo BrowneandClaude Fable 5 31891a1a0c feat(web): fold plan mode and token-by-token output into Legacy features (#5664)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 17:17:44 -07:00
Illia Panasenko 45d9aa90ba fix(web): show Stop button while input is pending (#5554) 2026-08-07 17:03:52 -04:00
Henry Zhang 7a84f6cf10 fix(web): reconnect the composer seam for remote non-Git projects (#5633) 2026-08-07 17:03:31 -04:00
maria f0fb406acf feat(web): make sidebar artwork theme-aware (#5636) 2026-08-07 15:41:59 -04:00
t3-code[bot] 82406bce99 chore: vouch chrisdeeming (#5641)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 15:01:39 -04:00
Chris Deeming 72d673a855 feat(desktop): remember recently used sites in the Browser panel (#5270) 2026-08-07 14:45:56 -04:00
t3-code[bot] e2cd2383ce chore(ci): vouch StiensWout (#5637)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 14:29:50 -04:00
555 changed files with 78437 additions and 13711 deletions

No files matched your search

+6
View File
@@ -11,9 +11,11 @@
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chrisdeeming
github:chuks-qua
github:cursoragent
github:gbarros-dev
github:gfsaaser24
github:github-actions[bot]
github:hwanseoc
github:jamesx0416
@@ -25,7 +27,9 @@ github:Noojuno
github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:saphid
github:shiroyasha9
github:StiensWout
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
@@ -33,3 +37,5 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
github:bil0000
+176 -5
View File
@@ -5,6 +5,25 @@ name: Mobile EAS Production
# in the same OS/pnpm as the EAS build; a macOS `eas build` computes a different
# fingerprint (platform-specific deps + pnpm version) and errors. On this Linux
# runner, with corepack pinning pnpm 10.24 in eas.json, local == build.
#
# Every merge to main that touches the mobile app reconciles, per platform:
# 1. Store builds: if the latest production build's version differs from
# app.config.ts, cut a new build and submit it (TestFlight + Play internal
# track). Bumping `version` is therefore all it takes to
# start the next release train — the first build of a version enters
# external-TestFlight beta review immediately, and later builds of the
# same version auto-approve until that version is released. After App
# Store approval, Apple closes the release train and `version` must be
# bumped before another iOS build can be submitted. Releasing to the App
# Store stays a manual App Store Connect step.
# 2. OTA: publish a production-channel update for each platform where at
# least one finished production build matches the current native
# fingerprint. Old-version binaries with a matching fingerprint receive
# it too. When native drift means no binary could install the update,
# it is skipped and flagged in the job summary instead of published
# into the void.
# workflow_dispatch remains as a manual override for both modes (e.g. to
# retry an errored build or force an OTA).
on:
workflow_dispatch:
inputs:
@@ -25,14 +44,38 @@ on:
- ios
- android
- all
version:
description: "Optional build version override (blank uses app.config.ts; an override is committed before building)"
required: false
type: string
message:
description: "OTA update message (mode=update only)"
required: false
type: string
push:
branches: [main]
paths:
- apps/mobile/**
- packages/client-runtime/**
- packages/contracts/**
- packages/shared/**
- assets/**
- scripts/**
- patches/**
- pnpm-lock.yaml
- pnpm-workspace.yaml
- .github/workflows/mobile-eas-production.yml
# Serialize runs so OTAs publish in merge order. GitHub keeps at most one
# queued run per group, so a burst of merges collapses into one run of the
# newest commit — intermediate commits don't need their own OTA.
concurrency:
group: mobile-eas-production
cancel-in-progress: false
jobs:
production:
name: EAS Production ${{ inputs.mode }}
name: EAS Production ${{ github.event_name == 'push' && 'auto' || inputs.mode }}
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
@@ -52,11 +95,21 @@ jobs:
echo "EXPO_TOKEN is not available; skipping EAS production job."
fi
- id: version_app_token
name: Mint release app token for version override
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build' && inputs.version != ''
uses: actions/create-github-app-token@v2
with:
app-id: ${{ secrets.RELEASE_APP_ID }}
private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
- name: Checkout
if: steps.expo-token.outputs.present == 'true'
uses: actions/checkout@v6
with:
fetch-depth: 0
token: ${{ steps.version_app_token.outputs.token || github.token }}
# No sparse-checkout here: it makes actions/checkout fetch with
# --filter=blob:none, and eas-cli archives the project via
# `git clone --depth 1 file://<workspace>`, which fails (exit 128)
@@ -98,15 +151,74 @@ jobs:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas env:pull production --non-interactive
- name: Build and submit
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'build'
- name: Apply manual version override
if: steps.version_app_token.outcome == 'success'
env:
GH_TOKEN: ${{ steps.version_app_token.outputs.token }}
APP_SLUG: ${{ steps.version_app_token.outputs.app-slug }}
RELEASE_VERSION: ${{ inputs.version }}
run: |
if [ "$GITHUB_REF_TYPE" != "branch" ]; then
echo "Version overrides require dispatching this workflow from a branch; received $GITHUB_REF_TYPE '$GITHUB_REF_NAME'." >&2
exit 1
fi
if ! [[ "$RELEASE_VERSION" =~ ^[0-9]+(\.[0-9]+){1,2}$ ]]; then
echo "Version override must contain two or three dot-separated integers; received '$RELEASE_VERSION'." >&2
exit 1
fi
node --input-type=module -e '
import fs from "node:fs";
const path = "apps/mobile/app.config.ts";
const source = fs.readFileSync(path, "utf8");
const next = source.replace(
/^( version: ")[^"]+(".*)$/m,
`$1${process.env.RELEASE_VERSION}$2`,
);
if (next === source && !source.includes(` version: "${process.env.RELEASE_VERSION}"`)) {
throw new Error("Could not update app version");
}
fs.writeFileSync(path, next);
'
vp fmt apps/mobile/app.config.ts
if git diff --quiet -- apps/mobile/app.config.ts; then
echo "app.config.ts is already at $RELEASE_VERSION; no version commit needed."
exit 0
fi
user_id="$(gh api "/users/${APP_SLUG}[bot]" --jq .id)"
git config user.name "${APP_SLUG}[bot]"
git config user.email "${user_id}+${APP_SLUG}[bot]@users.noreply.github.com"
git add apps/mobile/app.config.ts
git commit \
-m "chore(mobile): bump app version to $RELEASE_VERSION" \
-m "Co-authored-by: codex <[email protected]>"
git push origin "HEAD:refs/heads/${GITHUB_REF_NAME}"
- name: Summarize manual build version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
working-directory: apps/mobile
run: |
version="$(npx expo config --json --type public | jq -r '.version')"
{
echo "## Manual production build"
echo
echo "- App version: \`$version\`"
echo "- Platform: \`${{ inputs.platform }}\`"
echo
echo "> Apple closes an iOS release train after App Store approval. Before building iOS, confirm \`$version\` is newer than the approved App Store version."
} >> "$GITHUB_STEP_SUMMARY"
- name: Build and submit (manual)
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'build'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: eas build --platform ${{ inputs.platform }} --profile production --auto-submit --non-interactive --no-wait
- name: Publish OTA update
if: steps.expo-token.outputs.present == 'true' && inputs.mode == 'update'
- name: Publish OTA update (manual)
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'workflow_dispatch' && inputs.mode == 'update'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
@@ -117,3 +229,62 @@ jobs:
--platform ${{ inputs.platform }} \
--message "${{ inputs.message || format('Production OTA ({0})', github.sha) }}" \
--non-interactive
# No --status filter on build:list: an in-queue/in-progress build must
# count as existing, or every merge during the build window would cut a
# duplicate. After an errored build, retry via workflow_dispatch
# mode=build — pushes won't re-trigger it until the app version changes.
- id: store_builds
name: Ensure store builds exist for the current app version
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
continue-on-error: true
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
failed=0
version="$(npx expo config --json --type public | jq -r '.version')"
for platform in ios android; do
latest="$(eas build:list --platform "$platform" --build-profile production --limit 1 --json --non-interactive | jq -r '.[0].appVersion // "none"')"
if [ "$latest" = "$version" ]; then
echo "$platform: production build for $version already exists (or is in progress)"
continue
fi
echo "$platform: latest production build is $latest, app.config.ts says $version — building"
if eas build --platform "$platform" --profile production --auto-submit --non-interactive --no-wait; then
echo ":building_construction: $platform: scheduled production build and submission for $version" >> "$GITHUB_STEP_SUMMARY"
else
failed=1
echo ":x: $platform: production build or submission failed for $version" >> "$GITHUB_STEP_SUMMARY"
fi
done
exit "$failed"
- name: Publish fingerprint-gated OTA
if: steps.expo-token.outputs.present == 'true' && github.event_name == 'push'
working-directory: apps/mobile
env:
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
run: |
message="$(git log -1 --pretty=%s | head -c 120) ($(git rev-parse --short=9 HEAD))"
for platform in ios android; do
# eas-cli prints an environment-loaded notice to stdout before the
# JSON even with --json, so discard everything before the document.
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | sed -n '/^{/,$p' | jq -er '.hash | select(type == "string" and length > 0)')"
matching="$(eas build:list --platform "$platform" --build-profile production --status finished --fingerprint-hash "$hash" --limit 1 --json --non-interactive | jq 'length')"
if [ "$matching" -gt 0 ]; then
eas update \
--channel production \
--environment production \
--platform "$platform" \
--message "$message" \
--non-interactive
echo ":white_check_mark: $platform: OTA published to production (fingerprint \`$hash\`)" >> "$GITHUB_STEP_SUMMARY"
else
echo ":warning: $platform: no finished production build matches fingerprint \`$hash\` — OTA skipped; JS changes reach $platform only once a matching build ships" >> "$GITHUB_STEP_SUMMARY"
fi
done
- name: Propagate store build failure
if: steps.store_builds.outcome == 'failure'
run: exit 1
@@ -0,0 +1,205 @@
name: Mobile Fingerprint Check
# Detects whether a PR changes the native fingerprint — i.e. whether merging
# it would leave main un-OTA-able until a new store build ships. Native-change
# PRs get the "📱 Native Change" label so they can be held and merged as a
# batch right before the next store submission, keeping main OTA-able for
# everything else in between. (Once one native PR merges, every later merge
# inherits the drifted fingerprint and loses OTA reach too — that is why the
# signal has to fire before merge, not after.)
#
# The check is advisory: it always passes, the label is the signal. Both
# fingerprints are computed in this one job (same OS, same corepack-pinned
# pnpm), so the comparison is self-consistent; no EXPO_TOKEN needed.
on:
pull_request:
paths:
- apps/mobile/**
- packages/client-runtime/**
- packages/contracts/**
- packages/shared/**
- assets/**
- scripts/**
- patches/**
- pnpm-lock.yaml
- pnpm-workspace.yaml
- .github/workflows/mobile-fingerprint-check.yml
concurrency:
group: mobile-fingerprint-check-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
fingerprint:
name: Native fingerprint diff
runs-on: blacksmith-8vcpu-ubuntu-2404
permissions:
contents: read
issues: write
pull-requests: write
env:
APP_VARIANT: production
NODE_OPTIONS: --max-old-space-size=8192
steps:
- name: Checkout
uses: actions/checkout@v6
with:
# Default pull_request checkout is the merge commit (PR applied on
# top of base), so the "head" fingerprint is the state main would
# actually be in after merging — stale branches compare cleanly.
fetch-depth: 0
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/mobile...
- name: Expose pnpm
run: |
pnpm_version="$(node --print "require('./package.json').packageManager.split('@').pop()")"
vp_pnpm_bin="$HOME/.vite-plus/package_manager/pnpm/$pnpm_version/pnpm/bin"
echo "$vp_pnpm_bin" >> "$GITHUB_PATH"
"$vp_pnpm_bin/pnpm" --version
- name: Fingerprint merge result
working-directory: apps/mobile
run: |
mkdir -p "$RUNNER_TEMP/fp/head" "$RUNNER_TEMP/fp/base"
for platform in ios android; do
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/head/$platform.json"
done
- name: Fingerprint base
run: |
git checkout --quiet "${{ github.event.pull_request.base.sha }}"
# Re-sync node_modules to the base commit's lockfile before
# fingerprinting — a dep-changing PR must not fingerprint the base
# against head's installed packages.
pnpm install --filter=@t3tools/mobile...
cd apps/mobile
for platform in ios android; do
npx expo-updates fingerprint:generate --platform "$platform" > "$RUNNER_TEMP/fp/base/$platform.json"
done
- id: compare
name: Compare fingerprints
run: |
changed=""
{
echo "## Native fingerprint diff"
echo
for platform in ios android; do
head_hash="$(jq -r .hash "$RUNNER_TEMP/fp/head/$platform.json")"
base_hash="$(jq -r .hash "$RUNNER_TEMP/fp/base/$platform.json")"
if [ "$head_hash" = "$base_hash" ]; then
echo "- ✅ **$platform**: unchanged (\`$head_hash\`) — OTA-compatible"
continue
fi
changed="$changed $platform"
echo "- 📱 **$platform**: \`$base_hash\` → \`$head_hash\` — merging requires a new native build before OTAs work again"
jq -r -n \
--slurpfile h "$RUNNER_TEMP/fp/head/$platform.json" \
--slurpfile b "$RUNNER_TEMP/fp/base/$platform.json" '
($b[0].sources | map({ (.filePath // .id): .hash }) | add // {}) as $bm
| $h[0].sources[]
| select($bm[(.filePath // .id)] != .hash)
| " - \(.type): `\(.filePath // .id)`"'
done
} >> "$GITHUB_STEP_SUMMARY"
echo "changed_platforms=${changed# }" >> "$GITHUB_OUTPUT"
- name: Sync native change label
# Fork PRs get a read-only token under pull_request; the check stays
# advisory there (summary only). This workflow must not move to
# pull_request_target — it installs and runs PR code.
if: github.event.pull_request.head.repo.full_name == github.repository
uses: actions/github-script@v8
env:
CHANGED_PLATFORMS: ${{ steps.compare.outputs.changed_platforms }}
with:
script: |
const managedLabel = {
name: "📱 Native Change",
color: "d93f0b",
description:
"Changes the native fingerprint; merging blocks production OTAs until a new store build ships.",
};
const nativeChanged = (process.env.CHANGED_PLATFORMS ?? "").trim() !== "";
const issueNumber = context.payload.pull_request.number;
try {
const { data: existing } = await github.rest.issues.getLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
});
if (
existing.color !== managedLabel.color ||
(existing.description ?? "") !== managedLabel.description
) {
await github.rest.issues.updateLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
color: managedLabel.color,
description: managedLabel.description,
});
}
} catch (error) {
if (error.status !== 404) {
throw error;
}
try {
await github.rest.issues.createLabel({
owner: context.repo.owner,
repo: context.repo.repo,
name: managedLabel.name,
color: managedLabel.color,
description: managedLabel.description,
});
} catch (createError) {
if (createError.status !== 422) {
throw createError;
}
}
}
const { data: currentLabels } = await github.rest.issues.listLabelsOnIssue({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
per_page: 100,
});
const hasLabel = currentLabels.some((label) => label.name === managedLabel.name);
if (nativeChanged && !hasLabel) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
labels: [managedLabel.name],
});
} else if (!nativeChanged && hasLabel) {
try {
await github.rest.issues.removeLabel({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: issueNumber,
name: managedLabel.name,
});
} catch (removeError) {
if (removeError.status !== 404) {
throw removeError;
}
}
}
core.info(
`PR #${issueNumber}: native fingerprint ${nativeChanged ? `changed (${process.env.CHANGED_PLATFORMS})` : "unchanged"}`,
);
+1 -1
View File
@@ -746,7 +746,7 @@ jobs:
needs: [preflight, build, publish_cli]
if: ${{ !failure() && !cancelled() && needs.preflight.result == 'success' && needs.build.result == 'success' && needs.publish_cli.result == 'success' }}
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
timeout-minutes: 30
permissions:
contents: write
steps:
+132
View File
@@ -0,0 +1,132 @@
name: Web Preview
# Label a PR `preview:web` to get a hosted-web preview deployment on Vercel for
# that push and every subsequent push. The deployment is a plain (non-prod,
# non-aliased) deploy into the existing hosted-web Vercel project, so the
# latest/nightly channel aliases are never touched.
#
# The build intentionally omits the T3 Connect cloud config (Clerk keys, relay
# URL): previews boot as the hosted-static app with manual pairing only. Pair a
# server into a preview with `t3 pair --tailscale` (or any reachable HTTPS
# backend) and open the pairing URL against the preview origin.
#
# The preview must be opened at the exact deployment URL from the PR comment.
# Vite bakes that URL in as the hosted origin (via VERCEL_URL), and
# `isHostedStaticApp` matches on origin, so branch-alias URLs will not
# self-identify as the hosted app.
on:
pull_request:
types: [labeled, synchronize, reopened]
permissions:
contents: read
pull-requests: write
concurrency:
group: web-preview-${{ github.event.pull_request.number }}
cancel-in-progress: true
jobs:
deploy:
name: Deploy web preview
# Same-repo PRs only: fork PRs do not receive the Vercel secrets, and this
# workflow should skip rather than fail for them. On `labeled` events, only
# the preview label itself triggers a deploy.
if: >-
github.event.pull_request.head.repo.full_name == github.repository &&
contains(github.event.pull_request.labels.*.name, 'preview:web') &&
(github.event.action != 'labeled' || github.event.label.name == 'preview:web')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 10
env:
VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
VERCEL_ORG_ID: ${{ secrets.VERCEL_ORG_ID }}
VERCEL_PROJECT_ID: ${{ secrets.VERCEL_PROJECT_ID }}
VERCEL_TEAM_SLUG: ${{ vars.VERCEL_TEAM_SLUG }}
steps:
- name: Checkout
uses: actions/checkout@v6
with:
ref: ${{ github.event.pull_request.head.sha }}
sparse-checkout: |
/*
!/.repos/
sparse-checkout-cone-mode: false
- name: Setup Vite+
uses: voidzero-dev/setup-vp@v1
with:
node-version-file: package.json
cache: true
run-install: |
args:
- --filter=@t3tools/scripts...
- --filter=@t3tools/web...
- id: deploy
name: Deploy preview
shell: bash
run: |
set -euo pipefail
if [[ -z "${VERCEL_TOKEN:-}" || -z "${VERCEL_ORG_ID:-}" || -z "${VERCEL_PROJECT_ID:-}" ]]; then
echo "Missing one or more required Vercel secrets: VERCEL_TOKEN, VERCEL_ORG_ID, VERCEL_PROJECT_ID." >&2
exit 1
fi
vercel_scope="${VERCEL_TEAM_SLUG:-$VERCEL_ORG_ID}"
deployment_url="$(
vp dlx [email protected] deploy \
--archive=tgz \
--yes \
--token "$VERCEL_TOKEN" \
--scope "$vercel_scope"
)"
echo "Deployed $deployment_url"
echo "deployment_url=$deployment_url" >> "$GITHUB_OUTPUT"
- name: Comment deployment URL
uses: actions/github-script@v8
env:
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment_url }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
with:
script: |
const marker = "<!-- web-preview-deploy -->";
const body = [
marker,
"### Web preview",
"",
`${process.env.DEPLOYMENT_URL} (for ${process.env.HEAD_SHA.slice(0, 7)})`,
"",
"Open this exact URL — the hosted-app origin is baked in at build time.",
"Pair a server into it with `t3 pair --tailscale`, or paste a host + pairing",
"code under Settings → Connections.",
].join("\n");
const { data: comments } = await github.rest.issues.listComments({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
per_page: 100,
});
const existing = comments.find((comment) => comment.body?.includes(marker));
if (existing) {
await github.rest.issues.updateComment({
owner: context.repo.owner,
repo: context.repo.repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
body,
});
}
-1
View File
@@ -114,7 +114,6 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
- Never make a PR unless the developer explicitly asks you to do so.
- Conventional commit titles, plain language: `fix(web): new threads no longer spike CPU`.
- Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work.
- **Rebase onto latest main before opening.** Stale branches conflict and burn a review round.
- UI changes need before/after images. Motion or timing needs a short video.
- One concern per PR. If the description says "also", split it.
- When babysitting: poll checks and comments newer than the last push, verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit.
+1
View File
@@ -68,6 +68,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Install and first run](./docs/user/install.md)
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Customize a project icon](./docs/user/project-settings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.32",
"version": "0.0.33",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -78,6 +78,7 @@ describe("DesktopLifecycle", () => {
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.void,
zoomMain: () => Effect.void,
syncAppearance: Effect.void,
});
@@ -91,6 +91,7 @@ function makePoolLayer(
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: () => Effect.die("unexpected menu action"),
zoomMain: () => Effect.die("unexpected zoom"),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]),
),
@@ -28,70 +28,6 @@ describe("ElectronDialog", () => {
showErrorBoxMock.mockReset();
});
it.effect("returns false without opening a confirm dialog for empty messages", () =>
Effect.gen(function* () {
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: " ",
owner: Option.none(),
});
assert.isFalse(result);
assert.equal(showMessageBoxMock.mock.calls.length, 0);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens a confirm dialog for the owner window", () =>
Effect.gen(function* () {
const owner = { id: 1 } as BrowserWindow;
showMessageBoxMock.mockResolvedValue({ response: 1 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.some(owner),
});
assert.isTrue(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
owner,
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("opens an app-level confirm dialog when there is no owner window", () =>
Effect.gen(function* () {
showMessageBoxMock.mockResolvedValue({ response: 0 });
const dialog = yield* ElectronDialog.ElectronDialog;
const result = yield* dialog.confirm({
message: "Delete worktree?",
owner: Option.none(),
});
assert.isFalse(result);
assert.deepEqual(showMessageBoxMock.mock.calls[0], [
{
type: "question",
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: "Delete worktree?",
},
]);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves folder picker request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("folder picker failed");
@@ -117,31 +53,6 @@ describe("ElectronDialog", () => {
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves confirmation request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("confirmation failed");
const owner = { id: 9 } as BrowserWindow;
showMessageBoxMock.mockRejectedValue(cause);
const dialog = yield* ElectronDialog.ElectronDialog;
const error = yield* Effect.flip(
dialog.confirm({
owner: Option.some(owner),
message: " Confirm removal? ",
}),
);
assert.instanceOf(error, ElectronDialog.ElectronDialogConfirmError);
assert.strictEqual(error.ownerWindowId, 9);
assert.strictEqual(error.promptLength, "Confirm removal?".length);
assert.notProperty(error, "promptMessage");
assert.strictEqual(error.cause, cause);
assert.include(error.message, "window 9");
assert.notInclude(error.message, "Confirm removal?");
assert.notInclude(error.message, cause.message);
}).pipe(Effect.provide(ElectronDialog.layer)),
);
it.effect("preserves message box request context and cause", () =>
Effect.gen(function* () {
const cause = new Error("message box failed");
@@ -6,8 +6,6 @@ import * as Schema from "effect/Schema";
import * as Electron from "electron";
const CONFIRM_BUTTON_INDEX = 1;
export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<ElectronDialogPickFolderError>()(
"ElectronDialogPickFolderError",
{
@@ -38,20 +36,6 @@ export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<Electr
}
}
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
"ElectronDialogConfirmError",
{
ownerWindowId: Schema.NullOr(Schema.Number),
promptLength: Schema.Number,
cause: Schema.Defect(),
},
) {
override get message(): string {
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
return `Failed to open an Electron confirmation dialog for ${owner} with a ${this.promptLength}-character prompt.`;
}
}
export class ElectronDialogShowMessageBoxError extends Schema.TaggedErrorClass<ElectronDialogShowMessageBoxError>()(
"ElectronDialogShowMessageBoxError",
{
@@ -85,7 +69,6 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
export const ElectronDialogError = Schema.Union([
ElectronDialogPickFolderError,
ElectronDialogPickFilesError,
ElectronDialogConfirmError,
ElectronDialogShowMessageBoxError,
ElectronDialogShowErrorBoxError,
]);
@@ -103,11 +86,6 @@ export interface ElectronDialogPickFilesInput {
readonly filters: readonly Electron.FileFilter[];
}
export interface ElectronDialogConfirmInput {
readonly owner: Option.Option<Electron.BrowserWindow>;
readonly message: string;
}
export class ElectronDialog extends Context.Service<
ElectronDialog,
{
@@ -117,9 +95,6 @@ export class ElectronDialog extends Context.Service<
readonly pickFiles: (
input: ElectronDialogPickFilesInput,
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
readonly confirm: (
input: ElectronDialogConfirmInput,
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
readonly showMessageBox: (
options: Electron.MessageBoxOptions,
) => Effect.Effect<Electron.MessageBoxReturnValue, ElectronDialogShowMessageBoxError>;
@@ -188,39 +163,6 @@ export const make = ElectronDialog.of({
});
return result.canceled ? [] : result.filePaths;
}),
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
const normalizedMessage = input.message.trim();
if (normalizedMessage.length === 0) {
return false;
}
const options = {
type: "question" as const,
buttons: ["No", "Yes"],
defaultId: 0,
cancelId: 0,
noLink: true,
message: normalizedMessage,
};
const ownerWindowId = Option.match(input.owner, {
onNone: () => null,
onSome: (owner) => owner.id,
});
const result = yield* Effect.tryPromise({
try: () =>
Option.match(input.owner, {
onNone: () => Electron.dialog.showMessageBox(options),
onSome: (owner) => Electron.dialog.showMessageBox(owner, options),
}),
catch: (cause) =>
new ElectronDialogConfirmError({
ownerWindowId,
promptLength: normalizedMessage.length,
cause,
}),
});
return result.response === CONFIRM_BUTTON_INDEX;
}),
showMessageBox: (options) =>
Effect.tryPromise({
try: () => Electron.dialog.showMessageBox(options),
@@ -31,7 +31,6 @@ import {
setUpdateChannel,
} from "./methods/updates.ts";
import {
confirm,
getAppBranding,
getLocalEnvironmentBootstraps,
getLocalEnvironmentBearerToken,
@@ -81,7 +80,6 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
yield* ipc.handle(pickFolder);
yield* ipc.handle(pickThemeFiles);
yield* ipc.handle(confirm);
yield* ipc.handle(setTheme);
yield* ipc.handle(showContextMenu);
yield* ipc.handle(openExternal);
-1
View File
@@ -1,6 +1,5 @@
export const PICK_FOLDER_CHANNEL = "desktop:pick-folder";
export const PICK_THEME_FILES_CHANNEL = "desktop:pick-theme-files";
export const CONFIRM_CHANNEL = "desktop:confirm";
export const SET_THEME_CHANNEL = "desktop:set-theme";
export const CONTEXT_MENU_CHANNEL = "desktop:context-menu";
export const OPEN_EXTERNAL_CHANNEL = "desktop:open-external";
-13
View File
@@ -220,19 +220,6 @@ export const pickFolder = DesktopIpc.makeIpcMethod({
}),
});
export const confirm = DesktopIpc.makeIpcMethod({
channel: IpcChannels.CONFIRM_CHANNEL,
payload: Schema.String,
result: Schema.Boolean,
handler: Effect.fn("desktop.ipc.window.confirm")(function* (message) {
const dialog = yield* ElectronDialog.ElectronDialog;
const electronWindow = yield* ElectronWindow.ElectronWindow;
return yield* electronWindow.focusedMainOrFirst.pipe(
Effect.flatMap((owner) => dialog.confirm({ owner, message })),
);
}),
});
export const setTheme = DesktopIpc.makeIpcMethod({
channel: IpcChannels.SET_THEME_CHANNEL,
payload: DesktopThemeSchema,
-1
View File
@@ -98,7 +98,6 @@ contextBridge.exposeInMainWorld("desktopBridge", {
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
pickThemeFiles: () => ipcRenderer.invoke(IpcChannels.PICK_THEME_FILES_CHANNEL, undefined),
confirm: (message) => ipcRenderer.invoke(IpcChannels.CONFIRM_CHANNEL, message),
setTheme: (theme) => ipcRenderer.invoke(IpcChannels.SET_THEME_CHANNEL, theme),
showContextMenu: (items, position) =>
ipcRenderer.invoke(IpcChannels.CONTEXT_MENU_CHANNEL, {
@@ -32,6 +32,7 @@ const clientSettings: ClientSettings = {
planModeEnabled: false,
providerModelPreferences: {},
sidebarAutoSettleAfterDays: 3,
sidebarAutoSettleOnMerge: true,
sidebarProjectGroupingMode: "repository_path",
sidebarProjectGroupingOverrides: {
"environment-1:/tmp/project-a": "separate",
@@ -39,8 +40,7 @@ const clientSettings: ClientSettings = {
sidebarProjectSortOrder: "manual",
sidebarThreadSortOrder: "created_at",
sidebarThreadPreviewCount: 6,
sidebarV2Enabled: false,
sidebarV2ConfiguredByUser: false,
legacySidebarEnabled: false,
timestampFormat: "24-hour",
wordWrap: true,
};
@@ -231,6 +231,7 @@ describe("DesktopShellEnvironment", () => {
"C:\\Users\\testuser\\AppData\\Local\\Programs\\nodejs",
"C:\\Users\\testuser\\AppData\\Local\\Volta\\bin",
"C:\\Users\\testuser\\AppData\\Local\\pnpm",
"C:\\Users\\testuser\\.local\\bin",
"C:\\Users\\testuser\\.bun\\bin",
"C:\\Users\\testuser\\scoop\\shims",
"C:\\Custom\\Bin",
@@ -207,7 +207,7 @@ const knownWindowsCliDirs = (env: NodeJS.ProcessEnv): ReadonlyArray<string> => [
...trimNonEmpty(env.USERPROFILE).pipe(
Option.match({
onNone: () => [],
onSome: (value) => [`${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
onSome: (value) => [`${value}\\.local\\bin`, `${value}\\.bun\\bin`, `${value}\\scoop\\shims`],
}),
),
];
@@ -379,10 +379,18 @@ const installWindowsEnvironment = Effect.fn("desktop.shellEnvironment.installWin
function* (
config: ShellEnvironmentConfig,
): Effect.fn.Return<void, never, ChildProcessSpawner.ChildProcessSpawner> {
const noProfile = yield* readWindowsEnvironment(["PATH"], { loadProfile: false });
const profile = yield* readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, {
loadProfile: true,
});
// Concurrent, not sequential: these two probes are independent (only their
// results are combined below) and each spawns its own PowerShell. Run in
// series they sit at offset 0 of desktop.startup, before anything else, and
// launch traces measured them at 2718ms then 2066ms — the entire 4.8s
// startup span, of which desktop.bootstrap is ~30ms.
const [noProfile, profile] = yield* Effect.all(
[
readWindowsEnvironment(["PATH"], { loadProfile: false }),
readWindowsEnvironment(WINDOWS_PROFILE_ENV_NAMES, { loadProfile: true }),
],
{ concurrency: 2 },
);
const mergedPath = mergePaths("win32", [
trimNonEmpty(profile.PATH),
trimNonEmpty(knownWindowsCliDirs(config.env).join(";")),
@@ -53,7 +53,6 @@ const electronAppLayer = Layer.succeed(ElectronApp.ElectronApp, {
const electronDialogLayer = Layer.succeed(ElectronDialog.ElectronDialog, {
pickFolder: () => Effect.succeed(Option.none()),
pickFiles: () => Effect.succeed([]),
confirm: () => Effect.succeed(false),
showMessageBox: () => Effect.succeed({ response: 0, checkboxChecked: false }),
showErrorBox: () => Effect.void,
} satisfies ElectronDialog.ElectronDialog["Service"]);
@@ -81,6 +80,8 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
handleBackendNotReady: Effect.void,
flushMainWindowBounds: Effect.void,
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
zoomMain: (direction) =>
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
syncAppearance: Effect.void,
} satisfies DesktopWindow.DesktopWindow["Service"]);
@@ -94,6 +95,30 @@ const makeElectronMenuLayer = (
showContextMenu: () => Effect.succeed(Option.none()),
} satisfies ElectronMenu.ElectronMenu["Service"]);
const configureMenu = (
selectedAction: Deferred.Deferred<string>,
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
) =>
Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
describe("DesktopApplicationMenu", () => {
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
Effect.gen(function* () {
@@ -101,25 +126,7 @@ describe("DesktopApplicationMenu", () => {
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* Effect.gen(function* () {
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
yield* menu.configure;
}).pipe(
Effect.provide(
DesktopApplicationMenu.layer.pipe(
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
Layer.provideMerge(desktopUpdatesLayer),
Layer.provideMerge(electronDialogLayer),
Layer.provideMerge(electronAppLayer),
Layer.provideMerge(
DesktopEnvironment.layer(environmentInput).pipe(
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
),
),
),
),
);
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const fileMenu = template.find((item) => item.label === "File");
@@ -138,4 +145,38 @@ describe("DesktopApplicationMenu", () => {
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
}),
);
// Zoom must route through DesktopWindow.zoomMain instead of the Electron
// zoom roles: the roles zoom whichever webContents has focus, which breaks
// app zoom while an embedded preview WebContentsView holds focus.
it.effect("routes View menu zoom to the main window instead of zoom roles", () =>
Effect.gen(function* () {
const selectedAction = yield* Deferred.make<string>();
const applicationMenuTemplate =
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
yield* configureMenu(selectedAction, applicationMenuTemplate);
const template = yield* Deferred.await(applicationMenuTemplate);
const viewMenu = template.find((item) => item.label === "View");
assert.isDefined(viewMenu);
if (!Array.isArray(viewMenu.submenu)) {
throw new Error("Expected View menu submenu to be an array.");
}
assert.isUndefined(
viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")),
);
const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In");
assert.isDefined(zoomIn);
assert.equal(zoomIn.accelerator, "CmdOrCtrl+=");
if (typeof zoomIn.click !== "function") {
throw new Error("Expected Zoom In menu item to have a click handler.");
}
zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
}),
);
});
@@ -49,6 +49,13 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
yield* desktopWindow.dispatchMenuAction(action);
});
const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
direction: DesktopWindow.MainWindowZoomDirection,
): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
const desktopWindow = yield* DesktopWindow.DesktopWindow;
yield* desktopWindow.zoomMain(direction);
});
const checkForUpdatesFromMenu = Effect.gen(function* () {
const updates = yield* DesktopUpdates.DesktopUpdates;
const electronDialog = yield* ElectronDialog.ElectronDialog;
@@ -127,6 +134,9 @@ export const make = Effect.gen(function* () {
const settingsClick = () => {
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
};
const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
};
const template: Electron.MenuItemConstructorOptions[] = [];
if (environment.platform === "darwin") {
@@ -181,10 +191,21 @@ export const make = Effect.gen(function* () {
{ role: "forceReload" },
{ role: "toggleDevTools" },
{ type: "separator" },
{ role: "resetZoom" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
{ role: "zoomOut" },
/*
Not the zoom roles: those act on the focused webContents, so with
an embedded preview WebContentsView focused they zoom the guest
page and the app UI appears stuck. These always zoom the main
window (see DesktopWindow.zoomMain).
*/
{ label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
{ label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
{
label: "Zoom In",
accelerator: "CmdOrCtrl+Plus",
visible: false,
click: zoomClick("in"),
},
{ label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
{ type: "separator" },
{ role: "togglefullscreen" },
],
+20
View File
@@ -61,6 +61,8 @@ export type DesktopWindowError =
| ElectronWindow.ElectronWindowCreateError
| PreviewManager.PreviewManagerError;
export type MainWindowZoomDirection = "in" | "out" | "reset";
export class DesktopWindow extends Context.Service<
DesktopWindow,
{
@@ -87,6 +89,12 @@ export class DesktopWindow extends Context.Service<
readonly handleBackendNotReady: Effect.Effect<void>;
readonly flushMainWindowBounds: Effect.Effect<void>;
readonly dispatchMenuAction: (action: string) => Effect.Effect<void, DesktopWindowError>;
// Zooms the main window's own webContents. The Electron `zoomIn`/`zoomOut`
// menu roles act on whichever webContents has keyboard focus, so with an
// embedded preview WebContentsView (or DevTools) focused they zoom the
// guest page instead of the app UI. The menu routes here to always target
// the main window.
readonly zoomMain: (direction: MainWindowZoomDirection) => Effect.Effect<void>;
readonly syncAppearance: Effect.Effect<void>;
}
>()("@t3tools/desktop/window/DesktopWindow") {}
@@ -836,6 +844,18 @@ export const make = Effect.gen(function* () {
send();
}),
zoomMain: Effect.fn("desktop.window.zoomMain")(function* (direction) {
yield* Effect.annotateCurrentSpan({ direction });
const window = yield* focusedMainWindow;
if (Option.isNone(window) || window.value.isDestroyed()) {
return;
}
const webContents = window.value.webContents;
// Same step size as the Electron zoomIn/zoomOut menu roles.
webContents.setZoomLevel(
direction === "reset" ? 0 : webContents.getZoomLevel() + (direction === "in" ? 0.5 : -0.5),
);
}),
syncAppearance: Effect.gen(function* () {
const shouldUseDarkColors = yield* electronTheme.shouldUseDarkColors;
yield* electronWindow.syncAllAppearance((window) =>
+2 -1
View File
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
slug: "t3-code",
platforms: ["ios", "android"],
scheme: variant.scheme,
version: "1.0.2",
version: "1.0.3",
runtimeVersion: {
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
// project — native deps, config plugins, AND patches/ — matches the update.
@@ -338,6 +338,7 @@ const config: ExpoConfig = {
"./plugins/withAndroidModernPopupMenu.cjs",
"./plugins/withAndroidModernAlertDialog.cjs",
"./plugins/withAndroidPredictiveBackCompat.cjs",
"./plugins/withAndroidTabletOrientation.cjs",
...(isIosPersonalTeamBuild ? ["./plugins/withoutIosPersonalTeamCapabilities.cjs"] : []),
],
extra: {
@@ -4,16 +4,13 @@ import type { MarkdownNode } from "react-native-nitro-markdown/headless";
import { CopyTextButton } from "./CopyTextButton";
import { MarkdownTextPrimitive } from "./MarkdownTextPrimitive";
import {
nativeMarkdownDocumentRuns,
nativeMarkdownListItemBlocks,
nativeMarkdownTextRuns,
} from "./nativeMarkdownText";
import { nativeMarkdownDocumentRuns, nativeMarkdownListItemBlocks } from "./nativeMarkdownText";
import { NativeMarkdownSelectableText } from "./NativeMarkdownSelectableText.ios";
import type {
MarkdownCodeHighlighter,
MarkdownHighlightedToken,
NativeMarkdownTextStyle,
SelectableMarkdownSkill,
} from "./SelectableMarkdownText.types";
type HighlightedCode = ReadonlyArray<ReadonlyArray<MarkdownHighlightedToken>>;
@@ -48,12 +45,13 @@ function documentFor(node: MarkdownNode): MarkdownNode {
function SelectableNode(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
return (
<NativeMarkdownSelectableText
runs={nativeMarkdownDocumentRuns(documentFor(props.node))}
runs={nativeMarkdownDocumentRuns(documentFor(props.node), props.skills)}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -322,6 +320,7 @@ function collectTableRows(node: MarkdownNode): MarkdownNode[] {
function NativeTable(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
@@ -359,7 +358,7 @@ function NativeTable(props: {
}}
>
<NativeMarkdownSelectableText
runs={nativeMarkdownTextRuns(cell).map((run) =>
runs={nativeMarkdownDocumentRuns(documentFor(cell), props.skills).map((run) =>
rowIndex === 0 || cell.isHeader ? { ...run, bold: true } : run,
)}
textStyle={props.textStyle}
@@ -376,6 +375,7 @@ function NativeTable(props: {
function NativeMarkdownImage(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
@@ -384,6 +384,7 @@ function NativeMarkdownImage(props: {
return (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -445,6 +446,7 @@ function inlineGroups(nodes: ReadonlyArray<MarkdownNode>): MarkdownNode[] {
function NativeMixedParagraph(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly onLinkPress?: (href: string) => void;
}) {
@@ -455,6 +457,7 @@ function NativeMixedParagraph(props: {
<NativeMarkdownImage
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -462,6 +465,7 @@ function NativeMixedParagraph(props: {
<SelectableNode
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -473,6 +477,7 @@ function NativeMixedParagraph(props: {
function NativeList(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
@@ -534,6 +539,7 @@ function NativeList(props: {
<NativeMarkdownBlock
key={nodeKey(child, childIndex)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -551,6 +557,7 @@ function NativeList(props: {
export function NativeMarkdownBlock(props: {
readonly node: MarkdownNode;
readonly skills: ReadonlyArray<SelectableMarkdownSkill>;
readonly textStyle: NativeMarkdownTextStyle;
readonly highlightCode: MarkdownCodeHighlighter;
readonly onLinkPress?: (href: string) => void;
@@ -566,6 +573,7 @@ export function NativeMarkdownBlock(props: {
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -587,6 +595,7 @@ export function NativeMarkdownBlock(props: {
return (
<NativeTable
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -595,6 +604,7 @@ export function NativeMarkdownBlock(props: {
return (
<NativeMarkdownImage
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -624,6 +634,7 @@ export function NativeMarkdownBlock(props: {
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -637,6 +648,7 @@ export function NativeMarkdownBlock(props: {
return (
<NativeList
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -647,12 +659,14 @@ export function NativeMarkdownBlock(props: {
return (props.node.children ?? []).some((child) => child.type === "image") ? (
<NativeMixedParagraph
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
) : (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -673,6 +687,7 @@ export function NativeMarkdownBlock(props: {
>
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -690,6 +705,7 @@ export function NativeMarkdownBlock(props: {
<NativeMarkdownBlock
key={nodeKey(child, index)}
node={child}
skills={props.skills}
textStyle={props.textStyle}
highlightCode={props.highlightCode}
onLinkPress={props.onLinkPress}
@@ -703,6 +719,7 @@ export function NativeMarkdownBlock(props: {
return (
<SelectableNode
node={props.node}
skills={props.skills}
textStyle={props.textStyle}
onLinkPress={props.onLinkPress}
/>
@@ -69,6 +69,7 @@ export function SelectableMarkdownText({
chunk.kind === "rich" ? (
<NativeMarkdownBlock
node={chunk.node}
skills={skills}
textStyle={textStyle}
highlightCode={highlightCode}
onLinkPress={onLinkPress}
@@ -70,15 +70,22 @@ const EMPTY_CONTEXT: RunContext = {
const INLINE_HTML_TAG_PATTERN = /<\/?(?:kbd|mark|sub|sup|u)(?:\s[^>]*)?>/gi;
function decodeCodePoint(codePoint: number, entity: string): string {
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
return entity;
}
return String.fromCodePoint(codePoint);
}
function decodeHtmlEntitiesOnce(value: string): string {
return value.replace(
/&(?:#(\d+)|#x([0-9a-f]+)|amp|apos|gt|lt|nbsp|quot);/gi,
(entity, decimal: string | undefined, hexadecimal: string | undefined) => {
if (decimal) {
return String.fromCodePoint(Number.parseInt(decimal, 10));
return decodeCodePoint(Number.parseInt(decimal, 10), entity);
}
if (hexadecimal) {
return String.fromCodePoint(Number.parseInt(hexadecimal, 16));
return decodeCodePoint(Number.parseInt(hexadecimal, 16), entity);
}
switch (entity.toLowerCase()) {
case "&amp;":
@@ -661,6 +668,7 @@ function appendDocumentBlock(
function containsRichBlock(node: MarkdownNode): boolean {
if (
node.type === "code_block" ||
node.type === "blockquote" ||
node.type === "table" ||
node.type === "image" ||
node.type === "horizontal_rule" ||
@@ -1,97 +0,0 @@
package expo.modules.t3nativecontrols
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View
import expo.modules.kotlin.AppContext
import expo.modules.kotlin.viewevent.EventDispatcher
import expo.modules.kotlin.views.ExpoView
class T3HeaderButtonView(context: Context, appContext: AppContext) : ExpoView(context, appContext) {
private val iconView = HeaderIconView(context)
private val onTriggered by EventDispatcher()
init {
isClickable = true
isFocusable = true
setOnClickListener {
onTriggered(emptyMap<String, Any>())
}
addView(iconView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
}
fun setLabel(label: String) {
contentDescription = label
}
fun setSystemImage(systemImage: String) {
iconView.systemImage = systemImage
}
}
private class HeaderIconView(context: Context) : View(context) {
private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
color = Color.parseColor("#6B7280")
strokeCap = Paint.Cap.ROUND
strokeJoin = Paint.Join.ROUND
strokeWidth = 3f * resources.displayMetrics.density
style = Paint.Style.STROKE
}
var systemImage: String = "gearshape"
set(value) {
field = value
invalidate()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val cx = width / 2f
val cy = height / 2f
val size = minOf(width, height).toFloat()
if (systemImage == "square.and.pencil") {
drawNewTask(canvas, cx, cy, size)
} else {
drawSettings(canvas, cx, cy, size)
}
}
private fun drawSettings(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val radius = size * 0.12f
canvas.drawCircle(cx, cy, radius, paint)
for (index in 0 until 8) {
val angle = Math.PI * index / 4.0
val inner = size * 0.19f
val outer = size * 0.27f
val sx = cx + kotlin.math.cos(angle).toFloat() * inner
val sy = cy + kotlin.math.sin(angle).toFloat() * inner
val ex = cx + kotlin.math.cos(angle).toFloat() * outer
val ey = cy + kotlin.math.sin(angle).toFloat() * outer
canvas.drawLine(sx, sy, ex, ey, paint)
}
}
private fun drawNewTask(canvas: Canvas, cx: Float, cy: Float, size: Float) {
val left = cx - size * 0.2f
val top = cy - size * 0.16f
val right = cx + size * 0.14f
val bottom = cy + size * 0.2f
canvas.drawRoundRect(left, top, right, bottom, size * 0.04f, size * 0.04f, paint)
canvas.drawLine(
cx - size * 0.02f,
cy + size * 0.13f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
canvas.drawLine(
cx + size * 0.17f,
cy - size * 0.2f,
cx + size * 0.24f,
cy - size * 0.13f,
paint
)
}
}
@@ -32,16 +32,5 @@ class T3NativeControlsModule : Module() {
?.resolve("t3-showcase-ready")
?.writeText(scene)
}
View(T3HeaderButtonView::class) {
Prop("label") { view: T3HeaderButtonView, label: String ->
view.setLabel(label)
}
Prop("systemImage") { view: T3HeaderButtonView, systemImage: String ->
view.setSystemImage(systemImage)
}
Events("onTriggered")
}
}
}
@@ -1,62 +0,0 @@
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()
}
}
@@ -87,16 +87,5 @@ public final class T3NativeControlsModule: Module {
let readyPath = NSHomeDirectory() + "/Library/Caches/T3ShowcaseReadyScene"
try? scene.write(toFile: readyPath, atomically: true, encoding: .utf8)
}
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")
}
}
}
+1 -1
View File
@@ -49,7 +49,7 @@
"@expo-google-fonts/dm-sans": "^0.4.2",
"@expo/metro-runtime": "~56.0.15",
"@expo/ui": "~56.0.18",
"@legendapp/list": "3.3.3",
"@legendapp/list": "catalog:",
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
@@ -0,0 +1,80 @@
const { withMainActivity } = require("expo/config-plugins");
// The top-level `orientation: "portrait"` writes android:screenOrientation="portrait"
// into the manifest, which locks every Android device — including tablets — to
// portrait. iOS doesn't have this problem: iPads must support all orientations
// because the app is multitasking-capable, so only iPhones end up portrait-only.
// Mirror that split on Android: keep the manifest lock for phones and lift it at
// runtime on tablets (smallest width >= 600dp, the standard tablet breakpoint),
// since requestedOrientation set at runtime overrides the manifest value.
// FULL_USER allows all four orientations while still respecting the user's
// auto-rotate lock, matching iPad behavior. Foldables change
// smallestScreenWidthDp on fold/unfold without recreating the activity
// (smallestScreenSize is in the manifest's configChanges), so the policy is
// re-evaluated in onConfigurationChanged: unfolding past the tablet breakpoint
// unlocks rotation, and folding back restores the portrait lock.
const ORIENTATION_METHODS = `
// Applied in onCreate and re-applied on fold/unfold; added by
// withAndroidTabletOrientation.
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
applyTabletOrientation()
}
private fun applyTabletOrientation() {
requestedOrientation = if (resources.configuration.smallestScreenWidthDp >= 600) {
ActivityInfo.SCREEN_ORIENTATION_FULL_USER
} else {
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
`;
const ORIENTATION_ON_CREATE_CALL = `
applyTabletOrientation()`;
function insertAfter(contents, anchor, insertion, description) {
const index = contents.indexOf(anchor);
if (index === -1) {
throw new Error(
`withAndroidTabletOrientation: could not find ${description} in MainActivity — the Expo template changed; update the plugin anchors.`,
);
}
const end = index + anchor.length;
return contents.slice(0, end) + insertion + contents.slice(end);
}
module.exports = function withAndroidTabletOrientation(config) {
return withMainActivity(config, (nextConfig) => {
let contents = nextConfig.modResults.contents;
if (nextConfig.modResults.language !== "kt") {
throw new Error("withAndroidTabletOrientation: MainActivity must be Kotlin.");
}
if (contents.includes("SCREEN_ORIENTATION_FULL_USER")) {
return nextConfig;
}
contents = insertAfter(
contents,
"import android.os.Bundle",
"\nimport android.content.pm.ActivityInfo\nimport android.content.res.Configuration",
"the android.os.Bundle import",
);
contents = insertAfter(
contents,
"class MainActivity : ReactActivity() {",
ORIENTATION_METHODS,
"the MainActivity class declaration",
);
contents = insertAfter(
contents,
"super.onCreate(null)",
ORIENTATION_ON_CREATE_CALL,
"the super.onCreate call",
);
nextConfig.modResults.contents = contents;
return nextConfig;
});
};
+28 -13
View File
@@ -18,7 +18,6 @@ import { AppText as Text } from "./components/AppText";
import { getCompactBrandHeaderOptions } from "./components/CompactBrandTitle";
import { ArchivedThreadsRouteScreen } from "./features/archive/ArchivedThreadsRouteScreen";
import { useAgentNotificationNavigation } from "./features/agent-awareness/notificationNavigation";
import { ClerkSettingsSheetDetentProvider } from "./features/cloud/ClerkSettingsSheetDetent";
import { ConnectOnboardingRouteScreen } from "./features/cloud/ConnectOnboardingRouteScreen";
import { useConnectOnboardingNavigation } from "./features/cloud/connectOnboardingNavigation";
import { ThreadFilesTreeScreen, ThreadFileScreen } from "./features/files/ThreadFilesRouteScreen";
@@ -48,6 +47,7 @@ import { SettingsAuthRouteScreen } from "./features/settings/SettingsAuthRouteSc
import { SettingsEnvironmentsRouteScreen } from "./features/settings/SettingsEnvironmentsRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsProjectGroupingRouteScreen } from "./features/settings/SettingsProjectGroupingRouteScreen";
import { UsageRouteScreen } from "./features/usage/UsageRouteScreen";
import { SettingsRouteScreen } from "./features/settings/SettingsRouteScreen";
import { ShowcaseCaptureCoordinator } from "./features/showcase/ShowcaseCaptureCoordinator";
import {
@@ -133,7 +133,7 @@ const LEGAL_DOCUMENT_HEADER_OPTIONS: AppScreenOptions = {
presentation: "fullScreenModal",
};
const SettingsSheetStack = createNativeStackNavigator({
const SettingsContentStack = createNativeStackNavigator({
initialRouteName: "Settings",
screenOptions: {
...GLASS_HEADER_OPTIONS,
@@ -190,20 +190,37 @@ const SettingsSheetStack = createNativeStackNavigator({
title: "Client Storage",
},
}),
SettingsUsage: createNativeStackScreen({
screen: UsageRouteScreen,
linking: "usage",
options: {
title: "Usage",
},
}),
},
});
// The outer stack never owns visible chrome. Settings routes render inside a
// nested stack whose native header remains mounted, while Clerk owns auth chrome.
// Keeping bar visibility invariant avoids iOS 26's headerless-to-headered jump.
const SettingsSheetStack = createNativeStackNavigator({
initialRouteName: "SettingsContent",
screenOptions: {
headerShown: false,
},
screens: {
SettingsContent: createNativeStackScreen({
screen: SettingsContentStack,
linking: "",
}),
SettingsAuth: createNativeStackScreen({
screen: SettingsAuthRouteScreen,
linking: "auth",
options: {
title: "Sign in",
},
}),
SettingsWaitlist: createNativeStackScreen({
// Keep the old deep link working after the Connect GA launch.
screen: SettingsAuthRouteScreen,
linking: "waitlist",
options: {
title: "Sign in",
},
}),
},
});
@@ -339,11 +356,9 @@ function RootStackLayout(props: {
<HardwareKeyboardCommandProvider pathname={pathname}>
<ThreadOutboxDrainWorker />
<ShowcaseCaptureCoordinator pathname={pathname} />
<ClerkSettingsSheetDetentProvider initiallyExpanded={false}>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</ClerkSettingsSheetDetentProvider>
<AdaptiveWorkspaceLayout pathname={workspacePathname}>
{props.children}
</AdaptiveWorkspaceLayout>
</HardwareKeyboardCommandProvider>
);
}
+2
View File
@@ -14,6 +14,7 @@ import {
IconBellRinging,
IconBolt,
IconCamera,
IconChartBar,
IconCheck,
IconChevronDown,
IconCode,
@@ -97,6 +98,7 @@ const ANDROID_ICON_BY_SF_SYMBOL: Partial<Record<SFSymbol, Icon>> = {
"bolt.circle": IconBolt,
"bolt.horizontal.circle": IconBolt,
camera: IconCamera,
"chart.bar.xaxis": IconChartBar,
checkmark: IconCheck,
"checkmark.circle": IconCircleCheck,
clock: IconClock,
+43 -2
View File
@@ -6,6 +6,7 @@ import {
type ComponentProps,
type ReactElement,
type ReactNode,
useRef,
} from "react";
import { Platform, Pressable, useColorScheme, View } from "react-native";
import { useThemeColor } from "../lib/useThemeColor";
@@ -21,10 +22,31 @@ export function ControlPill(props: {
readonly label?: string;
readonly accessibilityLabel?: string;
readonly onPress?: () => void;
readonly activateOnPressIn?: boolean;
readonly variant?: "circle" | "pill" | "primary" | "danger";
readonly disabled?: boolean;
readonly className?: string;
}) {
const variant = props.variant ?? "circle";
const activatedOnPressInRef = useRef(false);
const handlePressIn = () => {
activatedOnPressInRef.current = true;
props.onPress?.();
};
const handlePressOut = () => {
// Pressability invokes onPressOut immediately before onPress on release.
// Defer the reset so onPress can identify the same physical gesture.
setTimeout(() => {
activatedOnPressInRef.current = false;
}, 0);
};
const handlePress = () => {
if (activatedOnPressInRef.current) {
return;
}
props.onPress?.();
};
const iconColor = useThemeColor("--color-icon");
const iconSubtle = useThemeColor("--color-icon-subtle");
@@ -54,6 +76,7 @@ export function ControlPill(props: {
: variant === "danger"
? "bg-danger"
: "bg-subtle",
props.className,
);
const labelClassName = cn(
"text-center text-xs font-t3-bold",
@@ -68,7 +91,9 @@ export function ControlPill(props: {
<Pressable
accessibilityLabel={props.accessibilityLabel ?? props.label}
accessibilityRole="button"
onPress={props.onPress}
onPress={props.activateOnPressIn ? handlePress : props.onPress}
onPressIn={props.activateOnPressIn ? handlePressIn : undefined}
onPressOut={props.activateOnPressIn ? handlePressOut : undefined}
disabled={props.disabled}
className={containerClassName}
>
@@ -133,9 +158,25 @@ export function ControlPillMenu(
}
const { className: _className, ...menuProps } = props;
let children = menuProps.children;
// In long-press mode the wrapped pressable still receives the touch (the
// patched MenuView button is touch-transparent) and RN's Fabric touch
// handler is never cancelled by the in-tree UIContextMenuInteraction, so a
// bare onPress would fire on finger-up even after the menu opened — and
// also on a long press released just under the menu threshold. A dispatched
// onLongPress makes Pressability swallow the release, so holds past 350ms
// (below the ~500ms context-menu threshold) can only open the menu, never
// tap through.
if (props.shouldOpenOnLongPress && isValidElement(children)) {
const child = children as ReactElement<{ onLongPress?: () => void; delayLongPress?: number }>;
children = cloneElement(child, {
onLongPress: child.props.onLongPress ?? (() => undefined),
delayLongPress: child.props.delayLongPress ?? 350,
});
}
return (
<MenuView {...menuProps} themeVariant={isDarkMode ? "dark" : "light"}>
{menuProps.children}
{children}
</MenuView>
);
}
@@ -24,13 +24,18 @@ export function ProjectFavicon(props: {
readonly size?: number;
readonly projectTitle: string;
readonly workspaceRoot?: string | null;
readonly faviconPath?: string | null;
}) {
const size = props.size ?? 42;
const faviconUrl = useAssetUrl(
props.environmentId,
props.workspaceRoot === null || props.workspaceRoot === undefined
? null
: { _tag: "project-favicon", cwd: props.workspaceRoot },
: {
_tag: "project-favicon",
cwd: props.workspaceRoot,
...(props.faviconPath ? { path: props.faviconPath } : {}),
},
);
const renderableFaviconUrl = isProjectFaviconFallbackUrl(faviconUrl) ? null : faviconUrl;
const cacheKey =
@@ -5,7 +5,6 @@ import { useFocusEffect } from "@react-navigation/native";
import { useCallback, useMemo, useState } from "react";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { useArchivedThreadListActions } from "../home/useThreadListActions";
import {
ArchivedThreadsScreen,
@@ -18,7 +17,6 @@ import {
} from "./useArchivedThreadSnapshots";
export function ArchivedThreadsRouteScreen() {
const { expand } = useClerkSettingsSheetDetent();
const { savedConnectionsById } = useSavedRemoteConnections();
const [searchQuery, setSearchQuery] = useState("");
const [selectedEnvironmentId, setSelectedEnvironmentId] = useState<EnvironmentId | null>(null);
@@ -70,9 +68,8 @@ export function ArchivedThreadsRouteScreen() {
useFocusEffect(
useCallback(() => {
expand();
refresh();
}, [expand, refresh]),
}, [refresh]),
);
return (
@@ -368,6 +368,7 @@ function ProjectGroupLabel(props: {
<View className="flex-row items-center gap-2.5 px-1 pb-2">
<ProjectFavicon
environmentId={props.project.environmentId}
faviconPath={props.project.faviconPath}
projectTitle={props.project.title}
size={18}
workspaceRoot={props.project.workspaceRoot}
@@ -1,44 +0,0 @@
import {
createContext,
type PropsWithChildren,
useCallback,
useContext,
useMemo,
useState,
} from "react";
interface ClerkSettingsSheetDetentValue {
collapse: () => void;
expand: () => void;
isExpanded: boolean;
}
const ClerkSettingsSheetDetentContext = createContext<ClerkSettingsSheetDetentValue | null>(null);
interface ClerkSettingsSheetDetentProviderProps extends PropsWithChildren {
initiallyExpanded: boolean;
}
export function ClerkSettingsSheetDetentProvider({
children,
initiallyExpanded,
}: ClerkSettingsSheetDetentProviderProps) {
const [isExpanded, setIsExpanded] = useState(initiallyExpanded);
const collapse = useCallback(() => setIsExpanded(false), []);
const expand = useCallback(() => setIsExpanded(true), []);
const value = useMemo(() => ({ collapse, expand, isExpanded }), [collapse, expand, isExpanded]);
return (
<ClerkSettingsSheetDetentContext value={value}>{children}</ClerkSettingsSheetDetentContext>
);
}
export function useClerkSettingsSheetDetent(): ClerkSettingsSheetDetentValue {
const value = useContext(ClerkSettingsSheetDetentContext);
if (!value) {
throw new Error(
"useClerkSettingsSheetDetent must be used inside ClerkSettingsSheetDetentProvider",
);
}
return value;
}
@@ -6,8 +6,8 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { clearConnectOnboardingRequest, connectOnboardingRequestAtom } from "./connectOnboarding";
import { isConnectOnboardingOptedOut } from "./connectOnboardingOptOut";
// Sign-in happens inside the Settings sheet; give its detent/session-state
// transitions a beat to settle before presenting another formSheet on top.
// Sign-in happens inside the Settings sheet; give its session-state transition
// a beat to settle before presenting another formSheet on top.
const PRESENT_ONBOARDING_DELAY_MS = 600;
/**
@@ -45,6 +45,7 @@ export function HomeRouteScreen() {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -134,7 +135,10 @@ export function HomeRouteScreen() {
<NativeStackScreenOptions
options={getConnectionAwareBrandHeaderOptions({
onOpenEnvironments: () =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
}),
})}
/>
<HomeHeader
@@ -148,9 +152,17 @@ export function HomeRouteScreen() {
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenEnvironments={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
})
}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
@@ -161,7 +173,10 @@ export function HomeRouteScreen() {
catalogState={catalogState}
environments={environments}
onAddConnection={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
@@ -172,9 +187,15 @@ export function HomeRouteScreen() {
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onRegenerateThreadTitle={regenerateThreadTitle}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
onOpenSettings={() =>
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
})
}
onProjectSortOrderChange={setProjectSortOrder}
onSearchQueryChange={setSearchQuery}
onSelectThread={(thread) => {
+31 -2
View File
@@ -115,6 +115,7 @@ interface HomeScreenProps {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -206,6 +207,9 @@ export function HomeScreen(props: HomeScreenProps) {
>(() => new Map());
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled();
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const openSwipeableRef = useRef<SwipeableMethods | null>(null);
const listRef = useRef<LegendListRef | null>(null);
@@ -482,8 +486,8 @@ export function HomeScreen(props: HomeScreenProps) {
// Settled threads stay in the live shell stream (settled ≠ archived), so
// the partition works directly off live shells — no snapshot merging or
// optimistic holds.
// PR states stream in per-row (rows own the VCS subscriptions); a merged or
// closed PR auto-settles its thread on the next partition (mirrors web).
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule, matching web.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
@@ -538,6 +542,12 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onUnpinThread],
);
const handleRegenerateThreadTitle = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onRegenerateThreadTitle(thread);
},
[props.onRegenerateThreadTitle],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -615,6 +625,15 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order (reorder-capable threads only) for the
// Move up/down position flags. Computed from all shells, not the rendered
// list, so search/scope filtering never disables or misdirects a move.
@@ -649,6 +668,7 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
@@ -660,6 +680,7 @@ export function HomeScreen(props: HomeScreenProps) {
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
@@ -811,6 +832,8 @@ export function HomeScreen(props: HomeScreenProps) {
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -842,6 +865,7 @@ export function HomeScreen(props: HomeScreenProps) {
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleRegenerateThreadTitle,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
@@ -863,6 +887,7 @@ export function HomeScreen(props: HomeScreenProps) {
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
@@ -967,6 +992,8 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery={props.searchQuery}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -988,6 +1015,7 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleSwipeableClose,
handleSwipeableWillOpen,
handleRegenerateThreadTitle,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
@@ -998,6 +1026,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
updateGroupDisplay,
],
);
@@ -48,6 +48,15 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
);
}
function environmentSupportsTitleRegeneration(
environmentId: EnvironmentThreadShell["environmentId"],
) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadTitleRegeneration === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -227,13 +236,18 @@ export function useThreadListActions(): {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
@@ -405,6 +419,47 @@ export function useThreadListActions(): {
},
[unpinMutation],
);
const regenerateThreadTitle = useCallback(
async (thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (
thread.titleRegeneration != null ||
titleRegenerationInFlightThreadKeys.current.has(key)
) {
return false;
}
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
Alert.alert(
"Could not regenerate title",
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
);
return false;
}
titleRegenerationInFlightThreadKeys.current.add(key);
selectionHaptic();
try {
const result = await updateThreadMetadata({
environmentId: thread.environmentId,
input: { threadId: thread.id, regenerateTitle: true },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not regenerate title",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread title could not be regenerated.",
);
return false;
}
return true;
} finally {
titleRegenerationInFlightThreadKeys.current.delete(key);
}
},
[updateThreadMetadata],
);
// Move up / Move down for the pinned block. Computed against the CANONICAL
// keyed pinned order (not the rendered list), so the move is valid even
@@ -497,6 +552,7 @@ export function useThreadListActions(): {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
};
}
@@ -429,13 +429,19 @@ function AdaptiveWorkspaceLayoutContent(
);
const handleOpenSettings = useCallback(() => {
navigation.navigate("SettingsSheet", { screen: "Settings" });
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "Settings" },
});
}, [navigation]);
// Minted here (root stack navigation) so the sidebar pane stays free of
// navigation hooks — on iOS it renders inside an independent nav tree.
const handleOpenEnvironmentSettings = useCallback(() => {
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" });
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironments" },
});
}, [navigation]);
const handleNewThreadInProject = useCallback(
@@ -1,8 +1,7 @@
import { useAuth } from "@clerk/expo";
import { AuthView, UserProfileView } from "@clerk/expo/native";
import { StackActions, useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useCallback, useEffect } from "react";
import { useCallback, useLayoutEffect } from "react";
import { View } from "react-native";
import { hasCloudPublicConfig } from "../cloud/publicConfig";
@@ -10,9 +9,9 @@ import { hasCloudPublicConfig } from "../cloud/publicConfig";
export function SettingsAuthRouteScreen() {
const navigation = useNavigation();
useEffect(() => {
useLayoutEffect(() => {
if (!hasCloudPublicConfig()) {
navigation.dispatch(StackActions.replace("Settings"));
navigation.dispatch(StackActions.replace("SettingsContent"));
}
}, [navigation]);
@@ -22,20 +21,20 @@ export function SettingsAuthRouteScreen() {
function ConfiguredSettingsAuthRouteScreen() {
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const navigation = useNavigation();
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
const handleHostBack = useCallback(
() => navigation.dispatch(StackActions.popTo("SettingsContent")),
[navigation],
);
return (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
) : (
<AuthView isDismissible={false} onHostBack={handleHostBack} />
)
) : null}
</View>
</>
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
{isLoaded ? (
isSignedIn ? (
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
) : (
<AuthView isDismissible={false} onHostBack={handleHostBack} />
)
) : null}
</View>
);
}
@@ -98,7 +98,10 @@ export function SettingsEnvironmentsRouteScreen() {
accessibilityLabel: "Add environment",
icon: "plus",
onPress: () =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" }),
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
}),
},
]}
/>
@@ -108,7 +111,10 @@ export function SettingsEnvironmentsRouteScreen() {
<NativeHeaderToolbar.Button
icon="plus"
onPress={() =>
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironmentNew" })
navigation.navigate("SettingsSheet", {
screen: "SettingsContent",
params: { screen: "SettingsEnvironmentNew" },
})
}
separateBackground
tintColor={headerIconColor}
@@ -2,7 +2,6 @@ import { useAuth, useUser } from "@clerk/expo";
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import * as Updates from "expo-updates";
import { useNavigation } from "@react-navigation/native";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { SymbolView } from "../../components/AppSymbol";
@@ -30,7 +29,6 @@ import {
subscribeAgentAwarenessRegistrationStatus,
} from "../agent-awareness/remoteRegistration";
import { refreshManagedRelayEnvironments } from "../cloud/managedRelayState";
import { useClerkSettingsSheetDetent } from "../cloud/ClerkSettingsSheetDetent";
import { hasCloudPublicConfig, resolveRelayClerkTokenOptions } from "../cloud/publicConfig";
import { withNativeGlassHeaderItem } from "../layout/native-glass-header-items";
import { WorkspaceSidebarToolbar } from "../layout/workspace-sidebar-toolbar";
@@ -40,6 +38,7 @@ import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/
import { useThreadListV2Enabled } from "../threads/use-thread-list-v2-enabled";
import {
type AppUpdateCheckState,
isAppUpdateCheckAvailable,
registerHiddenUpdateTap,
runAppUpdateCheck,
} from "../updates/app-updates";
@@ -131,7 +130,7 @@ function LocalSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<LegacySettingsSection />
<ArchivedThreadsSettingsSection />
@@ -147,7 +146,6 @@ function ConfiguredSettingsRouteScreen() {
const agentAwarenessPushAvailable = supportsAgentAwarenessPush();
const insets = useSafeAreaInsets();
const navigation = useNavigation();
const { expand: expandClerkSheet } = useClerkSettingsSheetDetent();
const { getToken, isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
const { user } = useUser();
const { savedConnectionsById } = useSavedRemoteConnections();
@@ -436,14 +434,8 @@ function ConfiguredSettingsRouteScreen() {
const openAccount = useCallback(() => {
if (!isLoaded) return;
if (!isSignedIn) {
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
return;
}
expandClerkSheet();
navigation.navigate("SettingsSheet", { screen: "SettingsAuth" });
}, [expandClerkSheet, isLoaded, isSignedIn, navigation]);
}, [isLoaded, navigation]);
return (
<View collapsable={false} className="flex-1 bg-sheet">
@@ -519,7 +511,7 @@ function ConfiguredSettingsRouteScreen() {
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
</SettingsSection>
<BetaSettingsSection />
<LegacySettingsSection />
<ArchivedThreadsSettingsSection />
@@ -530,34 +522,48 @@ function ConfiguredSettingsRouteScreen() {
}
function GeneralSettingsSection() {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
return (
<SettingsSection title="General">
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
<SettingsSwitchRow
icon="arrow.triangle.branch"
label="Auto-settle merged threads"
value={autoSettleOnMerge}
onValueChange={(value) => savePreferences({ autoSettleOnMerge: value })}
/>
<SettingsRow icon="chart.bar.xaxis" label="Usage" target="SettingsUsage" />
</SettingsSection>
);
}
/**
* Device-local beta toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → Beta backed by mobile preferences.
* Device-local legacy toggles. Mobile has no client-settings sync, so this is
* the counterpart of web's Settings → General → Legacy features backed by
* mobile preferences.
*/
function BetaSettingsSection() {
function LegacySettingsSection() {
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const threadListV2Enabled = useThreadListV2Enabled();
return (
<View className="gap-3">
<SettingsSection title="Beta">
<SettingsSection title="Legacy">
<SettingsSwitchRow
icon="sidebar.left"
label="Thread List v2"
value={threadListV2Enabled}
onValueChange={(value) => savePreferences({ threadListV2Enabled: value })}
label="Legacy Thread List"
value={!threadListV2Enabled}
onValueChange={(value) => savePreferences({ legacyThreadListEnabled: value })}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
One flat thread list in creation order. Active work renders as cards; settled threads
collapse to compact rows. Switch back any time.
Brings back the original grouped thread list. The default list is flat, in creation order:
active work renders as cards; settled threads collapse to compact rows.
</Text>
</View>
);
@@ -575,6 +581,7 @@ function AppSettingsSection() {
const variant = (Constants.expoConfig?.extra?.appVariant as string | undefined) ?? "production";
const variantLabel = variant === "production" ? "" : capitalize(variant);
const versionLabel = variantLabel ? `${version} · ${variantLabel}` : version;
const updateCheckAvailable = isAppUpdateCheckAvailable();
const busy =
updateState === "checking" || updateState === "downloading" || updateState === "restarting";
@@ -602,13 +609,13 @@ function AppSettingsSection() {
}, []);
const handleVersionPress = useCallback(() => {
if (!Updates.isEnabled || updateInFlight.current) return;
if (!updateCheckAvailable || updateInFlight.current) return;
const tap = registerHiddenUpdateTap(hiddenUpdateTapCount.current);
hiddenUpdateTapCount.current = tap.nextCount;
if (tap.shouldCheck) {
void checkForUpdate();
}
}, [checkForUpdate]);
}, [checkForUpdate, updateCheckAvailable]);
const statusLabel =
updateState === "checking"
@@ -644,7 +651,7 @@ function AppSettingsSection() {
<SettingsSection title="App">
<SettingsRow icon="internaldrive" label="Client Storage" target="SettingsClientStorage" />
<SettingsRow icon="doc.text" label="Legal" fullScreenTarget="SettingsLegal" />
{Updates.isEnabled ? (
{updateCheckAvailable ? (
<Pressable
accessibilityLabel={`Version ${versionLabel}`}
accessibilityRole="text"
@@ -64,7 +64,8 @@ export function SettingsRow(props: {
disabled={props.disabled}
onPress={() =>
navigation.navigate("SettingsSheet", {
screen: target,
screen: "SettingsContent",
params: { screen: target },
})
}
>
@@ -3,6 +3,7 @@ export type SettingsSheetTarget =
| "SettingsArchive"
| "SettingsAppearance"
| "SettingsProjectGrouping"
| "SettingsClientStorage";
| "SettingsClientStorage"
| "SettingsUsage";
export type SettingsLegalDocumentTarget = "SettingsLegal";
@@ -1,6 +1,12 @@
import { useEffect, useRef, useState } from "react";
import { Keyboard, View } from "react-native";
import { CommonActions, StackActions, useNavigation } from "@react-navigation/native";
import {
CommonActions,
type NavigationState,
type PartialState,
StackActions,
useNavigation,
} from "@react-navigation/native";
import { AsyncResult } from "effect/unstable/reactivity";
import { useConnectionController } from "../connection/useConnectionController";
@@ -25,6 +31,8 @@ import { retryShowcaseOperation } from "./showcaseRetry";
const SHOWCASE_ENABLED = process.env.EXPO_PUBLIC_SHOWCASE === "1";
const SHOWCASE_THREAD_ID = "remote-command-center";
type ShowcaseResetRoute = PartialState<NavigationState>["routes"][number];
function sceneFromPathname(pathname: string): ShowcaseScene | null {
const routePath = pathname.split(/[?#]/u, 1)[0] ?? pathname;
if (routePath === "/settings" || routePath.endsWith("/settings/environments")) {
@@ -166,17 +174,21 @@ export function ShowcaseCaptureCoordinator(props: { readonly pathname: string })
navigation.dispatch(StackActions.popToTop());
return;
}
const routes: Array<{
name: string;
params?: Record<string, unknown>;
state?: { index: number; routes: Array<{ name: string }> };
}> = [{ name: "Home" }];
const routes: ShowcaseResetRoute[] = [{ name: "Home" }];
if (requestedScene === "environments") {
routes.push({
name: "SettingsSheet",
state: {
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
index: 0,
routes: [
{
name: "SettingsContent",
state: {
index: 1,
routes: [{ name: "Settings" }, { name: "SettingsEnvironments" }],
},
},
],
},
});
} else {
@@ -1,4 +1,3 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ComposerTriggerKind } from "@t3tools/shared/composerTrigger";
import type { ServerProviderSkill, ServerProviderSlashCommand } from "@t3tools/contracts";
import { SymbolView } from "../../components/AppSymbol";
@@ -6,6 +5,7 @@ import { memo } from "react";
import { Pressable, ScrollView, useColorScheme, View, type ViewStyle } from "react-native";
import { AppText as Text } from "../../components/AppText";
import { GlassSurface } from "../../components/GlassSurface";
import { PierreEntryIcon } from "../../components/PierreEntryIcon";
export type ComposerCommandItem =
| {
@@ -56,33 +56,14 @@ function PopoverSurface(props: {
...props.style,
};
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="clear"
interactive={false}
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
colorScheme={props.isDarkMode ? "dark" : "light"}
style={baseStyle}
>
{props.children}
</LiquidGlassView>
);
}
return (
<View
style={[
baseStyle,
{
backgroundColor: props.isDarkMode ? "rgba(44,44,46,0.96)" : "rgba(255,255,255,0.96)",
borderWidth: 1,
borderColor: props.isDarkMode ? "rgba(255,255,255,0.08)" : "rgba(0,0,0,0.06)",
},
]}
<GlassSurface
glassEffectStyle="clear"
tintColor={props.isDarkMode ? "rgba(30,30,32,0.95)" : "rgba(255,255,255,0.92)"}
style={baseStyle}
>
{props.children}
</View>
</GlassSurface>
);
}
@@ -2,7 +2,11 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { StackActions, useNavigation, usePreventRemove } from "@react-navigation/native";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Alert, InteractionManager, Platform, View, useColorScheme } from "react-native";
import { KeyboardAvoidingView, useKeyboardState } from "react-native-keyboard-controller";
import {
KeyboardAvoidingView,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
@@ -25,15 +29,12 @@ import { ComposerAttachmentStrip } from "../../components/ComposerAttachmentStri
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import { ComposerSurface } from "./ThreadComposer";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
import { makeTurnCommandMetadata } from "../../lib/commandMetadata";
import { convertPastedImagesToAttachments, pickComposerImages } from "../../lib/composerImages";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import {
clearComposerDraftContent,
@@ -43,7 +44,7 @@ import {
type ComposerDraft,
} from "../../state/use-composer-drafts";
import { useEnvironmentServerConfig, useProjects } from "../../state/entities";
import { buildModelMenuActions, resolveSelectableModelSelection } from "../../lib/modelOptions";
import { resolveSelectableModelSelection } from "../../lib/modelOptions";
import { deriveThreadTitleFromPrompt } from "../../lib/projectThreadStartTurn";
import { armAgentAwarenessLiveActivityForLocalWork } from "../agent-awareness/remoteRegistration";
import { enqueueThreadOutboxMessage, removeThreadOutboxMessage } from "../../state/thread-outbox";
@@ -103,6 +104,10 @@ export function NewTaskDraftScreen(props: {
const promptInputRef = useRef<ComposerEditorHandle>(null);
const loadedBranchesProjectKeyRef = useRef<string | null>(null);
const [isComposerFocused, setIsComposerFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: promptInputRef,
isEditorFocused: isComposerFocused,
});
const [importingShareKey, setImportingShareKey] = useState<string | null>(null);
const [isCancellingShareImport, setIsCancellingShareImport] = useState(false);
const [cancelledIncomingShareId, setCancelledIncomingShareId] = useState<string | null>(null);
@@ -521,7 +526,15 @@ export function NewTaskDraftScreen(props: {
let focusFrame: ReturnType<typeof requestAnimationFrame> | null = null;
const interaction = InteractionManager.runAfterInteractions(() => {
focusFrame = requestAnimationFrame(() => promptInputRef.current?.focus());
focusFrame = requestAnimationFrame(() => {
// The delayed focus can land after the settings sheet opened, which
// would pop the keyboard underneath its modal.
if (!settingsSheetPresentation.isActiveRef.current) {
promptInputRef.current?.focus();
} else {
settingsSheetPresentation.restoreFocusAfterSave();
}
});
});
return () => {
@@ -530,7 +543,11 @@ export function NewTaskDraftScreen(props: {
cancelAnimationFrame(focusFrame);
}
};
}, [selectedProject]);
}, [
selectedProject,
settingsSheetPresentation.isActiveRef,
settingsSheetPresentation.restoreFocusAfterSave,
]);
const environmentMenuActions = useMemo(
() =>
@@ -544,10 +561,6 @@ export function NewTaskDraftScreen(props: {
[flow.environments, flow.selectedEnvironmentId, isIncomingShareTransferPending],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(flow.providerGroups, flow.selectedModel),
[flow.providerGroups, flow.selectedModel],
);
const providerOptionDescriptors = useMemo(
() =>
resolveProviderOptionDescriptors({
@@ -557,54 +570,6 @@ export function NewTaskDraftScreen(props: {
[flow.selectedModel?.options, flow.selectedModelOption?.capabilities],
);
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
flow.runtimeMode === "approval-required"
? "Approve actions"
: flow.runtimeMode === "auto-accept-edits"
? "Auto-accept edits"
: flow.runtimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: flow.runtimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: flow.interactionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: flow.interactionMode === value ? ("on" as const) : undefined,
};
}),
},
],
[flow.interactionMode, flow.runtimeMode, providerOptionDescriptors],
);
const workspaceMenuActions = useMemo(() => {
const branchActions =
flow.availableBranches.length === 0
@@ -675,10 +640,12 @@ export function NewTaskDraftScreen(props: {
flow.availableBranches.find((branch) => branch.current)?.name ??
flow.availableBranches.find((branch) => branch.isDefault)?.name ??
null;
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: flow.selectedModelOption?.label ?? "Model",
optionDescriptors: providerOptionDescriptors,
runtimeMode: flow.runtimeMode,
interactionMode: flow.interactionMode,
});
const workspaceLabel = useMemo(
() =>
formatWorkspaceLabel({
@@ -688,13 +655,6 @@ export function NewTaskDraftScreen(props: {
}),
[currentBranchName, flow.selectedBranchName, flow.workspaceMode],
);
function handleModelMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("model:")) {
return;
}
flow.setSelectedModelKey(event.slice("model:".length));
}
function handleEnvironmentMenuAction(event: string) {
if (isIncomingShareTransferPending || !event.startsWith("environment:")) {
return;
@@ -702,28 +662,6 @@ export function NewTaskDraftScreen(props: {
flow.selectEnvironment(EnvironmentId.make(event.slice("environment:".length)));
}
function handleOptionsMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
}
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
flow.setSelectedModelOptions(providerOptions);
return;
}
if (event.startsWith("options:runtime:")) {
flow.setRuntimeMode(
event.slice("options:runtime:".length) as Parameters<typeof flow.setRuntimeMode>[0],
);
return;
}
if (event.startsWith("options:interaction:")) {
flow.setInteractionMode(
event.slice("options:interaction:".length) as Parameters<typeof flow.setInteractionMode>[0],
);
}
}
function handleWorkspaceMenuAction(event: string) {
if (isIncomingShareTransferPending) {
return;
@@ -930,7 +868,9 @@ export function NewTaskDraftScreen(props: {
const isDarkMode = colorScheme === "dark";
// Android expansion follows native editor focus so relayout cannot race
// the touch gesture that opens the keyboard.
const isExpanded = !isAndroid || isComposerFocused;
// The settings sheet dismisses the keyboard, so its flag keeps the Android
// draft composer expanded through the blur (mirrors ThreadComposer).
const isExpanded = !isAndroid || isComposerFocused || settingsSheetPresentation.isActive;
const canStart =
Boolean(flow.selectedProject) &&
Boolean(flow.selectedModel) &&
@@ -984,28 +924,14 @@ export function NewTaskDraftScreen(props: {
showChevron={false}
disabled={isIncomingShareTransferPending}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Model"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={flow.selectedModelOption?.label ?? "Model"}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
disabled={isIncomingShareTransferPending}
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
disabled={isIncomingShareTransferPending}
iconNode={<ProviderIcon provider={flow.selectedModelOption?.providerDriver} size={16} />}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
<ControlPillMenu
actions={environmentMenuActions}
onPressAction={({ nativeEvent }) => handleEnvironmentMenuAction(nativeEvent.event)}
@@ -1031,6 +957,21 @@ export function NewTaskDraftScreen(props: {
</>
);
const settingsSheet = (
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={flow.providerGroups}
selectedModel={flow.selectedModel}
onSelectModel={(option) => flow.setSelectedModelKey(option.key, option.selection.options)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={flow.setSelectedModelOptions}
runtimeMode={flow.runtimeMode}
onUpdateRuntimeMode={flow.setRuntimeMode}
/>
);
const startButton = (
<ComposerToolbarButton
accessibilityLabel={
@@ -1048,14 +989,29 @@ export function NewTaskDraftScreen(props: {
// The draft is a thread that doesn't exist yet, so it mirrors the thread
// page: in-screen header, empty feed canvas above, and the same floating
// composer chrome as ThreadComposer (collapsed pill → expanded card).
//
// Composer positioning mirrors ThreadDetailScreen's floating overlay
// (KeyboardStickyView, absolute bottom overlay) rather than
// KeyboardAvoidingView's automaticOffset+padding: automaticOffset
// resolves the composer's on-screen frame via a native
// viewPositionInWindow measurement, which this app's Android
// edge-to-edge setup (KeyboardProvider's native content-view margin
// handling neutralizes windowSoftInputMode="adjustResize" while active)
// makes unreliable — the composer stayed under the keyboard instead of
// translating above it. KeyboardStickyView sticks directly to the
// animated keyboard height instead, sidestepping that measurement.
return (
<View className="flex-1 bg-screen">
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="New Thread" onBack={() => navigation.goBack()} />
<KeyboardAvoidingView automaticOffset behavior="padding" className="flex-1">
<View className="flex-1" />
<View className="flex-1" />
<KeyboardStickyView
enabled={isKeyboardVisible}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
<View
className="px-4 pt-2"
style={{
@@ -1119,7 +1075,8 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
) : null}
</View>
</KeyboardAvoidingView>
</KeyboardStickyView>
{settingsSheet}
</View>
);
}
@@ -1153,6 +1110,7 @@ export function NewTaskDraftScreen(props: {
</ComposerToolbarRow>
</View>
</KeyboardAvoidingView>
{settingsSheet}
</View>
);
}
@@ -296,6 +296,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
<View className="h-7 w-7 items-center justify-center">
<ProjectFavicon
environmentId={scope.representative.environmentId}
faviconPath={scope.representative.faviconPath}
size={20}
projectTitle={scope.title}
workspaceRoot={scope.representative.workspaceRoot}
@@ -330,6 +331,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
>
<ProjectFavicon
environmentId={project.environmentId}
faviconPath={project.faviconPath}
size={18}
projectTitle={project.title}
workspaceRoot={project.workspaceRoot}
@@ -1,18 +1,64 @@
import type { ApprovalRequestId } from "@t3tools/contracts";
import { Pressable, View } from "react-native";
import type { ApprovalRequestId, UserInputQuestion } from "@t3tools/contracts";
import { useCallback, useRef } from "react";
import { Platform, Pressable, ScrollView, View, type LayoutChangeEvent } from "react-native";
import Animated, {
Easing,
FadeInUp,
FadeOutDown,
LinearTransition,
useAnimatedStyle,
useSharedValue,
withTiming,
type SharedValue,
} from "react-native-reanimated";
import { USER_INPUT_TOGGLE_DURATION_MS } from "./pendingUserInputLayout";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { ControlPill } from "../../components/ControlPill";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
import { useThemeColor } from "../../lib/useThemeColor";
import {
isPendingUserInputOptionSelected,
type PendingUserInput,
type PendingUserInputDraftAnswer,
} from "../../lib/threadActivity";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
/**
* Constant while a request is pending (it reserves keyboard space), so the
* keyboard transition is pure translation; changes only on rare discrete
* corrections, which the layout transition smooths.
*/
readonly maxHeight: number;
readonly collapsed: boolean;
readonly onToggleCollapsed: () => void;
/** Renders a stop control on the collapsed bar, which replaces the composer. */
readonly onStopThread?: () => void;
/**
* 0 collapsed → 1 expanded. Slides the iOS overlay card down behind the
* collapsed bar (inside a clipping window) on the UI thread; the host
* animates it directly from the tap handler so the card and the feed
* inset glide start the same frame.
*/
readonly cardProgress?: SharedValue<number>;
/**
* Receives how far the expanded card extends above the bar footprint
* (written from onLayout with no re-render); the host adds it to the
* thread feed's end inset so the end of the chat stays visible above the
* card.
*/
readonly cardCoverage?: SharedValue<number>;
/** Fires on custom-answer focus/blur; hosts use it to vet stale keyboard state. */
readonly onInputFocusChange?: (focused: boolean) => void;
readonly drafts: Record<string, PendingUserInputDraftAnswer>;
readonly answers: Record<string, string> | null;
readonly answers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly onSelectOption: (
requestId: ApprovalRequestId,
questionId: string,
question: UserInputQuestion,
label: string,
) => void;
readonly onChangeCustomAnswer: (
@@ -23,74 +69,242 @@ export interface PendingUserInputCardProps {
readonly onSubmit: () => Promise<unknown>;
}
/**
* On iOS the collapsed bar is the PERMANENT in-flow footprint — the expanded
* card is an absolutely-positioned overlay rising above it. The overlay's
* measured height (which drives the thread feed's bottom inset) therefore
* never changes on collapse/expand, so the transcript stays perfectly still
* while the card animates over it.
*
* Android cannot use the overlay: it does not hit-test touches outside a
* parent's bounds, which made everything above the bar-sized wrapper
* untouchable. There the expanded card renders in-flow instead (the wrapper
* grows with it, and the host skips the coverage inset since the measured
* overlay already includes the card).
*/
const EXPANDED_CARD_IS_OVERLAY = Platform.OS === "ios";
const CARD_LAYOUT_TRANSITION = LinearTransition.duration(200);
export function PendingUserInputCard(props: PendingUserInputCardProps) {
// The surface is opaque on purpose: the card floats over the thread feed
// with no blur behind it, so a translucent background renders the questions
// on top of whatever message happens to sit underneath.
return (
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
Fill in the pending answers
</Text>
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
<View key={question.id} className="gap-2 pt-1">
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
{question.header}
</Text>
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
{question.question}
</Text>
<View className="flex-row flex-wrap gap-2.5">
{question.options.map((option) => {
const selected =
draft?.selectedOptionLabel === option.label && !draft.customAnswer?.trim().length;
return (
<Pressable
key={option.label}
className={cn(
"rounded-full border px-3 py-2.5 ",
selected
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
)}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
question.id,
option.label,
)
}
>
<Text
const iconSubtle = useThemeColor("--color-icon-subtle");
const questionCount = props.pendingUserInput.questions.length;
const cardCoverage = props.cardCoverage;
const barHeightRef = useRef(0);
const cardHeightRef = useRef(0);
// Measured card height, written straight from onLayout: the collapse slide
// distance. Not animated — it only changes on discrete relayouts.
const cardHeight = useSharedValue(0);
const notifyCoverage = useCallback(() => {
if (!cardCoverage) {
return;
}
const coverage = Math.max(0, cardHeightRef.current - barHeightRef.current);
if (coverage === cardCoverage.value) {
return;
}
if (cardCoverage.value === 0) {
// First measurement lands while the list is doing its initial
// end-pin (thread opened onto a pending request); animating it from
// zero would move the end anchor out from under that scroll.
cardCoverage.value = coverage;
return;
}
// Animated so a coverage change at rest (discrete max-height
// corrections) glides the feed instead of stepping it; toggle timing is
// owned by the host's progress values.
cardCoverage.value = withTiming(coverage, {
duration: USER_INPUT_TOGGLE_DURATION_MS,
easing: Easing.out(Easing.cubic),
});
}, [cardCoverage]);
const handleBarLayout = useCallback(
(event: LayoutChangeEvent) => {
barHeightRef.current = event.nativeEvent.layout.height;
notifyCoverage();
},
[notifyCoverage],
);
const handleCardLayout = useCallback(
(event: LayoutChangeEvent) => {
cardHeightRef.current = event.nativeEvent.layout.height;
cardHeight.value = event.nativeEvent.layout.height;
notifyCoverage();
},
[cardHeight, notifyCoverage],
);
const cardProgress = props.cardProgress;
// No opacity: fading an opaque card over the live transcript reads as a
// crossfade (card text, transcript, and bar all half-visible at once).
// Instead the card stays opaque and slides its full height down past the
// clipping window's bottom edge, so the transcript is only revealed where
// the card has physically left.
const cardAnimatedStyle = useAnimatedStyle(() => {
const progress = cardProgress === undefined ? 1 : cardProgress.value;
return {
transform: [{ translateY: (1 - progress) * cardHeight.value }],
};
});
// On iOS the card stays MOUNTED while collapsed (hidden via the animated
// style): expanding animates existing views on the UI thread the same
// frame the host starts the progress timing, instead of paying a React
// mount + layout before anything moves.
const renderCard = EXPANDED_CARD_IS_OVERLAY || !props.collapsed;
const showBar = props.collapsed || EXPANDED_CARD_IS_OVERLAY;
// The bar renders UNDER the card (earlier in JSX), always opaque: while
// expanded the opaque card covers it, and during the collapse slide the
// card's top edge wipes past and reveals it — no opacity handoff, so no
// crossfade frames.
const bar = showBar ? (
<View
onLayout={handleBarLayout}
pointerEvents={props.collapsed ? "auto" : "none"}
accessibilityElementsHidden={!props.collapsed}
importantForAccessibility={props.collapsed ? "auto" : "no-hide-descendants"}
className="flex-row items-center gap-2 rounded-full border border-neutral-200 bg-neutral-100 py-1.5 pl-4 pr-1.5 dark:border-white/6 dark:bg-neutral-900"
>
<Pressable
accessibilityRole="button"
accessibilityLabel={`Expand user input, ${questionCount} question${
questionCount === 1 ? "" : "s"
}`}
onPress={props.onToggleCollapsed}
className="min-h-10 flex-1 flex-row items-center gap-2 active:opacity-70"
>
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-sans text-xs text-neutral-500 dark:text-neutral-400">
{questionCount} question{questionCount === 1 ? "" : "s"}
</Text>
<View className="flex-1" />
<SymbolView name="chevron.up" size={12} tintColor={iconSubtle} type="monochrome" />
</Pressable>
{props.onStopThread ? (
<ControlPill
accessibilityLabel="Stop"
icon="stop.fill"
variant="danger"
className="h-9 w-9"
onPress={props.onStopThread}
/>
) : null}
</View>
) : null;
const card = renderCard ? (
// The surface is opaque on purpose: the card floats over the thread
// feed with no blur behind it, so a translucent background renders
// the questions on top of whatever message happens to sit underneath.
<Animated.View
onLayout={handleCardLayout}
pointerEvents={props.collapsed ? "none" : "auto"}
accessibilityElementsHidden={props.collapsed}
importantForAccessibility={props.collapsed ? "no-hide-descendants" : "auto"}
entering={
EXPANDED_CARD_IS_OVERLAY
? undefined
: FadeInUp.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
}
exiting={
EXPANDED_CARD_IS_OVERLAY
? undefined
: FadeOutDown.duration(USER_INPUT_TOGGLE_DURATION_MS).easing(Easing.out(Easing.cubic))
}
layout={CARD_LAYOUT_TRANSITION}
className="overflow-hidden gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100 p-4 dark:border-white/6 dark:bg-neutral-900"
style={
EXPANDED_CARD_IS_OVERLAY
? [{ maxHeight: props.maxHeight }, cardAnimatedStyle]
: { maxHeight: props.maxHeight }
}
>
<Pressable
accessibilityRole="button"
accessibilityLabel="Collapse user input"
onPress={props.onToggleCollapsed}
className="flex-row items-start gap-2"
>
<View className="flex-1 gap-2.5">
<Text className="font-t3-bold text-2xs uppercase tracking-[1.1px] text-sky-700 dark:text-sky-300">
User input needed
</Text>
<Text className="font-t3-bold text-lg text-neutral-950 dark:text-neutral-50">
Fill in the pending answers
</Text>
</View>
<View className="h-8 w-8 items-center justify-center rounded-full bg-neutral-200/70 dark:bg-white/8">
<SymbolView name="chevron.down" size={13} tintColor={iconSubtle} type="monochrome" />
</View>
</Pressable>
<ScrollView
bounces={false}
className="min-h-0"
contentContainerClassName="gap-2.5 pb-1"
keyboardShouldPersistTaps="handled"
nestedScrollEnabled
showsVerticalScrollIndicator
style={{ flexShrink: 1 }}
>
{props.pendingUserInput.questions.map((question) => {
const draft = props.drafts[question.id];
return (
<View key={question.id} className="gap-2 pt-1">
<Text className="font-t3-bold text-xs uppercase tracking-[1px] text-neutral-500 dark:text-neutral-500">
{question.header}
</Text>
<Text className="font-sans text-base leading-snug text-neutral-950 dark:text-neutral-50">
{question.question}
</Text>
<View className="flex-row flex-wrap gap-2.5">
{question.options.map((option) => {
const selected = isPendingUserInputOptionSelected(draft, option.label);
return (
<Pressable
key={option.label}
className={cn(
"font-t3-bold text-sm",
"rounded-full border px-3 py-2.5 ",
selected
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
? "border-blue-300/50 bg-blue-50 dark:border-blue-400/28 dark:bg-blue-400/14"
: "border-neutral-200 bg-white dark:border-white/6 dark:bg-neutral-950/70",
)}
onPress={() =>
props.onSelectOption(
props.pendingUserInput.requestId,
question,
option.label,
)
}
>
{option.label}
</Text>
</Pressable>
);
})}
<Text
className={cn(
"font-t3-bold text-sm",
selected
? "text-sky-700 dark:text-sky-300"
: "text-neutral-600 dark:text-neutral-300",
)}
>
{option.label}
</Text>
</Pressable>
);
})}
</View>
<TextInput
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
}
onFocus={() => props.onInputFocusChange?.(true)}
onBlur={() => props.onInputFocusChange?.(false)}
placeholder="Or type a custom answer"
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
/>
</View>
<TextInput
value={draft?.customAnswer ?? ""}
onChangeText={(value) =>
props.onChangeCustomAnswer(props.pendingUserInput.requestId, question.id, value)
}
placeholder="Or type a custom answer"
className="min-h-[54px] rounded-2xl border border-neutral-200 bg-white px-3.5 py-3 font-sans text-base text-neutral-950 dark:border-white/8 dark:bg-neutral-950/70 dark:text-neutral-50"
/>
</View>
);
})}
);
})}
</ScrollView>
<Pressable
className={cn(
"items-center justify-center rounded-2xl px-4 py-3.5",
@@ -103,6 +317,26 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</Animated.View>
) : null;
return (
<View className="relative">
{bar}
{EXPANDED_CARD_IS_OVERLAY ? (
// Clipping window for the collapse slide: same footprint as the
// expanded card, bottom edge on the bar's bottom edge. The sliding
// card exits through the bottom edge instead of drawing over the
// composer area, wiping the bar (and the transcript) into view.
<View
pointerEvents={props.collapsed ? "none" : "box-none"}
className="absolute inset-x-0 bottom-0 justify-end overflow-hidden"
style={{ height: props.maxHeight }}
>
{card}
</View>
) : (
card
)}
</View>
);
}
@@ -14,6 +14,7 @@ import {
serializeComposerFileLink,
type ComposerTrigger,
} from "@t3tools/shared/composerTrigger";
import * as Haptics from "expo-haptics";
import type { ReactNode } from "react";
import { memo, useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import {
@@ -54,7 +55,7 @@ import {
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
import { ProviderIcon } from "../../components/ProviderIcon";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { buildModelMenuActions, buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { buildModelOptions, groupByProvider } from "../../lib/modelOptions";
import { useScaledTextRole } from "../settings/appearance/useScaledTextRole";
import type { RemoteClientConnectionState } from "../../lib/connection";
import {
@@ -63,13 +64,14 @@ import {
scoreQueryMatch,
} from "@t3tools/shared/searchRanking";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
applyProviderOptionSelection,
resolveProviderOptionDescriptors,
} from "../../lib/providerOptions";
import { useComposerPathSearch } from "../../state/use-composer-path-search";
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
import { buildThreadSettingsMenu } from "./thread-settings-menu";
import { ThreadSettingsSheet, threadSettingsSummaryLabel } from "./ThreadSettingsSheet";
import { useThreadSettingsSheetPresentation } from "./use-thread-settings-sheet-presentation";
/**
* Height of the collapsed composer (pill + vertical padding, excluding safe-area inset).
@@ -116,6 +118,8 @@ export interface ThreadComposerProps {
readonly onUpdateInteractionMode: (interactionMode: ProviderInteractionMode) => void;
readonly onReconnectEnvironment: () => void;
readonly onExpandedChange?: (expanded: boolean) => void;
/** Fires on editor focus/blur; hosts use it to vet stale keyboard state. */
readonly onEditorFocusChange?: (focused: boolean) => void;
}
/**
@@ -273,15 +277,28 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
const fallbackInputRef = useRef<ComposerEditorHandle>(null);
const inputRef = props.editorRef ?? fallbackInputRef;
const [isFocused, setIsFocused] = useState(false);
const settingsSheetPresentation = useThreadSettingsSheetPresentation({
editorRef: inputRef,
isEditorFocused: isFocused,
});
const wasExpandedBeforePreviewRef = useRef(false);
const inFlightThreadIdsRef = useRef(new Set<string>());
const { onExpandedChange } = props;
const [previewImageUri, setPreviewImageUri] = useState<string | null>(null);
const hasContent = props.draftMessage.trim().length > 0 || props.draftAttachments.length > 0;
const isExpanded = isFocused;
// Opening and closing count as active so the composer stays expanded while
// focus moves between its native editor and the settings modal.
const isExpanded = isFocused || settingsSheetPresentation.isActive;
const canSend = hasContent;
// Notify the parent from the derived value, not focus events: the parent
// sizes the feed inset from this, and blur-during-sheet would otherwise
// report collapsed while the composer still renders expanded.
useEffect(() => {
onExpandedChange?.(isExpanded);
}, [isExpanded, onExpandedChange]);
const onPressImage = useCallback(
(uri: string) => {
wasExpandedBeforePreviewRef.current = isFocused;
@@ -297,15 +314,16 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}
}, [inputRef]);
const onEditorFocusChange = props.onEditorFocusChange;
const handleFocus = useCallback(() => {
setIsFocused(true);
onExpandedChange?.(true);
}, [onExpandedChange]);
onEditorFocusChange?.(true);
}, [onEditorFocusChange]);
const handleBlur = useCallback(() => {
setIsFocused(false);
onExpandedChange?.(false);
}, [onExpandedChange]);
onEditorFocusChange?.(false);
}, [onEditorFocusChange]);
const showStopAction =
props.selectedThread.session?.status === "running" ||
props.selectedThread.session?.status === "starting";
@@ -588,6 +606,12 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
[props.serverConfig, currentModelSelection],
);
const providerGroups = useMemo(() => groupByProvider(modelOptions), [modelOptions]);
// An existing thread is bound to its harness: sessions can't move between
// provider instances, so the picker only offers the thread's own group.
const threadProviderGroups = useMemo(
() => providerGroups.filter((group) => group.providerKey === currentModelSelection.instanceId),
[providerGroups, currentModelSelection.instanceId],
);
const currentModelOption =
modelOptions.find(
(option) =>
@@ -602,96 +626,68 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
}),
[currentModelOption?.capabilities, currentModelSelection.options],
);
const configurationLabel = useMemo(
() => providerOptionsConfigurationLabel(providerOptionDescriptors),
[providerOptionDescriptors],
);
const modelMenuActions = useMemo(
() => buildModelMenuActions(providerGroups, currentModelSelection),
[providerGroups, currentModelSelection],
const settingsSummaryLabel = threadSettingsSummaryLabel({
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
optionDescriptors: providerOptionDescriptors,
runtimeMode: currentRuntimeMode,
interactionMode: currentInteractionMode,
});
// iOS gets a native menu on the trigger pill: the everyday adjustments
// apply without resigning the keyboard, while "All Settings…" (and the
// Android trigger) still route through the sheet, which must dismiss it.
const settingsMenu = useMemo(
() =>
Platform.OS === "ios"
? buildThreadSettingsMenu({
providerGroups: threadProviderGroups,
selectedModel: currentModelSelection,
optionDescriptors: providerOptionDescriptors,
runtimeMode: currentRuntimeMode,
})
: null,
[threadProviderGroups, currentModelSelection, providerOptionDescriptors, currentRuntimeMode],
);
// ── Options menu ─────────────────────────────────────────
const optionsMenuActions = useMemo(
() => [
...buildProviderOptionMenuActions(providerOptionDescriptors),
{
id: "options-runtime",
title: "Runtime",
subtitle:
currentRuntimeMode === "approval-required"
? "Approve actions"
: currentRuntimeMode === "auto-accept-edits"
? "Auto-accept edits"
: currentRuntimeMode === "auto"
? "Auto"
: "Full access",
subactions: [
{ id: "options:runtime:approval-required", title: "Approve actions" },
{ id: "options:runtime:auto-accept-edits", title: "Auto-accept edits" },
{ id: "options:runtime:auto", title: "Auto" },
{ id: "options:runtime:full-access", title: "Full access" },
].map((option) => {
const value = option.id.replace("options:runtime:", "");
return {
id: option.id,
title: option.title,
state: currentRuntimeMode === value ? ("on" as const) : undefined,
};
}),
},
{
id: "options-interaction",
title: "Interaction",
subtitle: currentInteractionMode === "plan" ? "Plan" : "Default",
subactions: [
{ id: "options:interaction:default", title: "Default" },
{ id: "options:interaction:plan", title: "Plan" },
].map((option) => {
const value = option.id.replace("options:interaction:", "");
return {
id: option.id,
title: option.title,
state: currentInteractionMode === value ? ("on" as const) : undefined,
};
}),
},
const onUpdateModelSelection = props.onUpdateModelSelection;
const onUpdateRuntimeMode = props.onUpdateRuntimeMode;
const handleSettingsMenuAction = useCallback(
(eventId: string) => {
const event = settingsMenu?.events.get(eventId);
if (!event) {
return;
}
switch (event.type) {
case "select-model":
void Haptics.selectionAsync();
onUpdateModelSelection(event.option.selection);
return;
case "set-option": {
const options = applyProviderOptionSelection(providerOptionDescriptors, {
id: event.optionId,
value: event.value,
});
if (options) {
void Haptics.selectionAsync();
onUpdateModelSelection({ ...currentModelSelection, options });
}
return;
}
case "set-runtime":
void Haptics.selectionAsync();
onUpdateRuntimeMode(event.mode);
return;
}
},
[
currentModelSelection,
onUpdateModelSelection,
onUpdateRuntimeMode,
providerOptionDescriptors,
settingsMenu,
],
[currentInteractionMode, currentRuntimeMode, providerOptionDescriptors],
);
// ── Menu handlers ────────────────────────────────────────
function handleModelMenuAction(event: string) {
if (!event.startsWith("model:")) {
return;
}
const modelKey = event.slice("model:".length);
const option = modelOptions.find((o) => o.key === modelKey);
if (option) {
props.onUpdateModelSelection(option.selection);
}
}
function handleOptionsMenuAction(event: string) {
const providerOptions = applyProviderOptionMenuEvent(providerOptionDescriptors, event);
if (providerOptions) {
props.onUpdateModelSelection({
...currentModelSelection,
options: providerOptions,
});
return;
}
if (event.startsWith("options:runtime:")) {
const runtimeMode = event.slice("options:runtime:".length) as RuntimeMode;
props.onUpdateRuntimeMode(runtimeMode);
return;
}
if (event.startsWith("options:interaction:")) {
const interactionMode = event.slice("options:interaction:".length) as ProviderInteractionMode;
props.onUpdateInteractionMode(interactionMode);
}
}
return (
<Animated.View
className="px-4"
@@ -861,28 +857,31 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
onPress={() => void props.onPickDraftImages()}
showChevron={false}
/>
<ControlPillMenu
actions={modelMenuActions}
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
>
{settingsMenu ? (
<ControlPillMenu
actions={settingsMenu.actions}
onPressAction={({ nativeEvent }) => handleSettingsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={settingsSummaryLabel}
maxWidth={320}
/>
</ControlPillMenu>
) : (
<ComposerToolbarTrigger
accessibilityLabel="Model"
accessibilityLabel="Thread settings"
iconNode={
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
}
label={currentModelOption?.label ?? currentModelSelection.model}
label={settingsSummaryLabel}
maxWidth={320}
onPress={settingsSheetPresentation.open}
/>
</ControlPillMenu>
<ControlPillMenu
actions={optionsMenuActions}
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
>
<ComposerToolbarTrigger
accessibilityLabel="Configuration"
icon="slider.horizontal.3"
label={configurationLabel}
/>
</ControlPillMenu>
)}
{showStopAction ? (
<ComposerToolbarButton
accessibilityLabel="Stop"
@@ -916,6 +915,21 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
) : null}
</Animated.View>
<ThreadSettingsSheet
visible={settingsSheetPresentation.isVisible}
onClose={settingsSheetPresentation.close}
onDismissed={settingsSheetPresentation.onDismissed}
providerGroups={threadProviderGroups}
selectedModel={currentModelSelection}
onSelectModel={(option) => props.onUpdateModelSelection(option.selection)}
optionDescriptors={providerOptionDescriptors}
onUpdateOptionSelections={(options) =>
props.onUpdateModelSelection({ ...currentModelSelection, options })
}
runtimeMode={currentRuntimeMode}
onUpdateRuntimeMode={props.onUpdateRuntimeMode}
/>
<ImageViewing
images={previewImageUri ? [{ uri: previewImageUri }] : []}
imageIndex={0}
@@ -2,6 +2,7 @@ import { type EnvironmentConnectionPhase } from "@t3tools/client-runtime/connect
import type { EnvironmentThreadStatus } from "@t3tools/client-runtime/state/threads";
import { useKeyboardChatComposerInset, useKeyboardScrollToEnd } from "@legendapp/list/keyboard";
import type { LegendListRef } from "@legendapp/list/react-native";
import { HeaderHeightContext } from "@react-navigation/elements";
import type {
ApprovalRequestId,
EnvironmentId,
@@ -13,14 +14,45 @@ import type {
RuntimeMode,
ServerConfig as T3ServerConfig,
ThreadId,
UserInputQuestion,
} from "@t3tools/contracts";
import * as Haptics from "expo-haptics";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { Platform, View, type GestureResponderEvent } from "react-native";
import { KeyboardController, KeyboardStickyView } from "react-native-keyboard-controller";
import Animated, { FadeInDown, FadeOut } from "react-native-reanimated";
import {
memo,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import {
AppState,
Keyboard,
Platform,
useColorScheme,
useWindowDimensions,
View,
type GestureResponderEvent,
} from "react-native";
import {
KeyboardController,
KeyboardStickyView,
useKeyboardState,
} from "react-native-keyboard-controller";
import Animated, {
Easing,
FadeInDown,
FadeOut,
useAnimatedReaction,
useSharedValue,
withTiming,
} from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ControlPill } from "../../components/ControlPill";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
@@ -34,6 +66,11 @@ import type {
} from "../../lib/threadActivity";
import { PendingApprovalCard } from "./PendingApprovalCard";
import { PendingUserInputCard } from "./PendingUserInputCard";
import {
derivePendingUserInputMaxHeight,
ESTIMATED_KEYBOARD_HEIGHT,
USER_INPUT_TOGGLE_DURATION_MS,
} from "./pendingUserInputLayout";
import {
COMPOSER_COLLAPSED_CHROME,
COMPOSER_EXPANDED_CHROME,
@@ -54,7 +91,7 @@ export interface ThreadDetailScreenProps {
readonly respondingApprovalId: ApprovalRequestId | null;
readonly activePendingUserInput: PendingUserInput | null;
readonly activePendingUserInputDrafts: Record<string, PendingUserInputDraftAnswer>;
readonly activePendingUserInputAnswers: Record<string, string> | null;
readonly activePendingUserInputAnswers: Record<string, string | ReadonlyArray<string>> | null;
readonly respondingUserInputId: ApprovalRequestId | null;
readonly draftMessage: string;
readonly draftAttachments: ReadonlyArray<DraftComposerImageAttachment>;
@@ -89,7 +126,7 @@ export interface ThreadDetailScreenProps {
) => Promise<unknown>;
readonly onSelectUserInputOption: (
requestId: ApprovalRequestId,
questionId: string,
question: UserInputQuestion,
label: string,
) => void;
readonly onChangeUserInputCustomAnswer: (
@@ -171,8 +208,48 @@ function useStreamingHaptics(threadId: ThreadId, feed: ReadonlyArray<ThreadFeedE
}, [threadId, feed]);
}
const USER_INPUT_TOGGLE_TIMING = {
duration: USER_INPUT_TOGGLE_DURATION_MS,
easing: Easing.out(Easing.cubic),
};
export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: ThreadDetailScreenProps) {
const insets = useSafeAreaInsets();
const isKeyboardVisible = useKeyboardState((state) => state.isVisible);
const liveKeyboardHeight = useKeyboardState((state) => state.height);
// Android can swallow the IME hide callbacks when the app is backgrounded
// mid keyboard-hide (the reported repro: send — which blurs and starts the
// hide — then Home within a second). The keyboard library's height AND
// visibility then stay frozen open, so gating the sticky translation on
// visibility alone still strands the composer after resume. Quarantine the
// translation on every Android resume instead; any sign of a live keyboard
// stream — an owned input gaining focus, or any visibility/height movement —
// lifts it. A healthy resume sees no visual difference (the translation is
// already zero while the keyboard is closed).
const [keyboardStateSuspect, setKeyboardStateSuspect] = useState(false);
useEffect(() => {
if (Platform.OS !== "android") {
return;
}
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") {
setKeyboardStateSuspect(true);
}
});
return () => {
subscription.remove();
};
}, []);
useEffect(() => {
setKeyboardStateSuspect(false);
}, [isKeyboardVisible, liveKeyboardHeight]);
const handleOwnedInputFocusChange = useCallback((focused: boolean) => {
if (focused) {
setKeyboardStateSuspect(false);
}
}, []);
const windowHeight = useWindowDimensions().height;
const navigationHeaderHeight = useContext(HeaderHeightContext) || insets.top + 44;
const agentLabel = `${props.selectedThread.modelSelection.instanceId} agent`;
const selectedThreadKey = scopedThreadKey(props.environmentId, props.selectedThread.id);
const composerEditorRef = useRef<ComposerEditorHandle>(null);
@@ -183,7 +260,17 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const lastScrolledAnchorMessageIdRef = useRef<MessageId | null>(null);
const [composerExpanded, setComposerExpanded] = useState(false);
const [anchorMessageId, setAnchorMessageId] = useState<MessageId | null>(null);
const composerBottomInset = composerExpanded ? 0 : Math.max(insets.bottom, 12);
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
// Android keys the safe-area padding on keyboard visibility (#5988): the
// back gesture closes the keyboard while the editor stays focused, and a
// focus-keyed inset would leave the toolbar under the gesture bar. iOS must
// NOT use visibility — it only flips on keyboardDidHide, after the hide
// animation, so the composer would ride down flush to the screen edge and
// then snap up into the inset. On iOS blur precedes the hide, so the
// focus-keyed inset is already in place while the composer rides down.
const composerBottomInset = (Platform.OS === "android" ? isKeyboardVisible : composerExpanded)
? 0
: Math.max(insets.bottom, 12);
const contentPresentationKind = props.contentPresentation.kind;
// The raw sync status enters "synchronizing" on every full fetch, cached or
// not. Whether messages are already on screen decides the pill label: no
@@ -204,6 +291,41 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
const selectedThreadFeed = props.selectedThreadFeed;
const composerChrome = composerExpanded ? COMPOSER_EXPANDED_CHROME : COMPOSER_COLLAPSED_CHROME;
const composerOverlapHeight = composerChrome + composerBottomInset;
// While a user-input request is pending, the questionnaire owns the
// composer slot outright: expanded it is the full card, collapsed it is a
// composer-style bar in the same place (with its own stop control). The
// composer never mounts into the transition, which keeps the collapse and
// keyboard animations coherent. Collapse state is keyed by request id so a
// new request re-expands automatically.
const [collapsedUserInputRequestId, setCollapsedUserInputRequestId] =
useState<ApprovalRequestId | null>(null);
const activeUserInputRequestId = props.activePendingUserInput?.requestId ?? null;
const userInputCollapsed =
activeUserInputRequestId !== null && collapsedUserInputRequestId === activeUserInputRequestId;
// The card's height RESERVES keyboard space at all times instead of
// tracking the keyboard: transforms (the sticky translation) apply
// same-frame on the UI thread while layout props lag a Yoga pass behind,
// so any height that follows the keyboard flashes the card over the nav
// header on the way up. With a constant height the keyboard transition is
// pure translation — frame-perfect by construction — and the resting card
// stays compact over the transcript. Before the first open the reserve is
// an estimate; once a real height is known the card corrects once,
// discretely.
const [lastKnownKeyboardHeight, setLastKnownKeyboardHeight] = useState(0);
useEffect(() => {
if (liveKeyboardHeight > 0 && liveKeyboardHeight !== lastKnownKeyboardHeight) {
setLastKnownKeyboardHeight(liveKeyboardHeight);
}
}, [lastKnownKeyboardHeight, liveKeyboardHeight]);
const pendingUserInputMaxHeight = derivePendingUserInputMaxHeight({
windowHeight,
keyboardHeight:
lastKnownKeyboardHeight > 0 ? lastKnownKeyboardHeight : ESTIMATED_KEYBOARD_HEIGHT,
navigationHeaderHeight,
// The questionnaire owns the composer slot, so only the composer's
// bottom inset still overlaps.
composerOverlapHeight: composerBottomInset,
});
const estimatedOverlayHeight = composerOverlapHeight;
// The overlay's measured height includes the home-indicator inset (the
// composer pads it), but contentInsetAdjustmentBehavior="automatic" makes
@@ -220,7 +342,103 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
-nativeInsetOvercount,
);
// The expanded questionnaire is an absolute overlay on iOS, so it never
// changes the measured overlay height (that constancy is what keeps the
// feed from snapping on collapse/expand). The toggle choreography runs on
// SHARED VALUES set directly in the tap handler — one JS hop, then the
// card's rise/sink and the feed's end-inset glide animate in lockstep on
// the UI thread, keyboard-style, instead of waiting on React mount +
// onLayout + state round trips. Coverage (how far the card extends above
// the bar) is measured straight into a shared value by the card's
// onLayout, with no re-render.
const userInputCardProgress = useSharedValue(1);
const userInputInsetProgress = useSharedValue(1);
const userInputCardCoverage = useSharedValue(0);
// Android renders the expanded card in-flow (it cannot hit-test the iOS
// overlay outside the bar's bounds), so its measured overlay height already
// includes the card — the coverage extra is iOS-only.
const userInputCoverageApplies = Platform.OS === "ios" && activeUserInputRequestId !== null;
const combinedContentInsetEndAdjustment = useSharedValue(
Math.max(0, estimatedOverlayHeight - nativeInsetOvercount),
);
useAnimatedReaction(
() =>
contentInsetEndAdjustment.value +
(userInputCoverageApplies ? userInputInsetProgress.value * userInputCardCoverage.value : 0),
(value) => {
combinedContentInsetEndAdjustment.value = value;
},
[userInputCoverageApplies],
);
const { freeze, scrollMessageToEnd } = useKeyboardScrollToEnd({ listRef });
const endFollowEnabledRef = useRef(true);
endFollowEnabledRef.current = endFollowEnabled;
const userInputRepinTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// The list's own corrections for these inset changes drift on short
// content (and the error compounds across toggles), so deterministically
// re-pin the end once a toggle settles: a no-op when the resting position
// is already right, corrective when it is not. Follow state is re-checked
// inside the callback — the user may grab the list during the settle
// window, and yanking them back would override a live gesture.
const scheduleUserInputRepin = useCallback(
(delayMs: number) => {
if (userInputRepinTimerRef.current !== null) {
clearTimeout(userInputRepinTimerRef.current);
}
userInputRepinTimerRef.current = setTimeout(() => {
userInputRepinTimerRef.current = null;
if (!endFollowEnabledRef.current) {
return;
}
void scrollMessageToEnd({ animated: false, closeKeyboard: false }).catch(() => {
freeze.set(false);
});
}, delayMs);
},
[freeze, scrollMessageToEnd],
);
useEffect(
() => () => {
if (userInputRepinTimerRef.current !== null) {
clearTimeout(userInputRepinTimerRef.current);
}
},
[],
);
const handleToggleUserInputCollapsed = useCallback(() => {
if (activeUserInputRequestId === null) {
return;
}
if (userInputCollapsed) {
// Expanding: card and feed glide start NOW, on the UI thread.
userInputCardProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
userInputInsetProgress.value = withTiming(1, USER_INPUT_TOGGLE_TIMING);
setCollapsedUserInputRequestId(null);
scheduleUserInputRepin(USER_INPUT_TOGGLE_DURATION_MS + 50);
} else {
// Collapsing hides the custom-answer inputs; release the keyboard with
// them instead of leaving it up over a dead responder.
Keyboard.dismiss();
userInputCardProgress.value = withTiming(0, USER_INPUT_TOGGLE_TIMING);
// Instant: the sinking card still covers the strip being revealed, and
// animating the inset downward is what drifted the short-content end
// anchor.
userInputInsetProgress.value = 0;
setCollapsedUserInputRequestId(activeUserInputRequestId);
scheduleUserInputRepin(60);
}
}, [
activeUserInputRequestId,
scheduleUserInputRepin,
userInputCardProgress,
userInputCollapsed,
userInputInsetProgress,
]);
useEffect(() => {
// A new request always arrives expanded.
userInputCardProgress.value = 1;
userInputInsetProgress.value = 1;
}, [activeUserInputRequestId, userInputCardProgress, userInputInsetProgress]);
const showContent = props.showContent ?? true;
const layoutVariant = props.layoutVariant ?? "compact";
const isSplitLayout = layoutVariant === "split";
@@ -241,6 +459,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
setEndFollowEnabled(true);
freeze.set(false);
}, [freeze, selectedThreadKey]);
@@ -312,6 +531,16 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
composerEditorRef.current?.blur();
}, []);
const handleScrollToEnd = useCallback(() => {
void Haptics.selectionAsync();
void scrollMessageToEnd({ animated: true, closeKeyboard: false }).catch(() => {
freeze.set(false);
});
}, [freeze, scrollMessageToEnd]);
const showScrollToEndButton = contentPresentationKind === "ready" && !endFollowEnabled;
const isDarkMode = useColorScheme() === "dark";
const handleFeedTouchStart = useCallback((event: GestureResponderEvent) => {
feedTouchStartRef.current = {
pageX: event.nativeEvent.pageX,
@@ -365,13 +594,14 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
listRef={listRef}
freeze={freeze}
anchorMessageId={anchorMessageId}
contentInsetEndAdjustment={contentInsetEndAdjustment}
contentInsetEndAdjustment={combinedContentInsetEndAdjustment}
contentTopInset={0}
contentBottomInset={estimatedOverlayHeight}
contentMaxWidth={contentMaxWidth}
layoutVariant={layoutVariant}
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
onEndFollowEnabledChange={setEndFollowEnabled}
skills={selectedProviderSkills}
loadEarlier={props.loadEarlier ?? null}
/>
@@ -383,6 +613,10 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{/* Floating composer — sticks to keyboard via KeyboardStickyView */}
{showContent ? (
<KeyboardStickyView
// The animated keyboard height can remain stale after a dismissed
// IME on both platforms. Visibility is the authoritative closed
// state, so disable the translation rather than stranding the pill.
enabled={isKeyboardVisible && !keyboardStateSuspect}
style={{ position: "absolute", bottom: 0, left: 0, right: 0 }}
offset={{ closed: 0, opened: 0 }}
>
@@ -390,10 +624,60 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
list's bottom inset, so any padding above the pill/composer
pushes the resting content floor up by the same amount. */}
<View ref={composerOverlayRef} onLayout={onComposerLayout} className="w-full">
{showScrollToEndButton ? (
<Animated.View
pointerEvents="box-none"
className="absolute -top-11 left-0 right-0 z-20 items-center"
entering={FadeInDown.duration(160)}
exiting={FadeOut.duration(100)}
>
{isLiquidGlassSupported ? (
<LiquidGlassView
colorScheme={isDarkMode ? "dark" : "light"}
effect="regular"
interactive
// Interactive glass can render larger than the requested
// box (minimum touch size), so center the pill instead of
// relying on it filling the glass exactly.
style={{
alignItems: "center",
borderRadius: 18,
height: 36,
justifyContent: "center",
overflow: "hidden",
width: 36,
}}
>
<ControlPill
accessibilityLabel="Scroll to end"
activateOnPressIn
className="h-9 w-9 bg-transparent"
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
onPress={handleScrollToEnd}
/>
</LiquidGlassView>
) : (
<ControlPill
accessibilityLabel="Scroll to end"
activateOnPressIn
className="h-9 w-9 border border-border bg-card shadow-md shadow-black/10"
icon={{ ios: "chevron.down", android: "keyboard_arrow_down" }}
onPress={handleScrollToEnd}
/>
)}
</Animated.View>
) : null}
<View className="w-full self-center" style={{ maxWidth: contentMaxWidth }}>
{props.activePendingApproval || props.activePendingUserInput ? (
<Animated.View
className="shrink-0 gap-3 px-4 pb-3"
// The questionnaire replaces the composer, so it must pad
// the home indicator the composer normally covers.
style={
activeUserInputRequestId !== null
? { paddingBottom: composerBottomInset }
: undefined
}
entering={FadeInDown.duration(220)}
exiting={FadeOut.duration(140)}
>
@@ -407,6 +691,13 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
{props.activePendingUserInput ? (
<PendingUserInputCard
pendingUserInput={props.activePendingUserInput}
maxHeight={pendingUserInputMaxHeight}
collapsed={userInputCollapsed}
onToggleCollapsed={handleToggleUserInputCollapsed}
onStopThread={props.onStopThread}
cardProgress={userInputCardProgress}
cardCoverage={userInputCardCoverage}
onInputFocusChange={handleOwnedInputFocusChange}
drafts={props.activePendingUserInputDrafts}
answers={props.activePendingUserInputAnswers}
respondingUserInputId={props.respondingUserInputId}
@@ -419,35 +710,40 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
) : null}
</View>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
/>
{/* Hidden (not unmounted) while a user-input request owns the
composer slot, so composer drafts and editor state survive. */}
<View style={activeUserInputRequestId !== null ? { display: "none" } : undefined}>
<ThreadComposer
editorRef={composerEditorRef}
draftMessage={props.draftMessage}
draftAttachments={props.draftAttachments}
placeholder="Ask the repo agent, or run a command…"
contentMaxWidth={contentMaxWidth}
connectionState={props.connectionStateLabel}
connectionError={props.connectionError}
environmentLabel={props.environmentLabel}
threadSyncPhase={threadSyncPhase}
selectedThread={props.selectedThread}
serverConfig={props.serverConfig}
queueCount={props.selectedThreadQueueCount}
activeThreadBusy={props.activeThreadBusy}
environmentId={props.environmentId}
projectCwd={props.projectWorkspaceRoot}
bottomInset={composerBottomInset}
onChangeDraftMessage={props.onChangeDraftMessage}
onPickDraftImages={props.onPickDraftImages}
onNativePasteImages={props.onNativePasteImages}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
onSendMessage={handleSendMessage}
onReconnectEnvironment={props.onReconnectEnvironment}
onUpdateModelSelection={props.onUpdateThreadModelSelection}
onUpdateRuntimeMode={props.onUpdateThreadRuntimeMode}
onUpdateInteractionMode={props.onUpdateThreadInteractionMode}
onExpandedChange={setComposerExpanded}
onEditorFocusChange={handleOwnedInputFocusChange}
/>
</View>
</View>
</KeyboardStickyView>
) : null}
+112 -40
View File
@@ -48,7 +48,9 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
import { useThemeColor } from "../../lib/useThemeColor";
import { useFontFamily } from "../../lib/useFontFamily";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
import { hasWideMarkdownBlock } from "../../lib/wideMarkdownBlocks";
import {
hasNativeSelectableMarkdownText,
SelectableMarkdownText,
@@ -88,6 +90,10 @@ import {
type ThreadFeedLatestTurn,
} from "../../lib/threadActivity";
import type { ThreadContentPresentation } from "./threadContentPresentation";
import {
resolveThreadFeedLiveFollow,
type ThreadFeedLiveFollowEvent,
} from "./thread-feed-live-follow";
import {
collapsedWorkLogHeight,
ThreadWorkGroupToggle,
@@ -98,6 +104,10 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
includeOrderedLists: Platform.OS === "android",
} as const;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
@@ -148,6 +158,7 @@ export interface ThreadFeedProps {
readonly layoutVariant?: LayoutVariant;
readonly usesAutomaticContentInsets?: boolean;
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
readonly onEndFollowEnabledChange?: (enabled: boolean) => void;
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
/** Non-null when older turns exist beyond the loaded window. */
readonly loadEarlier?: {
@@ -876,6 +887,12 @@ function renderFeedEntry(
const timestampLabel = formatMessageTime(isUser ? message.createdAt : message.updatedAt);
const attachments = message.attachments ?? [];
const hasReviewCommentContext = message.text.includes("<review_comment");
// A bubble that sizes itself from its content cannot lay out a block whose
// intrinsic width overflows `maxWidth`: Android positions the bubble's
// children during the unclamped pass and never moves them once the width
// is clamped, so the paragraphs around the block end up drawn on top of
// each other. Pinning the width removes that pass.
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
@@ -898,7 +915,11 @@ function renderFeedEntry(
style={{
backgroundColor: userBubbleColor,
maxWidth: props.userBubbleMaxWidth,
...(hasReviewCommentContext ? { width: props.reviewCommentBubbleWidth } : null),
...(hasReviewCommentContext
? { width: props.reviewCommentBubbleWidth }
: hasWideBlock
? { width: props.userBubbleMaxWidth }
: null),
}}
>
{message.text.trim().length > 0 ? (
@@ -1313,6 +1334,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const disclosureAnchorKeyRef = useRef<string | null>(null);
const headerMaterialVisibleRef = useRef(false);
const previousLatestTurnRef = useRef(props.latestTurn);
const userScrollSettleTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const { width: windowWidth } = useWindowDimensions();
const { appearance } = useAppearancePreferences();
const [viewportWidth, setViewportWidth] = useState(() =>
@@ -1331,13 +1353,23 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// momentum; only motion inside a session can break follow, so MVCP
// compensations and programmatic scrolls never strand a follower.
const userScrollSessionRef = useRef(false);
const setEndFollow = useCallback((enabled: boolean) => {
if (endFollowEnabledRef.current === enabled) {
return;
}
endFollowEnabledRef.current = enabled;
setEndFollowEnabled(enabled);
}, []);
const setEndFollow = useCallback(
(enabled: boolean) => {
if (endFollowEnabledRef.current === enabled) {
return;
}
endFollowEnabledRef.current = enabled;
setEndFollowEnabled(enabled);
props.onEndFollowEnabledChange?.(enabled);
},
[props.onEndFollowEnabledChange],
);
const transitionEndFollow = useCallback(
(event: ThreadFeedLiveFollowEvent) => {
setEndFollow(resolveThreadFeedLiveFollow(endFollowEnabledRef.current, event));
},
[setEndFollow],
);
const [interactionState, setInteractionState] = useState<{
readonly copiedRowId: string | null;
readonly expandedWorkGroups: Record<string, boolean>;
@@ -1449,40 +1481,72 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// UIKit's adjustedContentInset, so topContentInset is 0 here). Add the
// header height back or the material toggles a full header too late.
reportHeaderMaterialVisibility(event.nativeEvent.contentOffset.y + anchorTopInset > 6);
// Latch bookkeeping. LegendList recomputes its inset-aware end distance
// before invoking this handler, so getState() is current. Returning to
// the end re-arms follow no matter who scrolled (the user, or our own
// scroll-to-end); moving away breaks it only during a user-initiated
// scroll session, so MVCP compensations and programmatic repositioning
// can never strand a follower.
// LegendList recomputes its inset-aware end distance before invoking
// this handler, so getState() is current. Only the actual end re-arms
// follow: its broader maintain-scroll threshold is large enough for a
// streaming chunk to pull a user back before their upward drag escapes.
// A live user-scroll session still wins even if the first scroll event
// remains inside LegendList's at-end tolerance.
const listState = props.listRef.current?.getState();
if (listState) {
if (listState.isWithinMaintainScrollAtEndThreshold) {
setEndFollow(true);
} else if (userScrollSessionRef.current) {
setEndFollow(false);
}
transitionEndFollow({
type: "scroll",
isAtEnd: listState.isAtEnd,
userScrollSessionActive: userScrollSessionRef.current,
});
}
},
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, transitionEndFollow],
);
const handleScrollBeginDrag = useCallback(() => {
userScrollSessionRef.current = true;
}, []);
// The session must survive past finger-lift so momentum that carries the
// user away from the end still breaks follow; a drag released with no
// momentum ends its session at the release itself, otherwise at momentum
// end. Leaving a session open would let a later animated maintain-scroll
// read as user motion and break follow spuriously.
const handleScrollEndDrag = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
const velocity = event.nativeEvent.velocity?.y ?? 0;
if (Math.abs(velocity) < 0.05) {
userScrollSessionRef.current = false;
const clearUserScrollSettle = useCallback(() => {
if (userScrollSettleTimerRef.current !== null) {
clearTimeout(userScrollSettleTimerRef.current);
userScrollSettleTimerRef.current = null;
}
}, []);
const handleScrollBeginDrag = useCallback(() => {
clearUserScrollSettle();
userScrollSessionRef.current = true;
// Pause before the first scroll event. Otherwise a stream update can run
// maintainScrollAtEnd between touch-down and the drag leaving its threshold.
transitionEndFollow({ type: "user-scroll-begin" });
}, [clearUserScrollSettle, transitionEndFollow]);
const finishUserScroll = useCallback(
(releaseIsAtEnd?: boolean) => {
clearUserScrollSettle();
const userScrollSessionActive = userScrollSessionRef.current;
userScrollSessionRef.current = false;
transitionEndFollow({
type: "user-scroll-end",
// With no momentum, preserve the finger-release position. Streaming
// growth during the native momentum-detection window must not turn a
// release at the live edge into an opt-out from follow.
isAtEnd: releaseIsAtEnd ?? props.listRef.current?.getState().isAtEnd ?? false,
userScrollSessionActive,
});
},
[clearUserScrollSettle, props.listRef, transitionEndFollow],
);
// Finger-lift velocity is not a reliable momentum signal: a gentle fling
// can report zero and still decelerate. Give native momentum a short window
// to announce itself; if it does, onMomentumScrollBegin cancels this fallback
// and the session survives until the settled momentum-end position. This
// mirrors the native-event handoff used by the home thread list's scroll gate.
const handleScrollEndDrag = useCallback(() => {
clearUserScrollSettle();
const releaseIsAtEnd = props.listRef.current?.getState().isAtEnd ?? false;
userScrollSettleTimerRef.current = setTimeout(() => finishUserScroll(releaseIsAtEnd), 160);
}, [clearUserScrollSettle, finishUserScroll, props.listRef]);
const handleMomentumScrollBegin = useCallback(() => {
if (userScrollSessionRef.current) {
clearUserScrollSettle();
}
}, [clearUserScrollSettle]);
const handleMomentumScrollEnd = useCallback(() => {
userScrollSessionRef.current = false;
}, []);
finishUserScroll();
}, [finishUserScroll]);
useEffect(() => clearUserScrollSettle, [clearUserScrollSettle]);
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
@@ -1491,23 +1555,30 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
setViewportHeight((current) => (Math.abs(current - nextHeight) > 1 ? nextHeight : current));
}, []);
// Thread identity is env-scoped: two environments can hold the same
// ThreadId, and keying resets (or the list mount) on the bare id would
// carry stale scroll/follow state across an environment switch.
const feedThreadKey = scopedThreadKey(props.environmentId, props.threadId);
useEffect(() => {
reportHeaderMaterialVisibility(false);
}, [props.threadId, reportHeaderMaterialVisibility]);
}, [feedThreadKey, reportHeaderMaterialVisibility]);
// A thread switch opens pinned to the end; a send explicitly returns to the
// live edge (ThreadDetailScreen scrolls the new message into place). Both
// re-arm follow regardless of where the user had scrolled before.
useEffect(() => {
clearUserScrollSettle();
userScrollSessionRef.current = false;
setEndFollow(true);
}, [props.threadId, setEndFollow]);
transitionEndFollow({ type: "reset" });
}, [clearUserScrollSettle, feedThreadKey, transitionEndFollow]);
useEffect(() => {
if (props.anchorMessageId !== null) {
clearUserScrollSettle();
userScrollSessionRef.current = false;
setEndFollow(true);
transitionEndFollow({ type: "reset" });
}
}, [props.anchorMessageId, setEndFollow]);
}, [clearUserScrollSettle, props.anchorMessageId, transitionEndFollow]);
const expandedWorkGroupIds = useMemo(() => {
const ids = new Set<string>();
@@ -1543,7 +1614,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
// initial scroll-to-end computes with a zero end inset and rests one
// composer-height short of the end. Layout effect: it must land before the
// list's first positioning tick or the one-shot initial scroll misses it.
const listMountKey = `${props.threadId}:${props.feed.length === 0 ? "empty" : "filled"}`;
const listMountKey = `${feedThreadKey}:${props.feed.length === 0 ? "empty" : "filled"}`;
useLayoutEffect(() => {
const bottom = props.contentInsetEndAdjustment.value;
if (bottom > 0) {
@@ -1910,6 +1981,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
onScroll={handleScroll}
onScrollBeginDrag={handleScrollBeginDrag}
onScrollEndDrag={handleScrollEndDrag}
onMomentumScrollBegin={handleMomentumScrollBegin}
onMomentumScrollEnd={handleMomentumScrollEnd}
scrollEventThrottle={16}
ListHeaderComponent={
@@ -10,6 +10,7 @@ import {
import { LegendList } from "@legendapp/list/react-native";
import type { MenuAction } from "@react-native-menu/menu";
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/unstable/reactivity";
import type { EnvironmentId } from "@t3tools/contracts";
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
@@ -29,6 +30,7 @@ import { NativeStackScreenOptions } from "../../native/StackHeader";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
import { useThemeColor } from "../../lib/useThemeColor";
import { useProjects, useThreadShells } from "../../state/entities";
import { mobilePreferencesAtom } from "../../state/preferences";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2Enabled } from "./use-thread-list-v2-enabled";
import { environmentServerConfigsAtom } from "../../state/server";
@@ -211,8 +213,13 @@ function ThreadNavigationSidebarPane(
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const autoSettleOnMerge =
!AsyncResult.isSuccess(preferencesResult) ||
preferencesResult.value.autoSettleOnMerge !== false;
const pendingTasks = usePendingNewTasks();
const { openPendingTask, confirmDeletePendingTask } = usePendingTaskListActions();
const environments = useMemo(
@@ -410,8 +417,8 @@ function ThreadNavigationSidebarPane(
// Thread List v2 (beta) support — same model as the compact Home list
// (HomeScreen.tsx): flat creation-order card block + settled recency tail.
// PR states stream in per-row; merged/closed PRs auto-settle their thread
// on the next partition.
// PR states stream in per-row. The next partition applies the configured
// merge rule and the always-on close rule.
const [changeRequestStateByKey, setChangeRequestStateByKey] = useState<
ReadonlyMap<string, "open" | "closed" | "merged">
>(() => new Map());
@@ -505,6 +512,15 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order for Move up/down flags — computed from
// all shells so search/scope filtering never disables a valid move.
const arrangedPinnedKeys = useMemo(() => {
@@ -536,6 +552,7 @@ function ThreadNavigationSidebarPane(
searchQuery: props.searchQuery,
matchedThreadKeys,
changeRequestStateByKey,
autoSettleOnMerge,
settlementEnvironmentIds,
snoozeEnvironmentIds,
settledLimit: settledVisibleCount,
@@ -547,6 +564,7 @@ function ThreadNavigationSidebarPane(
});
}, [
changeRequestStateByKey,
autoSettleOnMerge,
nowMinute,
snoozeWakeTick,
snoozedShelfExpanded,
@@ -950,6 +968,8 @@ function ThreadNavigationSidebarPane(
onSelectThread={handleSelectThread}
onDeleteThread={confirmDeleteThread}
onArchiveThread={archiveThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -1067,6 +1087,8 @@ function ThreadNavigationSidebarPane(
fullSwipeWidth={props.width - 20}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={handleSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1103,6 +1125,7 @@ function ThreadNavigationSidebarPane(
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
regenerateThreadTitle,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
@@ -1110,6 +1133,7 @@ function ThreadNavigationSidebarPane(
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -63,6 +63,7 @@ import { useSelectedThreadRequests } from "../../state/use-selected-thread-reque
import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktree";
import { useThreadComposerState } from "../../state/use-thread-composer-state";
import { threadEnvironment } from "../../state/threads";
import { useEnvironmentServerConfig } from "../../state/entities";
import { projectThreadContentPresentation } from "./threadContentPresentation";
import {
useAdaptiveWorkspaceLayout,
@@ -214,6 +215,33 @@ function ThreadRouteContent(
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
const markThreadViewed = useAtomCommand(threadEnvironment.markViewed, { reportFailure: false });
const selectedServerConfig = useEnvironmentServerConfig(selectedThread?.environmentId ?? null);
useFocusEffect(
useCallback(() => {
const thread = selectedThread;
const completedAt = thread?.latestTurn?.completedAt;
if (
thread == null ||
completedAt == null ||
selectedServerConfig?.environment.capabilities.threadViewStatus !== true
)
return;
void markThreadViewed({
environmentId: thread.environmentId,
input: {
threadId: thread.id,
viewedAt: completedAt,
},
});
}, [
markThreadViewed,
selectedServerConfig?.environment.capabilities.threadViewStatus,
selectedThread?.environmentId,
selectedThread?.id,
selectedThread?.latestTurn?.completedAt,
]),
);
const navigation = useNavigation();
const params = props.route.params;
const environmentIdRaw = firstRouteParam(params.environmentId);
@@ -0,0 +1,652 @@
import type {
ModelSelection,
ProviderInteractionMode,
ProviderOptionDescriptor,
ProviderOptionSelection,
RuntimeMode,
} from "@t3tools/contracts";
import {
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
import * as Haptics from "expo-haptics";
import { useCallback, useEffect, useRef, useState } from "react";
import {
Modal,
Platform,
Pressable,
ScrollView,
Switch,
useWindowDimensions,
View,
} from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { ProviderIcon } from "../../components/ProviderIcon";
import { cn } from "../../lib/cn";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { applyProviderOptionSelection, providerOptionValueLabels } from "../../lib/providerOptions";
import { useThemeColor } from "../../lib/useThemeColor";
import { RUNTIME_MODE_CHOICES, selectableChoices } from "./thread-settings-menu";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
import type { ThreadSettingsSheetCloseReason } from "./use-thread-settings-sheet-presentation";
/**
* The everyday harnesses stay expanded; every other provider (OpenRouter
* catalogs and friends) folds behind its header so a 300-model catalog can't
* bury the list.
*/
const PRIMARY_PROVIDER_DRIVERS: ReadonlySet<string> = new Set(["claudeAgent", "codex"]);
/**
* Compact "Fable 5 · Max · Auto" style summary for the composer trigger pill,
* covering model, provider options, runtime mode, and plan mode in one label.
*/
export function threadSettingsSummaryLabel(input: {
readonly modelLabel: string;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly runtimeMode: RuntimeMode;
readonly interactionMode: ProviderInteractionMode;
}): string {
const runtime = RUNTIME_MODE_CHOICES.find((choice) => choice.mode === input.runtimeMode);
return [
input.modelLabel,
...providerOptionValueLabels(input.optionDescriptors),
...(runtime ? [runtime.shortLabel] : []),
...(input.interactionMode === "plan" ? ["Plan"] : []),
].join(" · ");
}
function ModelRow(props: {
readonly option: ModelOption;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
// Selected rows get the same primary treatment as the submenu rows.
// Subtle backgrounds (bg-subtle-strong) get overridden by the OS
// selection chrome on iOS 26, so use the explicit high-contrast style
// everywhere instead.
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
numberOfLines={1}
>
{props.option.label}
</Text>
{props.option.isDefault ? (
<View className="rounded-md bg-subtle-strong px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Default</Text>
</View>
) : null}
{props.option.isLegacy ? (
<View className="rounded-md bg-subtle px-1.5 py-0.5">
<Text className="text-3xs font-t3-bold text-foreground-muted">Legacy</Text>
</View>
) : null}
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
/**
* Provider section header with the harness logo. Secondary providers render
* as a tappable fold (count + chevron while collapsed); primary providers
* and the group holding the current selection are static headers.
*/
function ProviderHeader(props: {
readonly driver: string | undefined;
readonly label: string;
readonly collapsible: boolean;
readonly collapsed: boolean;
readonly modelCount: number;
readonly onToggle: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole={props.collapsible ? "button" : "header"}
accessibilityState={props.collapsible ? { expanded: !props.collapsed } : undefined}
accessibilityLabel={
props.collapsible ? `${props.label}, ${props.modelCount} models` : props.label
}
disabled={!props.collapsible}
onPress={props.onToggle}
className={cn(
"mx-2.5 flex-row items-center gap-2 rounded-xl px-3",
props.collapsible ? "py-3.5 active:opacity-70" : "pb-2 pt-4",
)}
>
<ProviderIcon provider={props.driver} size={15} />
<Text className="text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{props.label}
</Text>
{props.collapsible ? (
<>
<View className="flex-1" />
{props.collapsed ? (
<Text className="text-2xs font-t3-medium text-foreground-muted">
{props.modelCount}
</Text>
) : null}
<SymbolView
name={props.collapsed ? "chevron.down" : "chevron.up"}
size={11}
tintColor={iconSubtle}
type="monochrome"
/>
</>
) : null}
</Pressable>
);
}
/** Compact row that opens a single-choice submenu panel. */
function DisclosureRow(props: {
readonly label: string;
readonly value: string | undefined;
readonly disabled?: boolean;
readonly onPress: () => void;
}) {
const iconSubtle = useThemeColor("--color-icon-subtle");
return (
<Pressable
accessibilityRole="button"
disabled={props.disabled}
onPress={props.onPress}
className={cn(
"flex-row items-center gap-2 px-5 py-3 active:opacity-70",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<View className="flex-1" />
{props.value ? (
<Text className="text-sm text-foreground-muted" numberOfLines={1}>
{props.value}
</Text>
) : null}
<SymbolView name="chevron.right" size={12} tintColor={iconSubtle} type="monochrome" />
</Pressable>
);
}
/** Single option inside a submenu panel. */
function ChoiceRow(props: {
readonly label: string;
readonly selected: boolean;
readonly onPress: () => void;
}) {
const primaryFg = useThemeColor("--color-primary-foreground");
return (
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: props.selected }}
onPress={props.onPress}
className={cn(
"mx-2.5 flex-row items-center rounded-xl px-3 py-3.5 active:opacity-70",
props.selected ? "bg-primary" : "bg-transparent",
)}
>
<Text
className={cn(
"shrink text-sm font-t3-medium",
props.selected ? "text-primary-foreground" : "text-foreground",
)}
>
{props.label}
</Text>
<View className="flex-1" />
{props.selected ? (
<SymbolView name="checkmark" size={14} tintColor={primaryFg} type="monochrome" />
) : null}
</Pressable>
);
}
function SwitchRow(props: {
readonly label: string;
readonly value: boolean;
readonly disabled?: boolean;
readonly onValueChange: (value: boolean) => void;
}) {
const activeTrack = String(useThemeColor("--color-switch-active"));
const track = String(useThemeColor("--color-secondary-border"));
return (
<View
className={cn(
"flex-row items-center justify-between px-5 py-2.5",
props.disabled && "opacity-40",
)}
>
<Text className="text-sm font-t3-medium text-foreground">{props.label}</Text>
<Switch
disabled={props.disabled}
ios_backgroundColor={track}
onValueChange={props.onValueChange}
trackColor={{ false: track, true: activeTrack }}
value={props.value}
/>
</View>
);
}
type SubmenuPage =
| { readonly kind: "descriptor"; readonly id: string }
| { readonly kind: "runtime" };
/**
* Unified thread settings: the sheet is the provider-grouped model list
* (primary harnesses expanded, other providers folded, legacy behind the
* top-right pill) with a Save button, plus compact disclosure rows whose
* single-choice submenus stack in a small panel over the sheet so it never
* changes size. Model changes stage until Save — while staged, the settings
* rows edit the staged model's options and Save applies everything together.
*
* Callers control which harnesses are offered via providerGroups: an
* existing thread must pass only its own provider's group, since a session
* can't switch harness mid-thread.
*
* Rendered through an RN Modal (not the root OverlayPortal) so it also
* presents above natively-presented form sheets like the new-task draft.
* Callers must dismiss the keyboard when opening — the iOS keyboard window
* would otherwise cover the lower half of the sheet.
*/
export function ThreadSettingsSheet(props: {
readonly visible: boolean;
/**
* "save" = the Save/Done button (the user is finished configuring);
* "dismiss" = backdrop, grabber, or system back. Hosts only restore the
* keyboard for "save" so a stray tap outside a control never pops it.
*/
readonly onClose: (reason: ThreadSettingsSheetCloseReason) => void;
readonly onDismissed: () => void;
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly onSelectModel: (option: ModelOption) => void;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly onUpdateOptionSelections: (selections: ReadonlyArray<ProviderOptionSelection>) => void;
readonly runtimeMode: RuntimeMode;
readonly onUpdateRuntimeMode: (mode: RuntimeMode) => void;
}) {
const insets = useSafeAreaInsets();
const { height: windowHeight } = useWindowDimensions();
const [showLegacyToggle, setShowLegacyToggle] = useState(false);
const [expandedProviders, setExpandedProviders] = useState<ReadonlySet<string>>(() => new Set());
const [pendingModel, setPendingModel] = useState<ModelOption | null>(null);
const [submenu, setSubmenu] = useState<SubmenuPage | null>(null);
const wasPresentedRef = useRef(false);
const notifyDismissed = useCallback(() => {
if (!wasPresentedRef.current) {
return;
}
wasPresentedRef.current = false;
props.onDismissed();
}, [props.onDismissed]);
// Every open starts fresh: no staged model, no submenu, legacy hidden,
// secondary providers folded. The sheet stays mounted between opens, so
// state would otherwise stick around.
useEffect(() => {
if (props.visible) {
wasPresentedRef.current = true;
setShowLegacyToggle(false);
setExpandedProviders(new Set());
setPendingModel(null);
setSubmenu(null);
} else if (Platform.OS === "android" && wasPresentedRef.current) {
// React Native only emits Modal.onDismiss on iOS. Android uses no exit
// animation below, so the post-commit effect is its dismissal boundary.
notifyDismissed();
}
}, [notifyDismissed, props.visible]);
const isApplied = (option: ModelOption) =>
option.selection.instanceId === props.selectedModel?.instanceId &&
option.selection.model === props.selectedModel.model;
// The list highlights the staged pick; Save turns it into the applied one.
const isDisplayed = (option: ModelOption) =>
pendingModel ? option.key === pendingModel.key : isApplied(option);
// While a model is staged, the settings rows describe and edit the staged
// model's options (kept on its pending selection); Save applies model and
// options together. Otherwise they edit the applied selection directly.
const displayedDescriptors = pendingModel
? pendingModel.capabilities
? getProviderOptionDescriptors({
caps: pendingModel.capabilities,
selections: pendingModel.selection.options,
})
: []
: props.optionDescriptors;
const hasLegacyModels = props.providerGroups.some((group) =>
group.models.some((model) => model.isLegacy),
);
// Legacy stays hidden unless the pill is toggled this open; a highlighted
// legacy model is exempted from the filter instead of forcing the whole
// legacy list visible.
const showLegacy = showLegacyToggle;
// Stable settings rows: the union of descriptors across the primary
// harnesses' current models (plus whatever the displayed model advertises)
// always renders, with unsupported rows disabled instead of vanishing when
// the selection changes. Keyed by label, not id — Claude and Codex use
// different ids for the same "Reasoning" concept.
const descriptorTemplate = (() => {
const seen = new Map<string, { type: "select" | "boolean" }>();
for (const group of props.providerGroups) {
const driver = group.models[0]?.providerDriver;
if (driver === undefined || !PRIMARY_PROVIDER_DRIVERS.has(driver)) {
continue;
}
for (const model of group.models) {
if (model.isLegacy) {
continue;
}
for (const descriptor of model.capabilities?.optionDescriptors ?? []) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
}
}
for (const descriptor of displayedDescriptors) {
if (!seen.has(descriptor.label)) {
seen.set(descriptor.label, { type: descriptor.type });
}
}
return [...seen.entries()].map(([label, entry]) => ({ label, ...entry }));
})();
const handleSave = () => {
if (pendingModel) {
void Haptics.selectionAsync();
props.onSelectModel(pendingModel);
}
props.onClose("save");
};
const handleOptionChange = (id: string, value: string | boolean) => {
const next = applyProviderOptionSelection(displayedDescriptors, { id, value });
if (!next) {
return;
}
if (pendingModel) {
setPendingModel({
...pendingModel,
selection: { ...pendingModel.selection, options: next },
});
} else {
props.onUpdateOptionSelections(next);
}
};
const toggleProvider = (providerKey: string) => {
setExpandedProviders((current) => {
const next = new Set(current);
if (!next.delete(providerKey)) {
next.add(providerKey);
}
return next;
});
};
const activeDescriptor =
submenu?.kind === "descriptor"
? displayedDescriptors.find(
(descriptor) => descriptor.type === "select" && descriptor.id === submenu.id,
)
: undefined;
const submenuContent =
submenu?.kind === "runtime"
? {
title: "Runtime",
rows: RUNTIME_MODE_CHOICES.map((choice) => ({
id: choice.mode,
label: choice.label,
selected: choice.mode === props.runtimeMode,
onPress: () => {
void Haptics.selectionAsync();
props.onUpdateRuntimeMode(choice.mode);
setSubmenu(null);
},
})),
}
: activeDescriptor?.type === "select"
? {
title: activeDescriptor.label,
rows: selectableChoices(activeDescriptor).map((choice) => ({
id: choice.id,
label: choice.label,
selected: choice.id === getProviderOptionCurrentValue(activeDescriptor),
onPress: () => {
void Haptics.selectionAsync();
handleOptionChange(activeDescriptor.id, choice.id);
setSubmenu(null);
},
})),
}
: null;
return (
<Modal
transparent
statusBarTranslucent
navigationBarTranslucent
animationType={Platform.OS === "ios" ? "fade" : "none"}
visible={props.visible}
onDismiss={notifyDismissed}
onRequestClose={submenuContent ? () => setSubmenu(null) : () => props.onClose("dismiss")}
>
<View className="flex-1 justify-end">
<Pressable
accessibilityLabel="Close thread settings"
className="absolute inset-0 bg-backdrop"
onPress={() => props.onClose("dismiss")}
/>
<View
className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet"
style={{ maxHeight: windowHeight * 0.85 }}
>
{/* The grabber doubles as the accessible close control: the dim
backdrop above a tall sheet is a sliver, and VoiceOver can't
reach it at all. */}
<Pressable
accessibilityLabel="Close thread settings"
accessibilityRole="button"
onPress={() => props.onClose("dismiss")}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
{hasLegacyModels ? (
<View className="flex-row justify-end px-4 pb-1.5">
<Pressable
accessibilityRole="button"
accessibilityState={{ selected: showLegacy }}
hitSlop={8}
onPress={() => {
void Haptics.selectionAsync();
setShowLegacyToggle(!showLegacy);
}}
className="rounded-full border border-border bg-subtle px-3 py-1.5 active:opacity-70"
>
<Text className="text-2xs font-t3-medium text-foreground-muted">
{showLegacy ? "Hide legacy models" : "Show legacy models"}
</Text>
</Pressable>
</View>
) : null}
{/* Only the model list scrolls. Provider catalogs can run to
hundreds of models (OpenRouter), so the rows below stay pinned
and reachable instead of living at the end of that scroll. */}
<ScrollView
style={{ flexShrink: 1 }}
contentContainerStyle={{ paddingBottom: 8 }}
showsVerticalScrollIndicator={false}
>
{props.providerGroups.map((group) => {
const driver = group.models[0]?.providerDriver;
const isPrimary = driver !== undefined && PRIMARY_PROVIDER_DRIVERS.has(driver);
const visibleModels = showLegacy
? group.models
: group.models.filter((model) => !model.isLegacy || isDisplayed(model));
if (visibleModels.length === 0) {
return null;
}
const containsSelection = group.models.some(isDisplayed);
const collapsible = !isPrimary && !containsSelection;
const collapsed = collapsible && !expandedProviders.has(group.providerKey);
return (
<View key={group.providerKey}>
<ProviderHeader
driver={driver}
label={group.providerLabel}
collapsible={collapsible}
collapsed={collapsed}
modelCount={visibleModels.length}
onToggle={() => toggleProvider(group.providerKey)}
/>
{collapsed
? null
: visibleModels.map((option) => (
<ModelRow
key={option.key}
option={option}
selected={isDisplayed(option)}
onPress={() => {
void Haptics.selectionAsync();
// Re-tapping the applied model cancels staging.
setPendingModel((current) =>
pendingModelAfterPress({
current,
pressed: option,
pressedIsApplied: isApplied(option),
}),
);
}}
/>
))}
</View>
);
})}
</ScrollView>
<View className="mx-5 h-px bg-border" />
<View style={{ paddingBottom: insets.bottom + 12 }}>
{descriptorTemplate.map((entry) => {
const live = displayedDescriptors.find(
(descriptor) => descriptor.label === entry.label,
);
if ((live?.type ?? entry.type) === "select") {
return (
<DisclosureRow
key={entry.label}
label={entry.label}
value={live ? getProviderOptionCurrentLabel(live) : undefined}
disabled={!live}
onPress={() => {
if (live) {
setSubmenu({ kind: "descriptor", id: live.id });
}
}}
/>
);
}
return (
<SwitchRow
key={entry.label}
label={entry.label}
value={live?.type === "boolean" ? (live.currentValue ?? false) : false}
disabled={!live}
onValueChange={(value) => {
if (live) {
handleOptionChange(live.id, value);
}
}}
/>
);
})}
<DisclosureRow
label="Runtime"
value={
RUNTIME_MODE_CHOICES.find((choice) => choice.mode === props.runtimeMode)?.label
}
onPress={() => setSubmenu({ kind: "runtime" })}
/>
<Pressable
accessibilityRole="button"
onPress={handleSave}
className="mx-4 mt-2 h-12 items-center justify-center rounded-full bg-primary active:opacity-80"
>
<Text className="text-sm font-t3-bold text-primary-foreground">
{pendingModel ? "Save" : "Done"}
</Text>
</Pressable>
</View>
</View>
{/* Submenus stack over the sheet instead of replacing its content,
so the main sheet keeps its size while drilling in and out. */}
{submenuContent ? (
<View className="absolute inset-0 justify-end">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
className="absolute inset-0 bg-backdrop"
onPress={() => setSubmenu(null)}
/>
<View className="overflow-hidden rounded-t-[24px] border border-b-0 border-border bg-sheet">
<Pressable
accessibilityLabel={`Close ${submenuContent.title}`}
accessibilityRole="button"
onPress={() => setSubmenu(null)}
className="items-center pb-1 pt-2.5"
>
<View className="h-1 w-9 rounded-full bg-subtle-strong" />
</Pressable>
<Text className="px-5 pb-1.5 text-2xs font-t3-bold uppercase tracking-widest text-foreground-muted">
{submenuContent.title}
</Text>
<ScrollView
style={{ maxHeight: windowHeight * 0.5 }}
contentContainerStyle={{ paddingBottom: insets.bottom + 12 }}
showsVerticalScrollIndicator={false}
bounces={false}
>
{submenuContent.rows.map((row) => (
<ChoiceRow
key={row.id}
label={row.label}
selected={row.selected}
onPress={row.onPress}
/>
))}
</ScrollView>
</View>
</View>
) : null}
</View>
</Modal>
);
}
@@ -3,6 +3,7 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"
import type {
EnvironmentId,
ModelSelection,
ProjectReadFileResult,
ProviderInteractionMode,
ProviderOptionSelection,
RuntimeMode,
@@ -13,8 +14,14 @@ import {
DEFAULT_PROVIDER_INTERACTION_MODE,
DEFAULT_RUNTIME_MODE,
MessageId,
T3_PROJECT_FILE_NAME,
ThreadId,
} from "@t3tools/contracts";
import { parseT3ProjectFile } from "@t3tools/shared/t3ProjectFile";
import {
isDefaultThreadEnvModeSettled,
resolveDefaultThreadEnvMode,
} from "@t3tools/shared/threadEnvMode";
import * as Arr from "effect/Array";
import { pipe } from "effect/Function";
@@ -25,10 +32,13 @@ import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import {
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "../../lib/modelOptions";
import { scopedProjectKey } from "../../lib/scopedEntities";
import { appAtomRegistry } from "../../state/atom-registry";
import { projectEnvironment } from "../../state/projects";
import { useEnvironmentQuery } from "../../state/query";
import {
appendComposerDraftAttachments,
clearComposerDraft,
@@ -147,7 +157,10 @@ type NewTaskFlowContextValue = {
readonly reset: () => void;
readonly setProject: (project: EnvironmentProject) => void;
readonly selectEnvironment: (environmentId: EnvironmentId) => void;
readonly setSelectedModelKey: (key: string | null) => void;
readonly setSelectedModelKey: (
key: string | null,
options?: ReadonlyArray<ProviderOptionSelection>,
) => void;
readonly setWorkspaceMode: (mode: WorkspaceMode) => void;
readonly selectBranch: (branch: VcsRef) => void;
readonly setStartFromOrigin: (value: boolean) => void;
@@ -341,10 +354,35 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const selectedProjectDraft = useComposerDraft(selectedProjectDraftKey);
const prompt = selectedProjectDraft.text;
const attachments = selectedProjectDraft.attachments;
// The server's configured default decides the mode until the user picks one
// explicitly — same resolution web uses for new draft threads.
const defaultWorkspaceMode: WorkspaceMode =
selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local";
// Default mode until the user picks one explicitly — same resolution web
// uses for new draft threads: per-project setting, then the repo's
// checked-in t3.json, then the server's configured default.
const t3ProjectFileQuery = useEnvironmentQuery(
selectedProject !== null && selectedProject.workspaceRoot !== ""
? projectEnvironment.readFile({
environmentId: selectedProject.environmentId,
input: { cwd: selectedProject.workspaceRoot, relativePath: T3_PROJECT_FILE_NAME },
})
: null,
);
const t3ProjectFileData = t3ProjectFileQuery.data as ProjectReadFileResult | null;
const t3ProjectFileDefaultMode = useMemo(() => {
if (t3ProjectFileData === null || t3ProjectFileData.truncated) return null;
return parseT3ProjectFile(t3ProjectFileData.contents)?.defaultThreadEnvMode ?? null;
}, [t3ProjectFileData]);
const defaultWorkspaceMode: WorkspaceMode = resolveDefaultThreadEnvMode({
projectSetting: selectedProject?.defaultThreadEnvMode,
projectFile: t3ProjectFileDefaultMode,
globalDefault: selectedEnvironmentServerConfig?.settings.defaultThreadEnvMode ?? "local",
});
// While unsettled the resolved default is provisional. Nothing may write
// it into the draft during that window (the auto-branch effect does), or
// the frozen interim value beats the t3.json default once it loads.
const defaultWorkspaceModeSettled = isDefaultThreadEnvModeSettled({
explicitMode: selectedProjectDraft.workspaceSelection?.mode,
projectSetting: selectedProject?.defaultThreadEnvMode,
projectFilePending: t3ProjectFileQuery.isPending,
});
const workspaceMode = selectedProjectDraft.workspaceSelection?.mode ?? defaultWorkspaceMode;
const selectedBranchName = selectedProjectDraft.workspaceSelection?.branch ?? null;
const selectedWorktreePath = selectedProjectDraft.workspaceSelection?.worktreePath ?? null;
@@ -359,14 +397,16 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
const runtimeMode = selectedProjectDraft.runtimeMode ?? DEFAULT_RUNTIME_MODE;
const interactionMode = selectedProjectDraft.interactionMode ?? DEFAULT_PROVIDER_INTERACTION_MODE;
// Stored selections (draft and project default) only count while their
// provider is usable on the server; otherwise the server's default model
// wins instead of silently targeting a disabled provider.
// Stored selections only count while their provider is usable on the
// server; otherwise the server's default model wins instead of silently
// targeting a disabled provider. The draft selection is an explicit pick
// and passes through as-is; the project default (last used, possibly from
// desktop) is implicit and additionally never resolves to a legacy model.
const draftModelSelection = resolveSelectableModelSelection(
selectedEnvironmentServerConfig,
selectedProjectDraft.modelSelection ?? null,
);
const projectDefaultModelSelection = resolveSelectableModelSelection(
const projectDefaultModelSelection = resolveDefaultableModelSelection(
selectedEnvironmentServerConfig,
selectedProject?.defaultModelSelection ?? null,
);
@@ -404,7 +444,9 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
[selectedEnvironmentServerConfig, selectedModel?.instanceId],
);
const setSelectedModelKey = useCallback(
(key: string | null) => {
// Options ride along in the same write: a follow-up setSelectedModelOptions
// call would rebuild the selection from the stale pre-switch model.
(key: string | null, options?: ReadonlyArray<ProviderOptionSelection>) => {
if (!key || !selectedProjectDraftKey) {
return;
}
@@ -413,7 +455,7 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
return;
}
updateComposerDraftSettings(selectedProjectDraftKey, {
modelSelection: option.selection,
modelSelection: options ? { ...option.selection, options } : option.selection,
});
},
[modelOptions, selectedProjectDraftKey],
@@ -610,7 +652,11 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
}, [refreshBranches, selectedProject]);
useEffect(() => {
if (workspaceMode !== "worktree" || selectedBranchName !== null) {
if (
!defaultWorkspaceModeSettled ||
workspaceMode !== "worktree" ||
selectedBranchName !== null
) {
return;
}
// The default may only exist as origin/<default> (isRemote), which
@@ -622,7 +668,14 @@ export function NewTaskFlowProvider(props: React.PropsWithChildren) {
if (preferredBranch) {
selectBranch(preferredBranch);
}
}, [allBranchRefs, availableBranches, selectBranch, selectedBranchName, workspaceMode]);
}, [
allBranchRefs,
availableBranches,
defaultWorkspaceModeSettled,
selectBranch,
selectedBranchName,
workspaceMode,
]);
const setRuntimeMode = useCallback(
(value: RuntimeMode) => {
@@ -0,0 +1,38 @@
import { describe, expect, it } from "vite-plus/test";
import { derivePendingUserInputMaxHeight } from "./pendingUserInputLayout";
describe("derivePendingUserInputMaxHeight", () => {
it("caps a tall portrait viewport", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 932,
keyboardHeight: 0,
navigationHeaderHeight: 103,
composerOverlapHeight: 94,
}),
).toBe(560);
});
it("subtracts the keyboard while editing a custom answer", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 932,
keyboardHeight: 336,
navigationHeaderHeight: 103,
composerOverlapHeight: 94,
}),
).toBe(387);
});
it("keeps the fixed action area usable in a short keyboard-open viewport", () => {
expect(
derivePendingUserInputMaxHeight({
windowHeight: 375,
keyboardHeight: 240,
navigationHeaderHeight: 44,
composerOverlapHeight: 94,
}),
).toBe(160);
});
});
@@ -0,0 +1,37 @@
const PENDING_USER_INPUT_MAX_HEIGHT = 560;
const PENDING_USER_INPUT_MIN_HEIGHT = 160;
const PENDING_USER_INPUT_VERTICAL_GAP = 12;
/**
* Reserve for a portrait iPhone keyboard with the QuickType bar until a real
* height has been observed. Overestimating only costs card height; an
* underestimate would let the card overshoot on the first keyboard open.
*/
export const ESTIMATED_KEYBOARD_HEIGHT = 336;
/**
* One clock for the questionnaire expand/collapse choreography: the card's
* enter/exit and the feed-inset glide must share it or they visibly drift.
* Sized for the near-full-height slide (the card travels its own height),
* in the same class as the iOS keyboard's ~250ms.
*/
export const USER_INPUT_TOGGLE_DURATION_MS = 220;
export function derivePendingUserInputMaxHeight(input: {
readonly windowHeight: number;
readonly keyboardHeight: number;
readonly navigationHeaderHeight: number;
readonly composerOverlapHeight: number;
}): number {
const availableHeight =
input.windowHeight -
Math.max(0, input.keyboardHeight) -
Math.max(0, input.navigationHeaderHeight) -
Math.max(0, input.composerOverlapHeight) -
PENDING_USER_INPUT_VERTICAL_GAP;
return Math.min(
PENDING_USER_INPUT_MAX_HEIGHT,
Math.max(PENDING_USER_INPUT_MIN_HEIGHT, availableHeight),
);
}
@@ -1,16 +0,0 @@
import { View } from "react-native";
import { T3HeaderButton } from "../../native/T3HeaderButton.android";
import type { SidebarHeaderActionsProps } from "./sidebar-header-actions";
export function SidebarHeaderActions(props: SidebarHeaderActionsProps) {
return (
<View className="h-11 flex-row gap-1">
<T3HeaderButton
accessibilityLabel="Open settings"
icon="gearshape"
onPress={props.onOpenSettings}
/>
</View>
);
}
@@ -0,0 +1,70 @@
import { describe, expect, it } from "vite-plus/test";
import { resolveThreadFeedLiveFollow } from "./thread-feed-live-follow";
describe("resolveThreadFeedLiveFollow", () => {
it("pauses immediately when the user starts scrolling", () => {
expect(resolveThreadFeedLiveFollow(true, { type: "user-scroll-begin" })).toBe(false);
});
it("stays paused away from the actual end", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "scroll",
isAtEnd: false,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("does not mistake programmatic layout compensation for a user scroll", () => {
expect(
resolveThreadFeedLiveFollow(true, {
type: "scroll",
isAtEnd: false,
userScrollSessionActive: false,
}),
).toBe(true);
});
it("does not re-arm at the end while a user scroll session is active", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "scroll",
isAtEnd: true,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("re-arms at the actual end only after the user scroll session ends", () => {
expect(
resolveThreadFeedLiveFollow(false, {
type: "user-scroll-end",
isAtEnd: true,
userScrollSessionActive: true,
}),
).toBe(true);
expect(
resolveThreadFeedLiveFollow(false, {
type: "user-scroll-end",
isAtEnd: false,
userScrollSessionActive: true,
}),
).toBe(false);
});
it("ignores momentum-end events from programmatic scrolling", () => {
expect(
resolveThreadFeedLiveFollow(true, {
type: "user-scroll-end",
isAtEnd: false,
userScrollSessionActive: false,
}),
).toBe(true);
});
it("re-arms after an explicit reset", () => {
expect(resolveThreadFeedLiveFollow(false, { type: "reset" })).toBe(true);
});
});
@@ -0,0 +1,35 @@
export type ThreadFeedLiveFollowEvent =
| { readonly type: "reset" }
| { readonly type: "user-scroll-begin" }
| {
readonly type: "user-scroll-end";
readonly isAtEnd: boolean;
readonly userScrollSessionActive: boolean;
}
| {
readonly type: "scroll";
readonly isAtEnd: boolean;
readonly userScrollSessionActive: boolean;
};
export function resolveThreadFeedLiveFollow(
current: boolean,
event: ThreadFeedLiveFollowEvent,
): boolean {
switch (event.type) {
case "reset":
return true;
case "user-scroll-begin":
return false;
case "user-scroll-end":
return event.userScrollSessionActive ? event.isAtEnd : current;
case "scroll":
if (event.userScrollSessionActive) {
return false;
}
if (event.isAtEnd) {
return true;
}
return current;
}
}
@@ -22,6 +22,7 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import { resolveThreadStatus } from "./threadPresentation";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
@@ -134,6 +135,7 @@ export const ThreadListGroupHeader = memo(function ThreadListGroupHeader(props:
>
<ProjectFavicon
environmentId={props.project.environmentId}
faviconPath={props.project.faviconPath}
open={!props.collapsed}
size={compact ? 22 : 18}
projectTitle={props.project.title}
@@ -429,6 +431,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly titleRegenerationSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
@@ -450,7 +454,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
props;
const status = resolveThreadStatus(thread);
const pr = useThreadPr(thread, props.projectCwd);
const timestamp = relativeTime(
@@ -470,6 +475,21 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const menuActions = useMemo<MenuAction[]>(
() => [
THREAD_ROW_MENU_ACTIONS[0]!,
...buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
THREAD_ROW_MENU_ACTIONS[1]!,
],
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const primaryAction = useMemo(
() => ({
accessibilityLabel: `Archive ${thread.title}`,
@@ -482,9 +502,10 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete],
[handleArchive, handleDelete, handleRegenerateTitle],
);
const statusPill = effectiveStatus ? (
@@ -673,7 +694,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
// ControlPillMenu injects onLongPress into the row and anchors the
// token-styled dropdown to it; taps and swipes are untouched.
<ControlPillMenu
actions={THREAD_ROW_MENU_ACTIONS}
actions={menuActions}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
@@ -27,6 +27,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
@@ -65,8 +66,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
}
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
// its own surface (thread screen / settings) rather than crowding the row.
// Menus keep lifecycle and title regeneration together. Archive keeps its
// own surface (thread screen / settings) rather than crowding v2 rows.
const CARD_MENU_ACTIONS: MenuAction[] = [
{ id: "settle", title: "Settle", image: "checkmark" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
@@ -230,6 +231,7 @@ export const ThreadListV2PendingRow = memo(function ThreadListV2PendingRow(props
{props.project ? (
<ProjectFavicon
environmentId={pendingTask.message.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={projectTitle}
workspaceRoot={props.project.workspaceRoot}
@@ -340,6 +342,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly fullSwipeWidth?: number;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
@@ -354,6 +357,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
/** False on servers that predate thread title regeneration. */
readonly titleRegenerationSupported: boolean;
/** False on servers that predate thread.pin.reorder. Gates the pinned
Move up / Move down menu items. */
readonly pinReorderSupported?: boolean;
@@ -364,8 +369,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly canMovePinnedDown?: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
/** Reports this row's live PR state up so the partition can auto-settle
merged/closed work (mirrors web's onChangeRequestState). */
/** Reports this row's live PR state for the partition's merge and close
rules. Mirrors web's onChangeRequestState. */
readonly onChangeRequestState?: (
threadKey: string,
state: "open" | "closed" | "merged" | null,
@@ -383,6 +388,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
variant,
onSelectThread,
onDeleteThread,
onRegenerateThreadTitle,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
@@ -416,6 +422,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
@@ -505,6 +515,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
props.pinningSupported,
],
);
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
() =>
buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
@@ -515,13 +533,31 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
subactions: snoozePresetActions,
},
...pinMenuItem,
...titleRegenerationMenuItems,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[pinMenuItem, snoozePresetActions],
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
() => [
CARD_MENU_ACTIONS[0]!,
...pinMenuItem,
...titleRegenerationMenuItems,
...CARD_MENU_ACTIONS.slice(1),
],
[pinMenuItem, titleRegenerationMenuItems],
);
const slimMenuActions = useMemo<MenuAction[]>(
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const snoozedMenuActions = useMemo<MenuAction[]>(
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const legacyMenuActions = useMemo<MenuAction[]>(
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -533,6 +569,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
@@ -548,6 +585,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleRegenerateTitle,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
@@ -630,6 +668,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
{props.project ? (
<ProjectFavicon
environmentId={thread.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
@@ -818,6 +857,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<View className="opacity-40">
<ProjectFavicon
environmentId={thread.environmentId}
faviconPath={props.project.faviconPath}
size={15}
projectTitle={props.projectTitle ?? props.project.title}
workspaceRoot={props.project.workspaceRoot}
@@ -887,11 +927,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ControlPillMenu
actions={
snoozedRow
? SNOOZED_MENU_ACTIONS
? snoozedMenuActions
: !props.settlementSupported
? LEGACY_MENU_ACTIONS
? legacyMenuActions
: canUnsettle
? SLIM_MENU_ACTIONS
? slimMenuActions
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: cardMenuActions
@@ -0,0 +1,284 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ProviderOptionDescriptor } from "@t3tools/contracts";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
import { buildThreadSettingsMenu, type ThreadSettingsMenuEvent } from "./thread-settings-menu";
function modelOption(
model: string,
overrides: Partial<Pick<ModelOption, "isDefault" | "isLegacy" | "providerKey">> = {},
): ModelOption {
const providerKey = overrides.providerKey ?? "codex";
return {
key: `${providerKey}:${model}`,
label: model,
subtitle: providerKey,
providerKey,
providerLabel: providerKey === "codex" ? "Codex" : "Claude",
providerDriver: providerKey === "codex" ? "codex" : "claudeAgent",
isDefault: overrides.isDefault ?? false,
isLegacy: overrides.isLegacy ?? false,
capabilities: null,
selection: {
instanceId: ProviderInstanceId.make(providerKey),
model,
options: [],
},
};
}
function group(models: ReadonlyArray<ModelOption>): ProviderGroup {
const first = models[0];
if (!first) {
throw new Error("group requires at least one model");
}
return {
providerKey: first.providerKey,
providerLabel: first.providerLabel,
models,
};
}
const effortDescriptor: ProviderOptionDescriptor = {
id: "effort",
label: "Reasoning",
type: "select",
options: [
{ id: "low", label: "Low" },
{ id: "medium", label: "Medium", isDefault: true },
{ id: "high", label: "High" },
{ id: "ultrathink", label: "Ultrathink" },
{ id: "ultracode", label: "Ultracode" },
],
currentValue: "high",
promptInjectedValues: ["ultrathink"],
};
const fastModeDescriptor: ProviderOptionDescriptor = {
id: "fastMode",
label: "Fast mode",
type: "boolean",
currentValue: false,
};
function baseInput() {
const models = [
modelOption("gpt-current", { isDefault: true }),
modelOption("gpt-next"),
modelOption("gpt-old", { isLegacy: true }),
];
return {
providerGroups: [group(models)],
selectedModel: models[0]?.selection ?? null,
optionDescriptors: [effortDescriptor, fastModeDescriptor],
runtimeMode: "auto",
} as const;
}
function eventFor(menu: ReturnType<typeof buildThreadSettingsMenu>, id: string | undefined) {
return id === undefined ? undefined : menu.events.get(id);
}
describe("buildThreadSettingsMenu", () => {
it("orders the top level as model, options, runtime", () => {
const menu = buildThreadSettingsMenu(baseInput());
expect(menu.actions.map((action) => action.title)).toEqual([
"Model",
"Reasoning",
"Fast mode",
"Runtime",
]);
});
it("summarizes the current choice on each submenu row", () => {
const menu = buildThreadSettingsMenu(baseInput());
expect(menu.actions.find((action) => action.title === "Model")?.subtitle).toBe("gpt-current");
expect(menu.actions.find((action) => action.title === "Reasoning")?.subtitle).toBe("High");
expect(menu.actions.find((action) => action.title === "Runtime")?.subtitle).toBe("Auto");
});
it("checkmarks the selected model and resolves selection events", () => {
const menu = buildThreadSettingsMenu(baseInput());
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
const current = modelItems.find((action) => action.title === "gpt-current");
expect(current?.state).toBe("on");
expect(current?.subtitle).toBe("Default");
expect(modelItems.find((action) => action.title === "gpt-next")?.state).toBe("off");
const event = eventFor(menu, modelItems.find((action) => action.title === "gpt-next")?.id);
expect(event?.type).toBe("select-model");
expect(event?.type === "select-model" ? event.option.selection.model : null).toBe("gpt-next");
});
it("folds unselected legacy models behind a nested submenu", () => {
const menu = buildThreadSettingsMenu(baseInput());
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(modelItems.map((action) => action.title)).toEqual([
"gpt-current",
"gpt-next",
"Legacy Models",
]);
expect(
modelItems
.find((action) => action.title === "Legacy Models")
?.subactions?.map((action) => action.title),
).toEqual(["gpt-old"]);
});
it("keeps a selected legacy model in the main list", () => {
const input = baseInput();
const legacy = input.providerGroups[0]?.models.find((model) => model.isLegacy);
const menu = buildThreadSettingsMenu({
...input,
selectedModel: legacy?.selection ?? null,
});
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(modelItems.map((action) => action.title)).toEqual([
"gpt-current",
"gpt-next",
"gpt-old",
]);
expect(modelItems.find((action) => action.title === "gpt-old")?.state).toBe("on");
});
it("hides prompt-injected and workflow-trigger efforts but still summarizes them", () => {
const menu = buildThreadSettingsMenu({
...baseInput(),
optionDescriptors: [{ ...effortDescriptor, currentValue: "ultracode" }],
});
const reasoning = menu.actions.find((action) => action.title === "Reasoning");
expect(reasoning?.subactions?.map((action) => action.title)).toEqual(["Low", "Medium", "High"]);
// The hidden value stays visible as the current summary; it just can't be
// picked from the phone.
expect(reasoning?.subtitle).toBe("Ultracode");
expect(reasoning?.subactions?.every((action) => action.state === "off")).toBe(true);
});
it("resolves select-option and runtime events with checkmarked current values", () => {
const menu = buildThreadSettingsMenu(baseInput());
const reasoningItems =
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
expect(reasoningItems.find((action) => action.title === "High")?.state).toBe("on");
expect(eventFor(menu, reasoningItems.find((action) => action.title === "Low")?.id)).toEqual({
type: "set-option",
optionId: "effort",
value: "low",
});
const runtimeItems =
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
expect(runtimeItems.find((action) => action.title === "Auto")?.state).toBe("on");
expect(
eventFor(menu, runtimeItems.find((action) => action.title === "Full access")?.id),
).toEqual({ type: "set-runtime", mode: "full-access" });
});
it("toggles boolean options with the inverted current value", () => {
const menu = buildThreadSettingsMenu(baseInput());
const fastMode = menu.actions.find((action) => action.title === "Fast mode");
expect(fastMode?.state).toBe("off");
expect(fastMode?.subactions).toBeUndefined();
expect(eventFor(menu, fastMode?.id)).toEqual({
type: "set-option",
optionId: "fastMode",
value: true,
});
const enabled = buildThreadSettingsMenu({
...baseInput(),
optionDescriptors: [{ ...fastModeDescriptor, currentValue: true }],
});
const enabledRow = enabled.actions.find((action) => action.title === "Fast mode");
expect(enabledRow?.state).toBe("on");
expect(eventFor(enabled, enabledRow?.id)).toEqual({
type: "set-option",
optionId: "fastMode",
value: false,
});
});
it("keeps the menu presented only for top-level toggles", () => {
const menu = buildThreadSettingsMenu(baseInput());
// Root-level boolean toggles refresh in place with clean chrome, so they
// keep the menu presented.
expect(
menu.actions.find((action) => action.title === "Fast mode")?.attributes?.keepsMenuPresented,
).toBe(true);
// Picks inside nested submenus close the menu: staying presented leaves
// the submenu on screen with an expanded-submenu header, and the
// bottom-anchored collapse back out drops by the levels' height delta.
const expected = undefined;
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
const reasoningItems =
menu.actions.find((action) => action.title === "Reasoning")?.subactions ?? [];
const runtimeItems =
menu.actions.find((action) => action.title === "Runtime")?.subactions ?? [];
const nestedPicks = [...modelItems, ...reasoningItems, ...runtimeItems].filter(
(action) => action.subactions === undefined,
);
expect(nestedPicks.length).toBeGreaterThan(0);
expect(nestedPicks.every((action) => action.attributes?.keepsMenuPresented === expected)).toBe(
true,
);
});
it("sections models by provider only when multiple groups are offered", () => {
const codexModels = [modelOption("gpt-current", { isDefault: true })];
const claudeModels = [modelOption("fable-5", { providerKey: "claude" })];
const menu = buildThreadSettingsMenu({
providerGroups: [group(codexModels), group(claudeModels)],
selectedModel: codexModels[0]?.selection ?? null,
optionDescriptors: [],
runtimeMode: "auto",
});
const modelItems = menu.actions.find((action) => action.title === "Model")?.subactions ?? [];
expect(
modelItems.map((action) => ({ title: action.title, inline: action.displayInline ?? false })),
).toEqual([
{ title: "Codex", inline: true },
{ title: "Claude", inline: true },
]);
const claudeSection = modelItems.find((action) => action.title === "Claude");
expect(claudeSection?.subactions?.map((action) => action.title)).toEqual(["fable-5"]);
});
const eventTypes = (menu: ReturnType<typeof buildThreadSettingsMenu>) => {
const types = new Set<ThreadSettingsMenuEvent["type"]>();
for (const event of menu.events.values()) {
types.add(event.type);
}
return types;
};
it("registers an event for every leaf action id", () => {
const menu = buildThreadSettingsMenu(baseInput());
const leafIds: string[] = [];
const collect = (items: ReadonlyArray<{ id?: string; subactions?: unknown[] }>) => {
for (const item of items) {
if (Array.isArray(item.subactions) && item.subactions.length > 0) {
collect(item.subactions as ReadonlyArray<{ id?: string; subactions?: unknown[] }>);
} else if (item.id !== undefined) {
leafIds.push(item.id);
}
}
};
collect(menu.actions);
for (const id of leafIds) {
expect(menu.events.get(id), `missing event for ${id}`).toBeDefined();
}
expect(eventTypes(menu)).toEqual(new Set(["select-model", "set-option", "set-runtime"]));
});
});
@@ -0,0 +1,202 @@
import type { MenuAction } from "@react-native-menu/menu";
import type { ModelSelection, ProviderOptionDescriptor, RuntimeMode } from "@t3tools/contracts";
import {
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
} from "@t3tools/shared/model";
import type { ModelOption, ProviderGroup } from "../../lib/modelOptions";
/**
* Desktop-oriented effort keywords that don't belong in the phone picker.
* Prompt-injected values (ultrathink and friends) are filtered from the
* descriptor metadata; ultracode is a real option but a workflow trigger, not
* a reasoning level. A value set elsewhere still displays, it just isn't
* offered.
*/
export const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
export const RUNTIME_MODE_CHOICES: ReadonlyArray<{
readonly mode: RuntimeMode;
readonly label: string;
readonly shortLabel: string;
}> = [
{ mode: "approval-required", label: "Approve actions", shortLabel: "Approve" },
{ mode: "auto-accept-edits", label: "Auto-accept edits", shortLabel: "Edits" },
{ mode: "auto", label: "Auto", shortLabel: "Auto" },
{ mode: "full-access", label: "Full access", shortLabel: "Full" },
];
export function selectableChoices(
descriptor: Extract<ProviderOptionDescriptor, { type: "select" }>,
) {
const injected = new Set(descriptor.promptInjectedValues ?? []);
return descriptor.options.filter(
(option) => !injected.has(option.id) && !HIDDEN_EFFORT_OPTION_IDS.has(option.id),
);
}
export type ThreadSettingsMenuEvent =
| { readonly type: "select-model"; readonly option: ModelOption }
| { readonly type: "set-option"; readonly optionId: string; readonly value: string | boolean }
| { readonly type: "set-runtime"; readonly mode: RuntimeMode };
export type ThreadSettingsMenu = {
readonly actions: MenuAction[];
/** Menu action id → the change it applies, for the onPressAction dispatch. */
readonly events: ReadonlyMap<string, ThreadSettingsMenuEvent>;
};
/**
* Native menu replacement for the thread settings sheet (model, select and
* boolean provider options, runtime mode). The menu presents from the
* composer pill without resigning the keyboard, so adjusting settings never
* bounces focus. A thread is bound to one harness, so the menu covers the
* sheet's full surface for existing threads; the sheet remains the Android
* and new-task-draft surface.
*
* Selections apply immediately — the sheet's stage-then-Save flow only exists
* because the sheet batches a model change with its option edits.
*/
export function buildThreadSettingsMenu(input: {
readonly providerGroups: ReadonlyArray<ProviderGroup>;
readonly selectedModel: ModelSelection | null;
readonly optionDescriptors: ReadonlyArray<ProviderOptionDescriptor>;
readonly runtimeMode: RuntimeMode;
}): ThreadSettingsMenu {
const events = new Map<string, ThreadSettingsMenuEvent>();
const actions: MenuAction[] = [];
const isSelected = (option: ModelOption) =>
option.selection.instanceId === input.selectedModel?.instanceId &&
option.selection.model === input.selectedModel.model;
// Only top-level leaves (boolean toggles) keep the menu presented (iOS
// 16+): the root refreshes in place with clean chrome. Picks inside nested
// submenus close the menu — keeping the submenu presented renders an
// expanded-submenu header with no way to pop back to the root, and the
// bottom-anchored collapse back out travels the levels' height difference.
const keepPresented = { keepsMenuPresented: true } as const;
const modelAction = (option: ModelOption, id: string): MenuAction => {
events.set(id, { type: "select-model", option });
return {
id,
title: option.label,
...(option.isDefault ? { subtitle: "Default" } : {}),
state: isSelected(option) ? "on" : "off",
};
};
const modelItems: MenuAction[] = [];
const legacyItems: MenuAction[] = [];
let selectedModelLabel: string | undefined;
input.providerGroups.forEach((group, groupIndex) => {
const groupItems: MenuAction[] = [];
group.models.forEach((option, modelIndex) => {
if (isSelected(option)) {
selectedModelLabel = option.label;
}
const id = `model:${groupIndex}:${modelIndex}`;
// A highlighted legacy model stays in the main list (mirroring the
// sheet) so the checkmark isn't hidden behind the Legacy fold.
if (option.isLegacy && !isSelected(option)) {
legacyItems.push(modelAction(option, id));
} else {
groupItems.push(modelAction(option, id));
}
});
if (groupItems.length === 0) {
return;
}
// A thread is bound to one harness, so provider sections only appear for
// multi-group callers (the new-task draft, if it ever adopts the menu).
if (input.providerGroups.length > 1) {
modelItems.push({
id: `model-group:${groupIndex}`,
title: group.providerLabel,
displayInline: true,
subactions: groupItems,
});
} else {
modelItems.push(...groupItems);
}
});
if (legacyItems.length > 0) {
modelItems.push({
id: "legacy-models",
title: "Legacy Models",
subactions: legacyItems,
});
}
if (modelItems.length > 0) {
actions.push({
id: "model",
title: "Model",
...(selectedModelLabel === undefined
? input.selectedModel
? { subtitle: input.selectedModel.model }
: {}
: { subtitle: selectedModelLabel }),
subactions: modelItems,
});
}
for (const descriptor of input.optionDescriptors) {
if (descriptor.type === "boolean") {
const id = `option:${descriptor.id}`;
events.set(id, {
type: "set-option",
optionId: descriptor.id,
value: !(descriptor.currentValue ?? false),
});
actions.push({
id,
title: descriptor.label,
state: descriptor.currentValue ? "on" : "off",
attributes: keepPresented,
});
continue;
}
const currentValue = getProviderOptionCurrentValue(descriptor);
const choices = selectableChoices(descriptor).map((choice): MenuAction => {
const id = `option:${descriptor.id}:${choice.id}`;
events.set(id, { type: "set-option", optionId: descriptor.id, value: choice.id });
return {
id,
title: choice.label,
state: choice.id === currentValue ? "on" : "off",
};
});
if (choices.length === 0) {
continue;
}
const currentLabel = getProviderOptionCurrentLabel(descriptor);
actions.push({
id: `option:${descriptor.id}`,
title: descriptor.label,
...(currentLabel === undefined ? {} : { subtitle: currentLabel }),
subactions: choices,
});
}
const runtimeLabel = RUNTIME_MODE_CHOICES.find(
(choice) => choice.mode === input.runtimeMode,
)?.label;
actions.push({
id: "runtime",
title: "Runtime",
...(runtimeLabel === undefined ? {} : { subtitle: runtimeLabel }),
subactions: RUNTIME_MODE_CHOICES.map((choice): MenuAction => {
const id = `runtime:${choice.mode}`;
events.set(id, { type: "set-runtime", mode: choice.mode });
return {
id,
title: choice.label,
state: choice.mode === input.runtimeMode ? "on" : "off",
};
}),
});
return { actions, events };
}
@@ -0,0 +1,64 @@
import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ProviderOptionSelection } from "@t3tools/contracts";
import type { ModelOption } from "../../lib/modelOptions";
import { pendingModelAfterPress } from "./thread-settings-sheet-state";
function modelOption(
model: string,
options: ReadonlyArray<ProviderOptionSelection> = [],
): ModelOption {
return {
key: `codex:${model}`,
label: model,
subtitle: "Codex",
providerKey: "codex",
providerLabel: "Codex",
providerDriver: "codex",
isDefault: false,
isLegacy: false,
capabilities: null,
selection: {
instanceId: ProviderInstanceId.make("codex"),
model,
options,
},
};
}
describe("thread settings sheet state", () => {
it("clears staging when the applied model is pressed", () => {
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed: modelOption("gpt-current"),
pressedIsApplied: true,
}),
).toBeNull();
});
it("preserves staged options when the highlighted model is pressed again", () => {
const pending = modelOption("gpt-next", [{ id: "effort", value: "high" }]);
expect(
pendingModelAfterPress({
current: pending,
pressed: modelOption("gpt-next"),
pressedIsApplied: false,
}),
).toBe(pending);
});
it("stages a different model", () => {
const pressed = modelOption("gpt-other");
expect(
pendingModelAfterPress({
current: modelOption("gpt-next"),
pressed,
pressedIsApplied: false,
}),
).toBe(pressed);
});
});
@@ -0,0 +1,13 @@
import type { ModelOption } from "../../lib/modelOptions";
/** Preserve staged provider options when the highlighted model is tapped again. */
export function pendingModelAfterPress(input: {
readonly current: ModelOption | null;
readonly pressed: ModelOption;
readonly pressedIsApplied: boolean;
}): ModelOption | null {
if (input.pressedIsApplied) {
return null;
}
return input.current?.key === input.pressed.key ? input.current : input.pressed;
}
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vite-plus/test";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
describe("buildThreadTitleRegenerationMenuItems", () => {
it("hides regeneration when the environment does not advertise support", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
).toEqual([]);
});
it("offers regeneration for a supported environment", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerate title",
image: "arrow.clockwise",
},
]);
});
it("shows and disables the pending state", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerating…",
image: "arrow.clockwise",
attributes: { disabled: true },
},
]);
});
});
@@ -0,0 +1,17 @@
import type { MenuAction } from "@react-native-menu/menu";
export function buildThreadTitleRegenerationMenuItems(input: {
readonly supported: boolean;
readonly isRegenerating: boolean;
}): MenuAction[] {
if (!input.supported) return [];
return [
{
id: "regenerate-title",
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
image: "arrow.clockwise",
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
},
];
}
@@ -104,20 +104,24 @@ describe("resolveThreadListV2SnoozeMenuSelection", () => {
describe("resolveThreadListV2Enabled", () => {
it("defaults on when the device has never chosen", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: true })).toBe(
true,
);
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: true }),
).toBe(true);
});
it("honors an explicit device opt-out", () => {
expect(resolveThreadListV2Enabled({ preference: false, preferencesLoaded: true })).toBe(false);
expect(resolveThreadListV2Enabled({ preference: true, preferencesLoaded: true })).toBe(true);
it("honors an explicit legacy opt-in", () => {
expect(resolveThreadListV2Enabled({ legacyPreference: true, preferencesLoaded: true })).toBe(
false,
);
expect(resolveThreadListV2Enabled({ legacyPreference: false, preferencesLoaded: true })).toBe(
true,
);
});
it("holds the default while preferences are still loading so the list does not remount", () => {
expect(resolveThreadListV2Enabled({ preference: undefined, preferencesLoaded: false })).toBe(
true,
);
expect(
resolveThreadListV2Enabled({ legacyPreference: undefined, preferencesLoaded: false }),
).toBe(true);
});
});
@@ -259,6 +263,21 @@ describe("sortThreadsForListV2", () => {
});
describe("buildThreadListV2Items", () => {
it("keeps a merged thread active when auto-settle on merge is off", () => {
const merged = makeThread({ id: ThreadId.make("merged"), title: "Merged" });
const layout = buildThreadListV2Items({
threads: [merged],
environmentId: null,
searchQuery: "",
changeRequestStateByKey: new Map([[`${environmentId}:${merged.id}`, "merged"]]),
autoSettleOnMerge: false,
now: NOW,
});
expect(layout.items.map((item) => item.thread.id)).toEqual(["merged"]);
expect(layout.settledCount).toBe(0);
});
it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -103,23 +103,23 @@ export const THREAD_LIST_V2_SETTLED_INITIAL_COUNT = 10;
export const THREAD_LIST_V2_SETTLED_PAGE_COUNT = 25;
/**
* Thread List v2 is on by default on every app variant; the Settings → Beta
* toggle is an opt-out. Preferences persist as sparse patches, so `undefined`
* genuinely means "never chosen".
* The flat Thread List v2 is the default on every app variant; the Settings →
* Legacy toggle opts a device back into the grouped legacy list. Preferences
* persist as sparse patches, so `undefined` genuinely means "never chosen".
*
* `preferencesLoaded` guards the startup window: preferences load
* asynchronously, and rendering one list before the stored choice arrives would
* remount the whole thing a tick later. While loading, hold the default — that
* is where every device without an explicit opt-out lands anyway.
* is where every device without an explicit legacy opt-in lands anyway.
*/
export function resolveThreadListV2Enabled(input: {
readonly preference: boolean | undefined;
readonly legacyPreference: boolean | undefined;
readonly preferencesLoaded: boolean;
}): boolean {
if (!input.preferencesLoaded) {
return true;
}
return input.preference ?? true;
return input.legacyPreference !== true;
}
export function resolveThreadListV2Status(
@@ -306,9 +306,8 @@ export function buildThreadListV2ListItems(input: {
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
* the default is fixed here rather than user-configurable.
* the settled recency tail, matching the web v2 list. Mobile stores these
* auto-settle preferences per device.
*/
export function buildThreadListV2Items(input: {
readonly threads: ReadonlyArray<EnvironmentThreadShell>;
@@ -329,6 +328,7 @@ export function buildThreadListV2Items(input: {
contract as settlementEnvironmentIds. */
readonly snoozeEnvironmentIds?: ReadonlySet<EnvironmentId>;
readonly autoSettleAfterDays?: number;
readonly autoSettleOnMerge?: boolean;
/** Max settled rows to render; the rest are counted, not built. */
readonly settledLimit?: number;
/** Injectable for tests; defaults to now. */
@@ -349,6 +349,7 @@ export function buildThreadListV2Items(input: {
const now = input.now ?? new Date().toISOString();
const snoozeNow = input.snoozeNow ?? now;
const autoSettleAfterDays = input.autoSettleAfterDays ?? 3;
const autoSettleOnMerge = input.autoSettleOnMerge ?? true;
const query = input.searchQuery.trim().toLocaleLowerCase();
const projectKeys = input.projectRefs
? new Set(input.projectRefs.map((ref) => `${ref.environmentId}:${ref.projectId}`))
@@ -405,7 +406,12 @@ export function buildThreadListV2Items(input: {
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
effectiveSettled(thread, {
now,
autoSettleAfterDays,
autoSettleOnMerge,
changeRequestState,
})
) {
settled.push(thread);
} else {
@@ -5,15 +5,15 @@ import { mobilePreferencesAtom } from "../../state/preferences";
import { resolveThreadListV2Enabled } from "./threadListV2";
/**
* Resolved Thread List v2 state: the device-local preference if the user has
* set one, otherwise the default (on). Every consumer must read through this
* Resolved Thread List v2 state: on unless the device opted into the legacy
* grouped list (Settings → Legacy). Every consumer must read through this
* rather than the raw preference, which is undefined until explicitly chosen.
*/
export function useThreadListV2Enabled(): boolean {
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const loaded = AsyncResult.isSuccess(preferencesResult);
return resolveThreadListV2Enabled({
preference: loaded ? preferencesResult.value.threadListV2Enabled : undefined,
legacyPreference: loaded ? preferencesResult.value.legacyThreadListEnabled : undefined,
preferencesLoaded: loaded,
});
}
@@ -0,0 +1,98 @@
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import { KeyboardController } from "react-native-keyboard-controller";
import type { ComposerEditorHandle } from "../../components/ComposerEditor";
export type ThreadSettingsSheetCloseReason = "save" | "dismiss";
type PresentationPhase = "closed" | "opening" | "visible" | "closing";
/**
* Keeps the custom native composer and the settings modal from owning focus at
* the same time. Opening waits for the keyboard dismissal to finish, while
* focus restoration waits for the modal's dismissal callback.
*/
export function useThreadSettingsSheetPresentation(input: {
readonly editorRef: RefObject<ComposerEditorHandle | null>;
readonly isEditorFocused: boolean;
}) {
const [phase, setPhase] = useState<PresentationPhase>("closed");
const isActiveRef = useRef(false);
const isMountedRef = useRef(true);
const openingIdRef = useRef(0);
const restoreFocusOnSaveRef = useRef(false);
const shouldRestoreAfterDismissRef = useRef(false);
useEffect(
() => () => {
isMountedRef.current = false;
isActiveRef.current = false;
openingIdRef.current += 1;
},
[],
);
const open = useCallback(() => {
if (isActiveRef.current) {
return;
}
isActiveRef.current = true;
restoreFocusOnSaveRef.current = input.isEditorFocused || KeyboardController.isVisible();
shouldRestoreAfterDismissRef.current = false;
setPhase("opening");
const openingId = openingIdRef.current + 1;
openingIdRef.current = openingId;
// Keyboard.dismiss() only tracks React Native TextInputs. The composer is
// a custom native text view, so explicitly resign its first responder too.
input.editorRef.current?.blur();
void KeyboardController.dismiss().then(() => {
if (!isMountedRef.current || !isActiveRef.current || openingIdRef.current !== openingId) {
return;
}
setPhase("visible");
});
}, [input.editorRef, input.isEditorFocused]);
const close = useCallback((reason: ThreadSettingsSheetCloseReason) => {
if (!isActiveRef.current) {
return;
}
openingIdRef.current += 1;
shouldRestoreAfterDismissRef.current = reason === "save" && restoreFocusOnSaveRef.current;
setPhase("closing");
}, []);
const onDismissed = useCallback(() => {
const shouldRestoreFocus = shouldRestoreAfterDismissRef.current;
shouldRestoreAfterDismissRef.current = false;
restoreFocusOnSaveRef.current = false;
isActiveRef.current = false;
setPhase("closed");
if (shouldRestoreFocus) {
input.editorRef.current?.focus();
}
}, [input.editorRef]);
// The new-task screen can have an autofocus queued before the sheet opens.
// Preserve that intent for Save without allowing it to focus under the modal.
const restoreFocusAfterSave = useCallback(() => {
if (isActiveRef.current) {
restoreFocusOnSaveRef.current = true;
}
}, []);
return {
isActive: phase !== "closed",
isActiveRef,
isVisible: phase === "visible",
open,
close,
onDismissed,
restoreFocusAfterSave,
} as const;
}
@@ -32,6 +32,19 @@ function makeUpdateClient(overrides: Partial<AppUpdateClient> = {}): AppUpdateCl
}
describe("runAppUpdateCheck", () => {
it("does nothing while running from the Metro development server", async () => {
vi.stubGlobal("__DEV__", true);
const client = makeUpdateClient();
try {
await runAppUpdateCheck({ client });
} finally {
vi.unstubAllGlobals();
}
expect(client.checkForUpdateAsync).not.toHaveBeenCalled();
});
it("downloads and restarts when a new update is available", async () => {
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => ({
@@ -100,6 +113,32 @@ describe("runAppUpdateCheck", () => {
reportError.mockRestore();
});
it.each(["ERR_NOT_AVAILABLE_IN_DEV_CLIENT", "ERR_UPDATES_DISABLED"])(
"treats Expo's %s failure as an unavailable update check",
async (code) => {
const reportError = vi.spyOn(console, "error").mockImplementation(() => {});
const error = Object.assign(new Error("Updates are unavailable"), { code });
const client = makeUpdateClient({
checkForUpdateAsync: vi.fn(async () => {
throw error;
}),
});
const failures: string[] = [];
const states: AppUpdateCheckState[] = [];
await runAppUpdateCheck({
client,
onFailure: (message) => failures.push(message),
onStateChange: (state) => states.push(state),
});
expect(reportError).not.toHaveBeenCalled();
expect(failures).toEqual([]);
expect(states).toEqual(["checking", "idle"]);
reportError.mockRestore();
},
);
it("coalesces overlapping launch and manual checks", async () => {
let resolveCheck!: (result: {
readonly isAvailable: boolean;
@@ -48,8 +48,17 @@ interface Deferred {
}
const HIDDEN_UPDATE_TAP_COUNT = 5;
const UPDATE_CHECK_UNAVAILABLE_ERROR_CODES = new Set([
"ERR_NOT_AVAILABLE_IN_DEV_CLIENT",
"ERR_UPDATES_DISABLED",
]);
let appUpdateCheckInFlight: AppUpdateCheckInFlight | undefined;
/** Expo's development launcher reports updates as enabled even though its OTA APIs reject. */
export function isAppUpdateCheckAvailable(client: Pick<AppUpdateClient, "isEnabled"> = Updates) {
return client.isEnabled && !(typeof __DEV__ !== "undefined" && __DEV__);
}
/**
* Keeps the manual update affordance discoverable only to someone deliberately
* tapping the version row five times.
@@ -73,7 +82,7 @@ export function registerHiddenUpdateTap(count: number): {
export async function runAppUpdateCheck(options: AppUpdateCheckOptions = {}): Promise<void> {
const client = options.client ?? Updates;
if (!client.isEnabled) return;
if (!isAppUpdateCheckAvailable(client)) return;
if (appUpdateCheckInFlight) {
await observeAppUpdateCheck(appUpdateCheckInFlight, options);
@@ -207,19 +216,27 @@ function reportUpdateFailure(
fallback: string,
onFailure: AppUpdateCheckOptions["onFailure"],
): void {
reportAtomCommandResult(result, { label: "app update check" });
if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;
const error = squashAtomCommandFailure(result);
if (isAppUpdateUnavailableError(error)) return;
reportAtomCommandResult(result, { label: "app update check" });
onFailure?.(error instanceof Error ? error.message : fallback);
}
function isAppUpdateUnavailableError(error: unknown): boolean {
if (typeof error !== "object" || error === null || !("code" in error)) return false;
const code = error.code;
return typeof code === "string" && UPDATE_CHECK_UNAVAILABLE_ERROR_CODES.has(code);
}
export function createAppUpdateLaunchCheck(
client: AppUpdateClient = Updates,
): () => Promise<void> | undefined {
let started = false;
return () => {
if (started || !client.isEnabled) return undefined;
if (started || !isAppUpdateCheckAvailable(client)) return undefined;
started = true;
return runAppUpdateCheck({ client });
};
@@ -0,0 +1,50 @@
import { Chart, Host, type ChartDataPoint } from "@expo/ui/swift-ui";
import { frame } from "@expo/ui/swift-ui/modifiers";
import { useMemo } from "react";
import type { DailyTotals } from "@t3tools/shared/usageMerge";
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
import { useProviderColors } from "./usageProviders";
export interface UsageDailyChartProps {
readonly days: readonly string[];
readonly daily: readonly DailyTotals[];
readonly metric: UsageChartMetric;
readonly height: number;
}
/**
* Native Swift Charts daily bars. Points sharing an x value stack, so emitting
* one point per provider per day yields per-provider bands whose stack height
* is the day's total; changes animate natively.
*
* Axes are hidden: 30-90 categorical day labels cannot fit on a phone, so the
* screen renders its own edge labels under the chart instead.
*/
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
const colors = useProviderColors();
const data = useMemo((): ChartDataPoint[] => {
return buildChartDays(days, daily, metric).flatMap((day) =>
day.values.map((entry) => ({
x: day.day,
y: entry.value,
color: colors[entry.provider],
})),
);
}, [days, daily, metric, colors]);
return (
<Host style={{ height, width: "100%" }}>
<Chart
type="bar"
data={data}
animate
showGrid={false}
barStyle={{ cornerRadius: 2 }}
modifiers={[frame({ height })]}
/>
</Host>
);
}
@@ -0,0 +1,44 @@
import { useMemo } from "react";
import { View } from "react-native";
import type { DailyTotals } from "@t3tools/shared/usageMerge";
import { buildChartDays, type UsageChartMetric } from "./usageChartData";
import { useProviderColors } from "./usageProviders";
export interface UsageDailyChartProps {
readonly days: readonly string[];
readonly daily: readonly DailyTotals[];
readonly metric: UsageChartMetric;
readonly height: number;
}
/**
* Stacked daily bars drawn with plain views. Android and any platform without
* Swift Charts land here; iOS resolves `UsageDailyChart.ios.tsx` instead.
*/
export function UsageDailyChart({ days, daily, metric, height }: UsageDailyChartProps) {
const colors = useProviderColors();
const chartDays = useMemo(() => buildChartDays(days, daily, metric), [days, daily, metric]);
const max = chartDays.reduce((peak, day) => Math.max(peak, day.total), 0);
return (
<View style={{ height }} className="flex-row items-end gap-px">
{/* column-reverse stacks the bottom-first provider values upward
without reversing the array (Hermes lacks Array#toReversed). */}
{chartDays.map((day) => (
<View key={day.day} className="h-full flex-1 flex-col-reverse overflow-hidden rounded-sm">
{day.values.map((entry) => (
<View
key={entry.provider}
style={{
height: max === 0 ? 0 : (entry.value / max) * height,
backgroundColor: colors[entry.provider],
}}
/>
))}
</View>
))}
</View>
);
}
@@ -0,0 +1,500 @@
import { useNavigation } from "@react-navigation/native";
import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";
import {
enumerateDays,
enumerateHourStarts,
formatCount,
formatDayShort,
formatHourShort,
formatPercent,
formatTokens,
formatUsd,
makeWindow,
} from "@t3tools/shared/usageFormat";
import { useMemo, useState } from "react";
import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
import { AppText as Text } from "../../components/AppText";
import { NativeStackScreenOptions } from "../../native/StackHeader";
import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";
import { SettingsSection } from "../settings/components/SettingsSection";
import { UsageDailyChart } from "./UsageDailyChart";
import type { UsageChartMetric } from "./usageChartData";
import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";
const WINDOW_OPTIONS = [
{ days: 1, label: "Past 24h" },
{ days: 7, label: "7 days" },
{ days: 30, label: "30 days" },
{ days: 90, label: "90 days" },
] as const;
const CHART_HEIGHT = 180;
export function UsageRouteScreen() {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
const [windowSelection, setWindowSelection] = useState(() => ({
days: 30,
window: makeWindow(30),
}));
const [metric, setMetric] = useState<UsageChartMetric>("cost");
const { days: windowDays, window } = windowSelection;
const isPast24Hours = windowDays === 1;
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
const days = useMemo(
() => enumerateDays(window.sinceDay, window.untilDay),
[window.sinceDay, window.untilDay],
);
const chartDays = useMemo(
() =>
isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined
? enumerateHourStarts(window.sinceTime, window.untilTime)
: days,
[days, isPast24Hours, window.sinceTime, window.untilTime],
);
const chartTotals = useMemo(
(): readonly DailyTotals[] =>
isPast24Hours
? merged.hourly.map((hour) => ({
day: hour.hourStart,
costUsd: hour.costUsd,
totalTokens: hour.totalTokens,
byProvider: hour.byProvider,
}))
: merged.daily,
[isPast24Hours, merged.daily, merged.hourly],
);
// The pull spinner tracks re-scans of environments that have answered
// before. The initial scan renders its own placeholder, and an unreachable
// environment stays pending forever — neither may pin the spinner on.
const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);
const selectWindow = (days: number) => {
setWindowSelection({
days,
window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),
});
};
const refreshWindow = () => {
const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");
if (
nextWindow.sinceDay === window.sinceDay &&
nextWindow.untilDay === window.untilDay &&
nextWindow.sinceTime === window.sinceTime &&
nextWindow.untilTime === window.untilTime
) {
refresh();
} else {
setWindowSelection({ days: windowDays, window: nextWindow });
}
};
return (
<View collapsable={false} className="flex-1 bg-sheet">
{Platform.OS === "android" ? (
<>
<NativeStackScreenOptions options={{ headerShown: false }} />
<AndroidScreenHeader title="Usage" onBack={() => navigation.goBack()} />
</>
) : null}
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-6 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}
>
<SegmentedControl
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
selected={windowDays}
onSelect={selectWindow}
/>
<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />
{isPending ? (
<Text className="py-16 text-center text-base text-foreground-muted">
Scanning provider transcripts…
</Text>
) : environments.length === 0 ? (
<Text className="py-16 text-center text-base text-foreground-muted">
Connect an environment to see usage.
</Text>
) : (
<>
<ChartCard
merged={merged}
days={chartDays}
daily={chartTotals}
metric={metric}
onMetricChange={setMetric}
sinceDay={window.sinceDay}
untilDay={window.untilDay}
isPast24Hours={isPast24Hours}
timeZone={window.timeZone}
/>
<ProviderSection merged={merged} metric={metric} />
<TotalsSection merged={merged} isPast24Hours={isPast24Hours} />
<ModelsSection merged={merged} />
</>
)}
</ScrollView>
</View>
);
}
function SegmentedControl<Value extends number | string>(props: {
readonly options: readonly { readonly value: Value; readonly label: string }[];
readonly selected: Value;
readonly onSelect: (value: Value) => void;
}) {
return (
<View className="flex-row overflow-hidden rounded-full border-continuous bg-card">
{props.options.map((option) => {
const active = option.value === props.selected;
return (
<Pressable
key={String(option.value)}
accessibilityRole="button"
accessibilityState={{ selected: active }}
onPress={() => props.onSelect(option.value)}
className={
active
? "flex-1 items-center rounded-full bg-subtle-strong py-2"
: "flex-1 items-center py-2"
}
>
<Text
className={
active ? "text-sm font-t3-medium text-foreground" : "text-sm text-foreground-muted"
}
>
{option.label}
</Text>
</Pressable>
);
})}
</View>
);
}
/** Headline figure, the animated daily chart, and its legend, in one card. */
function ChartCard(props: {
readonly merged: MergedUsage;
readonly days: readonly string[];
readonly daily: readonly DailyTotals[];
readonly metric: UsageChartMetric;
readonly onMetricChange: (metric: UsageChartMetric) => void;
readonly sinceDay: string;
readonly untilDay: string;
readonly isPast24Hours: boolean;
readonly timeZone: string;
}) {
const { merged, metric } = props;
const colors = useProviderColors();
const hasActivity = props.daily.some((period) => period.totalTokens > 0);
return (
<View className="gap-4 rounded-[24px] border-continuous bg-card p-4">
<View className="flex-row items-start justify-between gap-3">
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-sm text-foreground-muted">
{metric === "cost" ? "Raw token cost" : "Processed tokens"}
</Text>
<Text className="text-4xl font-t3-bold tabular-nums text-foreground">
{metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}
</Text>
<Text className="text-sm text-foreground-muted">
{metric === "cost"
? "* if billed at full API rate"
: `Across ${formatCount(merged.sessions)} sessions`}
</Text>
</View>
<MetricToggle metric={metric} onChange={props.onMetricChange} />
</View>
{hasActivity ? (
<UsageDailyChart
days={props.days}
daily={props.daily}
metric={metric}
height={CHART_HEIGHT}
/>
) : (
<View style={{ height: CHART_HEIGHT }} className="items-center justify-center">
<Text className="text-base text-foreground-muted">No activity in this window.</Text>
</View>
)}
<View className="flex-row items-center justify-between">
<Text className="text-xs text-foreground-tertiary">
{props.isPast24Hours
? formatHourShort(props.days[0] ?? "", props.timeZone)
: formatDayShort(props.sinceDay)}
</Text>
<View className="flex-row items-center gap-4">
{merged.providers.map((provider) => (
<View key={provider.provider} className="flex-row items-center gap-1.5">
<View
className="size-2 rounded-full"
style={{ backgroundColor: colors[provider.provider] }}
/>
<Text className="text-xs text-foreground-muted">
{PROVIDER_LABEL[provider.provider]}
</Text>
</View>
))}
</View>
<Text className="text-xs text-foreground-tertiary">
{props.isPast24Hours
? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)
: formatDayShort(props.untilDay)}
</Text>
</View>
</View>
);
}
function MetricToggle(props: {
readonly metric: UsageChartMetric;
readonly onChange: (metric: UsageChartMetric) => void;
}) {
return (
<View className="flex-row overflow-hidden rounded-full bg-subtle">
{(["cost", "tokens"] as const).map((option) => {
const active = option === props.metric;
return (
<Pressable
key={option}
accessibilityRole="button"
accessibilityState={{ selected: active }}
onPress={() => props.onChange(option)}
className={active ? "rounded-full bg-subtle-strong px-3 py-1.5" : "px-3 py-1.5"}
>
<Text
className={
active
? "text-xs font-t3-medium uppercase text-foreground"
: "text-xs uppercase text-foreground-muted"
}
>
{option}
</Text>
</Pressable>
);
})}
</View>
);
}
function ProviderSection(props: {
readonly merged: MergedUsage;
readonly metric: UsageChartMetric;
}) {
const { merged, metric } = props;
const colors = useProviderColors();
if (merged.providers.length === 0) return null;
// Ranked by whatever the toggle is showing, so the rows always descend.
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.
const ordered = [...merged.providers].sort((a, b) =>
metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,
);
return (
<SettingsSection title="Providers" card>
{ordered.map((provider, index) => {
const share = metric === "cost" ? provider.costShare : provider.tokenShare;
return (
<View
key={provider.provider}
className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}
>
<View className="flex-row items-baseline justify-between gap-3">
<View className="flex-row items-center gap-2">
<View
className="size-2.5 rounded-full"
style={{ backgroundColor: colors[provider.provider] }}
/>
<Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>
</View>
<Text className="text-lg tabular-nums text-foreground">
{metric === "cost"
? formatUsd(provider.costUsd)
: formatTokens(provider.totalTokens)}
</Text>
</View>
<View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">
<View
className="h-full rounded-full"
style={{ flex: share, backgroundColor: colors[provider.provider] }}
/>
<View style={{ flex: 1 - share }} />
</View>
<Text className="text-sm text-foreground-muted">
{metric === "cost"
? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`
: `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}
</Text>
</View>
);
})}
</SettingsSection>
);
}
function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {
const { merged } = props;
const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(
(period) => period.totalTokens > 0,
).length;
const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;
const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;
const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;
return (
<SettingsSection title="Totals" card>
<View className="flex-row flex-wrap">
<MetricCell
label="Processed tokens"
value={formatTokens(merged.totalTokens)}
detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}
/>
<MetricCell
label="Cache savings"
value={formatUsd(merged.costQuality.cacheSavingsUsd)}
detail={
merged.costUsd > 0
? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`
: "vs full input rates"
}
/>
<MetricCell
label="Cached input"
value={formatTokens(merged.cachedInputTokens)}
detail={`${formatPercent(cachedShare)} of observed input`}
/>
<MetricCell
label="Uncached input"
value={formatTokens(merged.uncachedInputTokens)}
detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}
/>
<MetricCell
label="Output"
value={formatTokens(merged.outputTokens)}
detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}
/>
<MetricCell
label="Unpriced"
value={formatPercent(merged.costQuality.unpricedShare)}
detail="of records, excluded from cost"
/>
</View>
</SettingsSection>
);
}
function MetricCell(props: {
readonly label: string;
readonly value: string;
readonly detail: string;
}) {
return (
<View className="w-1/2 gap-0.5 p-4">
<Text className="text-sm text-foreground-muted">{props.label}</Text>
<Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>
<Text className="text-xs text-foreground-tertiary">{props.detail}</Text>
</View>
);
}
function ModelsSection(props: { readonly merged: MergedUsage }) {
const { merged } = props;
const colors = useProviderColors();
if (merged.models.length === 0) return null;
return (
<SettingsSection title="By model" card>
{merged.models.map((model, index) => (
<View
key={`${model.provider}:${model.model}`}
className={
index === 0
? "flex-row items-center gap-3 p-4"
: "flex-row items-center gap-3 border-t border-border-subtle p-4"
}
>
<View
className="size-2.5 shrink-0 rounded-full"
style={{ backgroundColor: colors[model.provider] }}
/>
<View className="min-w-0 flex-1 gap-0.5">
<Text className="text-base text-foreground" numberOfLines={1}>
{model.model}
</Text>
<Text className="text-sm text-foreground-muted">
{formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens
</Text>
</View>
<Text className="text-base tabular-nums text-foreground">{formatUsd(model.costUsd)}</Text>
</View>
))}
</SettingsSection>
);
}
/**
* Says plainly when the totals are incomplete: an environment still answering,
* one that failed, or one whose transcripts another environment already
* reported.
*/
function UsageCoverageNotice(props: {
readonly environments: readonly EnvironmentUsageStatus[];
readonly merged: MergedUsage;
readonly isPartial: boolean;
}) {
const failed = props.environments.filter((environment) => environment.error !== null);
const stale = props.environments.filter((environment) =>
props.merged.staleEnvironments.includes(environment.environmentId),
);
const duplicateSources = props.merged.duplicateSources;
if (
failed.length === 0 &&
stale.length === 0 &&
duplicateSources.length === 0 &&
!props.isPartial
) {
return null;
}
return (
<View className="gap-1 rounded-[16px] border-continuous bg-card px-4 py-3">
{props.isPartial ? (
<Text className="text-sm text-foreground-muted">
Some environments are still reporting. Totals are partial.
</Text>
) : null}
{failed.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label} could not report usage.
</Text>
))}
{stale.map((environment) => (
<Text key={environment.environmentId} className="text-sm text-foreground-muted">
{environment.label} runs an older server version and is excluded from totals.
</Text>
))}
{duplicateSources.length > 0 ? (
<Text className="text-sm text-foreground-muted">
Counted once across environments sharing a transcript directory:{" "}
{duplicateSources.join(", ")}
</Text>
) : null}
</View>
);
}
@@ -0,0 +1,41 @@
/**
* Shapes merged daily totals into the per-day provider stacks both chart
* implementations (Swift Charts on iOS, plain views elsewhere) render.
*
* @module usageChartData
*/
import type { UsageProviderKind } from "@t3tools/contracts";
import type { DailyTotals } from "@t3tools/shared/usageMerge";
import { PROVIDER_ORDER } from "./usageProviders";
export type UsageChartMetric = "cost" | "tokens";
export interface UsageChartDay {
readonly day: string;
/** In {@link PROVIDER_ORDER}, i.e. bottom of the stack first. */
readonly values: readonly { readonly provider: UsageProviderKind; readonly value: number }[];
readonly total: number;
}
/** One entry per day in the window, zero-filled where nothing happened. */
export function buildChartDays(
days: readonly string[],
daily: readonly DailyTotals[],
metric: UsageChartMetric,
): readonly UsageChartDay[] {
const byDay = new Map(daily.map((totals) => [totals.day, totals]));
return days.map((day) => {
const totals = byDay.get(day);
const values = PROVIDER_ORDER.map((provider) => {
const entry = totals?.byProvider.get(provider);
const value = entry === undefined ? 0 : metric === "cost" ? entry.costUsd : entry.totalTokens;
return { provider, value };
});
return {
day,
values,
total: values.reduce((sum, entry) => sum + entry.value, 0),
};
});
}
@@ -0,0 +1,25 @@
import type { UsageProviderKind } from "@t3tools/contracts";
import { useColorScheme } from "react-native";
/**
* Series and table order. The chart stacks providers from the bottom in this
* order, so it also fixes which band sits on top of the bars.
*/
export const PROVIDER_ORDER: readonly UsageProviderKind[] = ["codex", "claude"];
export const PROVIDER_LABEL: Record<UsageProviderKind, string> = {
claude: "Claude Code",
codex: "Codex",
};
/**
* Claude's brand orange holds in both themes; Codex is neutral and must flip
* with the theme or its bars vanish against the matching background.
*/
export function useProviderColors(): Record<UsageProviderKind, string> {
const scheme = useColorScheme();
return {
claude: "#d97757",
codex: scheme === "dark" ? "#e6e6e6" : "#3c3c43",
};
}
+43 -46
View File
@@ -3,14 +3,14 @@ import { describe, expect, it } from "vite-plus/test";
import { ProviderInstanceId, type ServerConfig } from "@t3tools/contracts";
import {
buildModelMenuActions,
buildModelOptions,
groupByProvider,
resolveDefaultableModelSelection,
resolveSelectableModelSelection,
} from "./modelOptions";
describe("mobile model options", () => {
it("folds legacy models into a provider-scoped menu", () => {
it("groups models by provider and flags legacy entries", () => {
const config = {
providers: [
{
@@ -39,51 +39,14 @@ describe("mobile model options", () => {
],
} as unknown as ServerConfig;
const actions = buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null);
expect(actions).toMatchObject([
expect(groupByProvider(buildModelOptions(config, null))).toMatchObject([
{
title: "Codex",
subactions: [{ id: "model:codex:gpt-5.6-sol", title: "GPT-5.6 Sol" }],
},
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4", title: "GPT-5.4" }],
},
]);
});
it("omits an empty provider menu when every model is legacy", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
expect(
buildModelMenuActions(groupByProvider(buildModelOptions(config, null)), null),
).toMatchObject([
{
id: "legacy-models:codex",
title: "Codex legacy models",
subactions: [{ id: "model:codex:gpt-5.4" }],
providerKey: "codex",
providerLabel: "Codex",
models: [
{ key: "codex:gpt-5.6-sol", label: "GPT-5.6 Sol", isLegacy: false },
{ key: "codex:gpt-5.4", label: "GPT-5.4", isLegacy: true },
],
},
]);
});
@@ -174,4 +137,38 @@ describe("mobile model options", () => {
// No config (environment offline) — nothing to validate against.
expect(resolveSelectableModelSelection(null, disabled)).toBe(disabled);
});
it("keeps legacy models out of implicit defaults", () => {
const config = {
providers: [
{
instanceId: "codex",
driver: "codex",
displayName: "Codex",
enabled: true,
installed: true,
auth: { status: "authenticated" },
models: [
{ slug: "gpt-5.6-sol", name: "GPT-5.6 Sol", isCustom: false, capabilities: null },
{
slug: "gpt-5.4",
name: "GPT-5.4",
isCustom: false,
isLegacy: true,
capabilities: null,
},
],
},
],
} as unknown as ServerConfig;
const current = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.6-sol" };
const legacy = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" };
expect(resolveDefaultableModelSelection(config, current)).toBe(current);
// A legacy last-used selection falls through to the provider default.
expect(resolveDefaultableModelSelection(config, legacy)).toBeNull();
// Offline: nothing to validate against, selection passes through.
expect(resolveDefaultableModelSelection(null, legacy)).toBe(legacy);
});
});
+20 -51
View File
@@ -3,7 +3,6 @@ import type {
ModelSelection,
ServerConfig as T3ServerConfig,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionDescriptors,
@@ -85,6 +84,26 @@ export function resolveSelectableModelSelection(
: null;
}
/**
* Like resolveSelectableModelSelection, but additionally rejects legacy
* models. Used for implicit defaults (stored draft, project last-used): a
* new thread should never quietly start on a legacy model, so those fall
* through to the provider's default instead. Explicit picks in the settings
* sheet are unaffected.
*/
export function resolveDefaultableModelSelection(
config: T3ServerConfig | null | undefined,
selection: ModelSelection | null,
): ModelSelection | null {
const usable = resolveSelectableModelSelection(config, selection);
if (!usable || !config) {
return usable;
}
const provider = config.providers.find((candidate) => candidate.instanceId === usable.instanceId);
const model = provider?.models.find((candidate) => candidate.slug === usable.model);
return model?.isLegacy === true ? null : usable;
}
export function buildModelOptions(
config: T3ServerConfig | null | undefined,
fallbackModelSelection: ModelSelection | null,
@@ -168,53 +187,3 @@ export function groupByProvider(options: ReadonlyArray<ModelOption>): ReadonlyAr
models: group.models,
}));
}
function modelMenuAction(option: ModelOption, selectedModel: ModelSelection | null): MenuAction {
return {
id: `model:${option.key}`,
title: option.label,
state:
option.selection.instanceId === selectedModel?.instanceId &&
option.selection.model === selectedModel.model
? "on"
: undefined,
};
}
export function buildModelMenuActions(
groups: ReadonlyArray<ProviderGroup>,
selectedModel: ModelSelection | null,
): MenuAction[] {
return groups.flatMap((group) => {
const currentModels = group.models.filter((model) => !model.isLegacy);
const legacyModels = group.models.filter((model) => model.isLegacy);
const selected = group.models.find(
(model) =>
model.selection.instanceId === selectedModel?.instanceId &&
model.selection.model === selectedModel.model,
);
return [
...(currentModels.length > 0
? [
{
id: `provider:${group.providerKey}`,
title: group.providerLabel,
subtitle: selected && !selected.isLegacy ? selected.label : undefined,
subactions: currentModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
...(legacyModels.length > 0
? [
{
id: `legacy-models:${group.providerKey}`,
title: `${group.providerLabel} legacy models`,
subtitle: selected?.isLegacy ? selected.label : undefined,
subactions: legacyModels.map((option) => modelMenuAction(option, selectedModel)),
},
]
: []),
];
});
}
+69 -1
View File
@@ -126,6 +126,22 @@ describe("nativeMarkdownTextRuns", () => {
]);
});
it.each([
["&#128512;", "😀"],
["&#x1f680;", "🚀"],
["&#9999999999;", "&#9999999999;"],
["&#x110000;", "&#x110000;"],
["&amp;#9999999999;", "&#9999999999;"],
["&amp;#x110000;", "&#x110000;"],
])("normalizes numeric entity %s without throwing", (content, expected) => {
const node: MarkdownNode = {
type: "paragraph",
children: [{ type: "text", content }],
};
expect(nativeMarkdownTextRuns(node)).toEqual([{ text: expected }]);
});
it("reads inline content from nested text nodes", () => {
const node: MarkdownNode = {
type: "paragraph",
@@ -173,6 +189,25 @@ describe("nativeMarkdownDocumentRuns", () => {
]);
});
it("decorates known skill references inside blockquotes", () => {
const node: MarkdownNode = {
type: "blockquote",
children: [
{
type: "paragraph",
children: [{ type: "text", content: "Use $ui for this." }],
},
],
};
expect(nativeMarkdownDocumentRuns(node, [{ name: "ui", displayName: "UI" }])).toContainEqual({
text: "$ui",
role: "body",
skillName: "ui",
skillLabel: "UI",
});
});
it("leaves unknown skill-like text unchanged", () => {
const node: MarkdownNode = {
type: "document",
@@ -328,7 +363,7 @@ describe("nativeMarkdownDocumentRuns", () => {
]);
});
it("includes quotes and fenced code in the same selectable string", () => {
it("preserves quotes and fenced code in document runs", () => {
const node: MarkdownNode = {
type: "document",
children: [
@@ -414,6 +449,39 @@ describe("nativeMarkdownListItemBlocks", () => {
});
describe("nativeMarkdownDocumentChunks", () => {
it("renders plain blockquotes as rich blocks so their marker spans wrapped lines", () => {
const blockquote: MarkdownNode = {
type: "blockquote",
beg: 0,
end: 120,
children: [
{
type: "paragraph",
children: [
{
type: "text",
content:
"Persistent random per-result keys are the strongest design, even when this text wraps.",
},
],
},
],
};
expect(
nativeMarkdownDocumentChunks({
type: "document",
children: [blockquote],
}),
).toEqual([
{
kind: "rich",
key: "rich:blockquote:0:120",
node: blockquote,
},
]);
});
it("keeps headings and plain lists in one selectable document", () => {
const document: MarkdownNode = {
type: "document",
+15 -37
View File
@@ -3,9 +3,8 @@ import { describe, expect, it } from "vite-plus/test";
import type { ModelCapabilities } from "@t3tools/contracts";
import {
applyProviderOptionMenuEvent,
buildProviderOptionMenuActions,
providerOptionsConfigurationLabel,
applyProviderOptionSelection,
providerOptionValueLabels,
resolveProviderOptionDescriptors,
} from "./providerOptions";
@@ -35,31 +34,13 @@ const CODEX_CAPABILITIES: ModelCapabilities = {
};
describe("mobile provider options", () => {
it("renders the option descriptors advertised by the selected model", () => {
it("summarizes the option values currently in effect", () => {
const descriptors = resolveProviderOptionDescriptors({
capabilities: CODEX_CAPABILITIES,
selections: undefined,
});
expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([
{
title: "Reasoning",
subtitle: "Medium",
subactions: [
{ title: "Medium (default)", state: "on" },
{ title: "High", state: undefined },
],
},
{
title: "Service Tier",
subtitle: "Standard",
subactions: [
{ title: "Standard (default)", state: "on" },
{ title: "Fast", state: undefined },
],
},
]);
expect(providerOptionsConfigurationLabel(descriptors)).toBe("Medium · Standard");
expect(providerOptionValueLabels(descriptors)).toEqual(["Medium", "Standard"]);
});
it("updates generic select options without knowing provider-specific ids", () => {
@@ -67,14 +48,18 @@ describe("mobile provider options", () => {
capabilities: CODEX_CAPABILITIES,
selections: undefined,
});
const actions = buildProviderOptionMenuActions(descriptors);
const fastEvent = actions[1]?.subactions?.[1]?.id;
expect(fastEvent).toBeDefined();
expect(applyProviderOptionMenuEvent(descriptors, fastEvent!)).toEqual([
expect(
applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "priority" }),
).toEqual([
{ id: "reasoningEffort", value: "medium" },
{ id: "serviceTier", value: "priority" },
]);
// Choices the model doesn't advertise are rejected, not stored.
expect(
applyProviderOptionSelection(descriptors, { id: "serviceTier", value: "turbo" }),
).toBeNull();
expect(applyProviderOptionSelection(descriptors, { id: "unknown", value: "high" })).toBeNull();
});
it("treats an unspecified boolean capability as off", () => {
@@ -85,16 +70,9 @@ describe("mobile provider options", () => {
selections: undefined,
});
expect(buildProviderOptionMenuActions(descriptors)).toMatchObject([
{
title: "Fast Mode",
subtitle: "Off",
subactions: [
{ title: "Off", state: "on" },
{ title: "On", state: undefined },
],
},
expect(providerOptionValueLabels(descriptors)).toEqual([]);
expect(applyProviderOptionSelection(descriptors, { id: "fastMode", value: true })).toEqual([
{ id: "fastMode", value: true },
]);
expect(providerOptionsConfigurationLabel(descriptors)).toBe("Configuration");
});
});
+20 -87
View File
@@ -3,48 +3,12 @@ import type {
ProviderOptionDescriptor,
ProviderOptionSelection,
} from "@t3tools/contracts";
import type { MenuAction } from "@react-native-menu/menu";
import {
buildProviderOptionSelectionsFromDescriptors,
getProviderOptionCurrentLabel,
getProviderOptionCurrentValue,
getProviderOptionDescriptors,
} from "@t3tools/shared/model";
const PROVIDER_OPTION_EVENT_PREFIX = "provider-option:";
function providerOptionEvent(id: string, value: string | boolean): string {
return `${PROVIDER_OPTION_EVENT_PREFIX}${encodeURIComponent(JSON.stringify({ id, value }))}`;
}
function parseProviderOptionEvent(
event: string,
): { readonly id: string; readonly value: string | boolean } | null {
if (!event.startsWith(PROVIDER_OPTION_EVENT_PREFIX)) {
return null;
}
try {
const parsed: unknown = JSON.parse(
decodeURIComponent(event.slice(PROVIDER_OPTION_EVENT_PREFIX.length)),
);
if (
typeof parsed === "object" &&
parsed !== null &&
"id" in parsed &&
typeof parsed.id === "string" &&
"value" in parsed &&
(typeof parsed.value === "string" || typeof parsed.value === "boolean")
) {
return { id: parsed.id, value: parsed.value };
}
} catch {
return null;
}
return null;
}
export function resolveProviderOptionDescriptors(input: {
readonly capabilities: ModelCapabilities | null | undefined;
readonly selections: ReadonlyArray<ProviderOptionSelection> | null | undefined;
@@ -58,72 +22,41 @@ export function resolveProviderOptionDescriptors(input: {
});
}
export function buildProviderOptionMenuActions(
/**
* Labels for the option values currently in effect (select values plus
* enabled booleans), used to summarize the thread configuration in the
* composer trigger pill.
*/
export function providerOptionValueLabels(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
): ReadonlyArray<MenuAction> {
return descriptors.map((descriptor) => {
const currentValue =
descriptor.type === "boolean"
? (descriptor.currentValue ?? false)
: getProviderOptionCurrentValue(descriptor);
const choices =
descriptor.type === "select"
? descriptor.options.map((option) => ({
id: providerOptionEvent(descriptor.id, option.id),
title: `${option.label}${option.isDefault ? " (default)" : ""}`,
state: currentValue === option.id ? ("on" as const) : undefined,
}))
: ([false, true] as const).map((value) => ({
id: providerOptionEvent(descriptor.id, value),
title: value ? "On" : "Off",
state: currentValue === value ? ("on" as const) : undefined,
}));
return {
id: `provider-option-menu:${descriptor.id}`,
title: descriptor.label,
subtitle:
descriptor.type === "boolean"
? currentValue
? "On"
: "Off"
: getProviderOptionCurrentLabel(descriptor),
subactions: choices,
};
});
}
export function providerOptionsConfigurationLabel(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
): string {
const labels = descriptors.flatMap((descriptor) => {
): ReadonlyArray<string> {
return descriptors.flatMap((descriptor) => {
if (descriptor.type === "boolean") {
return descriptor.currentValue ? [descriptor.label] : [];
}
const label = getProviderOptionCurrentLabel(descriptor);
return label ? [label] : [];
});
return labels.length > 0 ? labels.join(" · ") : "Configuration";
}
export function applyProviderOptionMenuEvent(
/**
* Applies one option change (by descriptor id) and returns the full selection
* list to store on the model selection, or null when the change doesn't match
* an advertised descriptor / choice.
*/
export function applyProviderOptionSelection(
descriptors: ReadonlyArray<ProviderOptionDescriptor>,
event: string,
change: ProviderOptionSelection,
): ReadonlyArray<ProviderOptionSelection> | null {
const selection = parseProviderOptionEvent(event);
if (!selection) {
return null;
}
const descriptor = descriptors.find((candidate) => candidate.id === selection.id);
const descriptor = descriptors.find((candidate) => candidate.id === change.id);
if (!descriptor) {
return null;
}
if (
(descriptor.type === "boolean" && typeof selection.value !== "boolean") ||
(descriptor.type === "boolean" && typeof change.value !== "boolean") ||
(descriptor.type === "select" &&
(typeof selection.value !== "string" ||
!descriptor.options.some((option) => option.id === selection.value)))
(typeof change.value !== "string" ||
!descriptor.options.some((option) => option.id === change.value)))
) {
return null;
}
@@ -132,7 +65,7 @@ export function applyProviderOptionMenuEvent(
candidate.id === descriptor.id
? {
...candidate,
currentValue: selection.value,
currentValue: change.value,
}
: candidate,
) as ReadonlyArray<ProviderOptionDescriptor>;
@@ -12,12 +12,107 @@ import {
} from "@t3tools/contracts";
import {
buildPendingUserInputAnswers,
buildThreadFeed,
deriveThreadFeedPresentation,
isPendingUserInputOptionSelected,
setPendingUserInputCustomAnswer,
togglePendingUserInputOptionSelection,
type ThreadFeedActivity,
type ThreadFeedEntry,
} from "./threadActivity";
const singleSelectQuestion = {
id: "runtime",
header: "Runtime",
question: "Which runtime should be used?",
options: [
{ label: "Go", description: "One binary" },
{ label: "Node.js", description: "Reuse TypeScript" },
],
multiSelect: false,
} as const;
const multiSelectQuestion = {
id: "scope",
header: "Scope",
question: "Which data should be collected?",
options: [
{ label: "Orders", description: "Receipts" },
{ label: "Listings", description: "Inventory" },
],
multiSelect: true,
} as const;
describe("pending user input answers", () => {
it("replaces single-select options and toggles multi-select options", () => {
expect(
togglePendingUserInputOptionSelection(
singleSelectQuestion,
{ selectedOptionLabels: ["Go"] },
"Node.js",
),
).toEqual({ customAnswer: "", selectedOptionLabels: ["Node.js"] });
const orders = togglePendingUserInputOptionSelection(multiSelectQuestion, undefined, "Orders");
const ordersAndListings = togglePendingUserInputOptionSelection(
multiSelectQuestion,
orders,
"Listings",
);
expect(ordersAndListings).toEqual({
customAnswer: "",
selectedOptionLabels: ["Orders", "Listings"],
});
expect(
togglePendingUserInputOptionSelection(multiSelectQuestion, ordersAndListings, "Orders"),
).toEqual({ customAnswer: "", selectedOptionLabels: ["Listings"] });
const paddedOrders = togglePendingUserInputOptionSelection(
multiSelectQuestion,
undefined,
" Orders ",
);
expect(paddedOrders).toEqual({ customAnswer: "", selectedOptionLabels: ["Orders"] });
expect(
togglePendingUserInputOptionSelection(multiSelectQuestion, paddedOrders, " Orders "),
).toEqual({ customAnswer: "" });
});
it("builds array answers for multi-select questions", () => {
expect(
buildPendingUserInputAnswers([singleSelectQuestion, multiSelectQuestion], {
runtime: { selectedOptionLabels: ["Go"] },
scope: { selectedOptionLabels: ["Orders", "Listings"] },
}),
).toEqual({
runtime: "Go",
scope: ["Orders", "Listings"],
});
});
it("clears selected options while a custom answer is active", () => {
expect(
setPendingUserInputCustomAnswer(
{ selectedOptionLabels: ["Orders", "Listings"] },
"Orders first",
),
).toEqual({ customAnswer: "Orders first" });
});
it("matches selected chips against normalized option labels", () => {
expect(
isPendingUserInputOptionSelected({ selectedOptionLabels: ["Orders"] }, " Orders "),
).toBe(true);
expect(
isPendingUserInputOptionSelected(
{ selectedOptionLabels: ["Orders"], customAnswer: "Orders first" },
" Orders ",
),
).toBe(false);
});
});
function makeActivity(
input: Partial<OrchestrationThreadActivity> &
Pick<OrchestrationThreadActivity, "id" | "kind" | "summary" | "createdAt">,
+69 -9
View File
@@ -26,7 +26,7 @@ export interface PendingUserInput {
}
export interface PendingUserInputDraftAnswer {
readonly selectedOptionLabel?: string;
readonly selectedOptionLabels?: ReadonlyArray<string>;
readonly customAnswer?: string;
}
@@ -227,14 +227,32 @@ function normalizeDraftAnswer(value: string | undefined): string | null {
return trimmed.length > 0 ? trimmed : null;
}
function normalizeSelectedOptionLabels(
value: ReadonlyArray<string> | undefined,
): ReadonlyArray<string> {
if (!Array.isArray(value)) {
return [];
}
return Array.from(
new Set(value.map((entry) => entry.trim()).filter((entry) => entry.length > 0)),
);
}
function resolvePendingUserInputAnswer(
question: UserInputQuestion,
draft: PendingUserInputDraftAnswer | undefined,
): string | null {
): string | ReadonlyArray<string> | null {
const customAnswer = normalizeDraftAnswer(draft?.customAnswer);
if (customAnswer) {
return customAnswer;
}
return normalizeDraftAnswer(draft?.selectedOptionLabel);
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
if (question.multiSelect) {
return selectedOptionLabels.length > 0 ? selectedOptionLabels : null;
}
return selectedOptionLabels[0] ?? null;
}
/** Codex children settle via task.updated (idle/failed/interrupted), never
@@ -554,6 +572,8 @@ function toolDetailTextLooksLikeFailure(text: string): boolean {
normalized.includes("command not found") ||
(normalized.includes("cannot find path") && normalized.includes("because it does not exist")) ||
(normalized.includes("is not recognized") && normalized.includes("the term '")) ||
normalized.includes("is not recognized as the name of a cmdlet") ||
normalized.includes("a parameter cannot be found that matches parameter name") ||
/<exited with exit code\s+[1-9]\d*\s*>/i.test(text) ||
/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text) ||
/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)
@@ -1426,22 +1446,62 @@ export function setPendingUserInputCustomAnswer(
draft: PendingUserInputDraftAnswer | undefined,
customAnswer: string,
): PendingUserInputDraftAnswer {
const selectedOptionLabel =
customAnswer.trim().length > 0 ? undefined : draft?.selectedOptionLabel;
const selectedOptionLabels =
customAnswer.trim().length > 0
? undefined
: normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
return {
customAnswer,
...(selectedOptionLabel ? { selectedOptionLabel } : {}),
...(selectedOptionLabels && selectedOptionLabels.length > 0 ? { selectedOptionLabels } : {}),
};
}
export function isPendingUserInputOptionSelected(
draft: PendingUserInputDraftAnswer | undefined,
optionLabel: string,
): boolean {
if (normalizeDraftAnswer(draft?.customAnswer)) {
return false;
}
return normalizeSelectedOptionLabels(draft?.selectedOptionLabels).includes(optionLabel.trim());
}
export function togglePendingUserInputOptionSelection(
question: UserInputQuestion,
draft: PendingUserInputDraftAnswer | undefined,
optionLabel: string,
): PendingUserInputDraftAnswer {
const normalizedOptionLabel = optionLabel.trim();
if (question.multiSelect) {
const selectedOptionLabels = normalizeSelectedOptionLabels(draft?.selectedOptionLabels);
const nextSelectedOptionLabels = selectedOptionLabels.includes(normalizedOptionLabel)
? selectedOptionLabels.filter((label) => label !== normalizedOptionLabel)
: [...selectedOptionLabels, normalizedOptionLabel];
return {
customAnswer: "",
...(nextSelectedOptionLabels.length > 0
? { selectedOptionLabels: nextSelectedOptionLabels }
: {}),
};
}
return {
customAnswer: "",
selectedOptionLabels: [normalizedOptionLabel],
};
}
export function buildPendingUserInputAnswers(
questions: ReadonlyArray<UserInputQuestion>,
draftAnswers: Record<string, PendingUserInputDraftAnswer>,
): Record<string, string> | null {
const answers: Record<string, string> = {};
): Record<string, string | ReadonlyArray<string>> | null {
const answers: Record<string, string | ReadonlyArray<string>> = {};
for (const question of questions) {
const answer = resolvePendingUserInputAnswer(draftAnswers[question.id]);
const answer = resolvePendingUserInputAnswer(question, draftAnswers[question.id]);
if (!answer) {
return null;
}
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vite-plus/test";
import { hasWideMarkdownBlock } from "./wideMarkdownBlocks";
describe("hasWideMarkdownBlock", () => {
it("ignores prose, inline code, and emphasis", () => {
expect(hasWideMarkdownBlock("just a message")).toBe(false);
expect(hasWideMarkdownBlock("I found it in `secteurs_intervention` earlier")).toBe(false);
expect(hasWideMarkdownBlock("a | b in a sentence")).toBe(false);
expect(hasWideMarkdownBlock("an em dash — and a rule\n\n---\n")).toBe(false);
});
it("detects fenced code blocks", () => {
expect(hasWideMarkdownBlock("before\n```\ncode\n```\nafter")).toBe(true);
expect(hasWideMarkdownBlock("before\n```ts\ncode\n```")).toBe(true);
expect(hasWideMarkdownBlock("before\n~~~\ncode\n~~~")).toBe(true);
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
});
it("detects top-level and blockquoted ordered-list markers", () => {
expect(hasWideMarkdownBlock("1. One\n2. Two\n3. Three\n4. Four\n5. Five")).toBe(true);
expect(hasWideMarkdownBlock("before\n3) Three")).toBe(true);
expect(hasWideMarkdownBlock("> 1. One\n> 2. Two")).toBe(true);
expect(hasWideMarkdownBlock("> > 3) Three")).toBe(true);
});
it("detects nested ordered lists without treating indented code as a list", () => {
expect(hasWideMarkdownBlock("- Parent\n 1. Child\n 2. Child")).toBe(true);
expect(hasWideMarkdownBlock("> - Parent\n> 1. Child")).toBe(true);
expect(hasWideMarkdownBlock(" 1. indented code")).toBe(false);
expect(hasWideMarkdownBlock(" - code-like bullet\n 1. indented code")).toBe(false);
});
it("can limit ordered-list width pinning to Android", () => {
const orderedList = "1. One\n2. Two";
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: true })).toBe(true);
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: false })).toBe(false);
expect(hasWideMarkdownBlock("```\ncode\n```", { includeOrderedLists: false })).toBe(true);
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |", { includeOrderedLists: false })).toBe(
true,
);
});
it("detects GFM tables", () => {
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
});
});
+90
View File
@@ -0,0 +1,90 @@
/**
* Detects markdown that the JS renderer draws as a block requiring a definite
* user-bubble width — fenced code blocks, GFM tables, and ordered lists.
*
* Fenced code blocks and tables report an intrinsic width equal to their
* widest line, which is effectively unbounded. A user bubble sizes itself
* from its content
* (`maxWidth` with no `width`), so Android lays the bubble's children out
* during the unclamped intrinsic pass — where the surrounding paragraphs
* collapse to a single line — and never repositions them once the width is
* clamped back to `maxWidth`. The result is siblings drawn on top of each
* other inside an over-tall bubble. Pinning the bubble's width removes the
* intrinsic pass entirely, which is the same reason review-comment bubbles
* already carry an explicit width.
*
* Ordered lists hit the same Android layout bug because each item contains a
* flexing content column inside a shrink-to-fit row.
*
* A four-space ordered marker is only treated as a list when the preceding
* non-empty line is a less-indented list item. This keeps standalone indented
* code out of the heuristic while covering nested lists.
*/
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
// Trades some precision for a simple check, favoring false positives over false
// negatives: list-shaped paragraph may get a wider bubble
const ORDERED_LIST_ITEM = /^ {0,3}\d{1,9}[.)](?:[ \t]+|$)/;
const INDENTED_ORDERED_LIST_ITEM = /^( {4,})\d{1,9}[.)](?:[ \t]+|$)/;
const ANY_LIST_ITEM = /^( *)(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/;
const BLOCKQUOTE_PREFIX = /^ {0,3}>[ \t]?/;
export interface WideMarkdownBlockOptions {
readonly includeOrderedLists?: boolean;
}
function stripBlockquotePrefixes(line: string): string {
let content = line;
while (BLOCKQUOTE_PREFIX.test(content)) {
content = content.replace(BLOCKQUOTE_PREFIX, "");
}
return content;
}
function hasOrderedListItem(text: string): boolean {
let previousNonEmptyLine: string | null = null;
for (const rawLine of text.split("\n")) {
const line = stripBlockquotePrefixes(rawLine);
if (ORDERED_LIST_ITEM.test(line)) {
return true;
}
const nestedMatch = INDENTED_ORDERED_LIST_ITEM.exec(line);
const parentMatch =
previousNonEmptyLine === null ? null : ANY_LIST_ITEM.exec(previousNonEmptyLine);
if (nestedMatch && parentMatch && parentMatch[1].length < nestedMatch[1].length) {
return true;
}
if (line.trim().length > 0) {
previousNonEmptyLine = line;
}
}
return false;
}
function isTableDelimiterRow(line: string): boolean {
const trimmed = line.trim();
if (!trimmed.includes("|") || !trimmed.includes("-")) {
return false;
}
return /^[|\-: \t]+$/.test(trimmed);
}
export function hasWideMarkdownBlock(
text: string,
options: WideMarkdownBlockOptions = {},
): boolean {
if (FENCED_CODE_BLOCK.test(text)) {
return true;
}
if (options.includeOrderedLists !== false && hasOrderedListItem(text)) {
return true;
}
if (!text.includes("|")) {
return false;
}
return text.split("\n").some(isTableDelimiterRow);
}
@@ -1,26 +0,0 @@
import { requireNativeView } from "expo";
import type { NativeSyntheticEvent, StyleProp, ViewProps, ViewStyle } from "react-native";
interface NativeHeaderButtonProps extends ViewProps {
readonly label: string;
readonly systemImage: "gearshape" | "square.and.pencil";
readonly onTriggered: (event: NativeSyntheticEvent<Record<string, never>>) => void;
}
const NativeHeaderButton = requireNativeView<NativeHeaderButtonProps>("T3NativeControls");
export function T3HeaderButton(props: {
readonly accessibilityLabel: string;
readonly icon: NativeHeaderButtonProps["systemImage"];
readonly onPress: () => void;
readonly style?: StyleProp<ViewStyle>;
}) {
return (
<NativeHeaderButton
label={props.accessibilityLabel}
onTriggered={props.onPress}
style={[{ width: 44, height: 44 }, props.style]}
systemImage={props.icon}
/>
);
}
@@ -26,13 +26,15 @@ export interface Preferences {
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
readonly autoSettleOnMerge?: boolean;
/**
* Device-local mirror of the web beta's `sidebarV2Enabled`. Mobile has no
* client-settings sync, so the flat v2 thread list is opted out of per
* device. Undefined means the user has never chosen, which resolves to on —
* see `resolveThreadListV2Enabled`.
* Device-local mirror of the web `legacySidebarEnabled` setting. Mobile has
* no client-settings sync, so the legacy grouped thread list is opted into
* per device. Deliberately a fresh key (was `threadListV2Enabled`, an
* opt-out): sanitizing drops the old key, so every device resets to the
* default flat list — see `resolveThreadListV2Enabled`.
*/
readonly threadListV2Enabled?: boolean;
readonly legacyThreadListEnabled?: boolean;
}
export class MobilePreferencesLoadError extends Schema.TaggedErrorClass<MobilePreferencesLoadError>()(
@@ -84,7 +86,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
collapsedProjectGroups?: readonly string[];
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
threadListV2Enabled?: boolean;
autoSettleOnMerge?: boolean;
legacyThreadListEnabled?: boolean;
} = {};
if (typeof parsed.liveActivitiesEnabled === "boolean") {
@@ -121,8 +124,11 @@ function sanitizePreferences(parsed: Preferences): Preferences {
) {
preferences.projectGroupingMode = parsed.projectGroupingMode;
}
if (typeof parsed.threadListV2Enabled === "boolean") {
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
if (typeof parsed.autoSettleOnMerge === "boolean") {
preferences.autoSettleOnMerge = parsed.autoSettleOnMerge;
}
if (typeof parsed.legacyThreadListEnabled === "boolean") {
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
}
return preferences;
}
+3 -1
View File
@@ -15,7 +15,6 @@ import { environmentCatalog } from "../connection/catalog";
import { connectionAtomRuntime } from "../connection/runtime";
import { environmentSnapshotAtom } from "./shell";
export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime);
export const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);
export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(
environmentThreads.stateAtom,
@@ -24,6 +23,9 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({
catalogValueAtom: environmentCatalog.catalogValueAtom,
snapshotAtom: environmentSnapshotAtom,
});
export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime, {
threadShellAtom: environmentThreadShells.threadShellAtom,
});
const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(
Atom.withLabel("mobile-environment-thread:empty"),
+139
View File
@@ -0,0 +1,139 @@
/**
* Multi-environment usage state.
*
* Every connected environment answers the same typed query; the client merges
* the results. Raw transcripts never leave the machine that produced them.
*
* Mirror of `apps/web/src/state/usage.ts` over mobile's atom wiring; the merge
* rules themselves live in `@t3tools/shared/usageMerge`.
*
* @module state/usage
*/
import { useAtomValue } from "@effect/atom-react";
import {
USAGE_CONTRACT_VERSION,
type EnvironmentId,
type UsageSummary,
type UsageSummaryInput,
} from "@t3tools/contracts";
import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";
import * as Option from "effect/Option";
import { AsyncResult, Atom } from "effect/unstable/reactivity";
import { useCallback, useMemo } from "react";
import { appAtomRegistry } from "./atom-registry";
import { environmentPresentations } from "./presentation";
import { serverEnvironment } from "./server";
export interface EnvironmentUsageStatus {
readonly environmentId: EnvironmentId;
readonly label: string;
readonly isPending: boolean;
readonly error: string | null;
readonly summary: UsageSummary | null;
}
/**
* Reads every environment's summary for one window.
*
* Keyed by the serialised window so switching ranges does not thrash the atom
* cache, and so each environment's query is shared with any other reader of the
* same window.
*/
const usageByWindowAtom = Atom.family((windowKey: string) =>
Atom.make((get): readonly EnvironmentUsageStatus[] => {
const input = JSON.parse(windowKey) as UsageSummaryInput;
const presentations = get(environmentPresentations.presentationsAtom);
const statuses: EnvironmentUsageStatus[] = [];
for (const [environmentId, presentation] of presentations) {
const result = get(serverEnvironment.usageSummary({ environmentId, input }));
statuses.push({
environmentId,
label: presentation.entry.target.label,
isPending: result.waiting,
error: result._tag === "Failure" ? "This environment could not report usage." : null,
summary: Option.getOrNull(AsyncResult.value(result)),
});
}
return statuses;
}).pipe(Atom.withLabel(`mobile-usage:window:${windowKey}`)),
);
export interface UsageView {
readonly merged: MergedUsage;
readonly environments: readonly EnvironmentUsageStatus[];
/** True until at least one environment has answered. */
readonly isPending: boolean;
/**
* True while environments that have not failed are still answering. Failed
* environments are reported through their own error rows: totals will not
* improve by waiting on them, so they must not read as "still reporting".
*/
readonly isPartial: boolean;
readonly refresh: () => void;
}
export function useUsage(input: UsageSummaryInput): UsageView {
const windowKey = useMemo(
() =>
JSON.stringify({
sinceDay: input.sinceDay,
untilDay: input.untilDay,
timeZone: input.timeZone,
resolution: input.resolution,
sinceTime: input.sinceTime,
untilTime: input.untilTime,
}),
[
input.sinceDay,
input.untilDay,
input.timeZone,
input.resolution,
input.sinceTime,
input.untilTime,
],
);
const atom = usageByWindowAtom(windowKey);
const environments = useAtomValue(atom);
// Refreshing only the derived atom would re-read the per-environment SWR
// queries within their stale window and change nothing. Refresh each
// environment's query so pull-to-refresh always rescans.
const refresh = useCallback(() => {
const input = JSON.parse(windowKey) as UsageSummaryInput;
for (const environment of environments) {
appAtomRegistry.refresh(
serverEnvironment.usageSummary({ environmentId: environment.environmentId, input }),
);
}
}, [environments, windowKey]);
const merged = useMemo(() => {
const answered: EnvironmentUsage[] = environments.flatMap((environment) =>
environment.summary === null
? []
: [
{
environmentId: environment.environmentId,
label: environment.label,
summary: environment.summary,
},
],
);
return mergeUsage(answered, USAGE_CONTRACT_VERSION);
}, [environments]);
const answeredCount = environments.filter((environment) => environment.summary !== null).length;
const stillReporting = environments.filter(
(environment) => environment.summary === null && environment.error === null,
).length;
return {
merged,
environments,
isPending: answeredCount === 0 && stillReporting > 0,
isPartial: answeredCount > 0 && stillReporting > 0,
refresh,
};
}
@@ -1,7 +1,11 @@
import { useAtomValue } from "@effect/atom-react";
import { useCallback, useMemo, useState } from "react";
import { ApprovalRequestId, type ProviderApprovalDecision } from "@t3tools/contracts";
import {
ApprovalRequestId,
type ProviderApprovalDecision,
type UserInputQuestion,
} from "@t3tools/contracts";
import { Atom } from "effect/unstable/reactivity";
import { threadEnvironment } from "../state/threads";
@@ -12,6 +16,7 @@ import {
derivePendingUserInputs,
setPendingUserInputCustomAnswer,
sortThreadActivities,
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "../lib/threadActivity";
import { appAtomRegistry } from "./atom-registry";
@@ -23,15 +28,21 @@ const userInputDraftsByRequestKeyAtom = Atom.make<
Record<string, Record<string, PendingUserInputDraftAnswer>>
>({}).pipe(Atom.keepAlive, Atom.withLabel("mobile:user-input-drafts"));
function setUserInputDraftOption(requestKey: string, questionId: string, label: string): void {
function setUserInputDraftOption(
requestKey: string,
question: UserInputQuestion,
label: string,
): void {
const current = appAtomRegistry.get(userInputDraftsByRequestKeyAtom);
appAtomRegistry.set(userInputDraftsByRequestKeyAtom, {
...current,
[requestKey]: {
...current[requestKey],
[questionId]: {
selectedOptionLabel: label,
},
[question.id]: togglePendingUserInputOptionSelection(
question,
current[requestKey]?.[question.id],
label,
),
},
});
}
@@ -97,13 +108,13 @@ export function useSelectedThreadRequests() {
: null;
const onSelectUserInputOption = useCallback(
(requestId: ApprovalRequestId, questionId: string, label: string) => {
(requestId: ApprovalRequestId, question: UserInputQuestion, label: string) => {
if (!selectedThreadShell) {
return;
}
const requestKey = scopedRequestKey(selectedThreadShell.environmentId, requestId);
setUserInputDraftOption(requestKey, questionId, label);
setUserInputDraftOption(requestKey, question, label);
},
[selectedThreadShell],
);
@@ -23,6 +23,7 @@ import {
ProviderService,
type ProviderServiceShape,
} from "../src/provider/Services/ProviderService.ts";
import * as ServerConfig from "../src/config.ts";
import { ServerSettingsService } from "../src/serverSettings.ts";
import { AnalyticsService } from "../src/telemetry/Services/AnalyticsService.ts";
import { SqlitePersistenceMemory } from "../src/persistence/Layers/Sqlite.ts";
@@ -93,6 +94,7 @@ const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer<Ana
const shared = Layer.mergeAll(
directoryLayer,
Layer.succeed(ProviderAdapterRegistry, registry),
ServerConfig.layerTest(cwd, cwd).pipe(Layer.provide(NodeServices.layer)),
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
options?.analytics ?? AnalyticsService.layerTest,
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
Loaded 100 of 555 files, more files were not shown because too many files have changed in this diff. Show more