Compare commits
287
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f6b2005e38 | ||
|
|
3918b77c6c | ||
|
|
85f02f36fb | ||
|
|
a1039b80e6 | ||
|
|
4df9807141 | ||
|
|
7093830048 | ||
|
|
6725f379f1 | ||
|
|
69542f3162 | ||
|
|
50bd5cbba2 | ||
|
|
a4735b84e8 | ||
|
|
0a0f56c4ba | ||
|
|
6e7782ad9f | ||
|
|
ddd9ef5850 | ||
|
|
f98cab5535 | ||
|
|
9cc33eab68 | ||
|
|
6a0c3bc510 | ||
|
|
44f496fe43 | ||
|
|
355ef166c1 | ||
|
|
081c74352b | ||
|
|
d69c833127 | ||
|
|
ed5acbada3 | ||
|
|
2d357a51ea | ||
|
|
5b7ee58f6e | ||
|
|
aa067737b3 | ||
|
|
7541fca317 | ||
|
|
497f54f3e6 | ||
|
|
a6b7a371ef | ||
|
|
c08d206455 | ||
|
|
87828d9ef7 | ||
|
|
e94f59baa4 | ||
|
|
f60eb855b7 | ||
|
|
88b9e59e3f | ||
|
|
2cbfc2ec3a | ||
|
|
e3b3f2f62c | ||
|
|
99200e1567 | ||
|
|
96eeddb9bf | ||
|
|
a4462f7313 | ||
|
|
0ea57f93d5 | ||
|
|
46b6f3e131 | ||
|
|
00ad2fecd6 | ||
|
|
36cf824c12 | ||
|
|
035232aaed | ||
|
|
664bbfe6b0 | ||
|
|
24708b7024 | ||
|
|
ea3fe18354 | ||
|
|
7a9b0d36e7 | ||
|
|
5dfc70c016 | ||
|
|
5ce53e9e84 | ||
|
|
df65ee857a | ||
|
|
f67c2696e1 | ||
|
|
9aa6127f2c | ||
|
|
206de9dedb | ||
|
|
d60e09b3b4 | ||
|
|
67cfe020c4 | ||
|
|
82a8ab6df1 | ||
|
|
0f5a1c1049 | ||
|
|
cf79d65d1a | ||
|
|
3180cbcd04 | ||
|
|
58d043737d | ||
|
|
a038331398 | ||
|
|
66f7239232 | ||
|
|
be92cf8912 | ||
|
|
45fbdde909 | ||
|
|
55fe074aec | ||
|
|
ac796c5623 | ||
|
|
eb37434cd2 | ||
|
|
2b8a3ca847 | ||
|
|
13bb317da2 | ||
|
|
f502a5b495 | ||
|
|
dd039c3986 | ||
|
|
017b2b4605 | ||
|
|
157ded3786 | ||
|
|
a927e8d1d7 | ||
|
|
81c4330391 | ||
|
|
02916909f4 | ||
|
|
de73b9082a | ||
|
|
40e371b8cd | ||
|
|
45e56bc844 | ||
|
|
07e4e3108a | ||
|
|
041df3c44d | ||
|
|
106d7b866d | ||
|
|
99f78a7d1f | ||
|
|
4166c0b273 | ||
|
|
7e0c926c06 | ||
|
|
11537cfb3d | ||
|
|
b92c3f7e21 | ||
|
|
f83622d1e0 | ||
|
|
edcb10859b | ||
|
|
cc769910b8 | ||
|
|
ee639eb459 | ||
|
|
d2ac8dd511 | ||
|
|
cb12d183ce | ||
|
|
a4a0871a0b | ||
|
|
b01cc94775 | ||
|
|
14d1a9ed6b | ||
|
|
0689c2850d | ||
|
|
37365b4346 | ||
|
|
c5f28978e2 | ||
|
|
b4e25ed5e0 | ||
|
|
f6004211f2 | ||
|
|
3ddee9cbdd | ||
|
|
3239bbf7c3 | ||
|
|
909cfec0ad | ||
|
|
150a059888 | ||
|
|
764e160cc9 | ||
|
|
4225dea2a4 | ||
|
|
c3e4c98d3d | ||
|
|
f12f86f158 | ||
|
|
6b416ac5c3 | ||
|
|
c89d2ddfe9 | ||
|
|
8a5f9effc5 | ||
|
|
424509468b | ||
|
|
5a15aee2fb | ||
|
|
1a33ea1aa6 | ||
|
|
782f0d93a7 | ||
|
|
52d94ae0a5 | ||
|
|
71727f935c | ||
|
|
04bac5b412 | ||
|
|
fd67a621da | ||
|
|
fe48a626d1 | ||
|
|
509fe681c3 | ||
|
|
6e7216a53d | ||
|
|
54e19d96d1 | ||
|
|
3ee21d04fe | ||
|
|
c6a92ccb7b | ||
|
|
b3dd605074 | ||
|
|
557724c58e | ||
|
|
d61d049bdb | ||
|
|
8b0ce0d988 | ||
|
|
4e38137f2c | ||
|
|
64e6d6797b | ||
|
|
0a415b9f71 | ||
|
|
bc0348ffa1 | ||
|
|
3b0ef7881e | ||
|
|
3cceb302bb | ||
|
|
da2342f251 | ||
|
|
9b72bc4169 | ||
|
|
764698c6e0 | ||
|
|
5d8096dab1 | ||
|
|
67a1b6597f | ||
|
|
946e453fb1 | ||
|
|
504b8b5134 | ||
|
|
d29c9518b3 | ||
|
|
275ce96ba6 | ||
|
|
bcaa79b6cb | ||
|
|
29df7e63b3 | ||
|
|
ddebf960b8 | ||
|
|
e6fdb7bebc | ||
|
|
79c888651f | ||
|
|
ea65d2a2ad | ||
|
|
be932147ed | ||
|
|
a16db99c67 | ||
|
|
fe9ade88d2 | ||
|
|
313303d21e | ||
|
|
7610a07185 | ||
|
|
8cd49bd5aa | ||
|
|
f1cee0fb6a | ||
|
|
46bbbb1d48 | ||
|
|
5b169990f8 | ||
|
|
b19c18b293 | ||
|
|
7cd72c515a | ||
|
|
d42b8001ec | ||
|
|
27a28907d0 | ||
|
|
fb46f74eba | ||
|
|
80b89ac44a | ||
|
|
c9679c3ec4 | ||
|
|
411ba96443 | ||
|
|
3d74474f6c | ||
|
|
f0e2975180 | ||
|
|
d43210050b | ||
|
|
ef051bdb87 | ||
|
|
0ca9fb3fb5 | ||
|
|
cbd55d6374 | ||
|
|
96906805f1 | ||
|
|
73b2e8fdd4 | ||
|
|
5da45337f7 | ||
|
|
f21d5e444e | ||
|
|
9a1472d955 | ||
|
|
2abe66800c | ||
|
|
0d38866dcf | ||
|
|
f993fa1c5f | ||
|
|
83d769f02d | ||
|
|
c8ad4b8135 | ||
|
|
bd18d8d6d1 | ||
|
|
659986ce38 | ||
|
|
062b4618c2 | ||
|
|
deb901d638 | ||
|
|
02f4ce5667 | ||
|
|
285cf5947b | ||
|
|
1a003e383a | ||
|
|
963ebf5bd7 | ||
|
|
ba9c9ae81d | ||
|
|
076e9048dc | ||
|
|
05eb051184 | ||
|
|
ddaa6afef5 | ||
|
|
6f69b4407f | ||
|
|
6dbffa022d | ||
|
|
5bb8c03664 | ||
|
|
886195ec1e | ||
|
|
288d8e3457 | ||
|
|
5208bdeb0d | ||
|
|
a6c9b41f90 | ||
|
|
70c423a5e4 | ||
|
|
89c320df0b | ||
|
|
7b2cf4374f | ||
|
|
49964e38c0 | ||
|
|
e70cdb478d | ||
|
|
be01b287b9 | ||
|
|
c2f8cb7ca1 | ||
|
|
89ee692bf0 | ||
|
|
a20923ce46 | ||
|
|
8101cd0449 | ||
|
|
30164cb1ba | ||
|
|
0640410726 | ||
|
|
2c7267ad43 | ||
|
|
daf8ee0b2f | ||
|
|
ed886fe181 | ||
|
|
4eaf5ef8bb | ||
|
|
0de9540739 | ||
|
|
31891a1a0c | ||
|
|
45d9aa90ba | ||
|
|
7a84f6cf10 | ||
|
|
f0fb406acf | ||
|
|
82406bce99 | ||
|
|
72d673a855 | ||
|
|
e2cd2383ce | ||
|
|
5661c6116c | ||
|
|
6d70e6d778 | ||
|
|
be1a836745 | ||
|
|
239ef1c54d | ||
|
|
61b51ae0e3 | ||
|
|
bfc69e4b4d | ||
|
|
af281c9fc4 | ||
|
|
bd422fd8d1 | ||
|
|
33a03c8a7b | ||
|
|
a17459e8a9 | ||
|
|
b2ee17d7c1 | ||
|
|
7963cc70f3 | ||
|
|
b792ed9f7b | ||
|
|
2e66b1fdfc | ||
|
|
8100062a78 | ||
|
|
a1762fdd74 | ||
|
|
388b43a27c | ||
|
|
23f0a1ae38 | ||
|
|
85b1734d4d | ||
|
|
3ffe84f968 | ||
|
|
220efad62b | ||
|
|
b98a0f0d22 | ||
|
|
95305c36fa | ||
|
|
48aa875c0e | ||
|
|
a8cd2ad2eb | ||
|
|
4a07c1ca9d | ||
|
|
cf5c9948c8 | ||
|
|
2288d416aa | ||
|
|
ddfe45c66e | ||
|
|
9547cf2463 | ||
|
|
1c7d059f55 | ||
|
|
6fa4576078 | ||
|
|
ae7b27de82 | ||
|
|
6b73b3defe | ||
|
|
7aad7911f6 | ||
|
|
6da92244cc | ||
|
|
c471145e96 | ||
|
|
64a991ad45 | ||
|
|
0ec4fbc4a3 | ||
|
|
ea50b695a7 | ||
|
|
331c6dce7f | ||
|
|
4f5834ba72 | ||
|
|
aa16c180e5 | ||
|
|
470d4eb993 | ||
|
|
99d91ddaa4 | ||
|
|
ab3b55e29a | ||
|
|
e4abc31f1e | ||
|
|
b7d1981b57 | ||
|
|
64a3cd6d7d | ||
|
|
48e2c27f2f | ||
|
|
8b2ea5721a | ||
|
|
df2f1273e9 | ||
|
|
f9e8236899 | ||
|
|
8f341f20c9 | ||
|
|
808d685355 | ||
|
|
80720ad592 | ||
|
|
a483337a02 | ||
|
|
1ffba7093a | ||
|
|
3da315e7b5 | ||
|
|
a2ca89aa10 | ||
|
|
990bb0b689 |
No files matched your search
@@ -1,12 +1,19 @@
|
||||
---
|
||||
name: ios-debugger-agent
|
||||
description: Build, launch, inspect, and drive iOS apps with the repository-configured XcodeBuildMCP server. Use on macOS for iOS Simulator builds, focused native test runs, semantic UI automation, screenshots, logs, or debugging, including T3 Code Mobile verification.
|
||||
description: Build, launch, inspect, and drive iOS apps with the repository-configured XcodeBuildMCP server. Use on macOS for iOS Simulator builds, focused native test runs, semantic UI automation, screenshots, logs, or debugging, including either the React Native T3 client in apps/mobile or the separate native SwiftUI client in apps/swift-ios.
|
||||
---
|
||||
|
||||
# iOS Debugger Agent
|
||||
|
||||
Use the repository-configured `xcodebuildmcp` tools instead of requiring a globally installed Codex plugin. Prefer MCP tools over raw `xcodebuild`, `xcrun`, or `simctl` when the client exposes them.
|
||||
|
||||
T3 Code has two separate iOS clients. Identify the affected one before setting session defaults:
|
||||
|
||||
- React Native mobile: `apps/mobile/ios/T3CodeDev.xcworkspace`, scheme `T3CodeDev`
|
||||
- Native SwiftUI mobile: `apps/swift-ios/T3Code.xcodeproj`, scheme `T3Code`
|
||||
|
||||
Do not assume an installed React Native build verifies SwiftUI behavior, or vice versa. Use [`test-t3-mobile`](../test-t3-mobile/SKILL.md) for the full isolated-backend and pairing workflow.
|
||||
|
||||
## Confirm availability
|
||||
|
||||
This workflow requires macOS 14.5 or newer, Xcode 16 or newer, and Node.js 18 or newer. The repository pins XcodeBuildMCP in both `.mcp.json` for Claude Code and `.codex/config.toml` for Codex. Project MCP servers may require one-time trust or approval followed by a new session.
|
||||
|
||||
@@ -5,7 +5,7 @@ description: Launch, retain, and test the T3 Code web app in isolated developmen
|
||||
|
||||
# Test T3 App
|
||||
|
||||
Use this skill for the web client. For iOS Simulator, Android Emulator, or physical-device testing against an isolated T3 backend, use the sibling [`test-t3-mobile`](../test-t3-mobile/SKILL.md) skill.
|
||||
Use this skill for the web client. For iOS Simulator, Android Emulator, or physical-device testing against an isolated T3 backend, use the sibling [`test-t3-mobile`](../test-t3-mobile/SKILL.md) skill and select either the React Native client in `apps/mobile` or the separate native SwiftUI client in `apps/swift-ios` before building.
|
||||
|
||||
## Start an isolated web environment
|
||||
|
||||
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
|
||||
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
|
||||
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
|
||||
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
|
||||
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Include a pairing token only when the user still needs to pair (see below).
|
||||
|
||||
## Authenticate the browser on the first navigation
|
||||
|
||||
@@ -50,24 +50,13 @@ Treat the overall testing or implementation loop—not an assistant turn or one
|
||||
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
|
||||
5. Continue in the same browser context so its stored bearer session remains available.
|
||||
|
||||
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
|
||||
Keep pairing URLs out of screenshots, committed files, and durable logs. When the user asked for a shared environment, the deliverable IS the full pairing URL — paste it in your reply, token and all; a bare origin is useless to them. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it, so never open a URL you handed to the user.
|
||||
|
||||
## Recover a consumed or expired pairing token
|
||||
|
||||
Create another token against the same database and web URL as the running dev server:
|
||||
Run `node apps/server/src/bin.ts pair` from the repository root. It discovers the running dev server (worktree `.t3` first, same precedence as the dev runner) and prints a fresh `Pair URL` against the server's current web origin, including a `--share` tailnet origin. Pass `--base-dir <base-dir>` only when the server was started with `--home-dir`, using the identical path.
|
||||
|
||||
```bash
|
||||
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
--base-dir <base-dir> \
|
||||
--dev-url <web-url> \
|
||||
--base-url <web-url> \
|
||||
--ttl 15m \
|
||||
--label agent-ui-test
|
||||
```
|
||||
|
||||
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
|
||||
|
||||
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
|
||||
Tokens from `pair` carry standard client scopes. The startup pairing URL carries admin scopes; if the user needs Settings → Connections management (`access:write`), restart the server and hand over the new startup URL instead.
|
||||
|
||||
## Inspect or seed SQLite state
|
||||
|
||||
|
||||
@@ -1,19 +1,28 @@
|
||||
---
|
||||
name: test-t3-mobile
|
||||
description: Launch and test T3 Code Mobile on an iOS Simulator or Android Emulator against disposable local T3 environments, including Metro and dev-client reuse, native rebuild decisions, per-client pairing, seeded projects, semantic UI control, screenshots, and iOS serve-sim streaming. Use after mobile UI or native changes, when reproducing phone or tablet behavior, pairing an emulator to isolated state, or verifying mobile behavior on macOS, Linux, or Windows.
|
||||
description: "Launch and test either T3 Code mobile client against disposable local environments: the React Native iOS/Android app in apps/mobile or the separate native SwiftUI iOS app in apps/swift-ios. Covers client selection, native rebuild decisions, Metro and dev-client reuse for React Native only, per-client pairing, seeded projects, semantic UI control, screenshots, and iOS serve-sim streaming. Use after mobile UI or native changes, when reproducing phone or tablet behavior, pairing a device to isolated state, or verifying mobile behavior on macOS, Linux, or Windows."
|
||||
---
|
||||
|
||||
# Test T3 Mobile
|
||||
|
||||
Run one focused, end-to-end mobile verification pass against disposable T3 state. Use the sibling [`test-t3-app`](../test-t3-app/SKILL.md) skill as the detailed reference for pairing-token semantics and SQLite fixtures.
|
||||
|
||||
## Choose the mobile client first
|
||||
|
||||
T3 Code has two independent mobile implementations:
|
||||
|
||||
- **React Native mobile** lives in `apps/mobile` and targets iOS and Android. Its development workflow uses Expo, Metro, and the `T3 Code Dev` identity documented below.
|
||||
- **SwiftUI mobile** lives in `apps/swift-ios` and targets iOS. It is a native Xcode project and never uses Expo or Metro. Its Debug identity is `T3 Swift Dev`, bundle identifier `com.t3tools.t3code.swiftui.dev`, and URL scheme `t3code-swiftui-dev`.
|
||||
|
||||
Inspect the affected paths and choose one before launching anything. Do not use one client as verification for the other. For SwiftUI, load [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), set the project to `<repo>/apps/swift-ios/T3Code.xcodeproj`, scheme `T3Code`, configuration `Debug`, and use the selected simulator. Then use this skill's disposable-backend, pairing, UI-driving, and cleanup guidance while skipping every Metro, Expo, and Android step.
|
||||
|
||||
Command examples use POSIX shell syntax. On Windows, use PowerShell equivalents: set variables with `$env:NAME = "value"`, use an explicit temporary directory from `[System.IO.Path]::GetTempPath()`, and run multiline examples on one line or with PowerShell backticks. Use `$env:ANDROID_HOME\platform-tools\adb.exe` when `adb` is not already on `PATH`.
|
||||
|
||||
## Select a viable platform
|
||||
|
||||
Inspect the host and the affected code before launching processes:
|
||||
|
||||
- On macOS with Xcode, prefer one representative iOS Simulator when the change is cross-platform so the user can watch through serve-sim. Load and follow [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), and load [`ios-simulator-browser`](../ios-simulator-browser/SKILL.md) when live streaming is available.
|
||||
- On macOS with Xcode, prefer one representative iOS Simulator when the change is cross-platform so the user can watch through serve-sim. This can be either mobile client; use the project selected above. Load and follow [`ios-debugger-agent`](../ios-debugger-agent/SKILL.md), and load [`ios-simulator-browser`](../ios-simulator-browser/SKILL.md) when live streaming is available.
|
||||
- On macOS, Linux, or Windows with the Android SDK, use one Android Emulator when Android is the affected surface or iOS tooling is unavailable.
|
||||
- When the change is platform-specific, test that platform. When neither platform is viable, report the missing SDK, emulator, or dev-client prerequisite rather than claiming verification.
|
||||
|
||||
@@ -21,12 +30,13 @@ Do not treat unavailable iOS tooling as a blocker when Android is a valid repres
|
||||
|
||||
## Choose the lightest valid launch path
|
||||
|
||||
- For JavaScript, TypeScript, or asset-only changes, reuse a compatible installed development client and start Metro. Do not rebuild native code merely to load a new bundle.
|
||||
- For React Native JavaScript, TypeScript, or asset-only changes, reuse a compatible installed development client and start Metro. Do not rebuild native code merely to load a new bundle.
|
||||
- For SwiftUI changes, build or reuse the native `T3Code` scheme with `ios-debugger-agent`; Metro and Expo compatibility do not apply.
|
||||
- For native source, native dependencies, entitlements, config plugins, or generated project changes, rebuild the affected platform.
|
||||
- Use `vp run ios:dev` or `vp run android:dev` only when an Expo clean prebuild is actually required; both commands regenerate the native project.
|
||||
- If the user requested no native rebuild and no compatible app is installed, reuse an existing compatible `.app` or `.apk` artifact when available. Otherwise report the missing dev client instead of silently rebuilding.
|
||||
|
||||
The development identity on both platforms is:
|
||||
The React Native development identity on both platforms is:
|
||||
|
||||
- App: `T3 Code Dev`
|
||||
- Bundle/package identifier: `com.t3tools.t3code.dev`
|
||||
@@ -70,7 +80,7 @@ Enter the complete `http://` origin to make the test transport explicit. Bare IP
|
||||
|
||||
## Start or reuse Metro safely
|
||||
|
||||
Run Metro from `apps/mobile`.
|
||||
This section applies only to React Native mobile. Run Metro from `apps/mobile`. Skip it entirely for SwiftUI mobile.
|
||||
|
||||
1. Inspect any process on the intended Metro port and its `/status` response. Reuse it only when it is healthy, belongs to this worktree, and matches `APP_VARIANT=development`, `--dev-client`, and scheme `t3code-dev`.
|
||||
2. Never kill another worktree's Metro. Use a free explicit port when necessary.
|
||||
@@ -89,7 +99,7 @@ Run Metro from `apps/mobile`.
|
||||
|
||||
4. Open the exact development-client URL for the selected device and confirm the loaded bundle belongs to this worktree and Metro port.
|
||||
|
||||
### iOS launch
|
||||
### React Native iOS launch
|
||||
|
||||
Use `ios-debugger-agent` to select one UDID and set these XcodeBuildMCP session defaults:
|
||||
|
||||
@@ -108,7 +118,7 @@ xcrun simctl openurl <simulator-udid> <printed-dev-client-url>
|
||||
|
||||
Accept the iOS confirmation prompt and dismiss the developer menu when it obscures the app.
|
||||
|
||||
### Android launch
|
||||
### React Native Android launch
|
||||
|
||||
Select one running emulator serial from `adb devices` and check the installed client:
|
||||
|
||||
@@ -137,10 +147,16 @@ T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
|
||||
|
||||
In PowerShell, set `$env:T3CODE_PORT = "<server-port>"` first and run the `node ... auth pairing create` command without the leading assignment.
|
||||
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the app's registered route instead of guessing coordinates:
|
||||
If the visible Add Environment action is not exposed as a semantic target, open the selected app's registered route instead of guessing coordinates:
|
||||
|
||||
```bash
|
||||
# React Native iOS
|
||||
xcrun simctl openurl <simulator-udid> 't3code-dev://connections/new'
|
||||
|
||||
# SwiftUI iOS
|
||||
xcrun simctl openurl <simulator-udid> 't3code-swiftui-dev://connections/new'
|
||||
|
||||
# React Native Android
|
||||
adb -s <emulator-serial> shell am start -W \
|
||||
-a android.intent.action.VIEW \
|
||||
-d 't3code-dev://connections/new' \
|
||||
@@ -149,7 +165,7 @@ adb -s <emulator-serial> shell am start -W \
|
||||
|
||||
Run only the command for the selected platform.
|
||||
|
||||
In T3 Code Dev, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
|
||||
In the selected development app, open Add Environment and enter the complete `<mobile-origin>` and newly printed `Token`. Verify the expected seeded projects appear before exercising the affected flow.
|
||||
|
||||
Pairing credentials are secret, short-lived, and single-use. Create a different credential for every simulator, emulator, physical device, or browser. If an attempt fails, issue a new credential rather than retrying the old one. Do not expose tokens in screenshots, commits, or final responses.
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "Test T3 Mobile"
|
||||
short_description: "Test T3 Code on iOS or Android"
|
||||
default_prompt: "Use $test-t3-mobile to launch T3 Code against an isolated backend and verify the affected flow on an available simulator or emulator."
|
||||
short_description: "Test React Native or SwiftUI T3 clients"
|
||||
default_prompt: "Use $test-t3-mobile to select the affected React Native or SwiftUI client, launch it against an isolated backend, and verify the flow on an available simulator or emulator."
|
||||
+12
-9
@@ -1,12 +1,14 @@
|
||||
# Optional: T3 Connect source builds
|
||||
# Leave these unset to disable optional T3 Connect features in local source builds.
|
||||
# Release builds inject their public values at build time. Do not add server-side
|
||||
# secrets to this file.
|
||||
# `cp .env.example .env` enables T3 Connect against the production deployment.
|
||||
# These are the same public identifiers baked into official release builds, not
|
||||
# secrets. Remove or comment them out to build with cloud features disabled.
|
||||
# Do not add server-side secrets to this file.
|
||||
|
||||
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
|
||||
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
|
||||
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
|
||||
# Production Clerk instance. To use your own, get these from the Clerk Dashboard
|
||||
# under API keys, JWT templates, and OAuth applications.
|
||||
T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk
|
||||
T3CODE_CLERK_JWT_TEMPLATE=t3-relay
|
||||
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
|
||||
|
||||
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
|
||||
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
|
||||
@@ -15,8 +17,9 @@
|
||||
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
|
||||
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
|
||||
|
||||
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
|
||||
# T3CODE_RELAY_URL=https://relay.example.com
|
||||
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
|
||||
# automatically.
|
||||
T3CODE_RELAY_URL=https://relay.t3.codes
|
||||
|
||||
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
|
||||
# Defaults to https://app.t3.codes; override to test against a staging deployment.
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,429 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const ARTIFACT_NAME = "thread-transfer-results";
|
||||
const RESULT_FILE = "thread-transfer-result.json";
|
||||
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
|
||||
const PROVIDERS = ["codex", "claudeAgent"];
|
||||
const OBSERVED_KEYS = [
|
||||
"totalWireBytes",
|
||||
"threadSnapshotWireBytes",
|
||||
"threadSnapshotDecodedBytes",
|
||||
"measuredTurnWebSocketWireBytes",
|
||||
"measuredTurnWebSocketDecodedBytes",
|
||||
"measuredTurnWebSocketMessages",
|
||||
];
|
||||
const CEILING_KEYS = [
|
||||
"totalWireBytes",
|
||||
"threadSnapshotWireBytes",
|
||||
"measuredTurnWebSocketWireBytes",
|
||||
"measuredTurnWebSocketDecodedBytes",
|
||||
"measuredTurnWebSocketMessages",
|
||||
];
|
||||
const SCENARIO_KEYS = [
|
||||
"id",
|
||||
"historyTurns",
|
||||
"historyCommandToolsPerTurn",
|
||||
"historyMcpResultBytes",
|
||||
"measuredCommandTools",
|
||||
"measuredMcpResultBytes",
|
||||
];
|
||||
|
||||
function resultShaMarker(sha) {
|
||||
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
|
||||
}
|
||||
|
||||
function assertObject(value, label) {
|
||||
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
||||
throw new Error(`${label} must be an object`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertExactKeys(value, expected, label) {
|
||||
assertObject(value, label);
|
||||
const actual = Object.keys(value).sort();
|
||||
const wanted = [...expected].sort();
|
||||
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
|
||||
throw new Error(`${label} has unexpected fields`);
|
||||
}
|
||||
}
|
||||
|
||||
function assertMetric(value, label) {
|
||||
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
|
||||
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateResult(value) {
|
||||
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
|
||||
if (value.schemaVersion !== 1) {
|
||||
throw new Error("result.schemaVersion must be 1");
|
||||
}
|
||||
|
||||
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
|
||||
if (value.scenario.id !== "thread-transfer-v1") {
|
||||
throw new Error("result.scenario.id is not supported");
|
||||
}
|
||||
for (const key of SCENARIO_KEYS.slice(1)) {
|
||||
assertMetric(value.scenario[key], `result.scenario.${key}`);
|
||||
}
|
||||
|
||||
assertExactKeys(value.providers, PROVIDERS, "result.providers");
|
||||
for (const provider of PROVIDERS) {
|
||||
const entry = value.providers[provider];
|
||||
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
|
||||
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
|
||||
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
|
||||
for (const key of OBSERVED_KEYS) {
|
||||
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
|
||||
}
|
||||
for (const key of CEILING_KEYS) {
|
||||
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
|
||||
}
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function readResult(directory) {
|
||||
if (!directory) return undefined;
|
||||
const file = path.join(directory, RESULT_FILE);
|
||||
if (!fs.existsSync(file)) return undefined;
|
||||
const stat = fs.lstatSync(file);
|
||||
if (!stat.isFile() || stat.size > 64 * 1_024) {
|
||||
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
|
||||
}
|
||||
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
|
||||
}
|
||||
|
||||
function formatBytes(bytes) {
|
||||
if (bytes < 1_024) return `${bytes} B`;
|
||||
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
|
||||
return `${(bytes / 1_024).toFixed(1)} KiB`;
|
||||
}
|
||||
|
||||
function formatValue(value, kind) {
|
||||
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
|
||||
}
|
||||
|
||||
function formatImpact(current, baseline, kind) {
|
||||
if (baseline === undefined) return "—";
|
||||
const delta = current - baseline;
|
||||
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
|
||||
const magnitude = formatValue(Math.abs(delta), kind);
|
||||
const percent =
|
||||
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
|
||||
return `${prefix}${magnitude}${percent}`;
|
||||
}
|
||||
|
||||
function sameScenario(left, right) {
|
||||
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
|
||||
}
|
||||
|
||||
const METRICS = [
|
||||
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
|
||||
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
|
||||
{
|
||||
key: "measuredTurnWebSocketWireBytes",
|
||||
label: "Live turn WebSocket wire",
|
||||
kind: "bytes",
|
||||
},
|
||||
{
|
||||
key: "measuredTurnWebSocketDecodedBytes",
|
||||
label: "Live turn WebSocket decoded",
|
||||
kind: "bytes",
|
||||
},
|
||||
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
|
||||
];
|
||||
|
||||
function renderComment(input) {
|
||||
const current = input.current;
|
||||
const baseline = input.baseline;
|
||||
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
|
||||
const rows = [];
|
||||
const ceilingChanges = [];
|
||||
let failed = false;
|
||||
|
||||
for (const provider of PROVIDERS) {
|
||||
for (const metric of METRICS) {
|
||||
const observed = current.providers[provider].observed[metric.key];
|
||||
const ceiling = current.providers[provider].ceiling[metric.key];
|
||||
const baselineObserved = comparable
|
||||
? baseline.providers[provider].observed[metric.key]
|
||||
: undefined;
|
||||
const pass = observed <= ceiling;
|
||||
failed ||= !pass;
|
||||
rows.push(
|
||||
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
|
||||
);
|
||||
|
||||
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
|
||||
ceilingChanges.push(
|
||||
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const baselineLink = input.baselineRun
|
||||
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
|
||||
: "unavailable";
|
||||
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
|
||||
const notices = [];
|
||||
if (!baseline) {
|
||||
notices.push(
|
||||
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
|
||||
);
|
||||
} else if (!comparable) {
|
||||
notices.push(
|
||||
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
|
||||
);
|
||||
} else if (!input.baselineRun.matchesBase) {
|
||||
notices.push(
|
||||
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
|
||||
);
|
||||
}
|
||||
if (ceilingChanges.length > 0) {
|
||||
notices.push(
|
||||
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
|
||||
);
|
||||
}
|
||||
|
||||
return [
|
||||
COMMENT_MARKER,
|
||||
resultShaMarker(input.currentRun.sha),
|
||||
"## Thread transfer impact",
|
||||
"",
|
||||
failed
|
||||
? "❌ One or more thread transfer ceilings were exceeded."
|
||||
: "✅ Thread transfer remains within every enforced ceiling.",
|
||||
...(notices.length > 0 ? ["", ...notices] : []),
|
||||
"",
|
||||
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
|
||||
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
|
||||
...rows,
|
||||
"",
|
||||
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
|
||||
"",
|
||||
"<details>",
|
||||
"<summary>Scenario and decoded snapshot size</summary>",
|
||||
"",
|
||||
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
|
||||
"",
|
||||
...PROVIDERS.map(
|
||||
(provider) =>
|
||||
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
|
||||
),
|
||||
"",
|
||||
"</details>",
|
||||
"",
|
||||
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function artifactsForRun(github, owner, repo, runId) {
|
||||
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
|
||||
owner,
|
||||
repo,
|
||||
run_id: runId,
|
||||
per_page: 100,
|
||||
});
|
||||
}
|
||||
|
||||
function findResultArtifact(artifacts) {
|
||||
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
|
||||
}
|
||||
|
||||
async function resolve({ github, context, core }) {
|
||||
const source = context.payload.workflow_run;
|
||||
const { owner, repo } = context.repo;
|
||||
if (source.event !== "pull_request") {
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
let pullNumber = source.pull_requests?.[0]?.number;
|
||||
if (!pullNumber) {
|
||||
const associated = await github.paginate(
|
||||
github.rest.repos.listPullRequestsAssociatedWithCommit,
|
||||
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
|
||||
);
|
||||
const matchingPulls = associated.filter(
|
||||
(pull) =>
|
||||
pull.state === "open" &&
|
||||
pull.head.sha === source.head_sha &&
|
||||
pull.head.ref === source.head_branch,
|
||||
);
|
||||
if (matchingPulls.length !== 1) {
|
||||
core.info(
|
||||
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
|
||||
);
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
pullNumber = matchingPulls[0].number;
|
||||
}
|
||||
if (!pullNumber) {
|
||||
core.info("No open pull request is associated with the completed CI run.");
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
|
||||
if (pull.head.sha !== source.head_sha) {
|
||||
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
|
||||
core.setOutput("publish", "false");
|
||||
return;
|
||||
}
|
||||
|
||||
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
|
||||
const sourceArtifact = findResultArtifact(sourceArtifacts);
|
||||
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
|
||||
owner,
|
||||
repo,
|
||||
workflow_id: source.workflow_id,
|
||||
branch: pull.base.ref,
|
||||
event: "push",
|
||||
status: "success",
|
||||
per_page: 100,
|
||||
});
|
||||
const orderedRuns = [
|
||||
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
|
||||
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
|
||||
].slice(0, 20);
|
||||
|
||||
let baselineRun;
|
||||
for (const run of orderedRuns) {
|
||||
const artifacts = await artifactsForRun(github, owner, repo, run.id);
|
||||
if (findResultArtifact(artifacts)) {
|
||||
baselineRun = run;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
core.setOutput("publish", "true");
|
||||
core.setOutput("pull_number", String(pullNumber));
|
||||
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
|
||||
core.setOutput("pr_run_id", String(source.id));
|
||||
core.setOutput("pr_sha", source.head_sha);
|
||||
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
|
||||
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
|
||||
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
|
||||
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
|
||||
core.setOutput(
|
||||
"baseline_matches_base",
|
||||
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
|
||||
);
|
||||
}
|
||||
|
||||
async function upsertComment(github, context, pullNumber, body, options = {}) {
|
||||
const { owner, repo } = context.repo;
|
||||
const comments = await github.paginate(github.rest.issues.listComments, {
|
||||
owner,
|
||||
repo,
|
||||
issue_number: pullNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const existing = comments.find(
|
||||
(comment) =>
|
||||
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
|
||||
);
|
||||
if (
|
||||
options.preserveResultSha &&
|
||||
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
if (existing) {
|
||||
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
|
||||
} else {
|
||||
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
|
||||
}
|
||||
}
|
||||
|
||||
async function upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
expectedSha,
|
||||
body,
|
||||
options,
|
||||
) {
|
||||
const { owner, repo } = context.repo;
|
||||
const { data: pull } = await github.rest.pulls.get({
|
||||
owner,
|
||||
repo,
|
||||
pull_number: pullNumber,
|
||||
});
|
||||
if (pull.head.sha !== expectedSha) {
|
||||
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
|
||||
return false;
|
||||
}
|
||||
|
||||
await upsertComment(github, context, pullNumber, body, options);
|
||||
return true;
|
||||
}
|
||||
|
||||
async function publish({ github, context, core }) {
|
||||
const pullNumber = Number(process.env.PR_NUMBER);
|
||||
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
|
||||
throw new Error("PR_NUMBER is invalid");
|
||||
}
|
||||
|
||||
const current = readResult(process.env.PR_RESULT_DIR);
|
||||
const currentRun = {
|
||||
sha: process.env.PR_SHA,
|
||||
conclusion: process.env.PR_CONCLUSION,
|
||||
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
|
||||
};
|
||||
if (!current) {
|
||||
await upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
currentRun.sha,
|
||||
[
|
||||
COMMENT_MARKER,
|
||||
"## Thread transfer impact",
|
||||
"",
|
||||
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
|
||||
"",
|
||||
"_This comment will update automatically after the next completed run._",
|
||||
].join("\n"),
|
||||
{ preserveResultSha: currentRun.sha },
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
|
||||
const baselineRun = baseline
|
||||
? {
|
||||
sha: process.env.BASELINE_SHA,
|
||||
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
|
||||
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
|
||||
}
|
||||
: undefined;
|
||||
const body = renderComment({ current, baseline, currentRun, baselineRun });
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
github,
|
||||
context,
|
||||
core,
|
||||
pullNumber,
|
||||
currentRun.sha,
|
||||
body,
|
||||
);
|
||||
if (published) {
|
||||
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
publish,
|
||||
readResult,
|
||||
renderComment,
|
||||
resolve,
|
||||
upsertCommentForCurrentHead,
|
||||
validateResult,
|
||||
};
|
||||
@@ -0,0 +1,292 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const test = require("node:test");
|
||||
|
||||
const {
|
||||
renderComment,
|
||||
resolve,
|
||||
upsertCommentForCurrentHead,
|
||||
validateResult,
|
||||
} = require("./thread-transfer-report.cjs");
|
||||
|
||||
function result(overrides = {}) {
|
||||
const observed = {
|
||||
totalWireBytes: 2_200_000,
|
||||
threadSnapshotWireBytes: 1_950_000,
|
||||
threadSnapshotDecodedBytes: 9_100_000,
|
||||
measuredTurnWebSocketWireBytes: 250_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_150_000,
|
||||
measuredTurnWebSocketMessages: 15,
|
||||
};
|
||||
const ceiling = {
|
||||
totalWireBytes: 2_900_000,
|
||||
threadSnapshotWireBytes: 2_600_000,
|
||||
measuredTurnWebSocketWireBytes: 320_000,
|
||||
measuredTurnWebSocketDecodedBytes: 1_550_000,
|
||||
measuredTurnWebSocketMessages: 20,
|
||||
};
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
scenario: {
|
||||
id: "thread-transfer-v1",
|
||||
historyTurns: 10,
|
||||
historyCommandToolsPerTurn: 5,
|
||||
historyMcpResultBytes: 900_000,
|
||||
measuredCommandTools: 20,
|
||||
measuredMcpResultBytes: 1_100_000,
|
||||
},
|
||||
providers: {
|
||||
codex: { observed: { ...observed, ...overrides }, ceiling },
|
||||
claudeAgent: { observed, ceiling },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("validates the fixed artifact schema", () => {
|
||||
assert.equal(validateResult(result()).schemaVersion, 1);
|
||||
assert.throws(
|
||||
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
|
||||
/unexpected fields/,
|
||||
);
|
||||
assert.throws(
|
||||
() => validateResult(result({ totalWireBytes: "lots" })),
|
||||
/non-negative safe integer/,
|
||||
);
|
||||
});
|
||||
|
||||
test("renders baseline, impact, ceiling, and ceiling changes", () => {
|
||||
const baseline = result();
|
||||
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
|
||||
current.providers.codex.ceiling = {
|
||||
...current.providers.codex.ceiling,
|
||||
measuredTurnWebSocketWireBytes: 330_000,
|
||||
};
|
||||
const comment = renderComment({
|
||||
current,
|
||||
baseline,
|
||||
currentRun: {
|
||||
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
|
||||
conclusion: "success",
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
|
||||
},
|
||||
baselineRun: {
|
||||
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
matchesBase: true,
|
||||
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
|
||||
},
|
||||
});
|
||||
|
||||
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
|
||||
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
|
||||
assert.match(comment, /This PR changes transfer ceilings/);
|
||||
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
|
||||
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
|
||||
assert.match(
|
||||
comment,
|
||||
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
|
||||
const outputs = {};
|
||||
const listWorkflowRunArtifacts = () => {};
|
||||
const listWorkflowRuns = () => {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
const github = {
|
||||
paginate: async (method, input) => {
|
||||
if (method === listPullRequestsAssociatedWithCommit) {
|
||||
return [
|
||||
{
|
||||
number: 5350,
|
||||
state: "open",
|
||||
head: { sha: "head-sha", ref: "feature-branch", repo: null },
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRunArtifacts) {
|
||||
return [
|
||||
{
|
||||
name: "thread-transfer-results",
|
||||
expired: false,
|
||||
runId: input.run_id,
|
||||
},
|
||||
];
|
||||
}
|
||||
if (method === listWorkflowRuns) {
|
||||
return [{ id: 1, head_sha: "base-sha" }];
|
||||
}
|
||||
throw new Error("unexpected pagination call");
|
||||
},
|
||||
rest: {
|
||||
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
|
||||
pulls: {
|
||||
get: async () => ({
|
||||
data: {
|
||||
head: { sha: "head-sha" },
|
||||
base: { sha: "base-sha", ref: "main" },
|
||||
},
|
||||
}),
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
};
|
||||
await resolve({
|
||||
github,
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "true");
|
||||
assert.equal(outputs.pull_number, "5350");
|
||||
assert.equal(outputs.pr_artifact, "true");
|
||||
assert.equal(outputs.baseline_run_id, "1");
|
||||
assert.equal(outputs.baseline_matches_base, "true");
|
||||
});
|
||||
|
||||
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
|
||||
const outputs = {};
|
||||
const listPullRequestsAssociatedWithCommit = () => {};
|
||||
let fetchedPull = false;
|
||||
await resolve({
|
||||
github: {
|
||||
paginate: async (method) => {
|
||||
assert.equal(method, listPullRequestsAssociatedWithCommit);
|
||||
return [5350, 5351].map((number) => ({
|
||||
number,
|
||||
state: "open",
|
||||
head: {
|
||||
sha: "head-sha",
|
||||
ref: "feature-branch",
|
||||
repo: { full_name: "pingdotgg/t3code" },
|
||||
},
|
||||
}));
|
||||
},
|
||||
rest: {
|
||||
actions: {},
|
||||
pulls: {
|
||||
get: async () => {
|
||||
fetchedPull = true;
|
||||
},
|
||||
},
|
||||
repos: { listPullRequestsAssociatedWithCommit },
|
||||
},
|
||||
},
|
||||
context: {
|
||||
repo: { owner: "pingdotgg", repo: "t3code" },
|
||||
payload: {
|
||||
workflow_run: {
|
||||
id: 2,
|
||||
event: "pull_request",
|
||||
workflow_id: 3,
|
||||
head_sha: "head-sha",
|
||||
head_branch: "feature-branch",
|
||||
head_repository: { full_name: "pingdotgg/t3code" },
|
||||
conclusion: "success",
|
||||
pull_requests: [],
|
||||
},
|
||||
},
|
||||
},
|
||||
core: {
|
||||
info: () => {},
|
||||
setOutput: (key, value) => {
|
||||
outputs[key] = value;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
assert.equal(outputs.publish, "false");
|
||||
assert.equal(fetchedPull, false);
|
||||
});
|
||||
|
||||
test("does not publish a stale result after the PR head advances", async () => {
|
||||
let listedComments = false;
|
||||
const info = [];
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => {
|
||||
listedComments = true;
|
||||
return [];
|
||||
},
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
throw new Error("must not create a stale comment");
|
||||
},
|
||||
updateComment: () => {
|
||||
throw new Error("must not update a stale comment");
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: (message) => info.push(message) },
|
||||
5350,
|
||||
"old-head-sha",
|
||||
"stale body",
|
||||
);
|
||||
|
||||
assert.equal(published, false);
|
||||
assert.equal(listedComments, false);
|
||||
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
|
||||
});
|
||||
|
||||
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
|
||||
let updatedComment = false;
|
||||
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const published = await upsertCommentForCurrentHead(
|
||||
{
|
||||
paginate: async () => [
|
||||
{
|
||||
id: 1,
|
||||
user: { login: "github-actions[bot]" },
|
||||
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
|
||||
},
|
||||
],
|
||||
rest: {
|
||||
issues: {
|
||||
listComments: () => {},
|
||||
createComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
updateComment: () => {
|
||||
updatedComment = true;
|
||||
},
|
||||
},
|
||||
pulls: {
|
||||
get: async () => ({ data: { head: { sha } } }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ repo: { owner: "pingdotgg", repo: "t3code" } },
|
||||
{ info: () => {} },
|
||||
5350,
|
||||
sha,
|
||||
"missing artifact warning",
|
||||
{ preserveResultSha: sha },
|
||||
);
|
||||
|
||||
assert.equal(published, true);
|
||||
assert.equal(updatedComment, false);
|
||||
});
|
||||
@@ -84,8 +84,29 @@ jobs:
|
||||
run: vp run --filter @t3tools/desktop ensure:electron
|
||||
|
||||
- name: Test
|
||||
env:
|
||||
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
|
||||
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
|
||||
run: vp run test
|
||||
|
||||
- name: Publish transfer budget report
|
||||
if: always()
|
||||
run: |
|
||||
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
|
||||
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
|
||||
else
|
||||
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
|
||||
fi
|
||||
|
||||
- name: Upload thread transfer result
|
||||
if: always()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer-result.json
|
||||
if-no-files-found: ignore
|
||||
retention-days: 30
|
||||
|
||||
- name: Test resource monitor
|
||||
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
|
||||
|
||||
|
||||
@@ -5,6 +5,23 @@ 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 with --auto-submit (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. 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:
|
||||
@@ -29,10 +46,30 @@ on:
|
||||
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
|
||||
@@ -98,15 +135,15 @@ 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: 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 +154,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. Builds started here stay attached to this serialized run so
|
||||
# the queued run for a later merge cannot overtake them and lose its OTA.
|
||||
# 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; then
|
||||
echo ":building_construction: $platform: cut production build for $version (auto-submitted)" >> "$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
|
||||
hash="$(eas fingerprint:generate --platform "$platform" --environment production --json --non-interactive | jq -r '.hash')"
|
||||
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"}`,
|
||||
);
|
||||
@@ -0,0 +1,58 @@
|
||||
name: SwiftUI iOS
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- "apps/swift-ios/**"
|
||||
- "packages/contracts/**"
|
||||
- "scripts/generate-swift-wire-fixtures.ts"
|
||||
- "scripts/package.json"
|
||||
- ".github/workflows/swift-ios.yml"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "pnpm-workspace.yaml"
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "apps/swift-ios/**"
|
||||
- "packages/contracts/**"
|
||||
- "scripts/generate-swift-wire-fixtures.ts"
|
||||
- "scripts/package.json"
|
||||
- ".github/workflows/swift-ios.yml"
|
||||
- "package.json"
|
||||
- "pnpm-lock.yaml"
|
||||
- "pnpm-workspace.yaml"
|
||||
|
||||
concurrency:
|
||||
group: swift-ios-${{ github.event.pull_request.number || github.sha }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
jobs:
|
||||
test:
|
||||
name: Contract fixtures and native tests
|
||||
runs-on: blacksmith-6vcpu-macos-26
|
||||
timeout-minutes: 25
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
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...
|
||||
|
||||
- name: Verify generated wire fixtures
|
||||
run: node scripts/generate-swift-wire-fixtures.ts --check
|
||||
|
||||
- name: Test SwiftUI client
|
||||
run: apps/swift-ios/Scripts/ci-test.sh
|
||||
@@ -0,0 +1,75 @@
|
||||
name: Thread Transfer Report
|
||||
|
||||
on:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
|
||||
permissions:
|
||||
actions: read
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish PR comment
|
||||
if: github.event.workflow_run.event == 'pull_request'
|
||||
runs-on: ubuntu-24.04
|
||||
concurrency:
|
||||
group: thread-transfer-report-${{ github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.id }}
|
||||
cancel-in-progress: true
|
||||
steps:
|
||||
# workflow_run has a write-capable token even for fork PRs. Only load the
|
||||
# publisher from the trusted default branch and never execute PR code.
|
||||
- name: Checkout trusted publisher
|
||||
uses: actions/checkout@v6
|
||||
with:
|
||||
ref: ${{ github.event.repository.default_branch }}
|
||||
sparse-checkout: .github/scripts
|
||||
|
||||
- name: Test trusted publisher
|
||||
run: node --test .github/scripts/thread-transfer-report.test.cjs
|
||||
|
||||
- id: resolve
|
||||
name: Resolve PR and baseline artifacts
|
||||
uses: actions/github-script@v8
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.resolve({ github, context, core });
|
||||
|
||||
- name: Download PR result
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.pr_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/pr
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
|
||||
- name: Download main baseline
|
||||
if: steps.resolve.outputs.publish == 'true' && steps.resolve.outputs.baseline_artifact == 'true'
|
||||
uses: actions/download-artifact@v8
|
||||
with:
|
||||
name: thread-transfer-results
|
||||
path: ${{ runner.temp }}/thread-transfer/main
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
run-id: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
|
||||
- name: Update thread transfer comment
|
||||
if: steps.resolve.outputs.publish == 'true'
|
||||
uses: actions/github-script@v8
|
||||
env:
|
||||
PR_NUMBER: ${{ steps.resolve.outputs.pull_number }}
|
||||
PR_SHA: ${{ steps.resolve.outputs.pr_sha }}
|
||||
PR_CONCLUSION: ${{ steps.resolve.outputs.pr_conclusion }}
|
||||
PR_RUN_ID: ${{ steps.resolve.outputs.pr_run_id }}
|
||||
PR_RESULT_DIR: ${{ runner.temp }}/thread-transfer/pr
|
||||
BASELINE_SHA: ${{ steps.resolve.outputs.baseline_sha }}
|
||||
BASELINE_MATCHES_BASE: ${{ steps.resolve.outputs.baseline_matches_base }}
|
||||
BASELINE_RUN_ID: ${{ steps.resolve.outputs.baseline_run_id }}
|
||||
BASELINE_RESULT_DIR: ${{ runner.temp }}/thread-transfer/main
|
||||
with:
|
||||
script: |
|
||||
const reporter = require("./.github/scripts/thread-transfer-report.cjs");
|
||||
await reporter.publish({ github, context, core });
|
||||
@@ -0,0 +1,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,
|
||||
});
|
||||
}
|
||||
@@ -28,7 +28,12 @@ T3 Code has 3 key app surfaces: **web**, **desktop**, and **mobile**.
|
||||
|
||||
**Desktop** is the main surface most users install first. It's a full Electron app that bundles the server runner as well. The desktop app can also be used as the host server, allowing remote connections from app.t3.codes or the mobile app.
|
||||
|
||||
**Mobile** is a React Native app for both iOS and Android, available on the App Store and Google Play. The mobile app allows for connecting to any T3 Code server to control work remotely.
|
||||
**Mobile** has two separate clients that connect to the same T3 servers:
|
||||
|
||||
- `apps/mobile` is the React Native app for iOS and Android, available on the App Store and Google Play.
|
||||
- `apps/swift-ios` is the native SwiftUI app for iOS, with its own Xcode project, UI implementation, and app identities.
|
||||
|
||||
Treat them as distinct clients. UI, navigation, persistence, and build changes in one do not automatically reach the other. When implementation details matter, say **React Native mobile** or **SwiftUI mobile** instead of referring ambiguously to “the mobile app.”
|
||||
|
||||
## A note from Theo
|
||||
|
||||
@@ -67,9 +72,9 @@ We need to be on the same page with terminology. When communicating, use this la
|
||||
The most common defect in this repo is a change that works on the path you tested and is missing everywhere else. Before calling frontend work done, walk this list and say which entries applied:
|
||||
|
||||
- **Entry points.** A behavior reachable from the chat view is usually also reachable from Settings, the command palette, and a keybinding. Fixing one is not fixing the feature.
|
||||
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), and mobile (React Native, separate navigation). Shared logic lives in `packages/client-runtime`
|
||||
- **Clients.** Web, desktop (wraps web, adds Electron shell/IPC), React Native mobile, and SwiftUI mobile. Decide explicitly which mobile clients a change applies to. Shared TypeScript client logic lives in `packages/client-runtime`; the SwiftUI client is a separate native implementation.
|
||||
- **Providers.** Codex, Claude, Cursor, Grok, and OpenCode each have an adapter. Provider-shaped features need a decision per adapter, even if the decision is "not supported here".
|
||||
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. Change the schema and the server, web, mobile, and desktop all follow.
|
||||
- **Contracts.** Anything crossing the wire is typed in `packages/contracts`. When a schema changes, update the server, web, desktop, React Native mobile, and SwiftUI mobile implementations as applicable.
|
||||
- **Reverse states.** If you added a way in, add the way out and the way to see it. Snooze needs unsnooze. Close needs reopen. A one-way door is a bug.
|
||||
- **Connection modes.** Local, remote/relay, and tunnel behave differently. Multi-device and multi-environment cases are real.
|
||||
- **Docs.** `docs/` splits by audience. Behavior changes that a user would notice belong in `docs/user/` (shipped-product voice, no repo tooling or source paths); architecture and contributor changes in `docs/internals/`; runbooks in `docs/operations/`; new vocabulary in `docs/internals/glossary.md`.
|
||||
@@ -79,8 +84,8 @@ The most common defect in this repo is a change that works on the path you teste
|
||||
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
|
||||
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
|
||||
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
|
||||
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
|
||||
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
|
||||
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
|
||||
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
|
||||
- Stop what you started, by the PID you tracked. See rule 1.
|
||||
|
||||
## Test data
|
||||
@@ -107,7 +112,7 @@ An empty database is a bad test. Seed your worktree's `.t3` with a copy of real
|
||||
- **Do not run repo-wide checks.** No `vp check`, no `vp run -r test`, no `vp run -r typecheck` unless I ask. CI owns the full suite.
|
||||
- Backend behavior changes ship with focused tests for that behavior.
|
||||
- The server is event-sourced and its async flows emit typed receipts. Wait on receipts and worker drains, never on sleeps or polling. A test that needs a timeout to pass is wrong.
|
||||
- Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web, `test-t3-mobile` for mobile. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
|
||||
- Upon request, user-visible frontend changes should get one integrated pass in a real client: `test-t3-app` for web and `test-t3-mobile` for either mobile client. Select the React Native or SwiftUI path before building. The primary agent does this once after integrating. Subagents do not launch their own dev servers. Ask permission before doing computer use or spinning up browsers.
|
||||
|
||||
## Pull requests
|
||||
|
||||
@@ -128,10 +133,13 @@ Full glossary with file links: `docs/internals/glossary.md`
|
||||
## Where code lives
|
||||
|
||||
- `apps/server` - WebSocket, orchestration, providers, checkpointing. Effect-heavy: read `.repos/effect-smol/LLMS.md` before writing Effect code.
|
||||
- `apps/web` - React/Vite UI. `apps/desktop` wraps it, `apps/mobile` is React Native, `apps/marketing` is the site.
|
||||
- `apps/web` - React/Vite UI. `apps/desktop` wraps it and adds Electron behavior.
|
||||
- `apps/mobile` - React Native client for iOS and Android.
|
||||
- `apps/swift-ios` - Separate native SwiftUI client for iOS.
|
||||
- `apps/marketing` - Marketing site.
|
||||
- `packages/contracts` - Effect/Schema contracts plus small derived helpers. No heavy runtime logic.
|
||||
- `packages/shared` - shared runtime utils, subpath exports, no barrel.
|
||||
- `packages/client-runtime` - client code shared by web and mobile.
|
||||
- `packages/client-runtime` - TypeScript client code shared by web and React Native mobile. SwiftUI implements the corresponding native client behavior separately.
|
||||
- `.repos/` - vendored read-only references. Prefer their patterns over invented ones. Never edit or import from them. Sync with `vpr sync:repos` when bumping the matching dependency.
|
||||
|
||||
## Taste
|
||||
|
||||
@@ -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,6 +1,6 @@
|
||||
{
|
||||
"name": "@t3tools/desktop",
|
||||
"version": "0.0.31",
|
||||
"version": "0.0.32",
|
||||
"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"]),
|
||||
),
|
||||
|
||||
@@ -23,6 +23,21 @@ export class ElectronDialogPickFolderError extends Schema.TaggedErrorClass<Elect
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogPickFilesError extends Schema.TaggedErrorClass<ElectronDialogPickFilesError>()(
|
||||
"ElectronDialogPickFilesError",
|
||||
{
|
||||
ownerWindowId: Schema.NullOr(Schema.Number),
|
||||
defaultPath: Schema.NullOr(Schema.String),
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const owner = this.ownerWindowId === null ? "the application" : `window ${this.ownerWindowId}`;
|
||||
const defaultPath = this.defaultPath === null ? "no default path" : this.defaultPath;
|
||||
return `Failed to open the Electron file picker for ${owner} with ${defaultPath}.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class ElectronDialogConfirmError extends Schema.TaggedErrorClass<ElectronDialogConfirmError>()(
|
||||
"ElectronDialogConfirmError",
|
||||
{
|
||||
@@ -69,6 +84,7 @@ export class ElectronDialogShowErrorBoxError extends Schema.TaggedErrorClass<Ele
|
||||
|
||||
export const ElectronDialogError = Schema.Union([
|
||||
ElectronDialogPickFolderError,
|
||||
ElectronDialogPickFilesError,
|
||||
ElectronDialogConfirmError,
|
||||
ElectronDialogShowMessageBoxError,
|
||||
ElectronDialogShowErrorBoxError,
|
||||
@@ -81,6 +97,12 @@ export interface ElectronDialogPickFolderInput {
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
}
|
||||
|
||||
export interface ElectronDialogPickFilesInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly defaultPath: Option.Option<string>;
|
||||
readonly filters: readonly Electron.FileFilter[];
|
||||
}
|
||||
|
||||
export interface ElectronDialogConfirmInput {
|
||||
readonly owner: Option.Option<Electron.BrowserWindow>;
|
||||
readonly message: string;
|
||||
@@ -92,6 +114,9 @@ export class ElectronDialog extends Context.Service<
|
||||
readonly pickFolder: (
|
||||
input: ElectronDialogPickFolderInput,
|
||||
) => Effect.Effect<Option.Option<string>, ElectronDialogPickFolderError>;
|
||||
readonly pickFiles: (
|
||||
input: ElectronDialogPickFilesInput,
|
||||
) => Effect.Effect<readonly string[], ElectronDialogPickFilesError>;
|
||||
readonly confirm: (
|
||||
input: ElectronDialogConfirmInput,
|
||||
) => Effect.Effect<boolean, ElectronDialogConfirmError>;
|
||||
@@ -137,6 +162,32 @@ export const make = ElectronDialog.of({
|
||||
}
|
||||
return Option.fromNullishOr(result.filePaths[0]);
|
||||
}),
|
||||
pickFiles: Effect.fn("desktop.electron.dialog.pickFiles")(function* (input) {
|
||||
const ownerWindowId = Option.match(input.owner, {
|
||||
onNone: () => null,
|
||||
onSome: (owner) => owner.id,
|
||||
});
|
||||
const defaultPath = Option.getOrNull(input.defaultPath);
|
||||
const openDialogOptions: Electron.OpenDialogOptions = {
|
||||
properties: ["openFile", "multiSelections"],
|
||||
filters: [...input.filters],
|
||||
...(defaultPath === null ? {} : { defaultPath }),
|
||||
};
|
||||
const result = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Option.match(input.owner, {
|
||||
onNone: () => Electron.dialog.showOpenDialog(openDialogOptions),
|
||||
onSome: (owner) => Electron.dialog.showOpenDialog(owner, openDialogOptions),
|
||||
}),
|
||||
catch: (cause) =>
|
||||
new ElectronDialogPickFilesError({
|
||||
ownerWindowId,
|
||||
defaultPath,
|
||||
cause,
|
||||
}),
|
||||
});
|
||||
return result.canceled ? [] : result.filePaths;
|
||||
}),
|
||||
confirm: Effect.fn("desktop.electron.dialog.confirm")(function* (input) {
|
||||
const normalizedMessage = input.message.trim();
|
||||
if (normalizedMessage.length === 0) {
|
||||
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
getWindowFullscreenState,
|
||||
openExternal,
|
||||
pickFolder,
|
||||
pickThemeFiles,
|
||||
setTheme,
|
||||
showContextMenu,
|
||||
} from "./methods/window.ts";
|
||||
@@ -79,6 +80,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
|
||||
yield* ipc.handle(setWslOnly);
|
||||
|
||||
yield* ipc.handle(pickFolder);
|
||||
yield* ipc.handle(pickThemeFiles);
|
||||
yield* ipc.handle(confirm);
|
||||
yield* ipc.handle(setTheme);
|
||||
yield* ipc.handle(showContextMenu);
|
||||
|
||||
@@ -1,4 +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";
|
||||
|
||||
@@ -3,10 +3,15 @@ import {
|
||||
DesktopAppBrandingSchema,
|
||||
DesktopEnvironmentBootstrapSchema,
|
||||
DesktopThemeSchema,
|
||||
PickedThemeFileSchema,
|
||||
PickFolderOptionsSchema,
|
||||
PRIMARY_LOCAL_ENVIRONMENT_ID,
|
||||
type DesktopEnvironmentBootstrap,
|
||||
type PickedThemeFile,
|
||||
} from "@t3tools/contracts";
|
||||
import * as NodeOS from "node:os";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Schema from "effect/Schema";
|
||||
@@ -268,3 +273,49 @@ export const openExternal = DesktopIpc.makeIpcMethod({
|
||||
return yield* shell.openExternal(url);
|
||||
}),
|
||||
});
|
||||
|
||||
/** Theme files are a few KB; anything larger returns empty text and lets the
|
||||
* renderer reject it by size without the contents ever crossing the bridge. */
|
||||
const PICKED_THEME_FILE_MAX_BYTES = 256 * 1024;
|
||||
|
||||
export const pickThemeFiles = DesktopIpc.makeIpcMethod({
|
||||
channel: IpcChannels.PICK_THEME_FILES_CHANNEL,
|
||||
payload: Schema.Undefined,
|
||||
result: Schema.NullOr(Schema.Array(PickedThemeFileSchema)),
|
||||
handler: Effect.fn("desktop.ipc.window.pickThemeFiles")(function* () {
|
||||
const dialog = yield* ElectronDialog.ElectronDialog;
|
||||
const electronWindow = yield* ElectronWindow.ElectronWindow;
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
// The VS Code extensions directory is the same dotfolder on Windows,
|
||||
// macOS, and Linux; when it is missing the picker opens wherever the
|
||||
// platform would by default.
|
||||
const extensionsDir = path.join(NodeOS.homedir(), ".vscode", "extensions");
|
||||
const defaultPath = yield* fileSystem
|
||||
.exists(extensionsDir)
|
||||
.pipe(Effect.orElseSucceed(() => false));
|
||||
const paths = yield* dialog.pickFiles({
|
||||
owner: yield* electronWindow.focusedMainOrFirst,
|
||||
defaultPath: defaultPath ? Option.some(extensionsDir) : Option.none(),
|
||||
filters: [{ name: "JSON", extensions: ["json"] }],
|
||||
});
|
||||
if (paths.length === 0) {
|
||||
return null;
|
||||
}
|
||||
return yield* Effect.forEach(paths, (filePath) => {
|
||||
const name = path.basename(filePath);
|
||||
return Effect.gen(function* () {
|
||||
const info = yield* fileSystem.stat(filePath);
|
||||
const size = Number(info.size);
|
||||
if (size > PICKED_THEME_FILE_MAX_BYTES) {
|
||||
return { name, size, text: "" } satisfies PickedThemeFile;
|
||||
}
|
||||
const text = yield* fileSystem.readFileString(filePath);
|
||||
return { name, size, text } satisfies PickedThemeFile;
|
||||
}).pipe(
|
||||
// An unreadable file degrades to an entry the renderer reports.
|
||||
Effect.orElseSucceed((): PickedThemeFile => ({ name, size: 0, text: "" })),
|
||||
);
|
||||
});
|
||||
}),
|
||||
});
|
||||
@@ -97,6 +97,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
|
||||
setWslDistro: (distro) => ipcRenderer.invoke(IpcChannels.SET_WSL_DISTRO_CHANNEL, distro),
|
||||
setWslOnly: (enabled) => ipcRenderer.invoke(IpcChannels.SET_WSL_ONLY_CHANNEL, enabled),
|
||||
pickFolder: (options) => ipcRenderer.invoke(IpcChannels.PICK_FOLDER_CHANNEL, options),
|
||||
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) =>
|
||||
|
||||
@@ -13,7 +13,6 @@ import * as DesktopEnvironment from "../app/DesktopEnvironment.ts";
|
||||
import * as DesktopClientSettings from "./DesktopClientSettings.ts";
|
||||
|
||||
const clientSettings: ClientSettings = {
|
||||
autoOpenPlanSidebar: false,
|
||||
confirmThreadArchive: true,
|
||||
confirmThreadDelete: false,
|
||||
dismissedProviderUpdateNotificationKeys: [],
|
||||
@@ -30,6 +29,7 @@ const clientSettings: ClientSettings = {
|
||||
fontSizeTerminal: 12,
|
||||
fontSmoothing: true,
|
||||
glassOpacity: 80,
|
||||
planModeEnabled: false,
|
||||
providerModelPreferences: {},
|
||||
sidebarAutoSettleAfterDays: 3,
|
||||
sidebarProjectGroupingMode: "repository_path",
|
||||
@@ -39,8 +39,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`],
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
@@ -52,6 +52,7 @@ 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,
|
||||
@@ -80,6 +81,8 @@ const makeDesktopWindowLayer = (selectedAction: Deferred.Deferred<string>) =>
|
||||
handleBackendNotReady: Effect.void,
|
||||
flushMainWindowBounds: Effect.void,
|
||||
dispatchMenuAction: (action) => Deferred.succeed(selectedAction, action).pipe(Effect.asVoid),
|
||||
zoomMain: (direction) =>
|
||||
Deferred.succeed(selectedAction, `zoom-${direction}`).pipe(Effect.asVoid),
|
||||
syncAppearance: Effect.void,
|
||||
} satisfies DesktopWindow.DesktopWindow["Service"]);
|
||||
|
||||
@@ -93,6 +96,30 @@ const makeElectronMenuLayer = (
|
||||
showContextMenu: () => Effect.succeed(Option.none()),
|
||||
} satisfies ElectronMenu.ElectronMenu["Service"]);
|
||||
|
||||
const configureMenu = (
|
||||
selectedAction: Deferred.Deferred<string>,
|
||||
applicationMenuTemplate: Deferred.Deferred<readonly Electron.MenuItemConstructorOptions[]>,
|
||||
) =>
|
||||
Effect.gen(function* () {
|
||||
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
yield* menu.configure;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopApplicationMenu.layer.pipe(
|
||||
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
|
||||
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
|
||||
Layer.provideMerge(desktopUpdatesLayer),
|
||||
Layer.provideMerge(electronDialogLayer),
|
||||
Layer.provideMerge(electronAppLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopEnvironment.layer(environmentInput).pipe(
|
||||
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
describe("DesktopApplicationMenu", () => {
|
||||
it.effect("installs the native menu and routes Settings through DesktopWindow", () =>
|
||||
Effect.gen(function* () {
|
||||
@@ -100,25 +127,7 @@ describe("DesktopApplicationMenu", () => {
|
||||
const applicationMenuTemplate =
|
||||
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const menu = yield* DesktopApplicationMenu.DesktopApplicationMenu;
|
||||
yield* menu.configure;
|
||||
}).pipe(
|
||||
Effect.provide(
|
||||
DesktopApplicationMenu.layer.pipe(
|
||||
Layer.provideMerge(makeElectronMenuLayer(applicationMenuTemplate)),
|
||||
Layer.provideMerge(makeDesktopWindowLayer(selectedAction)),
|
||||
Layer.provideMerge(desktopUpdatesLayer),
|
||||
Layer.provideMerge(electronDialogLayer),
|
||||
Layer.provideMerge(electronAppLayer),
|
||||
Layer.provideMerge(
|
||||
DesktopEnvironment.layer(environmentInput).pipe(
|
||||
Layer.provide(Layer.mergeAll(NodeServices.layer, DesktopConfig.layerTest({}))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
yield* configureMenu(selectedAction, applicationMenuTemplate);
|
||||
|
||||
const template = yield* Deferred.await(applicationMenuTemplate);
|
||||
const fileMenu = template.find((item) => item.label === "File");
|
||||
@@ -137,4 +146,38 @@ describe("DesktopApplicationMenu", () => {
|
||||
assert.equal(yield* Deferred.await(selectedAction), "open-settings");
|
||||
}),
|
||||
);
|
||||
|
||||
// Zoom must route through DesktopWindow.zoomMain instead of the Electron
|
||||
// zoom roles: the roles zoom whichever webContents has focus, which breaks
|
||||
// app zoom while an embedded preview WebContentsView holds focus.
|
||||
it.effect("routes View menu zoom to the main window instead of zoom roles", () =>
|
||||
Effect.gen(function* () {
|
||||
const selectedAction = yield* Deferred.make<string>();
|
||||
const applicationMenuTemplate =
|
||||
yield* Deferred.make<readonly Electron.MenuItemConstructorOptions[]>();
|
||||
|
||||
yield* configureMenu(selectedAction, applicationMenuTemplate);
|
||||
|
||||
const template = yield* Deferred.await(applicationMenuTemplate);
|
||||
const viewMenu = template.find((item) => item.label === "View");
|
||||
assert.isDefined(viewMenu);
|
||||
if (!Array.isArray(viewMenu.submenu)) {
|
||||
throw new Error("Expected View menu submenu to be an array.");
|
||||
}
|
||||
|
||||
assert.isUndefined(
|
||||
viewMenu.submenu.find((item) => item.role?.toLowerCase().includes("zoom")),
|
||||
);
|
||||
|
||||
const zoomIn = viewMenu.submenu.find((item) => item.label === "Zoom In");
|
||||
assert.isDefined(zoomIn);
|
||||
assert.equal(zoomIn.accelerator, "CmdOrCtrl+=");
|
||||
if (typeof zoomIn.click !== "function") {
|
||||
throw new Error("Expected Zoom In menu item to have a click handler.");
|
||||
}
|
||||
|
||||
zoomIn.click({} as Electron.MenuItem, {} as Electron.BrowserWindow, {} as KeyboardEvent);
|
||||
assert.equal(yield* Deferred.await(selectedAction), "zoom-in");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -49,6 +49,13 @@ const dispatchMenuAction = Effect.fn("desktop.menu.dispatchMenuAction")(function
|
||||
yield* desktopWindow.dispatchMenuAction(action);
|
||||
});
|
||||
|
||||
const zoomMainWindow = Effect.fn("desktop.menu.zoomMainWindow")(function* (
|
||||
direction: DesktopWindow.MainWindowZoomDirection,
|
||||
): Effect.fn.Return<void, never, DesktopWindow.DesktopWindow> {
|
||||
const desktopWindow = yield* DesktopWindow.DesktopWindow;
|
||||
yield* desktopWindow.zoomMain(direction);
|
||||
});
|
||||
|
||||
const checkForUpdatesFromMenu = Effect.gen(function* () {
|
||||
const updates = yield* DesktopUpdates.DesktopUpdates;
|
||||
const electronDialog = yield* ElectronDialog.ElectronDialog;
|
||||
@@ -127,6 +134,9 @@ export const make = Effect.gen(function* () {
|
||||
const settingsClick = () => {
|
||||
runMenuEffect("open-settings", dispatchMenuAction("open-settings"));
|
||||
};
|
||||
const zoomClick = (direction: DesktopWindow.MainWindowZoomDirection) => () => {
|
||||
runMenuEffect(`zoom-${direction}`, zoomMainWindow(direction));
|
||||
};
|
||||
const template: Electron.MenuItemConstructorOptions[] = [];
|
||||
|
||||
if (environment.platform === "darwin") {
|
||||
@@ -181,10 +191,21 @@ export const make = Effect.gen(function* () {
|
||||
{ role: "forceReload" },
|
||||
{ role: "toggleDevTools" },
|
||||
{ type: "separator" },
|
||||
{ role: "resetZoom" },
|
||||
{ role: "zoomIn", accelerator: "CmdOrCtrl+=" },
|
||||
{ role: "zoomIn", accelerator: "CmdOrCtrl+Plus", visible: false },
|
||||
{ role: "zoomOut" },
|
||||
/*
|
||||
Not the zoom roles: those act on the focused webContents, so with
|
||||
an embedded preview WebContentsView focused they zoom the guest
|
||||
page and the app UI appears stuck. These always zoom the main
|
||||
window (see DesktopWindow.zoomMain).
|
||||
*/
|
||||
{ label: "Actual Size", accelerator: "CmdOrCtrl+0", click: zoomClick("reset") },
|
||||
{ label: "Zoom In", accelerator: "CmdOrCtrl+=", click: zoomClick("in") },
|
||||
{
|
||||
label: "Zoom In",
|
||||
accelerator: "CmdOrCtrl+Plus",
|
||||
visible: false,
|
||||
click: zoomClick("in"),
|
||||
},
|
||||
{ label: "Zoom Out", accelerator: "CmdOrCtrl+-", click: zoomClick("out") },
|
||||
{ type: "separator" },
|
||||
{ role: "togglefullscreen" },
|
||||
],
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -79,7 +79,7 @@ import { ANDROID_PLAY_STORE_URL, IOS_APP_STORE_URL } from "../lib/site";
|
||||
</div>
|
||||
|
||||
<p class="releases-link">
|
||||
Looking for older versions? Check the
|
||||
Looking for older versions? Check the{" "}
|
||||
<a href="https://github.com/pingdotgg/t3code/releases" target="_blank" rel="noopener noreferrer">
|
||||
GitHub releases page<span aria-hidden="true"> ↗</span>
|
||||
</a>
|
||||
|
||||
@@ -161,7 +161,7 @@ const config: ExpoConfig = {
|
||||
slug: "t3-code",
|
||||
platforms: ["ios", "android"],
|
||||
scheme: variant.scheme,
|
||||
version: "1.0.1",
|
||||
version: "1.0.2",
|
||||
runtimeVersion: {
|
||||
// Fingerprint (not appVersion) so an OTA only reaches binaries whose native
|
||||
// project — native deps, config plugins, AND patches/ — matches the update.
|
||||
|
||||
@@ -535,6 +535,12 @@ public final class T3TerminalView: ExpoView, UITextFieldDelegate {
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.isEmpty {
|
||||
feedData(Data("\u{1B}[3J\u{1B}[H\u{1B}[2J".utf8))
|
||||
lastAppliedBuffer = ""
|
||||
return
|
||||
}
|
||||
|
||||
if buffer.hasPrefix(lastAppliedBuffer) {
|
||||
let suffix = String(buffer.dropFirst(lastAppliedBuffer.count))
|
||||
feedData(Data(suffix.utf8))
|
||||
|
||||
@@ -138,5 +138,10 @@
|
||||
"@react-native-menu/menu"
|
||||
]
|
||||
}
|
||||
},
|
||||
"reanimated": {
|
||||
"staticFeatureFlags": {
|
||||
"DISABLE_COMMIT_PAUSING_MECHANISM": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,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 {
|
||||
@@ -190,6 +191,13 @@ const SettingsSheetStack = createNativeStackNavigator({
|
||||
title: "Client Storage",
|
||||
},
|
||||
}),
|
||||
SettingsUsage: createNativeStackScreen({
|
||||
screen: UsageRouteScreen,
|
||||
linking: "usage",
|
||||
options: {
|
||||
title: "Usage",
|
||||
},
|
||||
}),
|
||||
SettingsAuth: createNativeStackScreen({
|
||||
screen: SettingsAuthRouteScreen,
|
||||
linking: "auth",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -16,6 +16,18 @@ import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../native/native-glass";
|
||||
const IOS_NATIVE_LEADING_TITLE_OFFSET = -6;
|
||||
const IPAD_NATIVE_LEADING_TITLE_OFFSET = 7;
|
||||
|
||||
/**
|
||||
* Horizontal correction applied to content rendered in the brand title slot,
|
||||
* shared with the connection-status swap so both align identically.
|
||||
*/
|
||||
export function brandTitleOffset(nativeLeadingItem: boolean): number {
|
||||
if (Platform.OS !== "ios") return 0;
|
||||
if (nativeLeadingItem) {
|
||||
return Platform.isPad ? IPAD_NATIVE_LEADING_TITLE_OFFSET : IOS_NATIVE_LEADING_TITLE_OFFSET;
|
||||
}
|
||||
return Platform.isPad ? IPAD_HOME_TITLE_OFFSET : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact brand lockup sized for native navigation bars.
|
||||
*/
|
||||
@@ -28,16 +40,7 @@ export function CompactBrandTitle(
|
||||
const mutedColor = useThemeColor("--color-foreground-muted");
|
||||
const subtleColor = useThemeColor("--color-subtle");
|
||||
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
|
||||
const titleOffset =
|
||||
Platform.OS !== "ios"
|
||||
? 0
|
||||
: props.nativeLeadingItem
|
||||
? Platform.isPad
|
||||
? IPAD_NATIVE_LEADING_TITLE_OFFSET
|
||||
: IOS_NATIVE_LEADING_TITLE_OFFSET
|
||||
: Platform.isPad
|
||||
? IPAD_HOME_TITLE_OFFSET
|
||||
: 0;
|
||||
const titleOffset = brandTitleOffset(props.nativeLeadingItem === true);
|
||||
|
||||
return (
|
||||
<View
|
||||
|
||||
@@ -133,9 +133,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 =
|
||||
|
||||
@@ -17,7 +17,10 @@ import * as Schema from "effect/Schema";
|
||||
import * as MobileDatabase from "../persistence/mobile-database";
|
||||
|
||||
const SHELL_SNAPSHOT_CACHE_SCHEMA_VERSION = 1;
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 2;
|
||||
// v3 adds windowed (paginated) snapshots carrying `page` metadata; the bump
|
||||
// makes pre-pagination clients discard the record instead of decoding a
|
||||
// partial thread as complete (rollback safety).
|
||||
const THREAD_SNAPSHOT_CACHE_SCHEMA_VERSION = 3;
|
||||
const SERVER_CONFIG_CACHE_SCHEMA_VERSION = 1;
|
||||
const VCS_REFS_CACHE_SCHEMA_VERSION = 1;
|
||||
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -21,6 +21,7 @@ import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { ConnectedEnvironmentSummary } from "../../state/remote-runtime-types";
|
||||
import { availableCloudEnvironmentPresentation } from "../cloud/cloudEnvironmentPresentation";
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { ConnectionStatusDot } from "./ConnectionStatusDot";
|
||||
import { type RelayEnvironmentView, useConnectionController } from "./useConnectionController";
|
||||
|
||||
@@ -42,6 +43,11 @@ interface CloudEnvironmentRowsProps {
|
||||
* with connect switches, availability status, refresh, and loading/error
|
||||
* states. Shared between the Settings environments screen and the T3 Connect
|
||||
* onboarding sheet.
|
||||
*
|
||||
* Already-connected relay environments render even without cloud config or a
|
||||
* signed-in account — they are registered on this device and must stay
|
||||
* reachable and removable. Only discovery (the available list, refresh, and
|
||||
* its errors) requires a signed-in session.
|
||||
*/
|
||||
export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
// Showcase captures run without a Clerk publishable key, so `ClerkProvider`
|
||||
@@ -50,20 +56,33 @@ export function CloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
if (props.showcaseSignedIn !== undefined) {
|
||||
return props.showcaseSignedIn ? <CloudEnvironmentRowsContent {...props} /> : null;
|
||||
}
|
||||
// No cloud config means no `ClerkProvider` either, so `useAuth` would throw.
|
||||
if (!hasCloudPublicConfig()) {
|
||||
return <ConnectedOnlyCloudEnvironmentRows {...props} />;
|
||||
}
|
||||
return <SignedInCloudEnvironmentRows {...props} />;
|
||||
}
|
||||
|
||||
function SignedInCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
const { isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
if (!isSignedIn) return null;
|
||||
if (!isSignedIn) return <ConnectedOnlyCloudEnvironmentRows {...props} />;
|
||||
return <CloudEnvironmentRowsContent {...props} />;
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
function ConnectedOnlyCloudEnvironmentRows(props: CloudEnvironmentRowsProps) {
|
||||
if (props.connectedCloudEnvironments.length === 0) return null;
|
||||
return <CloudEnvironmentRowsContent {...props} discoveryAvailable={false} />;
|
||||
}
|
||||
|
||||
function CloudEnvironmentRowsContent(
|
||||
props: CloudEnvironmentRowsProps & { readonly discoveryAvailable?: boolean },
|
||||
) {
|
||||
const controller = useConnectionController();
|
||||
const iconColor = useThemeColor("--color-icon");
|
||||
const availableCloudEnvironments =
|
||||
props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments;
|
||||
const discoveryAvailable = props.discoveryAvailable ?? true;
|
||||
const availableCloudEnvironments = discoveryAvailable
|
||||
? (props.showcaseAvailableEnvironments ?? controller.availableRelayEnvironments)
|
||||
: [];
|
||||
const [expandedErrorId, setExpandedErrorId] = useState<string | null>(null);
|
||||
const hasCloudRows =
|
||||
props.connectedCloudEnvironments.length > 0 || availableCloudEnvironments.length > 0;
|
||||
@@ -89,25 +108,27 @@ function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
{showHeader ? (
|
||||
<View className="flex-row items-center justify-between px-1">
|
||||
<Text className="text-sm font-t3-bold uppercase text-foreground-muted">T3 Connect</Text>
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
onPress={() => {
|
||||
void controller.refreshRelayEnvironments();
|
||||
}}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{controller.relayDiscovery.isRefreshing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
{discoveryAvailable ? (
|
||||
<Pressable
|
||||
accessibilityRole="button"
|
||||
disabled={controller.relayDiscovery.isRefreshing}
|
||||
onPress={() => {
|
||||
void controller.refreshRelayEnvironments();
|
||||
}}
|
||||
className="h-9 w-9 items-center justify-center rounded-full bg-subtle active:opacity-70 disabled:opacity-50"
|
||||
>
|
||||
{controller.relayDiscovery.isRefreshing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="arrow.clockwise"
|
||||
size={14}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
@@ -152,7 +173,9 @@ function CloudEnvironmentRowsContent(props: CloudEnvironmentRowsProps) {
|
||||
|
||||
{/* Rendered alongside any connected rows — a failed discovery must not
|
||||
hide behind an otherwise-healthy list. */}
|
||||
{controller.relayDiscovery.error && !controller.relayDiscovery.isRefreshing ? (
|
||||
{discoveryAvailable &&
|
||||
controller.relayDiscovery.error &&
|
||||
!controller.relayDiscovery.isRefreshing ? (
|
||||
<View collapsable={false} className="gap-3 rounded-[24px] bg-card p-5">
|
||||
<Text className="text-base font-t3-bold text-foreground">
|
||||
Could not load T3 Connect environments
|
||||
|
||||
@@ -58,8 +58,8 @@ export function ConnectionsRouteScreen() {
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 16,
|
||||
}}
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
NATIVE_MAIL_SEARCH_TOOLBAR_SUPPORTED,
|
||||
} from "../layout/native-mail-search-toolbar";
|
||||
import type { HomeProjectSortOrder } from "./homeThreadList";
|
||||
import { WorkspaceConnectionTitle } from "./WorkspaceConnectionTitle";
|
||||
import {
|
||||
buildHomeListFilterMenu,
|
||||
type HomeListFilterMenuEnvironment,
|
||||
@@ -47,6 +48,7 @@ export function HomeHeader(props: {
|
||||
readonly onProjectChange: (projectKey: string | null) => void;
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
}) {
|
||||
@@ -207,18 +209,27 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
|
||||
>
|
||||
<View className="w-full max-w-[720px] self-center gap-3">
|
||||
<View className="flex-row items-center gap-2.5">
|
||||
<View className="flex-1 flex-row items-center gap-2">
|
||||
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
|
||||
<T3Wordmark color={iconColor} height={15} />
|
||||
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
|
||||
Code
|
||||
</RNText>
|
||||
<View className="rounded-full bg-subtle px-2 py-0.75">
|
||||
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
|
||||
{stageLabel}
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
{/* Brand slot doubles as the connection status surface: while an
|
||||
environment reconnects, the lockup fades to a status label in
|
||||
place (no layout shift in the list below). */}
|
||||
<WorkspaceConnectionTitle
|
||||
grow
|
||||
onPress={props.onOpenEnvironments}
|
||||
brand={
|
||||
<View className="flex-row items-center gap-2">
|
||||
{/* Mirrors the desktop SidebarBrand: T3 mark + muted "Code". */}
|
||||
<T3Wordmark color={iconColor} height={15} />
|
||||
<RNText className="-ml-0.5 text-[21px] font-t3-medium tracking-[-0.5px] text-foreground-muted">
|
||||
Code
|
||||
</RNText>
|
||||
<View className="rounded-full bg-subtle px-2 py-0.75">
|
||||
<RNText className="text-[11px] font-t3-bold tracking-[1.1px] text-foreground-muted uppercase">
|
||||
{stageLabel}
|
||||
</RNText>
|
||||
</View>
|
||||
</View>
|
||||
}
|
||||
/>
|
||||
|
||||
<ControlPillMenu
|
||||
actions={menuActions}
|
||||
|
||||
@@ -3,7 +3,6 @@ import * as Order from "effect/Order";
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
|
||||
import { getCompactBrandHeaderOptions } from "../../components/CompactBrandTitle";
|
||||
import { NativeHeaderToolbar, NativeStackScreenOptions } from "../../native/StackHeader";
|
||||
import { useProjects, useThreadShells } from "../../state/entities";
|
||||
import { usePendingNewTasks } from "../../state/use-pending-new-tasks";
|
||||
@@ -20,6 +19,7 @@ import { useHomeListOptions } from "./home-list-options";
|
||||
import { buildHomeProjectScopes } from "./homeThreadList";
|
||||
import { usePendingTaskListActions } from "./usePendingTaskListActions";
|
||||
import { useThreadListActions } from "./useThreadListActions";
|
||||
import { getConnectionAwareBrandHeaderOptions } from "./WorkspaceConnectionTitle";
|
||||
|
||||
/* ─── Route screen ───────────────────────────────────────────────────── */
|
||||
|
||||
@@ -44,6 +44,7 @@ export function HomeRouteScreen() {
|
||||
unsnoozeThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
unsettleThread,
|
||||
} = useThreadListActions();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -126,8 +127,16 @@ export function HomeRouteScreen() {
|
||||
onStartNewTask={() => navigation.navigate("NewTaskSheet", { screen: "NewTask" })}
|
||||
>
|
||||
<>
|
||||
{/* Restore the compact title after the split branch blanks the detail header. */}
|
||||
<NativeStackScreenOptions options={getCompactBrandHeaderOptions()} />
|
||||
{/* Restore the compact title after the split branch blanks the detail
|
||||
header. The brand slot doubles as the connection status surface:
|
||||
while an environment reconnects, the lockup fades to a status label
|
||||
in place (no layout shift in the list below). */}
|
||||
<NativeStackScreenOptions
|
||||
options={getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: () =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" }),
|
||||
})}
|
||||
/>
|
||||
<HomeHeader
|
||||
environments={environments}
|
||||
projects={projectFilterOptions}
|
||||
@@ -138,6 +147,9 @@ export function HomeRouteScreen() {
|
||||
threadSortOrder={listOptions.threadSortOrder}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
@@ -159,11 +171,9 @@ export function HomeRouteScreen() {
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onEnvironmentChange={setSelectedEnvironmentId}
|
||||
onProjectChange={setSelectedProjectKey}
|
||||
onOpenEnvironments={() =>
|
||||
navigation.navigate("SettingsSheet", { screen: "SettingsEnvironments" })
|
||||
}
|
||||
onOpenSettings={() => navigation.navigate("SettingsSheet", { screen: "Settings" })}
|
||||
onProjectSortOrderChange={setProjectSortOrder}
|
||||
onSearchQueryChange={setSearchQuery}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
threadSearchMatchKey,
|
||||
type EnvironmentThreadSearchMatch,
|
||||
} from "@t3tools/client-runtime/state/thread-search";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type {
|
||||
EnvironmentId,
|
||||
SidebarProjectGroupingMode,
|
||||
@@ -71,8 +72,6 @@ import {
|
||||
type HomeProjectSortOrder,
|
||||
} from "./homeThreadList";
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "./thread-swipe-actions";
|
||||
import { WorkspaceConnectionStatus } from "./WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "./workspace-connection-status";
|
||||
|
||||
/* ─── Types ──────────────────────────────────────────────────────────── */
|
||||
|
||||
@@ -97,7 +96,6 @@ interface HomeScreenProps {
|
||||
readonly onProjectSortOrderChange: (sortOrder: HomeProjectSortOrder) => void;
|
||||
readonly onThreadSortOrderChange: (sortOrder: SidebarThreadSortOrder) => void;
|
||||
readonly onAddConnection: () => void;
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly onOpenSettings: () => void;
|
||||
readonly onStartNewTask: () => void;
|
||||
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
|
||||
@@ -113,6 +111,10 @@ interface HomeScreenProps {
|
||||
readonly onUnsettleThread: (thread: EnvironmentThreadShell) => void;
|
||||
readonly onPinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onUnpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly onMovePinnedThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
|
||||
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
|
||||
@@ -524,6 +526,12 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
},
|
||||
[props.onPinThread],
|
||||
);
|
||||
const handleMovePinnedThread = useCallback(
|
||||
(thread: EnvironmentThreadShell, direction: "up" | "down") => {
|
||||
void props.onMovePinnedThread(thread, direction);
|
||||
},
|
||||
[props.onMovePinnedThread],
|
||||
);
|
||||
const handleUnpinThread = useCallback(
|
||||
(thread: EnvironmentThreadShell) => {
|
||||
void props.onUnpinThread(thread);
|
||||
@@ -598,6 +606,29 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinReorderEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinReorder === 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.
|
||||
const arrangedPinnedKeys = useMemo(() => {
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
props.threads.filter(
|
||||
(thread) =>
|
||||
thread.pinnedAt != null &&
|
||||
thread.archivedAt === null &&
|
||||
pinReorderEnvironmentIds.has(thread.environmentId),
|
||||
),
|
||||
);
|
||||
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
|
||||
}, [pinReorderEnvironmentIds, props.threads]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -784,11 +815,18 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onSettleThread={handleSettleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
|
||||
canMovePinnedUp={arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0}
|
||||
canMovePinnedDown={(() => {
|
||||
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
|
||||
return index !== -1 && index < arrangedPinnedKeys.length - 1;
|
||||
})()}
|
||||
onSnoozeThread={handleSnoozeThread}
|
||||
onUnsnoozeThread={handleUnsnoozeThread}
|
||||
onUnsettleThread={handleUnsettleThread}
|
||||
onPinThread={handlePinThread}
|
||||
onUnpinThread={handleUnpinThread}
|
||||
onMovePinnedThread={handleMovePinnedThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={
|
||||
projectCwdByKey.get(scopedProjectKey(thread.environmentId, thread.projectId)) ?? null
|
||||
@@ -801,6 +839,8 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
[
|
||||
handleChangeRequestState,
|
||||
handleDeleteThread,
|
||||
arrangedPinnedKeys,
|
||||
handleMovePinnedThread,
|
||||
handlePinThread,
|
||||
handleSettleThread,
|
||||
handleSnoozeThread,
|
||||
@@ -810,6 +850,7 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
handleSwipeableWillOpen,
|
||||
handleUnsettleThread,
|
||||
pinningEnvironmentIds,
|
||||
pinReorderEnvironmentIds,
|
||||
projectByKey,
|
||||
projectCwdByKey,
|
||||
props.onArchiveThread,
|
||||
@@ -976,20 +1017,13 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
? null
|
||||
: (props.savedConnectionsById[props.selectedEnvironmentId]?.environmentLabel ??
|
||||
"this environment");
|
||||
const shouldShowConnectionStatus = shouldShowWorkspaceConnectionStatus(props.catalogState);
|
||||
// Connection state surfaces in the header title slot
|
||||
// (WorkspaceConnectionTitle) — nothing renders inside the list, so
|
||||
// reconnects never shift the rows.
|
||||
const emptyState = deriveEmptyState({
|
||||
catalogState: props.catalogState,
|
||||
projectCount: props.projects.length,
|
||||
});
|
||||
const connectionStatus =
|
||||
shouldShowConnectionStatus && Platform.OS !== "ios" ? (
|
||||
<View
|
||||
className="absolute left-0 right-0 items-center"
|
||||
style={{ bottom: Math.max(insets.bottom, 18) + 76 }}
|
||||
>
|
||||
<WorkspaceConnectionStatus state={props.catalogState} onPress={props.onOpenEnvironments} />
|
||||
</View>
|
||||
) : null;
|
||||
|
||||
if (!hasAnyThreads) {
|
||||
return (
|
||||
@@ -1008,41 +1042,17 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
onAction={!props.catalogState.hasReadyEnvironment ? props.onAddConnection : undefined}
|
||||
variant="plain"
|
||||
/>
|
||||
{emptyState.loading && !shouldShowConnectionStatus ? (
|
||||
{emptyState.loading ? (
|
||||
<View className="mt-4 items-center">
|
||||
<ActivityIndicator color={accentColor} />
|
||||
</View>
|
||||
) : null}
|
||||
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||
<View className="mt-4">
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
onPress={props.onOpenEnvironments}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const listHeader = (
|
||||
<>
|
||||
{Platform.OS === "ios" ? null : <HomeTopContentSpacer />}
|
||||
|
||||
{shouldShowConnectionStatus && Platform.OS === "ios" ? (
|
||||
<View className="pb-4">
|
||||
<WorkspaceConnectionStatus
|
||||
state={props.catalogState}
|
||||
onPress={props.onOpenEnvironments}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
const listHeader = Platform.OS === "ios" ? null : <HomeTopContentSpacer />;
|
||||
|
||||
// Project scoping lives in the header filter menu (no inline chip row on
|
||||
// mobile — the menu is the one filter surface).
|
||||
@@ -1123,7 +1133,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1178,7 +1187,6 @@ export function HomeScreen(props: HomeScreenProps) {
|
||||
}
|
||||
/>
|
||||
</SwipeableScrollGateProvider>
|
||||
{connectionStatus}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { ActivityIndicator, Pressable } from "react-native";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import { workspaceConnectionStatusLabel } from "./workspace-connection-status";
|
||||
|
||||
export function WorkspaceConnectionStatus(props: {
|
||||
readonly state: WorkspaceState;
|
||||
readonly onPress: () => void;
|
||||
readonly variant?: "floating" | "sidebar";
|
||||
}) {
|
||||
const iconColor = useThemeColor("--color-icon-muted");
|
||||
const isSynchronizing =
|
||||
props.state.networkStatus !== "offline" &&
|
||||
props.state.connectionError === null &&
|
||||
(props.state.connectingEnvironments.length > 0 || props.state.hasPendingShellSnapshot);
|
||||
const variant = props.variant ?? "floating";
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityHint="Opens environment settings"
|
||||
accessibilityLabel={workspaceConnectionStatusLabel(props.state)}
|
||||
accessibilityRole="button"
|
||||
onPress={props.onPress}
|
||||
className={
|
||||
variant === "sidebar"
|
||||
? "mx-3 flex-row items-center gap-2 rounded-xl bg-subtle px-3 py-2.5"
|
||||
: "flex-row items-center gap-2 rounded-full bg-card px-4 py-2.5"
|
||||
}
|
||||
style={
|
||||
variant === "floating"
|
||||
? {
|
||||
shadowColor: "#000",
|
||||
shadowOffset: { width: 0, height: 10 },
|
||||
shadowOpacity: 0.12,
|
||||
shadowRadius: 24,
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isSynchronizing ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView name="wifi.slash" size={15} tintColor={iconColor} type="monochrome" />
|
||||
)}
|
||||
<Text className="min-w-0 flex-1 text-sm font-t3-bold text-foreground" numberOfLines={1}>
|
||||
{workspaceConnectionStatusLabel(props.state)}
|
||||
</Text>
|
||||
{variant === "sidebar" ? (
|
||||
<SymbolView name="chevron.right" size={11} tintColor={iconColor} type="monochrome" />
|
||||
) : null}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import type {
|
||||
NativeStackHeaderItem,
|
||||
NativeStackNavigationOptions,
|
||||
} from "@react-navigation/native-stack";
|
||||
import { useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { ActivityIndicator, Animated, Platform, Pressable, View } from "react-native";
|
||||
|
||||
import { SymbolView } from "../../components/AppSymbol";
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { brandTitleOffset, CompactBrandTitle } from "../../components/CompactBrandTitle";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { NATIVE_LIQUID_GLASS_SUPPORTED } from "../../native/native-glass";
|
||||
import { useWorkspaceState } from "../../state/workspace";
|
||||
import {
|
||||
workspaceConnectionStatusPresentation,
|
||||
type WorkspaceConnectionStatusPresentation,
|
||||
} from "./workspace-connection-status";
|
||||
|
||||
/**
|
||||
* Delay before a connection interruption surfaces in the title slot. Sub-second
|
||||
* blips (the common reconnect case) resolve without any UI at all.
|
||||
*/
|
||||
const STATUS_SHOW_DELAY_MS = 800;
|
||||
const FADE_IN_MS = 250;
|
||||
|
||||
/**
|
||||
* Connection status presentation, debounced for display: null until the
|
||||
* workspace has been in a non-connected state for STATUS_SHOW_DELAY_MS,
|
||||
* then live-updating until the workspace reconnects (null again immediately).
|
||||
*/
|
||||
function useDelayedConnectionStatus(): WorkspaceConnectionStatusPresentation | null {
|
||||
const { state } = useWorkspaceState();
|
||||
const presentation = workspaceConnectionStatusPresentation(state);
|
||||
const hasStatus = presentation !== null;
|
||||
const [visible, setVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!hasStatus) {
|
||||
setVisible(false);
|
||||
return;
|
||||
}
|
||||
const timer = setTimeout(() => setVisible(true), STATUS_SHOW_DELAY_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [hasStatus]);
|
||||
|
||||
return visible ? presentation : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One-shot entrance fade for the status label. Deliberately JS-driven: this can
|
||||
* mount inside a native header item (RNSScreenStackHeaderSubview), where
|
||||
* native-driver animated nodes blank the re-hosted view entirely. The JS driver
|
||||
* updates opacity through the ordinary style path, which those subviews handle.
|
||||
*/
|
||||
function StatusFadeIn(props: { readonly children: ReactNode; readonly grow?: boolean }) {
|
||||
const opacity = useRef(new Animated.Value(0)).current;
|
||||
|
||||
useEffect(() => {
|
||||
const animation = Animated.timing(opacity, {
|
||||
duration: FADE_IN_MS,
|
||||
toValue: 1,
|
||||
useNativeDriver: false,
|
||||
});
|
||||
animation.start();
|
||||
return () => animation.stop();
|
||||
}, [opacity]);
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
style={[
|
||||
{ alignItems: "center", flexDirection: "row", opacity },
|
||||
props.grow ? { flex: 1, minWidth: 0 } : null,
|
||||
]}
|
||||
>
|
||||
{props.children}
|
||||
</Animated.View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the brand/title slot of a thread-list surface, swapping the brand
|
||||
* for the workspace connection status while an environment is unavailable.
|
||||
*
|
||||
* Both states occupy the same slot, so connection changes never shift the
|
||||
* layout below. While connected the brand renders untouched — no wrapper —
|
||||
* keeping the native header item on the exact element tree that predates the
|
||||
* status swap. Replaces the old WorkspaceConnectionStatus pill, which inserted
|
||||
* a row above the thread list.
|
||||
*/
|
||||
export function WorkspaceConnectionTitle(props: {
|
||||
/** Content shown while connected (brand lockup or a screen title). */
|
||||
readonly brand: ReactNode;
|
||||
/** Opens environment settings. Status is not pressable when omitted. */
|
||||
readonly onPress?: () => void;
|
||||
/** Fill the available row width (in-flow headers) instead of hugging content (native title slots). */
|
||||
readonly grow?: boolean;
|
||||
readonly size?: "navbar" | "pageTitle";
|
||||
/** Horizontal correction so the status aligns with the brand in native title slots. */
|
||||
readonly statusOffset?: number;
|
||||
}) {
|
||||
const iconColor = String(useThemeColor("--color-icon-muted"));
|
||||
const status = useDelayedConnectionStatus();
|
||||
const size = props.size ?? "navbar";
|
||||
|
||||
if (status === null) {
|
||||
return props.grow ? (
|
||||
<View style={{ alignItems: "center", flex: 1, flexDirection: "row", minWidth: 0 }}>
|
||||
{props.brand}
|
||||
</View>
|
||||
) : (
|
||||
<>{props.brand}</>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<StatusFadeIn grow={props.grow}>
|
||||
<Pressable
|
||||
accessibilityHint="Opens environment settings"
|
||||
accessibilityLabel={status.label}
|
||||
accessibilityRole="button"
|
||||
disabled={props.onPress === undefined}
|
||||
hitSlop={8}
|
||||
onPress={props.onPress}
|
||||
className="flex-row items-center gap-2"
|
||||
style={{ marginLeft: props.statusOffset ?? 0 }}
|
||||
>
|
||||
{status.showsProgress ? (
|
||||
<ActivityIndicator color={iconColor} size="small" />
|
||||
) : (
|
||||
<SymbolView
|
||||
name="wifi.slash"
|
||||
size={size === "pageTitle" ? 17 : 15}
|
||||
tintColor={iconColor}
|
||||
type="monochrome"
|
||||
/>
|
||||
)}
|
||||
<Text
|
||||
className={
|
||||
size === "pageTitle"
|
||||
? "text-[20px] font-t3-bold text-foreground-muted"
|
||||
: "text-[16px] font-t3-bold text-foreground-muted"
|
||||
}
|
||||
numberOfLines={1}
|
||||
style={{ flexShrink: 1 }}
|
||||
>
|
||||
{status.label}
|
||||
</Text>
|
||||
</Pressable>
|
||||
</StatusFadeIn>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* getCompactBrandHeaderOptions with the brand slot upgraded to the
|
||||
* connection-status swap. Screens with an environment-settings callback apply
|
||||
* this over the static brand options at mount.
|
||||
*/
|
||||
export function getConnectionAwareBrandHeaderOptions(opts: {
|
||||
readonly onOpenEnvironments: () => void;
|
||||
readonly fallbackTitleStyle?: NativeStackNavigationOptions["headerTitleStyle"];
|
||||
}): NativeStackNavigationOptions {
|
||||
if (Platform.OS === "ios" && NATIVE_LIQUID_GLASS_SUPPORTED) {
|
||||
return {
|
||||
headerTitle: "Threads",
|
||||
headerTitleStyle: { color: "transparent", fontSize: 18, fontWeight: "800" },
|
||||
title: "Threads",
|
||||
unstable_headerLeftItems: (): NativeStackHeaderItem[] => [
|
||||
{
|
||||
element: (
|
||||
<WorkspaceConnectionTitle
|
||||
brand={<CompactBrandTitle nativeLeadingItem />}
|
||||
onPress={opts.onOpenEnvironments}
|
||||
statusOffset={brandTitleOffset(true)}
|
||||
/>
|
||||
),
|
||||
hidesSharedBackground: true,
|
||||
type: "custom",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
headerTitle: () => (
|
||||
<WorkspaceConnectionTitle
|
||||
brand={<CompactBrandTitle />}
|
||||
onPress={opts.onOpenEnvironments}
|
||||
statusOffset={brandTitleOffset(false)}
|
||||
/>
|
||||
),
|
||||
headerTitleStyle: opts.fallbackTitleStyle,
|
||||
title: "Threads",
|
||||
};
|
||||
}
|
||||
@@ -8,9 +8,14 @@ import { Alert } from "react-native";
|
||||
import { showConfirmDialog } from "../../components/ConfirmDialogHost";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { refreshArchivedThreadsForEnvironment } from "../archive/useArchivedThreadSnapshots";
|
||||
import {
|
||||
pinOrderKeyBetween,
|
||||
planPinnedMove,
|
||||
sortPinnedThreadsByOrderKey,
|
||||
} from "@t3tools/client-runtime/state/thread-sort";
|
||||
import { appAtomRegistry } from "../../state/atom-registry";
|
||||
import { environmentServerConfigsAtom } from "../../state/server";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { environmentThreadShells, threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
|
||||
/** Version skew: never send settle/unsettle to a server that predates them
|
||||
@@ -36,6 +41,13 @@ function environmentSupportsPinning(environmentId: EnvironmentThreadShell["envir
|
||||
);
|
||||
}
|
||||
|
||||
function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["environmentId"]) {
|
||||
return (
|
||||
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
|
||||
.threadPinReorder === true
|
||||
);
|
||||
}
|
||||
|
||||
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
|
||||
|
||||
const ACTION_VERBS: Record<ThreadListAction, string> = {
|
||||
@@ -211,6 +223,10 @@ export function useThreadListActions(): {
|
||||
readonly unsettleThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly pinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly unpinThread: (thread: EnvironmentThreadShell) => Promise<boolean>;
|
||||
readonly movePinnedThread: (
|
||||
thread: EnvironmentThreadShell,
|
||||
direction: "up" | "down",
|
||||
) => Promise<boolean>;
|
||||
} {
|
||||
const executeAction = useThreadActionExecutor();
|
||||
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
|
||||
@@ -331,9 +347,21 @@ export function useThreadListActions(): {
|
||||
return false;
|
||||
}
|
||||
selectionHaptic();
|
||||
// Same placement as web: a fresh pin takes the top of the arranged
|
||||
// run. Servers that predate reordering get the bare pin (keyless).
|
||||
let orderKey: string | undefined;
|
||||
if (environmentSupportsPinReorder(thread.environmentId)) {
|
||||
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
|
||||
let firstKey: string | null = null;
|
||||
for (const shell of shells) {
|
||||
if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
|
||||
if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
|
||||
}
|
||||
orderKey = pinOrderKeyBetween(null, firstKey) ?? undefined;
|
||||
}
|
||||
const result = await pinMutation({
|
||||
environmentId: thread.environmentId,
|
||||
input: { threadId: thread.id },
|
||||
input: { threadId: thread.id, ...(orderKey !== undefined ? { orderKey } : {}) },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
@@ -378,6 +406,85 @@ export function useThreadListActions(): {
|
||||
[unpinMutation],
|
||||
);
|
||||
|
||||
// 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
|
||||
// while search or a project scope filters rows: the same fractional-key
|
||||
// scheme web dragging uses, one write to one thread per move (plus a
|
||||
// one-time section materialization when legacy keyless pins are involved).
|
||||
const reorderPinnedMutation = useAtomCommand(threadEnvironment.reorderPin, {
|
||||
reportFailure: false,
|
||||
});
|
||||
// One move at a time: a second tap before the first write's event lands
|
||||
// would plan from the same stale snapshot and silently collapse two moves
|
||||
// into one — same double-dispatch guard as snoozeThread.
|
||||
const movePinnedInFlightRef = useRef(false);
|
||||
const movePinnedThread = useCallback(
|
||||
async (thread: EnvironmentThreadShell, direction: "up" | "down") => {
|
||||
if (movePinnedInFlightRef.current) return false;
|
||||
if (!environmentSupportsPinReorder(thread.environmentId)) {
|
||||
Alert.alert(
|
||||
"Could not move thread",
|
||||
"This environment's server does not support pinned reordering yet. Update the server to reorder pins.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
const shells = appAtomRegistry.get(environmentThreadShells.threadShellsAtom);
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
shells.filter(
|
||||
(shell) =>
|
||||
shell.pinnedAt != null &&
|
||||
shell.archivedAt === null &&
|
||||
environmentSupportsPinReorder(shell.environmentId),
|
||||
),
|
||||
);
|
||||
const orderedIds = pinned.map((shell) => scopedThreadKey(shell.environmentId, shell.id));
|
||||
const assignments = planPinnedMove({
|
||||
orderedIds,
|
||||
keysById: new Map(
|
||||
pinned.map((shell) => [
|
||||
scopedThreadKey(shell.environmentId, shell.id),
|
||||
shell.pinOrderKey ?? null,
|
||||
]),
|
||||
),
|
||||
movedId: scopedThreadKey(thread.environmentId, thread.id),
|
||||
direction,
|
||||
});
|
||||
if (assignments === null || assignments.length === 0) return false;
|
||||
const shellByKey = new Map(
|
||||
pinned.map((shell) => [scopedThreadKey(shell.environmentId, shell.id), shell]),
|
||||
);
|
||||
selectionHaptic();
|
||||
movePinnedInFlightRef.current = true;
|
||||
try {
|
||||
for (const assignment of assignments) {
|
||||
const target = shellByKey.get(assignment.id);
|
||||
if (target === undefined) continue;
|
||||
const result = await reorderPinnedMutation({
|
||||
environmentId: target.environmentId,
|
||||
input: { threadId: target.id, orderKey: assignment.orderKey },
|
||||
});
|
||||
if (result._tag === "Failure") {
|
||||
const error = Cause.squash(result.cause);
|
||||
Alert.alert(
|
||||
"Could not move thread",
|
||||
error instanceof Error && error.message.trim().length > 0
|
||||
? error.message
|
||||
: "The pinned thread could not be moved.",
|
||||
);
|
||||
// No rollback: keys already written are valid orderings on their
|
||||
// own (each write is a complete, consistent placement), so a
|
||||
// partial materialization leaves the list sensible, not corrupt.
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} finally {
|
||||
movePinnedInFlightRef.current = false;
|
||||
}
|
||||
},
|
||||
[reorderPinnedMutation],
|
||||
);
|
||||
|
||||
const confirmDeleteThread = useConfirmDeleteThread(executeAction);
|
||||
|
||||
return {
|
||||
@@ -389,6 +496,7 @@ export function useThreadListActions(): {
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
+33
@@ -4,6 +4,7 @@ import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
import {
|
||||
shouldShowWorkspaceConnectionStatus,
|
||||
workspaceConnectionStatusLabel,
|
||||
workspaceConnectionStatusPresentation,
|
||||
} from "./workspace-connection-status";
|
||||
|
||||
function workspaceState(overrides: Partial<WorkspaceState> = {}): WorkspaceState {
|
||||
@@ -84,4 +85,36 @@ describe("workspace connection status", () => {
|
||||
expect(shouldShowWorkspaceConnectionStatus(state)).toBe(true);
|
||||
expect(workspaceConnectionStatusLabel(state)).toBe("Loading threads...");
|
||||
});
|
||||
|
||||
it("presents nothing while connected", () => {
|
||||
expect(workspaceConnectionStatusPresentation(workspaceState())).toBeNull();
|
||||
});
|
||||
|
||||
it("presents progress while reconnecting but not while offline", () => {
|
||||
const reconnecting = workspaceState({
|
||||
hasConnectingEnvironment: true,
|
||||
hasReadyEnvironment: false,
|
||||
connectingEnvironments: [
|
||||
{
|
||||
environmentId: "environment-1" as never,
|
||||
environmentLabel: "Julius’s Mac mini",
|
||||
displayUrl: "",
|
||||
isRelayManaged: false,
|
||||
connectionState: "reconnecting",
|
||||
connectionError: null,
|
||||
connectionErrorTraceId: null,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(workspaceConnectionStatusPresentation(reconnecting)).toEqual({
|
||||
label: "Reconnecting to Julius’s Mac mini",
|
||||
showsProgress: true,
|
||||
});
|
||||
|
||||
const offline = workspaceState({ networkStatus: "offline", hasReadyEnvironment: false });
|
||||
expect(workspaceConnectionStatusPresentation(offline)).toEqual({
|
||||
label: "You are offline",
|
||||
showsProgress: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,11 @@
|
||||
import type { WorkspaceState } from "../../state/workspaceModel";
|
||||
|
||||
export interface WorkspaceConnectionStatusPresentation {
|
||||
readonly label: string;
|
||||
/** True while actively working (connecting/syncing) — render a spinner. False for offline/error/idle states — render a wifi-slash icon. */
|
||||
readonly showsProgress: boolean;
|
||||
}
|
||||
|
||||
export function shouldShowWorkspaceConnectionStatus(state: WorkspaceState): boolean {
|
||||
return (
|
||||
state.networkStatus === "offline" ||
|
||||
@@ -24,3 +30,17 @@ export function workspaceConnectionStatusLabel(state: WorkspaceState): string {
|
||||
}
|
||||
return "Not connected";
|
||||
}
|
||||
|
||||
/** Header-title presentation of the connection state, or null while connected. */
|
||||
export function workspaceConnectionStatusPresentation(
|
||||
state: WorkspaceState,
|
||||
): WorkspaceConnectionStatusPresentation | null {
|
||||
if (!shouldShowWorkspaceConnectionStatus(state)) return null;
|
||||
return {
|
||||
label: workspaceConnectionStatusLabel(state),
|
||||
showsProgress:
|
||||
state.networkStatus !== "offline" &&
|
||||
state.connectionError === null &&
|
||||
(state.connectingEnvironments.length > 0 || state.hasPendingShellSnapshot),
|
||||
};
|
||||
}
|
||||
@@ -2,7 +2,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 { useEffect } from "react";
|
||||
import { useCallback, useEffect } from "react";
|
||||
import { View } from "react-native";
|
||||
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
@@ -21,16 +21,18 @@ export function SettingsAuthRouteScreen() {
|
||||
|
||||
function ConfiguredSettingsAuthRouteScreen() {
|
||||
const { isLoaded, isSignedIn } = useAuth({ treatPendingAsSignedOut: false });
|
||||
const navigation = useNavigation();
|
||||
const handleHostBack = useCallback(() => navigation.goBack(), [navigation]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<NativeStackScreenOptions options={{ title: isSignedIn ? "Account" : "Sign in" }} />
|
||||
<NativeStackScreenOptions options={{ headerShown: false }} />
|
||||
<View collapsable={false} className="flex-1 overflow-hidden bg-sheet">
|
||||
{isLoaded ? (
|
||||
isSignedIn ? (
|
||||
<UserProfileView isDismissible={false} />
|
||||
<UserProfileView isDismissible={false} onHostBack={handleHostBack} />
|
||||
) : (
|
||||
<AuthView isDismissible={false} />
|
||||
<AuthView isDismissible={false} onHostBack={handleHostBack} />
|
||||
)
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
@@ -8,7 +8,6 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
|
||||
import { AppText as Text } from "../../components/AppText";
|
||||
import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";
|
||||
import { hasCloudPublicConfig } from "../cloud/publicConfig";
|
||||
import { CloudEnvironmentRows } from "../connection/CloudEnvironmentRows";
|
||||
import { ConnectionEnvironmentRow } from "../connection/ConnectionEnvironmentRow";
|
||||
import { splitEnvironmentSections } from "../connection/environmentSections";
|
||||
@@ -161,18 +160,19 @@ export function SettingsEnvironmentsRouteScreen() {
|
||||
</View>
|
||||
)}
|
||||
|
||||
{hasCloudPublicConfig() || SHOWCASE_ENABLED ? (
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
{...(SHOWCASE_ENABLED
|
||||
? {
|
||||
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
showcaseSignedIn: true,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
) : null}
|
||||
{/* Always mounted: already-connected relay environments must stay
|
||||
visible (and removable) even when cloud config is missing or the
|
||||
user is signed out — the component gates discovery itself. */}
|
||||
<CloudEnvironmentRows
|
||||
connectedCloudEnvironments={connectedCloudEnvironments}
|
||||
onReconnectEnvironment={onReconnectEnvironment}
|
||||
{...(SHOWCASE_ENABLED
|
||||
? {
|
||||
showcaseAvailableEnvironments: SHOWCASE_AVAILABLE_CLOUD_ENVIRONMENTS,
|
||||
showcaseSignedIn: true,
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
</ScrollView>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -131,7 +131,7 @@ function LocalSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
<LegacySettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
@@ -519,7 +519,7 @@ function ConfiguredSettingsRouteScreen() {
|
||||
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
|
||||
</SettingsSection>
|
||||
|
||||
<BetaSettingsSection />
|
||||
<LegacySettingsSection />
|
||||
|
||||
<ArchivedThreadsSettingsSection />
|
||||
|
||||
@@ -533,31 +533,33 @@ function GeneralSettingsSection() {
|
||||
return (
|
||||
<SettingsSection title="General">
|
||||
<SettingsRow icon="folder" label="Project Grouping" target="SettingsProjectGrouping" />
|
||||
<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>
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ export type SettingsSheetTarget =
|
||||
| "SettingsArchive"
|
||||
| "SettingsAppearance"
|
||||
| "SettingsProjectGrouping"
|
||||
| "SettingsClientStorage";
|
||||
| "SettingsClientStorage"
|
||||
| "SettingsUsage";
|
||||
|
||||
export type SettingsLegalDocumentTarget = "SettingsLegal";
|
||||
@@ -25,15 +25,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 +40,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 +100,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 +522,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 +539,11 @@ export function NewTaskDraftScreen(props: {
|
||||
cancelAnimationFrame(focusFrame);
|
||||
}
|
||||
};
|
||||
}, [selectedProject]);
|
||||
}, [
|
||||
selectedProject,
|
||||
settingsSheetPresentation.isActiveRef,
|
||||
settingsSheetPresentation.restoreFocusAfterSave,
|
||||
]);
|
||||
|
||||
const environmentMenuActions = useMemo(
|
||||
() =>
|
||||
@@ -544,10 +557,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 +566,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 +636,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 +651,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 +658,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 +864,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 +920,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 +953,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={
|
||||
@@ -1120,6 +1057,7 @@ export function NewTaskDraftScreen(props: {
|
||||
) : null}
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -1153,6 +1091,7 @@ export function NewTaskDraftScreen(props: {
|
||||
</ComposerToolbarRow>
|
||||
</View>
|
||||
</KeyboardAvoidingView>
|
||||
{settingsSheet}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -235,10 +235,9 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
contentInsetAdjustmentBehavior="automatic"
|
||||
showsVerticalScrollIndicator={false}
|
||||
className="flex-1"
|
||||
contentInset={{ bottom: Math.max(insets.bottom, 18) + 18 }}
|
||||
contentContainerStyle={{
|
||||
gap: 12,
|
||||
paddingBottom: 8,
|
||||
paddingBottom: Math.max(insets.bottom, 18) + 18,
|
||||
paddingHorizontal: 20,
|
||||
paddingTop: 8,
|
||||
}}
|
||||
@@ -297,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}
|
||||
@@ -331,6 +331,7 @@ export function NewTaskRouteScreen({ route }: StaticScreenProps<NewTaskRoutePara
|
||||
>
|
||||
<ProjectFavicon
|
||||
environmentId={project.environmentId}
|
||||
faviconPath={project.faviconPath}
|
||||
size={18}
|
||||
projectTitle={project.title}
|
||||
workspaceRoot={project.workspaceRoot}
|
||||
|
||||
@@ -14,8 +14,10 @@ export interface PendingApprovalCardProps {
|
||||
}
|
||||
|
||||
export function PendingApprovalCard(props: PendingApprovalCardProps) {
|
||||
// Opaque for the same reason as PendingUserInputCard: nothing blurs the feed
|
||||
// behind this card, so a translucent surface bleeds messages through it.
|
||||
return (
|
||||
<View className="gap-2.5 rounded-[20px] border border-neutral-200 bg-neutral-100/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<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">
|
||||
Approval needed
|
||||
</Text>
|
||||
|
||||
@@ -24,8 +24,11 @@ export interface PendingUserInputCardProps {
|
||||
}
|
||||
|
||||
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/80 p-4 dark:border-white/6 dark:bg-neutral-900/80">
|
||||
<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>
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
Image,
|
||||
Platform,
|
||||
Pressable,
|
||||
StyleSheet,
|
||||
useColorScheme,
|
||||
View,
|
||||
type ViewStyle,
|
||||
@@ -50,10 +51,10 @@ import {
|
||||
ComposerToolbarScroller,
|
||||
ComposerToolbarTrigger,
|
||||
} from "../../components/ComposerToolbarTrigger";
|
||||
import { ControlPill, ControlPillMenu } from "../../components/ControlPill";
|
||||
import { ControlPill } 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 {
|
||||
@@ -61,14 +62,11 @@ import {
|
||||
normalizeSearchQuery,
|
||||
scoreQueryMatch,
|
||||
} from "@t3tools/shared/searchRanking";
|
||||
import {
|
||||
applyProviderOptionMenuEvent,
|
||||
buildProviderOptionMenuActions,
|
||||
providerOptionsConfigurationLabel,
|
||||
resolveProviderOptionDescriptors,
|
||||
} from "../../lib/providerOptions";
|
||||
import { resolveProviderOptionDescriptors } from "../../lib/providerOptions";
|
||||
import { useComposerPathSearch } from "../../state/use-composer-path-search";
|
||||
import { ComposerCommandPopover, type ComposerCommandItem } from "./ComposerCommandPopover";
|
||||
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).
|
||||
@@ -272,15 +270,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;
|
||||
@@ -298,13 +309,11 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
|
||||
const handleFocus = useCallback(() => {
|
||||
setIsFocused(true);
|
||||
onExpandedChange?.(true);
|
||||
}, [onExpandedChange]);
|
||||
}, []);
|
||||
|
||||
const handleBlur = useCallback(() => {
|
||||
setIsFocused(false);
|
||||
onExpandedChange?.(false);
|
||||
}, [onExpandedChange]);
|
||||
}, []);
|
||||
const showStopAction =
|
||||
props.selectedThread.session?.status === "running" ||
|
||||
props.selectedThread.session?.status === "starting";
|
||||
@@ -587,6 +596,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) =>
|
||||
@@ -601,95 +616,12 @@ 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],
|
||||
);
|
||||
|
||||
// ── 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,
|
||||
};
|
||||
}),
|
||||
},
|
||||
],
|
||||
[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);
|
||||
}
|
||||
}
|
||||
const settingsSummaryLabel = threadSettingsSummaryLabel({
|
||||
modelLabel: currentModelOption?.label ?? currentModelSelection.model,
|
||||
optionDescriptors: providerOptionDescriptors,
|
||||
runtimeMode: currentRuntimeMode,
|
||||
interactionMode: currentInteractionMode,
|
||||
});
|
||||
|
||||
return (
|
||||
<Animated.View
|
||||
@@ -698,11 +630,22 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
style={{
|
||||
paddingTop: isExpanded ? 8 : 6,
|
||||
paddingBottom: (props.bottomInset ?? 0) + (isExpanded ? 8 : 6),
|
||||
experimental_backgroundImage: isDarkMode
|
||||
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
|
||||
}}
|
||||
>
|
||||
{/* The backdrop gradient lives on a plain View: Reanimated's Animated.View
|
||||
silently drops experimental_backgroundImage on Android, which left this
|
||||
strip fully transparent and the feed text legible through the composer. */}
|
||||
<View
|
||||
pointerEvents="none"
|
||||
style={[
|
||||
StyleSheet.absoluteFill,
|
||||
{
|
||||
experimental_backgroundImage: isDarkMode
|
||||
? "linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,0.6) 55%, rgba(0,0,0,0.9) 100%)"
|
||||
: "linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.6) 55%, rgba(255,255,255,0.9) 100%)",
|
||||
},
|
||||
]}
|
||||
/>
|
||||
<Animated.View
|
||||
className="relative w-full self-center"
|
||||
layout={COMPOSER_LAYOUT_TRANSITION}
|
||||
@@ -849,28 +792,15 @@ export const ThreadComposer = memo(function ThreadComposer(props: ThreadComposer
|
||||
onPress={() => void props.onPickDraftImages()}
|
||||
showChevron={false}
|
||||
/>
|
||||
<ControlPillMenu
|
||||
actions={modelMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleModelMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Model"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={currentModelOption?.label ?? currentModelSelection.model}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ControlPillMenu
|
||||
actions={optionsMenuActions}
|
||||
onPressAction={({ nativeEvent }) => handleOptionsMenuAction(nativeEvent.event)}
|
||||
>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Configuration"
|
||||
icon="slider.horizontal.3"
|
||||
label={configurationLabel}
|
||||
/>
|
||||
</ControlPillMenu>
|
||||
<ComposerToolbarTrigger
|
||||
accessibilityLabel="Thread settings"
|
||||
iconNode={
|
||||
<ProviderIcon provider={currentModelOption?.providerDriver} size={16} />
|
||||
}
|
||||
label={settingsSummaryLabel}
|
||||
maxWidth={320}
|
||||
onPress={settingsSheetPresentation.open}
|
||||
/>
|
||||
{showStopAction ? (
|
||||
<ComposerToolbarButton
|
||||
accessibilityLabel="Stop"
|
||||
@@ -904,6 +834,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}
|
||||
|
||||
@@ -61,6 +61,8 @@ export interface ThreadDetailScreenProps {
|
||||
readonly connectionStateLabel: EnvironmentConnectionPhase;
|
||||
/** Message sync status for the selected thread (drives the composer status pill). */
|
||||
readonly threadSyncStatus?: EnvironmentThreadStatus;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
|
||||
readonly activeThreadBusy: boolean;
|
||||
readonly environmentId: EnvironmentId;
|
||||
readonly projectWorkspaceRoot: string | null;
|
||||
@@ -371,6 +373,7 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
usesAutomaticContentInsets={props.usesAutomaticContentInsets}
|
||||
onHeaderMaterialVisibilityChange={props.onHeaderMaterialVisibilityChange}
|
||||
skills={selectedProviderSkills}
|
||||
loadEarlier={props.loadEarlier ?? null}
|
||||
/>
|
||||
</View>
|
||||
) : (
|
||||
|
||||
@@ -45,14 +45,7 @@ import {
|
||||
import { TouchableOpacity } from "react-native-gesture-handler";
|
||||
import ImageViewing from "react-native-image-viewing";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import Animated, {
|
||||
FadeIn,
|
||||
FadeInUp,
|
||||
useSharedValue,
|
||||
withTiming,
|
||||
type LayoutAnimationsValues,
|
||||
type SharedValue,
|
||||
} from "react-native-reanimated";
|
||||
import Animated, { FadeIn, FadeInUp, type SharedValue } from "react-native-reanimated";
|
||||
import { useThemeColor } from "../../lib/useThemeColor";
|
||||
import { useFontFamily } from "../../lib/useFontFamily";
|
||||
import { copyTextWithHaptic } from "../../lib/copyTextWithHaptic";
|
||||
@@ -117,14 +110,6 @@ function formatMessageTime(input: string): string {
|
||||
return MESSAGE_TIME_FORMATTER.format(timestamp);
|
||||
}
|
||||
|
||||
// Rows shift when content above them grows (streaming text, work-log folds);
|
||||
// animating the container position turns those jumps into slides. Applied
|
||||
// conditionally — see the gated transition in ThreadFeed: while browsing
|
||||
// history the animation must NOT run, or every estimate→actual size
|
||||
// correction plays as a visible slide against the instant scroll-offset
|
||||
// compensation from maintainVisibleContentPosition.
|
||||
const FEED_ITEM_LAYOUT_DURATION_MS = 180;
|
||||
|
||||
// Pre-measurement heights for getFixedItemSize, mirroring renderFeedEntry's
|
||||
// classNames. The fold row's min-h-11 (44px) stays taller than its single
|
||||
// text-sm line at every supported base font size (26px at the 22pt maximum),
|
||||
@@ -164,6 +149,11 @@ export interface ThreadFeedProps {
|
||||
readonly usesAutomaticContentInsets?: boolean;
|
||||
readonly onHeaderMaterialVisibilityChange?: (visible: boolean) => void;
|
||||
readonly skills?: ReadonlyArray<SelectableMarkdownSkill>;
|
||||
/** Non-null when older turns exist beyond the loaded window. */
|
||||
readonly loadEarlier?: {
|
||||
readonly loading: boolean;
|
||||
readonly onLoadEarlier: () => void;
|
||||
} | null;
|
||||
}
|
||||
|
||||
function MessageAttachmentImage(props: {
|
||||
@@ -1330,6 +1320,24 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
);
|
||||
const [viewportHeight, setViewportHeight] = useState(0);
|
||||
const [disclosureToggleSettling, setDisclosureToggleSettling] = useState(false);
|
||||
// Live-follow latch. LegendList's maintainScrollAtEnd alone re-pins the feed
|
||||
// whenever the viewport drifts back inside its geometric threshold, which
|
||||
// yanked users off history they were reading every time a stream chunk grew
|
||||
// a row. Follow breaks when the user scrolls up and away, and re-arms only
|
||||
// when the list actually returns to the end (or on send / thread switch).
|
||||
const [endFollowEnabled, setEndFollowEnabled] = useState(true);
|
||||
const endFollowEnabledRef = useRef(true);
|
||||
// A "user scroll session" spans from drag start through the end of its
|
||||
// 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 [interactionState, setInteractionState] = useState<{
|
||||
readonly copiedRowId: string | null;
|
||||
readonly expandedWorkGroups: Record<string, boolean>;
|
||||
@@ -1434,11 +1442,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
},
|
||||
[props.onHeaderMaterialVisibilityChange],
|
||||
);
|
||||
// True while the viewport sits within ~one screen of the list end — the
|
||||
// only region where layout shifts should animate. Starts true because the
|
||||
// list opens pinned to the end.
|
||||
const nearListEnd = useSharedValue(true);
|
||||
|
||||
const handleScroll = useCallback(
|
||||
(event: NativeSyntheticEvent<NativeScrollEvent>) => {
|
||||
// anchorTopInset, not topContentInset: under automatic insets the list
|
||||
@@ -1446,40 +1449,41 @@ 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);
|
||||
const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
|
||||
nearListEnd.value =
|
||||
contentSize.height - layoutMeasurement.height - contentOffset.y < layoutMeasurement.height;
|
||||
// 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.
|
||||
const listState = props.listRef.current?.getState();
|
||||
if (listState) {
|
||||
if (listState.isWithinMaintainScrollAtEndThreshold) {
|
||||
setEndFollow(true);
|
||||
} else if (userScrollSessionRef.current) {
|
||||
setEndFollow(false);
|
||||
}
|
||||
}
|
||||
},
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, nearListEnd],
|
||||
[reportHeaderMaterialVisibility, anchorTopInset, props.listRef, setEndFollow],
|
||||
);
|
||||
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 handleMomentumScrollEnd = useCallback(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
}, []);
|
||||
|
||||
// Gated variant of the 180ms feed layout slide. Instant while browsing
|
||||
// history: maintainVisibleContentPosition compensates the scroll offset in
|
||||
// the same frame a row's measured size lands, so an instant reposition is
|
||||
// invisible — animating it is exactly what made cold upward scrolls slide
|
||||
// and jump. Near the end the slide stays on: streaming growth and sends
|
||||
// shift rows at rest, where the animation is the thing preventing a hard
|
||||
// visual snap.
|
||||
const feedItemLayoutTransition = useMemo(() => {
|
||||
return (values: LayoutAnimationsValues) => {
|
||||
"worklet";
|
||||
const duration = nearListEnd.value ? FEED_ITEM_LAYOUT_DURATION_MS : 0;
|
||||
return {
|
||||
initialValues: {
|
||||
originX: values.currentOriginX,
|
||||
originY: values.currentOriginY,
|
||||
width: values.currentWidth,
|
||||
height: values.currentHeight,
|
||||
},
|
||||
animations: {
|
||||
originX: withTiming(values.targetOriginX, { duration }),
|
||||
originY: withTiming(values.targetOriginY, { duration }),
|
||||
width: withTiming(values.targetWidth, { duration }),
|
||||
height: withTiming(values.targetHeight, { duration }),
|
||||
},
|
||||
};
|
||||
};
|
||||
}, [nearListEnd]);
|
||||
const handleViewportLayout = useCallback((event: LayoutChangeEvent) => {
|
||||
const nextWidth = Math.round(event.nativeEvent.layout.width);
|
||||
const nextHeight = Math.round(event.nativeEvent.layout.height);
|
||||
@@ -1491,6 +1495,20 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
reportHeaderMaterialVisibility(false);
|
||||
}, [props.threadId, 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(() => {
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}, [props.threadId, setEndFollow]);
|
||||
useEffect(() => {
|
||||
if (props.anchorMessageId !== null) {
|
||||
userScrollSessionRef.current = false;
|
||||
setEndFollow(true);
|
||||
}
|
||||
}, [props.anchorMessageId, setEndFollow]);
|
||||
|
||||
const expandedWorkGroupIds = useMemo(() => {
|
||||
const ids = new Set<string>();
|
||||
for (const [groupId, expanded] of Object.entries(expandedWorkGroups)) {
|
||||
@@ -1817,7 +1835,6 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
}
|
||||
: { scrollIndicatorInsets: { top: topContentInset, bottom: 0 } })}
|
||||
{...(anchoredEndSpace ? { anchoredEndSpace } : {})}
|
||||
itemLayoutAnimation={feedItemLayoutTransition}
|
||||
// Patched LegendList prop (patches/@[email protected]):
|
||||
// lets its scroll math clamp programmatic scrolls to -headerInset
|
||||
// instead of 0, so initialScrollAtEnd/maintainScrollAtEnd on short
|
||||
@@ -1842,7 +1859,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
// anchor scrolls also lets it correct a scroll that landed on a
|
||||
// stale end target once the anchor row finishes measuring.
|
||||
maintainScrollAtEnd={
|
||||
disclosureToggleSettling
|
||||
disclosureToggleSettling || !endFollowEnabled
|
||||
? false
|
||||
: {
|
||||
animated: true,
|
||||
@@ -1891,9 +1908,25 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
|
||||
alignItemsAtEnd
|
||||
initialScrollAtEnd
|
||||
onScroll={handleScroll}
|
||||
onScrollBeginDrag={handleScrollBeginDrag}
|
||||
onScrollEndDrag={handleScrollEndDrag}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
ListHeaderComponent={
|
||||
usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />
|
||||
<>
|
||||
{usesNativeAutomaticInsets ? null : <View style={{ height: topContentInset }} />}
|
||||
{props.loadEarlier != null ? (
|
||||
<Pressable
|
||||
onPress={props.loadEarlier.onLoadEarlier}
|
||||
disabled={props.loadEarlier.loading}
|
||||
className="items-center py-2"
|
||||
>
|
||||
<Text className="text-xs text-foreground-secondary">
|
||||
{props.loadEarlier.loading ? "Loading earlier turns…" : "Load earlier turns"}
|
||||
</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
contentContainerStyle={{
|
||||
paddingTop: 12,
|
||||
|
||||
@@ -11,6 +11,7 @@ import { LegendList } from "@legendapp/list/react-native";
|
||||
import type { MenuAction } from "@react-native-menu/menu";
|
||||
import { useAtomValue } from "@effect/atom-react";
|
||||
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";
|
||||
import type { LayoutChangeEvent, NativeScrollEvent, NativeSyntheticEvent } from "react-native";
|
||||
import { Platform, Pressable, StyleSheet, TextInput, View, useColorScheme } from "react-native";
|
||||
@@ -55,8 +56,10 @@ import { buildHomeProjectScopes, buildHomeThreadGroups } from "../home/homeThrea
|
||||
import { SwipeableScrollGateProvider, useSwipeableScrollGate } from "../home/thread-swipe-actions";
|
||||
import { usePendingTaskListActions } from "../home/usePendingTaskListActions";
|
||||
import { useThreadListActions } from "../home/useThreadListActions";
|
||||
import { WorkspaceConnectionStatus } from "../home/WorkspaceConnectionStatus";
|
||||
import { shouldShowWorkspaceConnectionStatus } from "../home/workspace-connection-status";
|
||||
import {
|
||||
getConnectionAwareBrandHeaderOptions,
|
||||
WorkspaceConnectionTitle,
|
||||
} from "../home/WorkspaceConnectionTitle";
|
||||
import { SidebarHeaderActions } from "./sidebar-header-actions";
|
||||
import { SidebarFilterButton } from "./sidebar-filter-button";
|
||||
import { createSidebarHeaderItems } from "./sidebar-native-header-items";
|
||||
@@ -207,6 +210,7 @@ function ThreadNavigationSidebarPane(
|
||||
unsettleThread,
|
||||
pinThread,
|
||||
unpinThread,
|
||||
movePinnedThread,
|
||||
} = useThreadListActions();
|
||||
const threadListV2Enabled = useThreadListV2Enabled();
|
||||
const pendingTasks = usePendingNewTasks();
|
||||
@@ -492,6 +496,28 @@ function ThreadNavigationSidebarPane(
|
||||
}
|
||||
return supported;
|
||||
}, [serverConfigs]);
|
||||
const pinReorderEnvironmentIds = useMemo(() => {
|
||||
const supported = new Set<EnvironmentId>();
|
||||
for (const [environmentId, config] of serverConfigs) {
|
||||
if (config.environment.capabilities.threadPinReorder === 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(() => {
|
||||
const pinned = sortPinnedThreadsByOrderKey(
|
||||
threads.filter(
|
||||
(thread) =>
|
||||
thread.pinnedAt != null &&
|
||||
thread.archivedAt === null &&
|
||||
pinReorderEnvironmentIds.has(thread.environmentId),
|
||||
),
|
||||
);
|
||||
return pinned.map((thread) => `${thread.environmentId}:${thread.id}`);
|
||||
}, [pinReorderEnvironmentIds, threads]);
|
||||
const threadListV2Layout = useMemo(() => {
|
||||
if (!threadListV2Enabled)
|
||||
return {
|
||||
@@ -600,7 +626,6 @@ function ThreadNavigationSidebarPane(
|
||||
threadListV2Enabled,
|
||||
threadListV2Layout,
|
||||
]);
|
||||
const showsConnectionStatus = shouldShowWorkspaceConnectionStatus(catalogState);
|
||||
const listMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
{
|
||||
@@ -929,11 +954,20 @@ function ThreadNavigationSidebarPane(
|
||||
onSettleThread={settleThread}
|
||||
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
|
||||
pinningSupported={pinningEnvironmentIds.has(thread.environmentId)}
|
||||
pinReorderSupported={pinReorderEnvironmentIds.has(thread.environmentId)}
|
||||
canMovePinnedUp={
|
||||
arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`) > 0
|
||||
}
|
||||
canMovePinnedDown={(() => {
|
||||
const index = arrangedPinnedKeys.indexOf(`${thread.environmentId}:${thread.id}`);
|
||||
return index !== -1 && index < arrangedPinnedKeys.length - 1;
|
||||
})()}
|
||||
onSnoozeThread={snoozeThread}
|
||||
onUnsnoozeThread={unsnoozeThread}
|
||||
onUnsettleThread={unsettleThread}
|
||||
onPinThread={pinThread}
|
||||
onUnpinThread={unpinThread}
|
||||
onMovePinnedThread={movePinnedThread}
|
||||
onChangeRequestState={handleChangeRequestState}
|
||||
projectCwd={projectCwdByKey.get(scopeKey) ?? null}
|
||||
onSwipeableClose={handleSwipeableClose}
|
||||
@@ -1054,13 +1088,16 @@ function ThreadNavigationSidebarPane(
|
||||
},
|
||||
[
|
||||
archiveThread,
|
||||
arrangedPinnedKeys,
|
||||
confirmDeletePendingTask,
|
||||
confirmDeleteThread,
|
||||
handleChangeRequestState,
|
||||
handleSelectThread,
|
||||
handleSwipeableClose,
|
||||
handleSwipeableWillOpen,
|
||||
movePinnedThread,
|
||||
openPendingTask,
|
||||
pinReorderEnvironmentIds,
|
||||
pinThread,
|
||||
pinningEnvironmentIds,
|
||||
projectByKey,
|
||||
@@ -1153,6 +1190,13 @@ function ThreadNavigationSidebarPane(
|
||||
<NativeStackScreenOptions
|
||||
optionsVersion={nativeHeaderItems}
|
||||
options={{
|
||||
// Re-applies the shell's static brand slot with the
|
||||
// connection-status swap so reconnects surface in the header
|
||||
// instead of shifting the list.
|
||||
...getConnectionAwareBrandHeaderOptions({
|
||||
onOpenEnvironments: props.onOpenEnvironmentSettings,
|
||||
fallbackTitleStyle: { fontSize: 18, fontWeight: "800" },
|
||||
}),
|
||||
headerSearchBarOptions: {
|
||||
ref: searchBarRef,
|
||||
autoCapitalize: "none",
|
||||
@@ -1203,17 +1247,6 @@ function ThreadNavigationSidebarPane(
|
||||
scrollEventThrottle={16}
|
||||
showsVerticalScrollIndicator={false}
|
||||
style={styles.threadList}
|
||||
ListHeaderComponent={
|
||||
showsConnectionStatus ? (
|
||||
<View className="px-1.5 pt-0.5 pb-2">
|
||||
<WorkspaceConnectionStatus
|
||||
onPress={props.onOpenEnvironmentSettings}
|
||||
state={catalogState}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null
|
||||
}
|
||||
ListEmptyComponent={listEmpty}
|
||||
/>
|
||||
</GestureDetector>
|
||||
@@ -1304,9 +1337,19 @@ function ThreadNavigationSidebarPane(
|
||||
</Svg>
|
||||
</View>
|
||||
<View className="h-[50px] flex-row items-end gap-0.5 pr-2 pl-5">
|
||||
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
|
||||
Threads
|
||||
</Text>
|
||||
{/* Title slot doubles as the connection status surface: while an
|
||||
environment reconnects, "Threads" fades to a status label in
|
||||
place (no layout shift in the list below). */}
|
||||
<WorkspaceConnectionTitle
|
||||
grow
|
||||
onPress={props.onOpenEnvironmentSettings}
|
||||
size="pageTitle"
|
||||
brand={
|
||||
<Text className="flex-1 text-[34px] font-t3-bold text-foreground" numberOfLines={1}>
|
||||
Threads
|
||||
</Text>
|
||||
}
|
||||
/>
|
||||
<SidebarHeaderButtonGroup colorScheme={colorScheme}>
|
||||
<ControlPillMenu actions={listMenuActions} onPressAction={handleListMenuAction}>
|
||||
<SidebarFilterButton
|
||||
@@ -1335,16 +1378,6 @@ function ThreadNavigationSidebarPane(
|
||||
value={props.searchQuery}
|
||||
/>
|
||||
</View>
|
||||
|
||||
{showsConnectionStatus ? (
|
||||
<View className="px-3.5 pt-2.5">
|
||||
<WorkspaceConnectionStatus
|
||||
onPress={props.onOpenEnvironmentSettings}
|
||||
state={catalogState}
|
||||
variant="sidebar"
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -8,6 +8,10 @@ import {
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
|
||||
import * as Option from "effect/Option";
|
||||
import { EnvironmentId, ThreadId, type ProjectScript } from "@t3tools/contracts";
|
||||
import {
|
||||
requestOlderThreadTurns,
|
||||
threadHasOlderTurns,
|
||||
} from "@t3tools/client-runtime/state/threads";
|
||||
import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";
|
||||
import { Platform, ScrollView, View } from "react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
@@ -190,6 +194,20 @@ function ThreadRouteContent(
|
||||
useThreadSelection();
|
||||
const selectedThreadDetailState = props.selectedThreadDetailState;
|
||||
const selectedThreadDetail = Option.getOrNull(selectedThreadDetailState.data);
|
||||
// "Load earlier turns" header state for windowed (paginated) thread loads.
|
||||
const loadEarlierTurns = useMemo(() => {
|
||||
if (selectedThread === null || !threadHasOlderTurns(selectedThreadDetailState)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
loading:
|
||||
selectedThreadDetailState.page._tag === "Some" &&
|
||||
selectedThreadDetailState.page.value.loadingOlder,
|
||||
onLoadEarlier: () => {
|
||||
requestOlderThreadTurns(selectedThread.environmentId, selectedThread.id);
|
||||
},
|
||||
};
|
||||
}, [selectedThread, selectedThreadDetailState]);
|
||||
const { selectedThreadCwd } = useSelectedThreadWorktree();
|
||||
const composer = useThreadComposerState();
|
||||
const gitState = useSelectedThreadGitState();
|
||||
@@ -766,6 +784,7 @@ function ThreadRouteContent(
|
||||
draftAttachments={composer.draftAttachments}
|
||||
connectionStateLabel={routeConnectionState}
|
||||
threadSyncStatus={selectedThreadDetailState.status}
|
||||
loadEarlier={loadEarlierTurns}
|
||||
activeThreadBusy={composer.activeThreadBusy}
|
||||
environmentId={selectedThread.environmentId}
|
||||
projectWorkspaceRoot={selectedThreadProject?.workspaceRoot ?? null}
|
||||
|
||||
@@ -0,0 +1,678 @@
|
||||
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 { 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"]);
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
const HIDDEN_EFFORT_OPTION_IDS: ReadonlySet<string> = new Set(["ultracode"]);
|
||||
|
||||
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" },
|
||||
];
|
||||
|
||||
/**
|
||||
* 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 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),
|
||||
);
|
||||
}
|
||||
|
||||
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) => {
|
||||
|
||||
@@ -134,6 +134,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}
|
||||
|
||||
@@ -230,6 +230,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}
|
||||
@@ -354,6 +355,14 @@ 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.pin.reorder. Gates the pinned
|
||||
Move up / Move down menu items. */
|
||||
readonly pinReorderSupported?: boolean;
|
||||
readonly onMovePinnedThread?: (thread: EnvironmentThreadShell, direction: "up" | "down") => void;
|
||||
/** Position flags for the pinned block so the menu disables the move that
|
||||
would fall off the end of the list. */
|
||||
readonly canMovePinnedUp?: boolean;
|
||||
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
|
||||
@@ -382,6 +391,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
onArchiveThread,
|
||||
onPinThread,
|
||||
onUnpinThread,
|
||||
onMovePinnedThread,
|
||||
onChangeRequestState,
|
||||
} = props;
|
||||
const snoozedRow = props.snoozed === true;
|
||||
@@ -416,6 +426,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const handleUnsettle = useCallback(() => onUnsettleThread(thread), [onUnsettleThread, thread]);
|
||||
const handlePin = useCallback(() => onPinThread(thread), [onPinThread, thread]);
|
||||
const handleUnpin = useCallback(() => onUnpinThread(thread), [onUnpinThread, thread]);
|
||||
const handleMovePinnedUp = useCallback(
|
||||
() => onMovePinnedThread?.(thread, "up"),
|
||||
[onMovePinnedThread, thread],
|
||||
);
|
||||
const handleMovePinnedDown = useCallback(
|
||||
() => onMovePinnedThread?.(thread, "down"),
|
||||
[onMovePinnedThread, thread],
|
||||
);
|
||||
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
|
||||
|
||||
// Swipe: the v2 primary action is the lifecycle transition. Every settled
|
||||
@@ -459,12 +477,34 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
() =>
|
||||
props.pinningSupported
|
||||
? [
|
||||
...(pinnedRow && props.pinReorderSupported === true
|
||||
? [
|
||||
{
|
||||
id: "move-pin-up",
|
||||
title: "Move up",
|
||||
image: "arrow.up",
|
||||
attributes: { disabled: props.canMovePinnedUp !== true },
|
||||
} satisfies MenuAction,
|
||||
{
|
||||
id: "move-pin-down",
|
||||
title: "Move down",
|
||||
image: "arrow.down",
|
||||
attributes: { disabled: props.canMovePinnedDown !== true },
|
||||
} satisfies MenuAction,
|
||||
]
|
||||
: []),
|
||||
pinnedRow
|
||||
? { id: "unpin", title: "Unpin", image: "pin.slash" }
|
||||
: { id: "pin", title: "Pin", image: "pin" },
|
||||
]
|
||||
: [],
|
||||
[pinnedRow, props.pinningSupported],
|
||||
[
|
||||
pinnedRow,
|
||||
props.canMovePinnedDown,
|
||||
props.canMovePinnedUp,
|
||||
props.pinReorderSupported,
|
||||
props.pinningSupported,
|
||||
],
|
||||
);
|
||||
const snoozableCardMenuActions = useMemo<MenuAction[]>(
|
||||
() => [
|
||||
@@ -491,6 +531,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
if (nativeEvent.event === "unsnooze") handleUnsnooze();
|
||||
if (nativeEvent.event === "pin") handlePin();
|
||||
if (nativeEvent.event === "unpin") handleUnpin();
|
||||
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
|
||||
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
|
||||
if (nativeEvent.event === "archive") handleArchive();
|
||||
if (nativeEvent.event === "delete") handleDelete();
|
||||
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
|
||||
@@ -507,6 +549,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
[
|
||||
handleArchive,
|
||||
handleDelete,
|
||||
handleMovePinnedDown,
|
||||
handleMovePinnedUp,
|
||||
handlePin,
|
||||
handleSettle,
|
||||
handleSnooze,
|
||||
@@ -587,6 +631,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}
|
||||
@@ -775,6 +820,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}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
|
||||
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
|
||||
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
|
||||
import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/thread-sort";
|
||||
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
|
||||
|
||||
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
|
||||
@@ -102,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(
|
||||
@@ -383,8 +384,8 @@ export function buildThreadListV2Items(input: {
|
||||
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
|
||||
// Visibility parity with web: snooze outranks everything, including a
|
||||
// pin — a snoozed thread leaves the list until it wakes (or raises its
|
||||
// hand). The pin survives underneath, so a woken thread reappears at
|
||||
// its original spot in the creation-ordered pinned block.
|
||||
// hand). The pin (and its pinOrderKey) survives underneath, so a woken
|
||||
// thread reappears at its exact spot in the pinned block.
|
||||
if (supportsSnooze && effectiveSnoozed(thread, { now: snoozeNow })) {
|
||||
snoozed.push(thread);
|
||||
if (
|
||||
@@ -444,7 +445,7 @@ export function buildThreadListV2Items(input: {
|
||||
);
|
||||
|
||||
const items: ThreadListV2Item[] = [];
|
||||
for (const thread of sortThreadsForListV2(pinned)) {
|
||||
for (const thread of sortPinnedThreadsByOrderKey(pinned)) {
|
||||
items.push({
|
||||
thread,
|
||||
variant: "card",
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,442 @@
|
||||
import { useNavigation } from "@react-navigation/native";
|
||||
import type { MergedUsage } from "@t3tools/shared/usageMerge";
|
||||
import {
|
||||
enumerateDays,
|
||||
formatCount,
|
||||
formatDayShort,
|
||||
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: 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 [windowDays, setWindowDays] = useState<number>(30);
|
||||
const [metric, setMetric] = useState<UsageChartMetric>("cost");
|
||||
|
||||
// Recomputed only when the window length changes, so a re-render does not
|
||||
// shift the range and refetch every environment.
|
||||
const window = useMemo(() => makeWindow(windowDays), [windowDays]);
|
||||
const { merged, environments, isPending, isPartial, refresh } = useUsage(window);
|
||||
|
||||
const days = useMemo(
|
||||
() => enumerateDays(window.sinceDay, window.untilDay),
|
||||
[window.sinceDay, window.untilDay],
|
||||
);
|
||||
|
||||
// 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);
|
||||
|
||||
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={refresh} />}
|
||||
>
|
||||
<SegmentedControl
|
||||
options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}
|
||||
selected={windowDays}
|
||||
onSelect={setWindowDays}
|
||||
/>
|
||||
|
||||
<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={days}
|
||||
metric={metric}
|
||||
onMetricChange={setMetric}
|
||||
sinceDay={window.sinceDay}
|
||||
untilDay={window.untilDay}
|
||||
/>
|
||||
<ProviderSection merged={merged} metric={metric} />
|
||||
<TotalsSection merged={merged} />
|
||||
<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 metric: UsageChartMetric;
|
||||
readonly onMetricChange: (metric: UsageChartMetric) => void;
|
||||
readonly sinceDay: string;
|
||||
readonly untilDay: string;
|
||||
}) {
|
||||
const { merged, metric } = props;
|
||||
const colors = useProviderColors();
|
||||
const hasActivity = merged.daily.some((day) => day.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={merged.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">{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">{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 }) {
|
||||
const { merged } = props;
|
||||
const activeDays = merged.daily.filter((day) => day.totalTokens > 0).length;
|
||||
const dailyAverage = activeDays === 0 ? 0 : merged.totalTokens / activeDays;
|
||||
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(dailyAverage)} per active 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",
|
||||
};
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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)),
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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>;
|
||||
|
||||
@@ -532,3 +532,39 @@ describe("buildThreadFeed", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("quiet timeline: nested agents", () => {
|
||||
it("keeps a nested agent's terminal row but hides its background work", () => {
|
||||
const thread = makeThread({
|
||||
id: ThreadId.make("thread-nested"),
|
||||
projectId: ProjectId.make("project-1"),
|
||||
title: "Nested agents",
|
||||
activities: [
|
||||
// A subagent's own shell: internal, covered by the owner's liveness.
|
||||
makeActivity({
|
||||
id: EventId.make("shell-done"),
|
||||
kind: "task.completed",
|
||||
summary: "Task completed",
|
||||
createdAt: "2026-04-01T00:00:02.000Z",
|
||||
payload: { taskId: "sh-1", agentId: "owner", agentKind: "background" },
|
||||
}),
|
||||
// A nested AGENT's completion: mobile has no Agents sheet, so this
|
||||
// terminal row is the only signal it ever finished.
|
||||
makeActivity({
|
||||
id: EventId.make("nested-done"),
|
||||
kind: "task.completed",
|
||||
summary: "Task completed",
|
||||
createdAt: "2026-04-01T00:00:03.000Z",
|
||||
payload: { taskId: "n-1", agentId: "owner", agentKind: "agent" },
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
const feed = buildThreadFeed(thread);
|
||||
const ids = feed.flatMap((entry) =>
|
||||
entry.type === "activity-group" ? entry.activities.map((row) => row.id) : [],
|
||||
);
|
||||
expect(ids).toContain("nested-done");
|
||||
expect(ids).not.toContain("shell-done");
|
||||
});
|
||||
});
|
||||
@@ -80,6 +80,8 @@ interface WorkLogEntry {
|
||||
interface DerivedWorkLogEntry extends WorkLogEntry {
|
||||
activityKind: OrchestrationThreadActivity["kind"];
|
||||
collapseKey?: string;
|
||||
/** Grouping key for subagent lifecycle rows (one row per agent). */
|
||||
taskId?: string;
|
||||
}
|
||||
|
||||
type RawThreadFeedEntry =
|
||||
@@ -235,6 +237,63 @@ function resolvePendingUserInputAnswer(
|
||||
return normalizeDraftAnswer(draft?.selectedOptionLabel);
|
||||
}
|
||||
|
||||
/** Codex children settle via task.updated (idle/failed/interrupted), never
|
||||
* task.completed — these rows are mobile's only terminal signal for them. */
|
||||
const MOBILE_TERMINAL_UPDATE_STATUSES: ReadonlySet<string> = new Set([
|
||||
"idle",
|
||||
"completed",
|
||||
"failed",
|
||||
"cancelled",
|
||||
"interrupted",
|
||||
]);
|
||||
|
||||
function isTerminalBypassUpdate(activity: OrchestrationThreadActivity): boolean {
|
||||
if (activity.kind !== "task.updated") {
|
||||
return false;
|
||||
}
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
return (
|
||||
payload?.timelineBypass === true &&
|
||||
typeof payload.status === "string" &&
|
||||
MOBILE_TERMINAL_UPDATE_STATUSES.has(payload.status)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Quiet-timeline guarantee (mirrors web's session-logic): agent-internal
|
||||
* activity lives in the Agents sheet, not the work log. Terminal rows are
|
||||
* kept — with no Agents surface on mobile they are the terminal signal
|
||||
* (a surface that hides rows must keep its own terminal signal). That means
|
||||
* task.completed (Claude) AND terminal bypassed task.updated (Codex, whose
|
||||
* children never emit task.completed — review finding).
|
||||
*/
|
||||
function isAgentInternalActivity(activity: OrchestrationThreadActivity): boolean {
|
||||
const payload =
|
||||
activity.payload && typeof activity.payload === "object"
|
||||
? (activity.payload as Record<string, unknown>)
|
||||
: null;
|
||||
if (!payload) {
|
||||
return false;
|
||||
}
|
||||
const isTerminalTaskRow = activity.kind === "task.completed" || isTerminalBypassUpdate(activity);
|
||||
if (payload.timelineBypass === true && !isTerminalTaskRow) {
|
||||
return true;
|
||||
}
|
||||
// agentId marks ownership, not "hide me": a NESTED AGENT's terminal row is
|
||||
// the only signal mobile gets (no Agents sheet), so it stays. Only an
|
||||
// agent's own background work (stamped "background") is internal — same
|
||||
// rule as web (review finding: hiding on agentId alone dropped nested
|
||||
// completions with no replacement UI).
|
||||
const ownedByAgent = typeof payload.agentId === "string" && payload.agentId.trim().length > 0;
|
||||
if (!ownedByAgent) {
|
||||
return false;
|
||||
}
|
||||
return !(isTerminalTaskRow && payload.agentKind === "agent");
|
||||
}
|
||||
|
||||
function deriveWorkLogEntries(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
@@ -243,9 +302,13 @@ function deriveWorkLogEntries(
|
||||
for (const activity of ordered) {
|
||||
if (activity.kind === "tool.started") continue;
|
||||
if (activity.kind === "task.started") continue;
|
||||
// Terminal bypassed updates pass: Codex children's only terminal signal.
|
||||
if (activity.kind === "task.updated" && !isTerminalBypassUpdate(activity)) continue;
|
||||
if (activity.kind === "tool.progress") continue;
|
||||
if (activity.kind === "context-window.updated") continue;
|
||||
if (activity.summary === "Checkpoint captured") continue;
|
||||
if (isPlanBoundaryToolActivity(activity)) continue;
|
||||
if (isAgentInternalActivity(activity)) continue;
|
||||
entries.push(toDerivedWorkLogEntry(activity));
|
||||
}
|
||||
return collapseDerivedWorkLogEntries(entries);
|
||||
@@ -271,7 +334,13 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
const commandPreview = extractToolCommand(payload);
|
||||
const changedFiles = extractChangedFiles(payload);
|
||||
const title = extractToolTitle(payload);
|
||||
const isTaskActivity = activity.kind === "task.progress" || activity.kind === "task.completed";
|
||||
// task.updated included: terminal bypassed updates (Codex children's only
|
||||
// terminal signal) must carry task identity so they collapse per child
|
||||
// instead of stacking anonymous "Task idle" rows.
|
||||
const isTaskActivity =
|
||||
activity.kind === "task.progress" ||
|
||||
activity.kind === "task.completed" ||
|
||||
activity.kind === "task.updated";
|
||||
const taskSummary =
|
||||
isTaskActivity && typeof payload?.summary === "string" && payload.summary.length > 0
|
||||
? payload.summary
|
||||
@@ -284,10 +353,15 @@ function toDerivedWorkLogEntry(activity: OrchestrationThreadActivity): DerivedWo
|
||||
? payload.detail
|
||||
: null;
|
||||
const taskLabel = taskSummary || taskDetailAsLabel;
|
||||
const taskId =
|
||||
isTaskActivity && typeof payload?.taskId === "string" && payload.taskId.length > 0
|
||||
? payload.taskId
|
||||
: undefined;
|
||||
const entry: DerivedWorkLogEntry = {
|
||||
id: activity.id,
|
||||
createdAt: activity.createdAt,
|
||||
turnId: activity.turnId,
|
||||
...(taskId ? { taskId } : {}),
|
||||
label: taskLabel || activity.summary,
|
||||
tone:
|
||||
activity.kind === "task.progress"
|
||||
@@ -352,7 +426,25 @@ function collapseDerivedWorkLogEntries(
|
||||
entries: ReadonlyArray<DerivedWorkLogEntry>,
|
||||
): DerivedWorkLogEntry[] {
|
||||
const collapsed: DerivedWorkLogEntry[] = [];
|
||||
// Subagent rows collapse by identity, not adjacency (quiet-timeline
|
||||
// guarantee; mirrors web's session-logic).
|
||||
const taskRowIndex = new Map<string, number>();
|
||||
for (const entry of entries) {
|
||||
const isTaskRow =
|
||||
entry.taskId !== undefined &&
|
||||
(entry.activityKind === "task.progress" ||
|
||||
entry.activityKind === "task.completed" ||
|
||||
entry.activityKind === "task.updated");
|
||||
if (isTaskRow && entry.taskId !== undefined) {
|
||||
const existingIndex = taskRowIndex.get(entry.taskId);
|
||||
if (existingIndex !== undefined) {
|
||||
collapsed[existingIndex] = mergeDerivedWorkLogEntries(collapsed[existingIndex]!, entry);
|
||||
continue;
|
||||
}
|
||||
taskRowIndex.set(entry.taskId, collapsed.length);
|
||||
collapsed.push(entry);
|
||||
continue;
|
||||
}
|
||||
const previous = collapsed.at(-1);
|
||||
if (previous && shouldCollapseToolLifecycleEntries(previous, entry)) {
|
||||
collapsed[collapsed.length - 1] = mergeDerivedWorkLogEntries(previous, entry);
|
||||
|
||||
@@ -27,12 +27,13 @@ export interface Preferences {
|
||||
readonly projectGroupingEnabled?: boolean;
|
||||
readonly projectGroupingMode?: SidebarProjectGroupingMode;
|
||||
/**
|
||||
* 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 +85,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
collapsedProjectGroups?: readonly string[];
|
||||
projectGroupingEnabled?: boolean;
|
||||
projectGroupingMode?: SidebarProjectGroupingMode;
|
||||
threadListV2Enabled?: boolean;
|
||||
legacyThreadListEnabled?: boolean;
|
||||
} = {};
|
||||
|
||||
if (typeof parsed.liveActivitiesEnabled === "boolean") {
|
||||
@@ -121,8 +122,8 @@ function sanitizePreferences(parsed: Preferences): Preferences {
|
||||
) {
|
||||
preferences.projectGroupingMode = parsed.projectGroupingMode;
|
||||
}
|
||||
if (typeof parsed.threadListV2Enabled === "boolean") {
|
||||
preferences.threadListV2Enabled = parsed.threadListV2Enabled;
|
||||
if (typeof parsed.legacyThreadListEnabled === "boolean") {
|
||||
preferences.legacyThreadListEnabled = parsed.legacyThreadListEnabled;
|
||||
}
|
||||
return preferences;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* 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,
|
||||
}),
|
||||
[input.sinceDay, input.untilDay, input.timeZone],
|
||||
);
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// @effect-diagnostics nodeBuiltinImport:off - Measures the real Node HTTP and WebSocket transports.
|
||||
import * as NodeHttp from "node:http";
|
||||
import * as NodeZlib from "node:zlib";
|
||||
|
||||
import * as NodeSocket from "@effect/platform-node/NodeSocket";
|
||||
import { WsRpcGroup } from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Schema from "effect/Schema";
|
||||
import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
|
||||
import * as Socket from "effect/unstable/socket/Socket";
|
||||
|
||||
export class TransferHttpRequestError extends Schema.TaggedErrorClass<TransferHttpRequestError>()(
|
||||
"TransferHttpRequestError",
|
||||
{
|
||||
url: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {}
|
||||
|
||||
export interface HttpTransferMeasurement {
|
||||
readonly status: number;
|
||||
readonly contentEncoding: string | null;
|
||||
readonly encodedBody: Uint8Array;
|
||||
readonly encodedBodyBytes: number;
|
||||
readonly decodedBody: Uint8Array;
|
||||
readonly decodedBodyBytes: number;
|
||||
/** HTTP response bytes read from the socket, including status line and headers. */
|
||||
readonly wireBytes: number;
|
||||
}
|
||||
|
||||
export const measureHttpGet = Effect.fn("TransferBudget.measureHttpGet")(function* (input: {
|
||||
readonly url: string;
|
||||
readonly headers?: Readonly<Record<string, string>>;
|
||||
}) {
|
||||
return yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
new Promise<HttpTransferMeasurement>((resolve, reject) => {
|
||||
let socketBytesBeforeResponse = 0;
|
||||
const request = NodeHttp.get(
|
||||
input.url,
|
||||
{
|
||||
agent: false,
|
||||
headers: {
|
||||
"accept-encoding": "gzip",
|
||||
connection: "close",
|
||||
...input.headers,
|
||||
},
|
||||
},
|
||||
(response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
response.on("data", (chunk: Buffer) => chunks.push(chunk));
|
||||
response.once("error", reject);
|
||||
response.once("end", () => {
|
||||
try {
|
||||
const encodedBody = Buffer.concat(chunks);
|
||||
const header = response.headers["content-encoding"];
|
||||
const contentEncoding = Array.isArray(header)
|
||||
? (header[0] ?? null)
|
||||
: (header ?? null);
|
||||
const decodedBody =
|
||||
contentEncoding === "gzip" ? NodeZlib.gunzipSync(encodedBody) : encodedBody;
|
||||
resolve({
|
||||
status: response.statusCode ?? 0,
|
||||
contentEncoding,
|
||||
encodedBody,
|
||||
encodedBodyBytes: encodedBody.byteLength,
|
||||
decodedBody,
|
||||
decodedBodyBytes: decodedBody.byteLength,
|
||||
wireBytes: Math.max(0, response.socket.bytesRead - socketBytesBeforeResponse),
|
||||
});
|
||||
} catch (cause) {
|
||||
reject(cause);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
request.once("socket", (socket) => {
|
||||
socketBytesBeforeResponse = socket.bytesRead;
|
||||
});
|
||||
request.once("error", reject);
|
||||
request.setTimeout(10_000, () => {
|
||||
request.destroy(new Error(`Timed out reading ${input.url}`));
|
||||
});
|
||||
}),
|
||||
catch: (cause) => new TransferHttpRequestError({ url: input.url, cause }),
|
||||
});
|
||||
});
|
||||
|
||||
export interface WebSocketTransferTotals {
|
||||
readonly wireBytes: number;
|
||||
readonly decodedBytes: number;
|
||||
readonly messages: number;
|
||||
}
|
||||
|
||||
export interface WebSocketTransferRecorder {
|
||||
readonly connect: (
|
||||
url: string,
|
||||
protocols: string | string[] | undefined,
|
||||
cookie: string,
|
||||
) => globalThis.WebSocket;
|
||||
readonly totals: () => WebSocketTransferTotals;
|
||||
readonly negotiatedExtensions: () => string;
|
||||
}
|
||||
|
||||
interface NodeWebSocketWithTransport extends NodeSocket.NodeWS.WebSocket {
|
||||
readonly _socket?: {
|
||||
readonly bytesRead: number;
|
||||
};
|
||||
}
|
||||
|
||||
function rawDataBytes(data: NodeSocket.NodeWS.RawData): number {
|
||||
if (Array.isArray(data)) {
|
||||
return data.reduce((total, chunk) => total + chunk.byteLength, 0);
|
||||
}
|
||||
return data.byteLength;
|
||||
}
|
||||
|
||||
export function makeWebSocketTransferRecorder(): WebSocketTransferRecorder {
|
||||
let socket: NodeWebSocketWithTransport | null = null;
|
||||
let decodedBytes = 0;
|
||||
let messages = 0;
|
||||
|
||||
return {
|
||||
connect: (url, protocols, cookie) => {
|
||||
const nextSocket = new NodeSocket.NodeWS.WebSocket(url, protocols, {
|
||||
headers: { cookie },
|
||||
perMessageDeflate: true,
|
||||
}) as NodeWebSocketWithTransport;
|
||||
socket = nextSocket;
|
||||
nextSocket.on("message", (data) => {
|
||||
const bytes = rawDataBytes(data);
|
||||
decodedBytes += bytes;
|
||||
messages += 1;
|
||||
});
|
||||
return nextSocket as unknown as globalThis.WebSocket;
|
||||
},
|
||||
totals: () => ({
|
||||
wireBytes: socket?._socket?.bytesRead ?? 0,
|
||||
decodedBytes,
|
||||
messages,
|
||||
}),
|
||||
negotiatedExtensions: () => socket?.extensions ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
export function transferDelta(
|
||||
start: WebSocketTransferTotals,
|
||||
end: WebSocketTransferTotals,
|
||||
): WebSocketTransferTotals {
|
||||
return {
|
||||
wireBytes: Math.max(0, end.wireBytes - start.wireBytes),
|
||||
decodedBytes: Math.max(0, end.decodedBytes - start.decodedBytes),
|
||||
messages: Math.max(0, end.messages - start.messages),
|
||||
};
|
||||
}
|
||||
|
||||
export function countingWsRpcProtocolLayer(input: {
|
||||
readonly url: string;
|
||||
readonly cookie: string;
|
||||
readonly recorder: WebSocketTransferRecorder;
|
||||
}) {
|
||||
const webSocketConstructorLayer = Layer.succeed(Socket.WebSocketConstructor, (url, protocols) =>
|
||||
input.recorder.connect(url, protocols, input.cookie),
|
||||
);
|
||||
return RpcClient.layerProtocolSocket().pipe(
|
||||
Layer.provide(
|
||||
Socket.layerWebSocket(input.url, { openTimeout: "10 seconds" }).pipe(
|
||||
Layer.provide(webSocketConstructorLayer),
|
||||
),
|
||||
),
|
||||
Layer.provide(RpcSerialization.layerJson),
|
||||
);
|
||||
}
|
||||
|
||||
export const makeCountingWsRpcClient = RpcClient.make(WsRpcGroup);
|
||||
export type CountingWsRpcClient = Effect.Success<typeof makeCountingWsRpcClient>;
|
||||
@@ -50,10 +50,14 @@ import * as RepositoryIdentityResolver from "../src/project/RepositoryIdentityRe
|
||||
import { OrchestrationEngineLive } from "../src/orchestration/Layers/OrchestrationEngine.ts";
|
||||
import { OrchestrationProjectionPipelineLive } from "../src/orchestration/Layers/ProjectionPipeline.ts";
|
||||
import { OrchestrationProjectionSnapshotQueryLive } from "../src/orchestration/Layers/ProjectionSnapshotQuery.ts";
|
||||
import * as ThreadBackgroundLiveness from "../src/orchestration/ThreadBackgroundLiveness.ts";
|
||||
import * as ThreadPlanProgress from "../src/orchestration/ThreadPlanProgress.ts";
|
||||
import { RuntimeReceiptBusTest } from "../src/orchestration/Layers/RuntimeReceiptBus.ts";
|
||||
import { OrchestrationReactorLive } from "../src/orchestration/Layers/OrchestrationReactor.ts";
|
||||
import { ProviderCommandReactorLive } from "../src/orchestration/Layers/ProviderCommandReactor.ts";
|
||||
import { ProviderRuntimeIngestionLive } from "../src/orchestration/Layers/ProviderRuntimeIngestion.ts";
|
||||
import { CheckpointReactor } from "../src/orchestration/Services/CheckpointReactor.ts";
|
||||
import { ProviderRuntimeIngestionService } from "../src/orchestration/Services/ProviderRuntimeIngestion.ts";
|
||||
import {
|
||||
OrchestrationEngineService,
|
||||
type OrchestrationEngineShape,
|
||||
@@ -217,6 +221,8 @@ export interface OrchestrationIntegrationHarness {
|
||||
timeoutMs?: number,
|
||||
): Effect.Effect<Receipt, never>;
|
||||
};
|
||||
readonly drainProviderRuntime: Effect.Effect<void>;
|
||||
readonly drainCheckpointReactor: Effect.Effect<void>;
|
||||
readonly dispose: Effect.Effect<void, never>;
|
||||
}
|
||||
|
||||
@@ -305,6 +311,9 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
checkpointStoreLayer,
|
||||
providerLayer,
|
||||
RuntimeReceiptBusTest,
|
||||
).pipe(
|
||||
Layer.provideMerge(ThreadBackgroundLiveness.layer),
|
||||
Layer.provideMerge(ThreadPlanProgress.layer),
|
||||
);
|
||||
const serverSettingsLayer = ServerSettingsService.layerTest();
|
||||
const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe(
|
||||
@@ -391,6 +400,13 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
const reactor = yield* tryRuntimePromise("load OrchestrationReactor service", () =>
|
||||
runtime.runPromise(Effect.service(OrchestrationReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const providerRuntimeIngestion = yield* tryRuntimePromise(
|
||||
"load ProviderRuntimeIngestion service",
|
||||
() => runtime.runPromise(Effect.service(ProviderRuntimeIngestionService)),
|
||||
).pipe(Effect.orDie);
|
||||
const checkpointReactor = yield* tryRuntimePromise("load CheckpointReactor service", () =>
|
||||
runtime.runPromise(Effect.service(CheckpointReactor)),
|
||||
).pipe(Effect.orDie);
|
||||
const snapshotQuery = yield* tryRuntimePromise("load ProjectionSnapshotQuery service", () =>
|
||||
runtime.runPromise(Effect.service(ProjectionSnapshotQuery)),
|
||||
).pipe(Effect.orDie);
|
||||
@@ -555,6 +571,8 @@ export const makeOrchestrationIntegrationHarness = (
|
||||
waitForDomainEvent,
|
||||
waitForPendingApproval,
|
||||
waitForReceipt,
|
||||
drainProviderRuntime: providerRuntimeIngestion.drain,
|
||||
drainCheckpointReactor: checkpointReactor.drain,
|
||||
dispose,
|
||||
} satisfies OrchestrationIntegrationHarness;
|
||||
});
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
ProviderDriverKind,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
@@ -226,9 +225,9 @@ function missingSessionEffect(
|
||||
export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapterHarnessOptions) =>
|
||||
Effect.gen(function* () {
|
||||
const provider = options?.provider ?? ProviderDriverKind.make("codex");
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
const runtimeEvents = yield* Queue.unbounded<ProviderRuntimeEvent>();
|
||||
let sessionCount = 0;
|
||||
let eventCount = 0;
|
||||
const sessions = new Map<ThreadId, SessionState>();
|
||||
const queuedResponsesForNextSession: TestTurnResponse[] = [];
|
||||
const interruptCallsBySession = new Map<ThreadId, Array<TurnId | undefined>>();
|
||||
@@ -242,18 +241,10 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
>();
|
||||
|
||||
const emit = (event: ProviderRuntimeEvent) => Queue.offer(runtimeEvents, event);
|
||||
const randomUUIDv4 = (threadId: ThreadId) =>
|
||||
crypto.randomUUIDv4.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new ProviderAdapterValidationError({
|
||||
provider,
|
||||
operation: "crypto/randomUUIDv4",
|
||||
issue: `Failed to generate test runtime identifier for thread '${threadId}'.`,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const nextEventId = (threadId: ThreadId) => {
|
||||
eventCount += 1;
|
||||
return EventId.make(`test-provider:${provider}:${threadId}:${eventCount}`);
|
||||
};
|
||||
|
||||
const startSession: ProviderAdapterShape<ProviderAdapterError>["startSession"] = (input) =>
|
||||
Effect.gen(function* () {
|
||||
@@ -322,7 +313,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
for (const fixtureEvent of response.events) {
|
||||
const rawEvent: Record<string, unknown> = {
|
||||
...(fixtureEvent as Record<string, unknown>),
|
||||
eventId: yield* randomUUIDv4(input.threadId),
|
||||
eventId: nextEventId(input.threadId),
|
||||
provider,
|
||||
sessionId: RuntimeSessionId.make(String(input.threadId)),
|
||||
};
|
||||
@@ -379,7 +370,7 @@ export const makeTestProviderAdapterHarness = (options?: MakeTestProviderAdapter
|
||||
if (deferredTurnCompletedEvents.length === 0) {
|
||||
yield* emit({
|
||||
type: "turn.completed",
|
||||
eventId: EventId.make(yield* randomUUIDv4(input.threadId)),
|
||||
eventId: nextEventId(input.threadId),
|
||||
provider,
|
||||
createdAt: nowIso(),
|
||||
threadId: state.snapshot.threadId,
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import type { ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import type {
|
||||
HttpTransferMeasurement,
|
||||
WebSocketTransferTotals,
|
||||
} from "./NetworkTransferMeasurement.integration.ts";
|
||||
import {
|
||||
TRANSFER_HISTORY_MCP_RESULT_BYTES,
|
||||
TRANSFER_HISTORY_TOOLS_PER_TURN,
|
||||
TRANSFER_HISTORY_TURN_COUNT,
|
||||
TRANSFER_MEASURED_MCP_RESULT_BYTES,
|
||||
TRANSFER_MEASURED_TOOLS,
|
||||
} from "./fixtures/transferBudget.ts";
|
||||
|
||||
export interface TransferBudgetRun {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadSnapshot: HttpTransferMeasurement;
|
||||
readonly measuredTurnWebSocket: WebSocketTransferTotals;
|
||||
}
|
||||
|
||||
interface ProviderTransferBudget {
|
||||
readonly totalWireBytes: number;
|
||||
readonly threadSnapshotWireBytes: number;
|
||||
readonly measuredTurnWebSocketWireBytes: number;
|
||||
readonly measuredTurnWebSocketDecodedBytes: number;
|
||||
readonly measuredTurnWebSocketMessages: number;
|
||||
}
|
||||
|
||||
// These caps leave roughly 30% headroom above the client projection of the
|
||||
// deterministic 9 MB retained-result fixture. Full MCP results stay in
|
||||
// persistence, so accidentally shipping them again exceeds these caps by
|
||||
// orders of magnitude. The CI report preserves exact values for review.
|
||||
const TRANSFER_BUDGET = {
|
||||
totalWireBytes: 15_500,
|
||||
threadSnapshotWireBytes: 7_500,
|
||||
measuredTurnWebSocketWireBytes: 8_000,
|
||||
measuredTurnWebSocketDecodedBytes: 68_000,
|
||||
measuredTurnWebSocketMessages: 21,
|
||||
} satisfies ProviderTransferBudget;
|
||||
|
||||
export const TRANSFER_BUDGETS: Readonly<Record<string, ProviderTransferBudget>> = {
|
||||
codex: TRANSFER_BUDGET,
|
||||
claudeAgent: TRANSFER_BUDGET,
|
||||
};
|
||||
|
||||
function totalWireBytes(run: TransferBudgetRun): number {
|
||||
return run.threadSnapshot.wireBytes + run.measuredTurnWebSocket.wireBytes;
|
||||
}
|
||||
|
||||
function observedTransfer(run: TransferBudgetRun) {
|
||||
return {
|
||||
totalWireBytes: totalWireBytes(run),
|
||||
threadSnapshotWireBytes: run.threadSnapshot.wireBytes,
|
||||
threadSnapshotDecodedBytes: run.threadSnapshot.decodedBodyBytes,
|
||||
measuredTurnWebSocketWireBytes: run.measuredTurnWebSocket.wireBytes,
|
||||
measuredTurnWebSocketDecodedBytes: run.measuredTurnWebSocket.decodedBytes,
|
||||
measuredTurnWebSocketMessages: run.measuredTurnWebSocket.messages,
|
||||
};
|
||||
}
|
||||
|
||||
/** Machine-readable input for the trusted PR comment publisher. */
|
||||
export function formatTransferBudgetResult(runs: ReadonlyArray<TransferBudgetRun>): string {
|
||||
const providers = Object.fromEntries(
|
||||
runs.flatMap((run) => {
|
||||
const ceiling = TRANSFER_BUDGETS[run.provider];
|
||||
return ceiling ? [[run.provider, { observed: observedTransfer(run), ceiling }]] : [];
|
||||
}),
|
||||
);
|
||||
|
||||
return `${JSON.stringify(
|
||||
{
|
||||
schemaVersion: 1,
|
||||
scenario: {
|
||||
id: "thread-transfer-v1",
|
||||
historyTurns: TRANSFER_HISTORY_TURN_COUNT,
|
||||
historyCommandToolsPerTurn: TRANSFER_HISTORY_TOOLS_PER_TURN,
|
||||
historyMcpResultBytes: TRANSFER_HISTORY_MCP_RESULT_BYTES,
|
||||
measuredCommandTools: TRANSFER_MEASURED_TOOLS,
|
||||
measuredMcpResultBytes: TRANSFER_MEASURED_MCP_RESULT_BYTES,
|
||||
},
|
||||
providers,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
)}\n`;
|
||||
}
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1_024) return `${bytes} B`;
|
||||
if (bytes >= 1_024 * 1_024) {
|
||||
return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB (${bytes.toLocaleString("en-US")} B)`;
|
||||
}
|
||||
return `${(bytes / 1_024).toFixed(1)} KiB (${bytes.toLocaleString("en-US")} B)`;
|
||||
}
|
||||
|
||||
function row(
|
||||
provider: ProviderDriverKind,
|
||||
phase: string,
|
||||
metric: string,
|
||||
observed: number,
|
||||
maximum: number,
|
||||
format: (value: number) => string = formatBytes,
|
||||
): string {
|
||||
const status = observed <= maximum ? "PASS" : "FAIL";
|
||||
return `| ${provider} | ${phase} | ${metric} | ${format(observed)} | ${format(maximum)} | ${status} |`;
|
||||
}
|
||||
|
||||
export function transferBudgetViolations(runs: ReadonlyArray<TransferBudgetRun>): string[] {
|
||||
const violations: string[] = [];
|
||||
for (const run of runs) {
|
||||
const budget = TRANSFER_BUDGETS[run.provider];
|
||||
if (!budget) {
|
||||
violations.push(`${run.provider}: no transfer budget is configured`);
|
||||
continue;
|
||||
}
|
||||
const checks = [
|
||||
["total thread wire bytes", totalWireBytes(run), budget.totalWireBytes],
|
||||
["thread snapshot wire bytes", run.threadSnapshot.wireBytes, budget.threadSnapshotWireBytes],
|
||||
[
|
||||
"measured-turn WebSocket wire bytes",
|
||||
run.measuredTurnWebSocket.wireBytes,
|
||||
budget.measuredTurnWebSocketWireBytes,
|
||||
],
|
||||
[
|
||||
"measured-turn WebSocket decoded bytes",
|
||||
run.measuredTurnWebSocket.decodedBytes,
|
||||
budget.measuredTurnWebSocketDecodedBytes,
|
||||
],
|
||||
[
|
||||
"measured-turn WebSocket messages",
|
||||
run.measuredTurnWebSocket.messages,
|
||||
budget.measuredTurnWebSocketMessages,
|
||||
],
|
||||
] as const;
|
||||
for (const [metric, observed, maximum] of checks) {
|
||||
if (observed > maximum) {
|
||||
violations.push(`${run.provider}: ${metric} was ${observed}, maximum ${maximum}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
return violations;
|
||||
}
|
||||
|
||||
export function formatTransferBudgetReport(runs: ReadonlyArray<TransferBudgetRun>): string {
|
||||
const lines = [
|
||||
"# T3 Code thread transfer budget",
|
||||
"",
|
||||
"Wire values are thread data bytes read from local HTTP and WebSocket sockets. HTTP includes response headers; WebSocket measurement starts after the resumed thread subscription synchronizes. TCP/IP, TLS framing, and the WebSocket upgrade are excluded. WebSocket permessage-deflate is negotiated.",
|
||||
`Scenario: ${TRANSFER_HISTORY_TURN_COUNT} historical turns with ${TRANSFER_HISTORY_TOOLS_PER_TURN} command tools and one retained ${formatBytes(TRANSFER_HISTORY_MCP_RESULT_BYTES)} MCP result each, followed by one measured turn with ${TRANSFER_MEASURED_TOOLS} command tools and a retained ${formatBytes(TRANSFER_MEASURED_MCP_RESULT_BYTES)} MCP result. Payload sizes are calibrated from heavy local Codex and Claude histories and contain no user data.`,
|
||||
"",
|
||||
"| Provider | Total thread wire | Budget | Result |",
|
||||
"| --- | ---: | ---: | --- |",
|
||||
...runs.flatMap((run) => {
|
||||
const budget = TRANSFER_BUDGETS[run.provider];
|
||||
if (!budget) return [];
|
||||
const observed = observedTransfer(run).totalWireBytes;
|
||||
return [
|
||||
`| ${run.provider} | ${formatBytes(observed)} | ${formatBytes(budget.totalWireBytes)} | ${observed <= budget.totalWireBytes ? "PASS" : "FAIL"} |`,
|
||||
];
|
||||
}),
|
||||
"",
|
||||
"## Detailed measurements",
|
||||
"",
|
||||
"| Provider | Phase | Metric | Observed | Budget | Result |",
|
||||
"| --- | --- | --- | ---: | ---: | --- |",
|
||||
];
|
||||
|
||||
for (const run of runs) {
|
||||
const budget = TRANSFER_BUDGETS[run.provider];
|
||||
if (!budget) continue;
|
||||
lines.push(
|
||||
row(
|
||||
run.provider,
|
||||
"thread snapshot",
|
||||
"HTTP wire",
|
||||
run.threadSnapshot.wireBytes,
|
||||
budget.threadSnapshotWireBytes,
|
||||
),
|
||||
row(
|
||||
run.provider,
|
||||
"measured turn",
|
||||
"WebSocket wire",
|
||||
run.measuredTurnWebSocket.wireBytes,
|
||||
budget.measuredTurnWebSocketWireBytes,
|
||||
),
|
||||
row(
|
||||
run.provider,
|
||||
"measured turn",
|
||||
"WebSocket decoded",
|
||||
run.measuredTurnWebSocket.decodedBytes,
|
||||
budget.measuredTurnWebSocketDecodedBytes,
|
||||
),
|
||||
row(
|
||||
run.provider,
|
||||
"measured turn",
|
||||
"WebSocket messages",
|
||||
run.measuredTurnWebSocket.messages,
|
||||
budget.measuredTurnWebSocketMessages,
|
||||
String,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
lines.push("", "## Compression diagnostics", "");
|
||||
for (const run of runs) {
|
||||
lines.push(
|
||||
`- ${run.provider}: thread snapshot ${formatBytes(run.threadSnapshot.decodedBodyBytes)} decoded to ${formatBytes(run.threadSnapshot.encodedBodyBytes)} gzip.`,
|
||||
);
|
||||
}
|
||||
|
||||
return `${lines.join("\n")}\n`;
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import {
|
||||
CommandId,
|
||||
defaultInstanceIdForDriver,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_MODEL_BY_PROVIDER,
|
||||
DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
MessageId,
|
||||
ProjectId,
|
||||
ProviderDriverKind,
|
||||
ThreadId,
|
||||
} from "@t3tools/contracts";
|
||||
import * as Effect from "effect/Effect";
|
||||
|
||||
import type { TurnProcessingQuiescedReceipt } from "../src/orchestration/Services/RuntimeReceiptBus.ts";
|
||||
import type { OrchestrationIntegrationHarness } from "./OrchestrationEngineHarness.integration.ts";
|
||||
import {
|
||||
expectedRecordedAssistantText,
|
||||
makeRecordedTransferTurn,
|
||||
TRANSFER_HISTORY_TURN_COUNT,
|
||||
} from "./fixtures/transferBudget.ts";
|
||||
|
||||
export const TRANSFER_PROJECT_ID = ProjectId.make("transfer-budget-project");
|
||||
export const TRANSFER_THREAD_ID = ThreadId.make("transfer-budget-thread");
|
||||
export const TRANSFER_MEASURED_TURN_INDEX = TRANSFER_HISTORY_TURN_COUNT;
|
||||
|
||||
export function transferModelSelection(provider: ProviderDriverKind) {
|
||||
return {
|
||||
instanceId: defaultInstanceIdForDriver(provider),
|
||||
model: DEFAULT_MODEL_BY_PROVIDER[provider] ?? DEFAULT_MODEL,
|
||||
};
|
||||
}
|
||||
|
||||
function turnTimestamp(turnIndex: number): string {
|
||||
return `2026-06-01T00:${String(turnIndex).padStart(2, "0")}:00.000Z`;
|
||||
}
|
||||
|
||||
export const TRANSFER_MEASURED_TURN_CREATED_AT = turnTimestamp(TRANSFER_MEASURED_TURN_INDEX);
|
||||
|
||||
const waitForTurnQuiesced = Effect.fn("TransferBudget.waitForTurnQuiesced")(function* (
|
||||
harness: OrchestrationIntegrationHarness,
|
||||
checkpointTurnCount: number,
|
||||
) {
|
||||
const receipt = yield* harness.waitForReceipt(
|
||||
(receipt): receipt is TurnProcessingQuiescedReceipt =>
|
||||
receipt.type === "turn.processing.quiesced" &&
|
||||
receipt.threadId === TRANSFER_THREAD_ID &&
|
||||
receipt.checkpointTurnCount === checkpointTurnCount,
|
||||
);
|
||||
yield* harness.drainProviderRuntime;
|
||||
yield* harness.drainCheckpointReactor;
|
||||
return receipt;
|
||||
});
|
||||
|
||||
export const seedTransferBudgetHistory = Effect.fn("TransferBudget.seedHistory")(function* (
|
||||
harness: OrchestrationIntegrationHarness,
|
||||
provider: ProviderDriverKind,
|
||||
) {
|
||||
if (!harness.adapterHarness) {
|
||||
return yield* Effect.die(new Error("Transfer budget history requires the replay adapter."));
|
||||
}
|
||||
|
||||
const modelSelection = transferModelSelection(provider);
|
||||
yield* harness.engine.dispatch({
|
||||
type: "project.create",
|
||||
commandId: CommandId.make(`transfer:${provider}:project-create`),
|
||||
projectId: TRANSFER_PROJECT_ID,
|
||||
title: "Transfer Budget Project",
|
||||
workspaceRoot: harness.workspaceDir,
|
||||
defaultModelSelection: modelSelection,
|
||||
createdAt: turnTimestamp(0),
|
||||
});
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.create",
|
||||
commandId: CommandId.make(`transfer:${provider}:thread-create`),
|
||||
threadId: TRANSFER_THREAD_ID,
|
||||
projectId: TRANSFER_PROJECT_ID,
|
||||
title: `${provider} transfer history`,
|
||||
modelSelection,
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
branch: "main",
|
||||
worktreePath: harness.workspaceDir,
|
||||
createdAt: turnTimestamp(0),
|
||||
});
|
||||
|
||||
for (let turnIndex = 0; turnIndex < TRANSFER_HISTORY_TURN_COUNT; turnIndex += 1) {
|
||||
const response = makeRecordedTransferTurn(provider, turnIndex);
|
||||
if (turnIndex === 0) {
|
||||
yield* harness.adapterHarness.queueTurnResponseForNextSession(response);
|
||||
} else {
|
||||
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
|
||||
}
|
||||
|
||||
yield* harness.engine.dispatch({
|
||||
type: "thread.turn.start",
|
||||
commandId: CommandId.make(`transfer:${provider}:turn:${turnIndex + 1}`),
|
||||
threadId: TRANSFER_THREAD_ID,
|
||||
message: {
|
||||
messageId: MessageId.make(`transfer-user-${turnIndex + 1}`),
|
||||
role: "user",
|
||||
text: `Inspect transfer behavior for historical turn ${turnIndex + 1}.`,
|
||||
attachments: [],
|
||||
},
|
||||
modelSelection,
|
||||
runtimeMode: "approval-required",
|
||||
interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
|
||||
createdAt: turnTimestamp(turnIndex),
|
||||
});
|
||||
yield* waitForTurnQuiesced(harness, turnIndex + 1);
|
||||
}
|
||||
});
|
||||
|
||||
export const queueMeasuredTransferTurn = Effect.fn("TransferBudget.queueMeasuredTurn")(function* (
|
||||
harness: OrchestrationIntegrationHarness,
|
||||
provider: ProviderDriverKind,
|
||||
) {
|
||||
if (!harness.adapterHarness) {
|
||||
return yield* Effect.die(new Error("Transfer budget measurement requires the replay adapter."));
|
||||
}
|
||||
const response = makeRecordedTransferTurn(provider, TRANSFER_MEASURED_TURN_INDEX);
|
||||
yield* harness.adapterHarness.queueTurnResponse(TRANSFER_THREAD_ID, response);
|
||||
});
|
||||
|
||||
export function expectedMeasuredAssistantText(provider: ProviderDriverKind): string {
|
||||
return expectedRecordedAssistantText(provider, TRANSFER_MEASURED_TURN_INDEX);
|
||||
}
|
||||
|
||||
export { TRANSFER_HISTORY_TURN_COUNT, waitForTurnQuiesced };
|
||||
@@ -0,0 +1,372 @@
|
||||
import { EventId, ProviderDriverKind } from "@t3tools/contracts";
|
||||
|
||||
import type {
|
||||
FixtureProviderRuntimeEvent,
|
||||
TestTurnResponse,
|
||||
} from "../TestProviderAdapter.integration.ts";
|
||||
|
||||
const FIXTURE_THREAD_ID = "transfer-budget-thread";
|
||||
const FIXTURE_TURN_ID = "transfer-budget-turn";
|
||||
|
||||
export const TRANSFER_HISTORY_TURN_COUNT = 10;
|
||||
export const TRANSFER_HISTORY_TOOLS_PER_TURN = 5;
|
||||
export const TRANSFER_MEASURED_TOOLS = 20;
|
||||
export const TRANSFER_HISTORY_MCP_RESULT_BYTES = 900_000;
|
||||
export const TRANSFER_MEASURED_MCP_RESULT_BYTES = 1_100_000;
|
||||
|
||||
const sourceModules = [
|
||||
"connection/session.ts",
|
||||
"connection/supervisor.ts",
|
||||
"rpc/client.ts",
|
||||
"rpc/protocol.ts",
|
||||
"state/threads.ts",
|
||||
"state/threadReducer.ts",
|
||||
"state/threadSnapshotHttp.ts",
|
||||
"orchestration/http.ts",
|
||||
"orchestration/Normalizer.ts",
|
||||
"orchestration/ActivityPayloadProjection.ts",
|
||||
"provider/ProviderService.ts",
|
||||
"provider/ProviderRuntimeIngestion.ts",
|
||||
"persistence/ProjectionSnapshotQuery.ts",
|
||||
"persistence/OrchestrationEventStore.ts",
|
||||
"checkpointing/CheckpointStore.ts",
|
||||
"checkpointing/CheckpointDiffQuery.ts",
|
||||
"server.ts",
|
||||
] as const;
|
||||
|
||||
function fixtureTimestamp(turnIndex: number, eventIndex: number): string {
|
||||
const minute = String(turnIndex).padStart(2, "0");
|
||||
const second = String(Math.floor(eventIndex / 1_000)).padStart(2, "0");
|
||||
const millisecond = String(eventIndex % 1_000).padStart(3, "0");
|
||||
return `2026-06-01T00:${minute}:${second}.${millisecond}Z`;
|
||||
}
|
||||
|
||||
function mix(value: number): number {
|
||||
let mixed = value | 0;
|
||||
mixed ^= mixed >>> 16;
|
||||
mixed = Math.imul(mixed, 0x7feb352d);
|
||||
mixed ^= mixed >>> 15;
|
||||
mixed = Math.imul(mixed, 0x846ca68b);
|
||||
mixed ^= mixed >>> 16;
|
||||
return mixed >>> 0;
|
||||
}
|
||||
|
||||
function digest(seed: number): string {
|
||||
return [0, 1, 2, 3]
|
||||
.map((offset) =>
|
||||
mix(seed + offset * 0x9e3779b9)
|
||||
.toString(16)
|
||||
.padStart(8, "0"),
|
||||
)
|
||||
.join("");
|
||||
}
|
||||
|
||||
/** Produces safe, deterministic output with enough entropy to exercise gzip. */
|
||||
function diagnosticOutput(input: {
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly turnIndex: number;
|
||||
readonly toolIndex: number;
|
||||
readonly targetBytes: number;
|
||||
}): string {
|
||||
const chunks: string[] = [];
|
||||
const providerSeed = input.provider === "codex" ? 0x43_4f_44_45 : 0x43_4c_41_55;
|
||||
let length = 0;
|
||||
let lineIndex = 0;
|
||||
|
||||
while (length < input.targetBytes) {
|
||||
const modulePath = sourceModules[(input.toolIndex + lineIndex) % sourceModules.length];
|
||||
const seed =
|
||||
providerSeed + input.turnIndex * 100_003 + input.toolIndex * 10_007 + lineIndex * 101;
|
||||
const line =
|
||||
`${String(lineIndex + 1).padStart(6, "0")} ${modulePath} ` +
|
||||
`operation=project-transfer-${input.turnIndex + 1}-${input.toolIndex + 1} ` +
|
||||
`cursor=${mix(seed)} digest=${digest(seed)} status=completed\n`;
|
||||
chunks.push(line);
|
||||
length += line.length;
|
||||
lineIndex += 1;
|
||||
}
|
||||
|
||||
return chunks.join("").slice(0, input.targetBytes);
|
||||
}
|
||||
|
||||
function assistantChunks(provider: ProviderDriverKind, turnIndex: number): ReadonlyArray<string> {
|
||||
const providerName = provider === "codex" ? "Codex" : "Claude";
|
||||
const paragraphs: string[] = [
|
||||
`I traced the ${providerName} request through the environment connection and orchestration layers. `,
|
||||
];
|
||||
let paragraphIndex = 0;
|
||||
while (paragraphs.join("").length < 4_096) {
|
||||
const modulePath = sourceModules[paragraphIndex % sourceModules.length];
|
||||
paragraphs.push(
|
||||
`Pass ${paragraphIndex + 1} reviewed ${modulePath} for turn ${turnIndex + 1}. ` +
|
||||
"The shell cursor stayed monotonic, the thread snapshot remained resumable, and the client received only incremental events. ",
|
||||
);
|
||||
paragraphIndex += 1;
|
||||
}
|
||||
const text = paragraphs.join("").slice(0, 4_096);
|
||||
return Array.from({ length: Math.ceil(text.length / 256) }, (_, index) =>
|
||||
text.slice(index * 256, (index + 1) * 256),
|
||||
);
|
||||
}
|
||||
|
||||
export function expectedRecordedAssistantText(
|
||||
provider: ProviderDriverKind,
|
||||
turnIndex: number,
|
||||
): string {
|
||||
return assistantChunks(provider, turnIndex).join("");
|
||||
}
|
||||
|
||||
function unifiedDiff(provider: ProviderDriverKind, turnIndex: number): string {
|
||||
const lines = sourceModules
|
||||
.slice(0, 8)
|
||||
.flatMap((modulePath, index) => [
|
||||
`diff --git a/${modulePath} b/${modulePath}`,
|
||||
`--- a/${modulePath}`,
|
||||
`+++ b/${modulePath}`,
|
||||
`@@ -${index + 1},2 +${index + 1},3 @@`,
|
||||
` const provider = "${provider}";`,
|
||||
`+const transferTurn = ${turnIndex + 1};`,
|
||||
`+const transferSample = ${1_500 + index * 97};`,
|
||||
]);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
function baseEvent(
|
||||
provider: ProviderDriverKind,
|
||||
turnIndex: number,
|
||||
eventIndex: number,
|
||||
): Pick<FixtureProviderRuntimeEvent, "eventId" | "provider" | "createdAt" | "threadId"> {
|
||||
return {
|
||||
eventId: EventId.make(`recorded:${provider}:${turnIndex}:${eventIndex}`),
|
||||
provider,
|
||||
createdAt: fixtureTimestamp(turnIndex, eventIndex),
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthetic canonical events calibrated from heavy local Codex and Claude
|
||||
* threads. Ten historical turns produce 9 MB of retained MCP results without
|
||||
* committing user content. Command output is intentionally modest because the
|
||||
* client projection strips it.
|
||||
*/
|
||||
export function makeRecordedTransferTurn(
|
||||
provider: ProviderDriverKind,
|
||||
turnIndex: number,
|
||||
): TestTurnResponse {
|
||||
const measuredTurn = turnIndex >= TRANSFER_HISTORY_TURN_COUNT;
|
||||
const toolCount = measuredTurn ? TRANSFER_MEASURED_TOOLS : TRANSFER_HISTORY_TOOLS_PER_TURN;
|
||||
const turnId = `${FIXTURE_TURN_ID}-${turnIndex + 1}`;
|
||||
const events: FixtureProviderRuntimeEvent[] = [];
|
||||
let eventIndex = 0;
|
||||
|
||||
events.push({
|
||||
type: "turn.started",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
payload: {
|
||||
model: provider === "codex" ? "gpt-5.4" : "claude-opus-4-1",
|
||||
effort: provider === "codex" ? "high" : "default",
|
||||
},
|
||||
});
|
||||
|
||||
for (let toolIndex = 0; toolIndex < toolCount; toolIndex += 1) {
|
||||
const itemId = `tool-${turnIndex + 1}-${toolIndex + 1}`;
|
||||
const command =
|
||||
provider === "codex"
|
||||
? `vp test transfer-budget-${toolIndex + 1}`
|
||||
: `review transfer budget ${toolIndex + 1}`;
|
||||
events.push(
|
||||
{
|
||||
type: "item.started",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "inProgress",
|
||||
title: `Inspect transfer path ${toolIndex + 1}`,
|
||||
detail: "Inspecting the HTTP snapshot and WebSocket projection boundaries.",
|
||||
data: {
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
startedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
item: {
|
||||
id: itemId,
|
||||
type: "commandExecution",
|
||||
command,
|
||||
cwd: "/workspace/transfer-budget",
|
||||
processId: String(toolIndex + 1),
|
||||
status: "inProgress",
|
||||
commandActions: [],
|
||||
aggregatedOutput: "",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId,
|
||||
payload: {
|
||||
itemType: "command_execution",
|
||||
status: "completed",
|
||||
title: `Inspected transfer path ${toolIndex + 1}`,
|
||||
detail: "Collected a deterministic multi-module transfer diagnostic.",
|
||||
data: {
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
completedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
item: {
|
||||
id: itemId,
|
||||
type: "commandExecution",
|
||||
command,
|
||||
cwd: "/workspace/transfer-budget",
|
||||
processId: String(toolIndex + 1),
|
||||
status: "completed",
|
||||
commandActions: [],
|
||||
aggregatedOutput: diagnosticOutput({
|
||||
provider,
|
||||
turnIndex,
|
||||
toolIndex,
|
||||
targetBytes: 1_000,
|
||||
}),
|
||||
exitCode: 0,
|
||||
durationMs: 500 + toolIndex,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const mcpItemId = `mcp-${turnIndex + 1}`;
|
||||
const mcpResultBytes = measuredTurn
|
||||
? TRANSFER_MEASURED_MCP_RESULT_BYTES
|
||||
: TRANSFER_HISTORY_MCP_RESULT_BYTES;
|
||||
events.push(
|
||||
{
|
||||
type: "item.started",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId: mcpItemId,
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
status: "inProgress",
|
||||
title: "fixture-history · inspect_transfer_log",
|
||||
detail: "Reading a retained diagnostic result from the provider history.",
|
||||
data: {
|
||||
startedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: mcpItemId,
|
||||
server: "fixture-history",
|
||||
tool: "inspect_transfer_log",
|
||||
arguments: { turn: turnIndex + 1 },
|
||||
status: "inProgress",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "item.completed",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId: mcpItemId,
|
||||
payload: {
|
||||
itemType: "mcp_tool_call",
|
||||
status: "completed",
|
||||
title: "fixture-history · inspect_transfer_log",
|
||||
detail: "Retained a deterministic diagnostic result in the thread history.",
|
||||
data: {
|
||||
completedAtMs: turnIndex * 60_000 + eventIndex,
|
||||
threadId: FIXTURE_THREAD_ID,
|
||||
turnId,
|
||||
item: {
|
||||
type: "mcpToolCall",
|
||||
id: mcpItemId,
|
||||
server: "fixture-history",
|
||||
tool: "inspect_transfer_log",
|
||||
arguments: { turn: turnIndex + 1 },
|
||||
durationMs: 1_000 + turnIndex,
|
||||
error: null,
|
||||
result: {
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: diagnosticOutput({
|
||||
provider,
|
||||
turnIndex,
|
||||
toolIndex: toolCount,
|
||||
targetBytes: mcpResultBytes,
|
||||
}),
|
||||
},
|
||||
],
|
||||
},
|
||||
status: "completed",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const chunks = assistantChunks(provider, turnIndex);
|
||||
for (const [contentIndex, delta] of chunks.entries()) {
|
||||
events.push({
|
||||
type: "content.delta",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
itemId: `assistant-${turnIndex + 1}`,
|
||||
payload: {
|
||||
streamKind: "assistant_text",
|
||||
delta,
|
||||
contentIndex,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
events.push(
|
||||
{
|
||||
type: "thread.token-usage.updated",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 18_000 + turnIndex * 1_900,
|
||||
maxTokens: 200_000,
|
||||
inputTokens: 15_000 + turnIndex * 1_700,
|
||||
cachedInputTokens: 9_000 + turnIndex * 1_100,
|
||||
outputTokens: 3_000 + turnIndex * 200,
|
||||
toolUses: toolCount,
|
||||
durationMs: 4_000 + turnIndex * 250,
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.diff.updated",
|
||||
...baseEvent(provider, turnIndex, eventIndex++),
|
||||
turnId,
|
||||
payload: {
|
||||
unifiedDiff: unifiedDiff(provider, turnIndex),
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "turn.completed",
|
||||
...baseEvent(provider, turnIndex, eventIndex),
|
||||
turnId,
|
||||
payload: {
|
||||
state: "completed",
|
||||
stopReason: "end_turn",
|
||||
usage: {
|
||||
inputTokens: 15_000 + turnIndex * 1_700,
|
||||
outputTokens: 3_000 + turnIndex * 200,
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return { events };
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Queue from "effect/Queue";
|
||||
import * as Ref from "effect/Ref";
|
||||
import * as Stream from "effect/Stream";
|
||||
|
||||
import { ProviderAdapterRegistry } from "../src/provider/Services/ProviderAdapterRegistry.ts";
|
||||
@@ -22,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";
|
||||
@@ -54,35 +56,59 @@ interface IntegrationFixture {
|
||||
readonly layer: Layer.Layer<ProviderService, unknown, never>;
|
||||
}
|
||||
|
||||
const makeIntegrationFixture = Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
interface RecordedAnalyticsEvent {
|
||||
readonly event: string;
|
||||
readonly properties: Readonly<Record<string, unknown>> | undefined;
|
||||
}
|
||||
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntime.layer),
|
||||
/**
|
||||
* Analytics layer that keeps captured events in memory so tests can assert on
|
||||
* telemetry payloads. `AnalyticsService.layerTest` discards them.
|
||||
*/
|
||||
const makeRecordingAnalytics = Effect.gen(function* () {
|
||||
const recorded = yield* Ref.make<ReadonlyArray<RecordedAnalyticsEvent>>([]);
|
||||
const layer = Layer.succeed(
|
||||
AnalyticsService,
|
||||
AnalyticsService.of({
|
||||
record: (event, properties) =>
|
||||
Ref.update(recorded, (current) => [...current, { event, properties }]),
|
||||
flush: Effect.void,
|
||||
}),
|
||||
);
|
||||
|
||||
const shared = Layer.mergeAll(
|
||||
directoryLayer,
|
||||
Layer.succeed(ProviderAdapterRegistry, registry),
|
||||
ServerSettingsService.layerTest(DEFAULT_SERVER_SETTINGS),
|
||||
AnalyticsService.layerTest,
|
||||
Layer.succeed(ProviderEventLoggers, NoOpProviderEventLoggers),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
|
||||
return {
|
||||
cwd,
|
||||
harness,
|
||||
layer,
|
||||
} satisfies IntegrationFixture;
|
||||
return { layer, get: Ref.get(recorded) } as const;
|
||||
});
|
||||
|
||||
const makeIntegrationFixture = (options?: { readonly analytics?: Layer.Layer<AnalyticsService> }) =>
|
||||
Effect.gen(function* () {
|
||||
const cwd = yield* makeWorkspaceDirectory;
|
||||
const harness = yield* makeTestProviderAdapterHarness();
|
||||
|
||||
const registry = makeAdapterRegistryMock({
|
||||
[ProviderDriverKind.make("codex")]: harness.adapter,
|
||||
});
|
||||
|
||||
const directoryLayer = ProviderSessionDirectoryLive.pipe(
|
||||
Layer.provide(ProviderSessionRuntime.layer),
|
||||
);
|
||||
|
||||
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),
|
||||
).pipe(Layer.provide(SqlitePersistenceMemory));
|
||||
|
||||
const layer = makeProviderServiceLive().pipe(Layer.provide(shared));
|
||||
|
||||
return {
|
||||
cwd,
|
||||
harness,
|
||||
layer,
|
||||
} satisfies IntegrationFixture;
|
||||
});
|
||||
|
||||
const collectEventsDuring = <A, E, R>(
|
||||
stream: Stream.Stream<ProviderRuntimeEvent>,
|
||||
count: number,
|
||||
@@ -126,7 +152,7 @@ const runTurn = (input: {
|
||||
|
||||
it.live("replays typed runtime fixture events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
@@ -161,7 +187,7 @@ it.live("replays typed runtime fixture events", () =>
|
||||
|
||||
it.live("replays file-changing fixture turn events", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -198,7 +224,7 @@ it.live("replays file-changing fixture turn events", () =>
|
||||
|
||||
it.live("runs multi-turn tool/approval flow", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -250,7 +276,7 @@ it.live("runs multi-turn tool/approval flow", () =>
|
||||
|
||||
it.live("rolls back provider conversation state only", () =>
|
||||
Effect.gen(function* () {
|
||||
const fixture = yield* makeIntegrationFixture;
|
||||
const fixture = yield* makeIntegrationFixture();
|
||||
const { join } = yield* Path.Path;
|
||||
const { writeFileString, readFileString } = yield* FileSystem.FileSystem;
|
||||
|
||||
@@ -302,3 +328,59 @@ it.live("rolls back provider conversation state only", () =>
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
|
||||
it.live("reports runtime mode per turn and on mode transitions", () =>
|
||||
Effect.gen(function* () {
|
||||
const analytics = yield* makeRecordingAnalytics;
|
||||
const fixture = yield* makeIntegrationFixture({ analytics: analytics.layer });
|
||||
const threadId = ThreadId.make("thread-integration-runtime-mode");
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const provider = yield* ProviderService;
|
||||
const startSession = (runtimeMode: "approval-required" | "full-access") =>
|
||||
provider.startSession(threadId, {
|
||||
threadId,
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
providerInstanceId: codexInstanceId,
|
||||
cwd: fixture.cwd,
|
||||
runtimeMode,
|
||||
});
|
||||
|
||||
yield* startSession("approval-required");
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId,
|
||||
userText: "supervised turn",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
|
||||
// Toggling the mode restarts the session, which is the only place the
|
||||
// transition is observable.
|
||||
yield* startSession("full-access");
|
||||
yield* runTurn({
|
||||
provider,
|
||||
harness: fixture.harness,
|
||||
threadId,
|
||||
userText: "full access turn",
|
||||
response: { events: codexTurnTextFixture },
|
||||
});
|
||||
|
||||
const recorded = yield* analytics.get;
|
||||
|
||||
assert.deepEqual(
|
||||
recorded
|
||||
.filter((entry) => entry.event === "provider.turn.sent")
|
||||
.map((entry) => entry.properties?.runtimeMode),
|
||||
["approval-required", "full-access"],
|
||||
);
|
||||
|
||||
assert.deepEqual(
|
||||
recorded
|
||||
.filter((entry) => entry.event === "provider.runtime_mode.changed")
|
||||
.map((entry) => [entry.properties?.from, entry.properties?.to]),
|
||||
[["approval-required", "full-access"]],
|
||||
);
|
||||
}).pipe(Effect.provide(fixture.layer));
|
||||
}).pipe(Effect.provide(NodeServices.layer)),
|
||||
);
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "t3",
|
||||
"version": "0.0.31",
|
||||
"version": "0.0.32",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { assert, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Path from "effect/Path";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
|
||||
import { runMigrations } from "../src/persistence/Migrations.ts";
|
||||
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
|
||||
import { runMigrateDevDb } from "./migrate-dev-db.ts";
|
||||
|
||||
const withDatabase = <A, E>(
|
||||
databasePath: string,
|
||||
effect: Effect.Effect<A, E, SqlClient.SqlClient>,
|
||||
) => effect.pipe(Effect.provide(NodeSqliteClient.layer({ filename: databasePath })));
|
||||
|
||||
/** A migrated source db with one thread per lifecycle state. Only
|
||||
* `stopped-thread` qualifies for the clone. */
|
||||
const createFixtureSource = Effect.fn("createMigrateDevDbFixtureSource")(function* (
|
||||
baseDir: string,
|
||||
) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const databasePath = path.join(stateDir, "state.sqlite");
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true });
|
||||
yield* withDatabase(
|
||||
databasePath,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* runMigrations();
|
||||
// The real shared db carries this column from a branch build without a
|
||||
// matching migration; reproduce that drift so the filter is exercised.
|
||||
yield* sql`ALTER TABLE projection_threads ADD COLUMN monitor_json TEXT`;
|
||||
|
||||
yield* sql`INSERT INTO projection_projects
|
||||
(project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at)
|
||||
VALUES
|
||||
('project-kept', 'Kept', '/tmp/kept', '[]', '2026-08-01', '2026-08-01', NULL),
|
||||
('project-deleted', 'Deleted', '/tmp/deleted', '[]', '2026-08-01', '2026-08-02', '2026-08-02')`;
|
||||
|
||||
const threads = [
|
||||
["stopped-thread", "project-kept", "stopped", null, null],
|
||||
["running-thread", "project-kept", "running", null, null],
|
||||
["settled-thread", "project-kept", "stopped", "2026-08-01", null],
|
||||
["monitored-thread", "project-kept", "stopped", null, '{"kind":"pr"}'],
|
||||
["deleted-project-thread", "project-deleted", "stopped", null, null],
|
||||
] as const;
|
||||
for (const [threadId, projectId, status, settledAt, monitorJson] of threads) {
|
||||
yield* sql`INSERT INTO projection_threads
|
||||
(thread_id, project_id, title, created_at, updated_at, settled_at, monitor_json)
|
||||
VALUES (${threadId}, ${projectId}, ${threadId}, '2026-08-01', '2026-08-01', ${settledAt}, ${monitorJson})`;
|
||||
yield* sql`INSERT INTO projection_thread_sessions (thread_id, status, updated_at)
|
||||
VALUES (${threadId}, ${status}, '2026-08-01')`;
|
||||
yield* sql`INSERT INTO orchestration_events
|
||||
(event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json)
|
||||
VALUES (${`event-${threadId}`}, 'thread', ${threadId}, 0, 'thread.created', '2026-08-01', 'user', '{}', '{}')`;
|
||||
}
|
||||
yield* sql`INSERT INTO auth_sessions (session_id, subject, scopes, method, issued_at, expires_at)
|
||||
VALUES ('session-1', 'user', '[]', 'pairing', '2026-08-01', '2027-08-01')`;
|
||||
}),
|
||||
);
|
||||
return databasePath;
|
||||
});
|
||||
|
||||
it.layer(NodeServices.layer)("migrate-dev-db", (it) => {
|
||||
it.effect("keeps only stopped threads from live projects and clears auth state", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-src-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-dest-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
|
||||
const result = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
);
|
||||
|
||||
assert.equal(result.databasePath, path.join(destDir, "userdata", "state.sqlite"));
|
||||
const kept = yield* withDatabase(
|
||||
result.databasePath,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const threads = yield* sql<{ thread_id: string }>`
|
||||
SELECT thread_id FROM projection_threads ORDER BY thread_id`;
|
||||
const events = yield* sql<{ stream_id: string }>`
|
||||
SELECT stream_id FROM orchestration_events`;
|
||||
const [auth] = yield* sql<{ count: number }>`
|
||||
SELECT COUNT(*) AS count FROM auth_sessions`;
|
||||
return { threads, events, authCount: auth?.count ?? 0 };
|
||||
}),
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
kept.threads.map((row) => row.thread_id),
|
||||
["stopped-thread"],
|
||||
);
|
||||
assert.deepStrictEqual(
|
||||
kept.events.map((row) => row.stream_id),
|
||||
["stopped-thread"],
|
||||
);
|
||||
assert.equal(kept.authCount, 0);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("fails loudly on a migration slot collision", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-slot-dest-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
// Simulate another branch having claimed slot 1 first: the id is
|
||||
// recorded, so this checkout's migration 1 silently never runs.
|
||||
yield* withDatabase(
|
||||
source,
|
||||
Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`UPDATE effect_sql_migrations
|
||||
SET name = 'SomebodyElsesMigration' WHERE migration_id = 1`;
|
||||
}),
|
||||
);
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbSlotCollisionError");
|
||||
if (error._tag === "MigrateDevDbSlotCollisionError") {
|
||||
assert.equal(error.slot, 1);
|
||||
assert.equal(error.appliedName, "SomebodyElsesMigration");
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses while a dev server holds the destination", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-busy-dest-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
// This test process stands in for a live dev server.
|
||||
const stateDir = path.join(destDir, "userdata");
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true });
|
||||
yield* fs.writeFileString(
|
||||
path.join(stateDir, "server-runtime.json"),
|
||||
`{"version":1,"pid":${process.pid}}`,
|
||||
);
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbServerRunningError");
|
||||
if (error._tag === "MigrateDevDbServerRunningError") {
|
||||
assert.equal(error.pid, process.pid);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses a source that resolves to a destination path", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const sharedDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-" });
|
||||
const destDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-overlap-dest-" });
|
||||
// A leftover snapshot from a prior failed run, passed as --source: it
|
||||
// must not be deleted before it is read.
|
||||
const leftoverSnapshot = path.join(destDir, "userdata", "state.sqlite.migrate-dev-db-tmp");
|
||||
yield* fs.makeDirectory(path.dirname(leftoverSnapshot), { recursive: true });
|
||||
yield* fs.writeFileString(leftoverSnapshot, "not a real db");
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: destDir, source: leftoverSnapshot, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sharedDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbSourceIsDestinationError");
|
||||
assert.equal(yield* fs.exists(leftoverSnapshot), true);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("refuses to rebuild the shared home", () =>
|
||||
Effect.gen(function* () {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const sourceDir = yield* fs.makeTempDirectoryScoped({ prefix: "migrate-dev-db-shared-" });
|
||||
const source = yield* createFixtureSource(sourceDir);
|
||||
|
||||
const error = yield* runMigrateDevDb(
|
||||
{ baseDir: sourceDir, source, projects: 5, threadsPerProject: 10 },
|
||||
{ sharedHome: sourceDir },
|
||||
).pipe(Effect.flip);
|
||||
assert.equal(error._tag, "MigrateDevDbSharedHomeError");
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,560 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Rebuild an isolated dev database from a pruned snapshot of the real
|
||||
* ~/.t3 database, then run this checkout's migrations against it.
|
||||
*
|
||||
* `vp run migrate-dev-db` from a worktree:
|
||||
* 1. Nukes `<worktree>/.t3/userdata/state.sqlite`.
|
||||
* 2. Snapshots the real db (read-only VACUUM INTO) and prunes it to the
|
||||
* most recently updated projects and, per project, the most recent
|
||||
* threads that have fully stopped. Working, settled, and monitored
|
||||
* threads are skipped so the dev server never adopts live work.
|
||||
* Auth sessions, pairing links, command receipts, and provider
|
||||
* runtime rows are dropped — pair a fresh browser against dev.
|
||||
* 3. Runs migrations on the result. Because the clone carries the real
|
||||
* `effect_sql_migrations` table, this proves a new migration applies
|
||||
* on top of the real applied set, and the slot check below catches
|
||||
* the silent failure where two branches claim the same
|
||||
* `Migrations/NNN_` id (the second one's CREATE TABLE is skipped).
|
||||
*
|
||||
* The event log (`orchestration_events`) is pruned per stream while
|
||||
* `sqlite_sequence` and `projection_state` carry over untouched, so new
|
||||
* events keep appending after the old high-water mark and projection
|
||||
* cursors never rewind.
|
||||
*/
|
||||
|
||||
// @effect-diagnostics nodeBuiltinImport:off - node:os resolves the shared T3 home guard.
|
||||
import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import * as NodeOS from "node:os";
|
||||
import { resolveWorktreeT3Home } from "@t3tools/shared/devHome";
|
||||
import * as Console from "effect/Console";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Option from "effect/Option";
|
||||
import * as Path from "effect/Path";
|
||||
import * as Schema from "effect/Schema";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
import { Command, Flag } from "effect/unstable/cli";
|
||||
|
||||
import { migrationManifest, runMigrations } from "../src/persistence/Migrations.ts";
|
||||
import * as NodeSqliteClient from "../src/persistence/NodeSqliteClient.ts";
|
||||
|
||||
export class MigrateDevDbNotInWorktreeError extends Schema.TaggedErrorClass<MigrateDevDbNotInWorktreeError>()(
|
||||
"MigrateDevDbNotInWorktreeError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Not inside a linked git worktree. Pass --base-dir to target an isolated .t3 directory.";
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbSharedHomeError extends Schema.TaggedErrorClass<MigrateDevDbSharedHomeError>()(
|
||||
"MigrateDevDbSharedHomeError",
|
||||
{},
|
||||
) {
|
||||
override get message(): string {
|
||||
return "Refusing to rebuild the shared ~/.t3 database. Use an isolated --base-dir.";
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbSourceMissingError extends Schema.TaggedErrorClass<MigrateDevDbSourceMissingError>()(
|
||||
"MigrateDevDbSourceMissingError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Source database does not exist at '${this.sourcePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbSourceIsDestinationError extends Schema.TaggedErrorClass<MigrateDevDbSourceIsDestinationError>()(
|
||||
"MigrateDevDbSourceIsDestinationError",
|
||||
{
|
||||
sourcePath: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Source database '${this.sourcePath}' resolves to a path this command rewrites. Pick a different --source or --base-dir.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbServerRunningError extends Schema.TaggedErrorClass<MigrateDevDbServerRunningError>()(
|
||||
"MigrateDevDbServerRunningError",
|
||||
{
|
||||
databasePath: Schema.String,
|
||||
pid: Schema.Number,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Dev database at '${this.databasePath}' is open by a running server (pid ${this.pid} per server-runtime.json). Stop that server first; if that pid is not actually a T3 server (stale descriptor, reused pid), delete the server-runtime.json next to the database and retry.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbDestinationBusyError extends Schema.TaggedErrorClass<MigrateDevDbDestinationBusyError>()(
|
||||
"MigrateDevDbDestinationBusyError",
|
||||
{
|
||||
databasePath: Schema.String,
|
||||
reason: Schema.Literals(["write-locked", "wal-held"]),
|
||||
cause: Schema.optional(Schema.Defect()),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
const detail =
|
||||
this.reason === "write-locked"
|
||||
? "the database is write-locked"
|
||||
: "another connection is holding its WAL";
|
||||
return `Dev database at '${this.databasePath}' looks in use (${detail}). Stop the dev server first; if none is running, delete the -wal/-shm files next to it.`;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Two branches claimed the same Migrations/NNN_ slot: the id was already
|
||||
* recorded under a different name, so this checkout's migration was
|
||||
* silently skipped and its schema changes never applied.
|
||||
*/
|
||||
export class MigrateDevDbSlotCollisionError extends Schema.TaggedErrorClass<MigrateDevDbSlotCollisionError>()(
|
||||
"MigrateDevDbSlotCollisionError",
|
||||
{
|
||||
slot: Schema.Number,
|
||||
codeName: Schema.String,
|
||||
appliedName: Schema.String,
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `Migration slot collision at ${this.slot}: this checkout registers '${this.codeName}' but the database already applied '${this.appliedName}' in that slot. Renumber the new migration to a free slot.`;
|
||||
}
|
||||
}
|
||||
|
||||
export class MigrateDevDbPhaseError extends Schema.TaggedErrorClass<MigrateDevDbPhaseError>()(
|
||||
"MigrateDevDbPhaseError",
|
||||
{
|
||||
phase: Schema.Literals(["snapshot", "prune", "compact", "migrate", "verify"]),
|
||||
databasePath: Schema.String,
|
||||
cause: Schema.Defect(),
|
||||
},
|
||||
) {
|
||||
override get message(): string {
|
||||
return `migrate-dev-db failed during ${this.phase} on '${this.databasePath}'.`;
|
||||
}
|
||||
}
|
||||
|
||||
export interface RunMigrateDevDbInput {
|
||||
/** Isolated .t3 directory. Defaults to `<worktree>/.t3` of the cwd. */
|
||||
readonly baseDir?: string | undefined;
|
||||
/** Source database. Defaults to `~/.t3/userdata/state.sqlite`. */
|
||||
readonly source?: string | undefined;
|
||||
readonly projects: number;
|
||||
readonly threadsPerProject: number;
|
||||
}
|
||||
|
||||
export interface RunMigrateDevDbOptions {
|
||||
/** Overridable for tests; the directory writes must never target. */
|
||||
readonly sharedHome?: string | undefined;
|
||||
}
|
||||
|
||||
interface KeptProject {
|
||||
readonly title: string;
|
||||
readonly threads: number;
|
||||
}
|
||||
|
||||
const removeDatabaseFiles = Effect.fn("removeDatabaseFiles")(function* (databasePath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
for (const suffix of ["", "-wal", "-shm"]) {
|
||||
yield* fs.remove(`${databasePath}${suffix}`).pipe(Effect.orElseSucceed(() => undefined));
|
||||
}
|
||||
});
|
||||
|
||||
/** The slice of server-runtime.json this script cares about. */
|
||||
const ServerRuntimeState = Schema.fromJsonString(Schema.Struct({ pid: Schema.Number }));
|
||||
const decodeServerRuntimeState = Schema.decodeEffect(ServerRuntimeState);
|
||||
|
||||
const isProcessAlive = (pid: number): boolean => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
// EPERM means the process exists but belongs to someone else.
|
||||
return (error as NodeJS.ErrnoException).code === "EPERM";
|
||||
}
|
||||
};
|
||||
|
||||
/** Liveness probe for a running dev server. The server writes its pid to
|
||||
* server-runtime.json next to the database, which also catches an idle
|
||||
* server holding an open-but-inactive connection. The SQL probes below back
|
||||
* that up: BEGIN IMMEDIATE fails while a writer is active, and
|
||||
* wal_checkpoint(TRUNCATE) reports busy while another connection holds the
|
||||
* WAL. A leftover -shm alone is not a signal — read-only connections cannot
|
||||
* clean it up on close. */
|
||||
const ensureNotInUse = Effect.fn("ensureDevDbNotInUse")(function* (databasePath: string) {
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const runtimeStatePath = path.join(path.dirname(databasePath), "server-runtime.json");
|
||||
const runtimeState = yield* fs.readFileString(runtimeStatePath).pipe(
|
||||
Effect.flatMap(decodeServerRuntimeState),
|
||||
// A missing or malformed descriptor is not a liveness signal.
|
||||
Effect.option,
|
||||
);
|
||||
if (Option.isSome(runtimeState) && isProcessAlive(runtimeState.value.pid)) {
|
||||
return yield* new MigrateDevDbServerRunningError({
|
||||
databasePath,
|
||||
pid: runtimeState.value.pid,
|
||||
});
|
||||
}
|
||||
|
||||
if (!(yield* fs.exists(databasePath))) {
|
||||
return;
|
||||
}
|
||||
const checkpoint = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql.unsafe("PRAGMA busy_timeout = 0").unprepared;
|
||||
yield* sql.unsafe("BEGIN IMMEDIATE").unprepared;
|
||||
yield* sql.unsafe("ROLLBACK").unprepared;
|
||||
return yield* sql.unsafe<{ busy: number }>("PRAGMA wal_checkpoint(TRUNCATE)").unprepared;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new MigrateDevDbDestinationBusyError({
|
||||
databasePath,
|
||||
reason: "write-locked",
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
if (checkpoint[0] !== undefined && Number(checkpoint[0].busy) !== 0) {
|
||||
return yield* new MigrateDevDbDestinationBusyError({
|
||||
databasePath,
|
||||
reason: "wal-held",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const pruneSnapshot = Effect.fn("pruneDevDbSnapshot")(function* (input: RunMigrateDevDbInput) {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
|
||||
// The shared db can carry monitor_json from a branch build even though no
|
||||
// migration in this checkout creates it, so filter it only when present.
|
||||
const threadColumns = yield* sql<{ name: string }>`
|
||||
SELECT name FROM pragma_table_info('projection_threads')`;
|
||||
const monitorFilter = threadColumns.some((column) => column.name === "monitor_json")
|
||||
? "AND t.monitor_json IS NULL"
|
||||
: "";
|
||||
|
||||
// "Stopped" is the persisted subset of the UI's thread status: the session
|
||||
// reached status 'stopped' and nothing marks the thread settled or
|
||||
// monitored. The in-memory working/monitoring liveness never persists, so
|
||||
// filtering the session status is sufficient.
|
||||
yield* sql.unsafe(`CREATE TEMP TABLE stopped_threads AS
|
||||
SELECT t.thread_id, t.project_id, t.updated_at
|
||||
FROM projection_threads t
|
||||
JOIN projection_thread_sessions s ON s.thread_id = t.thread_id
|
||||
WHERE t.deleted_at IS NULL
|
||||
AND t.archived_at IS NULL
|
||||
AND t.settled_at IS NULL
|
||||
AND (t.settled_override IS NULL OR t.settled_override <> 'settled')
|
||||
${monitorFilter}
|
||||
AND s.status = 'stopped'`).unprepared;
|
||||
|
||||
// Projects with clonable threads outrank empty-but-recent ones: the point
|
||||
// of the exercise is thread data, not the project list.
|
||||
yield* sql`CREATE TEMP TABLE kept_projects AS
|
||||
SELECT p.project_id
|
||||
FROM projection_projects p
|
||||
LEFT JOIN (
|
||||
SELECT project_id, MAX(updated_at) AS last_stopped_at
|
||||
FROM stopped_threads
|
||||
GROUP BY project_id
|
||||
) q ON q.project_id = p.project_id
|
||||
WHERE p.deleted_at IS NULL
|
||||
ORDER BY (q.last_stopped_at IS NULL) ASC,
|
||||
COALESCE(q.last_stopped_at, p.updated_at) DESC
|
||||
LIMIT ${input.projects}`;
|
||||
|
||||
yield* sql`CREATE TEMP TABLE kept_threads AS
|
||||
SELECT thread_id FROM (
|
||||
SELECT
|
||||
st.thread_id,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY st.project_id
|
||||
ORDER BY st.updated_at DESC
|
||||
) AS recency_rank
|
||||
FROM stopped_threads st
|
||||
JOIN kept_projects kp ON kp.project_id = st.project_id
|
||||
)
|
||||
WHERE recency_rank <= ${input.threadsPerProject}`;
|
||||
|
||||
yield* sql.withTransaction(
|
||||
Effect.gen(function* () {
|
||||
yield* sql`DELETE FROM projection_projects
|
||||
WHERE project_id NOT IN (SELECT project_id FROM kept_projects)`;
|
||||
yield* sql`DELETE FROM projection_threads
|
||||
WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`;
|
||||
for (const table of [
|
||||
"projection_thread_messages",
|
||||
"projection_thread_activities",
|
||||
"projection_thread_sessions",
|
||||
"projection_turns",
|
||||
"projection_pending_approvals",
|
||||
"projection_thread_proposed_plans",
|
||||
"checkpoint_diff_blobs",
|
||||
]) {
|
||||
yield* sql.unsafe(
|
||||
`DELETE FROM ${table} WHERE thread_id NOT IN (SELECT thread_id FROM kept_threads)`,
|
||||
).unprepared;
|
||||
}
|
||||
yield* sql`DELETE FROM orchestration_events
|
||||
WHERE (aggregate_kind = 'thread'
|
||||
AND stream_id NOT IN (SELECT thread_id FROM kept_threads))
|
||||
OR (aggregate_kind = 'project'
|
||||
AND stream_id NOT IN (SELECT project_id FROM kept_projects))`;
|
||||
yield* sql`DELETE FROM orchestration_command_receipts`;
|
||||
yield* sql`DELETE FROM provider_session_runtime`;
|
||||
yield* sql`DELETE FROM auth_sessions`;
|
||||
yield* sql`DELETE FROM auth_pairing_links`;
|
||||
}),
|
||||
);
|
||||
|
||||
const keptProjects = yield* sql<{ title: string; threads: number }>`
|
||||
SELECT
|
||||
p.title,
|
||||
(SELECT COUNT(*) FROM projection_threads t WHERE t.project_id = p.project_id) AS threads
|
||||
FROM projection_projects p
|
||||
ORDER BY p.updated_at DESC`;
|
||||
const [events] = yield* sql<{ count: number }>`
|
||||
SELECT COUNT(*) AS count FROM orchestration_events`;
|
||||
|
||||
return {
|
||||
projects: keptProjects as ReadonlyArray<KeptProject>,
|
||||
eventCount: events?.count ?? 0,
|
||||
};
|
||||
});
|
||||
|
||||
/** Compare this checkout's migration registry against what the cloned
|
||||
* database recorded: same slot under a different name means the migration
|
||||
* was skipped, not applied. */
|
||||
const verifyMigrationSlots = Effect.fn("verifyMigrationSlots")(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
const applied = yield* sql<{ migration_id: number; name: string }>`
|
||||
SELECT migration_id, name FROM effect_sql_migrations`;
|
||||
const appliedById = new Map(applied.map((row) => [Number(row.migration_id), row.name]));
|
||||
for (const [slot, codeName] of migrationManifest) {
|
||||
const appliedName = appliedById.get(slot);
|
||||
if (appliedName !== undefined && appliedName !== codeName) {
|
||||
return yield* new MigrateDevDbSlotCollisionError({ slot, codeName, appliedName });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export const runMigrateDevDb = Effect.fn("runMigrateDevDb")(function* (
|
||||
input: RunMigrateDevDbInput,
|
||||
options: RunMigrateDevDbOptions = {},
|
||||
) {
|
||||
// SQLite treats a negative LIMIT as "no limit", which would clone
|
||||
// everything. The CLI flags validate this too; this covers direct callers.
|
||||
if (input.projects < 1 || input.threadsPerProject < 0) {
|
||||
return yield* Effect.die("projects must be >= 1 and threadsPerProject >= 0");
|
||||
}
|
||||
const fs = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
|
||||
const sharedHome = path.resolve(options.sharedHome ?? path.join(NodeOS.homedir(), ".t3"));
|
||||
const sourcePath = path.resolve(
|
||||
input.source ?? path.join(sharedHome, "userdata", "state.sqlite"),
|
||||
);
|
||||
|
||||
const baseDir =
|
||||
input.baseDir !== undefined
|
||||
? path.resolve(input.baseDir)
|
||||
: yield* resolveWorktreeT3Home(process.cwd());
|
||||
if (baseDir === undefined) {
|
||||
return yield* new MigrateDevDbNotInWorktreeError();
|
||||
}
|
||||
const stateDir = path.join(baseDir, "userdata");
|
||||
const databasePath = path.join(stateDir, "state.sqlite");
|
||||
const snapshotPath = `${databasePath}.migrate-dev-db-tmp`;
|
||||
|
||||
if (!(yield* fs.exists(sourcePath))) {
|
||||
return yield* new MigrateDevDbSourceMissingError({ sourcePath });
|
||||
}
|
||||
const [canonicalBaseDir, canonicalSharedHome] = yield* Effect.all([
|
||||
fs.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)),
|
||||
fs.realPath(sharedHome).pipe(Effect.orElseSucceed(() => sharedHome)),
|
||||
]);
|
||||
if (canonicalBaseDir === canonicalSharedHome) {
|
||||
return yield* new MigrateDevDbSharedHomeError();
|
||||
}
|
||||
// The destination db and snapshot both get deleted below; a --source that
|
||||
// resolves to either (e.g. a leftover snapshot file) would be destroyed
|
||||
// before it is ever read.
|
||||
const canonicalSourcePath = yield* fs
|
||||
.realPath(sourcePath)
|
||||
.pipe(Effect.orElseSucceed(() => sourcePath));
|
||||
for (const destination of [databasePath, snapshotPath]) {
|
||||
const canonicalDestination = yield* fs
|
||||
.realPath(destination)
|
||||
.pipe(Effect.orElseSucceed(() => destination));
|
||||
if (canonicalSourcePath === canonicalDestination) {
|
||||
return yield* new MigrateDevDbSourceIsDestinationError({ sourcePath });
|
||||
}
|
||||
}
|
||||
|
||||
yield* fs.makeDirectory(stateDir, { recursive: true });
|
||||
yield* ensureNotInUse(databasePath);
|
||||
|
||||
const wrapPhase =
|
||||
(phase: MigrateDevDbPhaseError["phase"], phaseDatabasePath: string) =>
|
||||
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(
|
||||
Effect.mapError(
|
||||
(cause) => new MigrateDevDbPhaseError({ phase, databasePath: phaseDatabasePath, cause }),
|
||||
),
|
||||
);
|
||||
|
||||
yield* removeDatabaseFiles(snapshotPath);
|
||||
// The snapshot is a full-size copy of the source; make sure it is removed
|
||||
// even when a phase fails partway through.
|
||||
const { executedMigrations, pruned } = yield* Effect.gen(function* () {
|
||||
yield* Console.log(`Snapshotting ${sourcePath} (read-only)...`);
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`VACUUM INTO ${snapshotPath}`;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: sourcePath, readonly: true })),
|
||||
wrapPhase("snapshot", sourcePath),
|
||||
);
|
||||
|
||||
// Migrate before pruning: a source older than this checkout would
|
||||
// otherwise crash the prune queries on columns that don't exist yet.
|
||||
// Running against the full snapshot also exercises new migrations on the
|
||||
// same data volume the real database would face.
|
||||
yield* Console.log("Running migrations on the snapshot...");
|
||||
const executed = yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
// Mirror server boot (persistence/Layers/Sqlite.ts).
|
||||
yield* sql.unsafe("PRAGMA foreign_keys = ON").unprepared;
|
||||
return yield* runMigrations();
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
wrapPhase("migrate", snapshotPath),
|
||||
);
|
||||
|
||||
// Verify while the snapshot is still the only thing touched: a slot
|
||||
// collision must abort before the old worktree db gets replaced with a
|
||||
// schema whose colliding migration was silently skipped.
|
||||
yield* verifyMigrationSlots().pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
Effect.catchTags({
|
||||
SqlError: (cause) =>
|
||||
Effect.fail(
|
||||
new MigrateDevDbPhaseError({ phase: "verify", databasePath: snapshotPath, cause }),
|
||||
),
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Console.log(
|
||||
`Pruning to ${input.projects} projects, ${input.threadsPerProject} stopped threads each...`,
|
||||
);
|
||||
const result = yield* pruneSnapshot(input).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
wrapPhase("prune", snapshotPath),
|
||||
);
|
||||
|
||||
yield* Console.log(`Compacting into ${databasePath}...`);
|
||||
// Re-check right before the swap: a dev server started while the
|
||||
// snapshot was migrating and pruning must not lose its database.
|
||||
yield* ensureNotInUse(databasePath);
|
||||
yield* removeDatabaseFiles(databasePath);
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
yield* sql`VACUUM INTO ${databasePath}`;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: snapshotPath })),
|
||||
wrapPhase("compact", databasePath),
|
||||
);
|
||||
return { executedMigrations: executed, pruned: result };
|
||||
}).pipe(Effect.ensuring(removeDatabaseFiles(snapshotPath)));
|
||||
yield* fs.chmod(databasePath, 0o600);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
const sql = yield* SqlClient.SqlClient;
|
||||
// WAL does not survive VACUUM INTO; set it so first `vp run dev` finds
|
||||
// the database exactly as server boot would have left it.
|
||||
yield* sql.unsafe("PRAGMA journal_mode = WAL").unprepared;
|
||||
}).pipe(
|
||||
Effect.provide(NodeSqliteClient.layer({ filename: databasePath })),
|
||||
wrapPhase("compact", databasePath),
|
||||
);
|
||||
|
||||
const size = (yield* fs.stat(databasePath)).size;
|
||||
return {
|
||||
databasePath,
|
||||
sizeBytes: Number(size),
|
||||
projects: pruned.projects,
|
||||
eventCount: pruned.eventCount,
|
||||
executedMigrations: executedMigrations.map(([id, name]) => `${id}_${name}`),
|
||||
};
|
||||
});
|
||||
|
||||
const formatSize = (bytes: number): string =>
|
||||
bytes >= 1024 * 1024
|
||||
? `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
: `${(bytes / 1024).toFixed(0)} KB`;
|
||||
|
||||
export const migrateDevDbCommand = Command.make(
|
||||
"migrate-dev-db",
|
||||
{
|
||||
projects: Flag.integer("projects").pipe(
|
||||
Flag.withDefault(5),
|
||||
Flag.withDescription("How many recently updated projects to keep."),
|
||||
),
|
||||
threadsPerProject: Flag.integer("threads-per-project").pipe(
|
||||
Flag.withDefault(10),
|
||||
Flag.withDescription("How many recent stopped threads to keep per project."),
|
||||
),
|
||||
baseDir: Flag.string("base-dir").pipe(
|
||||
Flag.optional,
|
||||
Flag.withDescription("Isolated .t3 directory. Defaults to the current worktree's .t3."),
|
||||
),
|
||||
source: Flag.string("source").pipe(
|
||||
Flag.optional,
|
||||
Flag.withDescription("Source database. Defaults to ~/.t3/userdata/state.sqlite."),
|
||||
),
|
||||
},
|
||||
({ projects, threadsPerProject, baseDir, source }) =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* runMigrateDevDb({
|
||||
projects,
|
||||
threadsPerProject,
|
||||
baseDir: Option.getOrUndefined(baseDir),
|
||||
source: Option.getOrUndefined(source),
|
||||
});
|
||||
yield* Console.log("");
|
||||
yield* Console.log(
|
||||
`Dev database ready: ${result.databasePath} (${formatSize(result.sizeBytes)})`,
|
||||
);
|
||||
for (const project of result.projects) {
|
||||
yield* Console.log(` ${project.title}: ${project.threads} threads`);
|
||||
}
|
||||
yield* Console.log(` ${result.eventCount} orchestration events kept`);
|
||||
yield* Console.log(
|
||||
result.executedMigrations.length === 0
|
||||
? " Migrations: already current (no new migrations in this checkout)"
|
||||
: ` Migrations applied: ${result.executedMigrations.join(", ")}`,
|
||||
);
|
||||
}),
|
||||
).pipe(
|
||||
Command.withDescription(
|
||||
"Rebuild the worktree dev database from a pruned snapshot of the real ~/.t3 data, then run migrations.",
|
||||
),
|
||||
);
|
||||
|
||||
if (import.meta.main) {
|
||||
Command.run(migrateDevDbCommand, { version: "0.0.0" }).pipe(
|
||||
Effect.provide(NodeServices.layer),
|
||||
NodeRuntime.runMain,
|
||||
);
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { ThreadId } from "@t3tools/contracts";
|
||||
import { AssetPreviewTypeValidationError, ThreadId } from "@t3tools/contracts";
|
||||
import { PROJECT_FAVICON_FALLBACK_MARKER } from "@t3tools/shared/projectFavicon";
|
||||
import { describe, expect, it } from "@effect/vitest";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
@@ -225,6 +225,7 @@ describe("AssetAccess", () => {
|
||||
const faviconResult = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(faviconResult.sourcePath).toBe("favicon.svg");
|
||||
expect(faviconResult.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
expect(
|
||||
yield* issueAssetUrl({
|
||||
@@ -253,6 +254,7 @@ describe("AssetAccess", () => {
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
expect(fallbackResult.relativeUrl.endsWith(`/${PROJECT_FAVICON_FALLBACK_MARKER}`)).toBe(true);
|
||||
expect(fallbackResult.sourcePath).toBeUndefined();
|
||||
const fallbackSuffix = fallbackResult.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
|
||||
const fallbackSeparatorIndex = fallbackSuffix.indexOf("/");
|
||||
expect(
|
||||
@@ -264,6 +266,86 @@ describe("AssetAccess", () => {
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("issues project favicon capabilities for a saved override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-override-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "custom.svg"), "<svg />");
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>auto</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
projectFaviconPath: "brand/custom.svg",
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("brand/custom.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-custom\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("ignores a client favicon path hint", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-hint-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "hint.svg"), "<svg>hint</svg>");
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root, path: "brand/hint.svg" },
|
||||
projectFaviconPath: "brand/saved.svg",
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("brand/saved.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-saved\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("keeps automatic favicon resolution separate from a saved override", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-automatic-",
|
||||
});
|
||||
yield* fileSystem.makeDirectory(path.join(root, "brand"));
|
||||
yield* fileSystem.writeFileString(path.join(root, "brand", "saved.svg"), "<svg>saved</svg>");
|
||||
yield* fileSystem.writeFileString(path.join(root, "favicon.svg"), "<svg>automatic</svg>");
|
||||
|
||||
const result = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
});
|
||||
|
||||
expect(result.sourcePath).toBe("favicon.svg");
|
||||
expect(result.relativeUrl).toMatch(/\/v[0-9a-f]{64}-favicon\.svg$/);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("rejects a resolved project favicon with a non-image extension", () =>
|
||||
Effect.gen(function* () {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
const root = yield* fileSystem.makeTempDirectoryScoped({
|
||||
prefix: "t3-asset-favicon-type-",
|
||||
});
|
||||
yield* fileSystem.writeFileString(path.join(root, "secret.txt"), "not an image");
|
||||
|
||||
const error = yield* issueAssetUrl({
|
||||
resource: { _tag: "project-favicon", cwd: root },
|
||||
projectFaviconPath: "secret.txt",
|
||||
}).pipe(Effect.flip);
|
||||
|
||||
expect(error).toBeInstanceOf(AssetPreviewTypeValidationError);
|
||||
}).pipe(Effect.provide(testLayer)),
|
||||
);
|
||||
|
||||
it.effect("buckets project favicon expiry after content hashing", () =>
|
||||
Effect.gen(function* () {
|
||||
const crypto = yield* Crypto.Crypto;
|
||||
|
||||
@@ -169,6 +169,7 @@ const resolveCanonicalWorkspaceFileForRequest = (input: {
|
||||
export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (input: {
|
||||
readonly resource: AssetResource;
|
||||
readonly workspaceRoot?: string;
|
||||
readonly projectFaviconPath?: string;
|
||||
}) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
const path = yield* Path.Path;
|
||||
@@ -176,6 +177,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
let expiresAt = (yield* Clock.currentTimeMillis) + ASSET_TOKEN_TTL_MS;
|
||||
let claims: AssetClaims;
|
||||
let fileName: string;
|
||||
let sourcePath: string | undefined;
|
||||
|
||||
switch (input.resource._tag) {
|
||||
case "workspace-file": {
|
||||
@@ -287,16 +289,22 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
),
|
||||
);
|
||||
const faviconResolver = yield* ProjectFaviconResolver.ProjectFaviconResolver;
|
||||
const faviconPath = yield* faviconResolver.resolvePath(workspaceRoot).pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const faviconPath = yield* faviconResolver
|
||||
.resolvePath(workspaceRoot, input.projectFaviconPath ?? undefined)
|
||||
.pipe(
|
||||
Effect.mapError(
|
||||
(cause) =>
|
||||
new AssetProjectFaviconResolutionError({
|
||||
resource: input.resource,
|
||||
cause,
|
||||
}),
|
||||
),
|
||||
);
|
||||
const relativePath = faviconPath ? path.relative(workspaceRoot, faviconPath) : null;
|
||||
if (relativePath && !isWorkspaceImagePreviewPath(relativePath)) {
|
||||
return yield* new AssetPreviewTypeValidationError({ resource: input.resource });
|
||||
}
|
||||
sourcePath = relativePath ?? undefined;
|
||||
const canonicalFaviconPath = relativePath
|
||||
? yield* resolveCanonicalWorkspaceFile({ workspaceRoot, relativePath }).pipe(
|
||||
Effect.mapError(
|
||||
@@ -379,6 +387,7 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
|
||||
return {
|
||||
relativeUrl: `${ASSET_ROUTE_PREFIX}/${token}/${encodeURIComponent(fileName)}`,
|
||||
expiresAt,
|
||||
...(sourcePath !== undefined ? { sourcePath } : {}),
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -22,6 +22,7 @@ type WsRpcMethod = RpcGroup.Rpcs<typeof WsRpcGroup>["_tag"];
|
||||
*/
|
||||
export const RPC_REQUIRED_SCOPES = {
|
||||
[ORCHESTRATION_WS_METHODS.dispatchCommand]: AuthOrchestrationOperateScope,
|
||||
[ORCHESTRATION_WS_METHODS.getWorkflowScript]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getTurnDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope,
|
||||
[ORCHESTRATION_WS_METHODS.searchThreads]: AuthOrchestrationReadScope,
|
||||
@@ -44,6 +45,7 @@ export const RPC_REQUIRED_SCOPES = {
|
||||
[WS_METHODS.serverGetProcessResourceHistory]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverGetResourceTelemetryHistory]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverRetryResourceTelemetry]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverGetUsageSummary]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverSignalProcess]: AuthOrchestrationOperateScope,
|
||||
[WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope,
|
||||
[WS_METHODS.serverReportHostPowerState]: AuthOrchestrationOperateScope,
|
||||
|
||||
Loaded 100 of 627 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user