Compare commits

..
Author SHA1 Message Date
t3-code[bot] ee0d31d5e6 fix(web): make community theme updates explicit 2026-08-08 00:25:58 +00:00
t3-code[bot] dd8a0db88b fix(web): preserve community theme provenance 2026-08-08 00:25:58 +00:00
t3-code[bot] 62d130714d fix(web): keep community theme identity 2026-08-08 00:25:58 +00:00
t3-code[bot] af4383e893 fix(web): show active theme variants 2026-08-08 00:25:57 +00:00
t3-code[bot] a33718663d fix(web): preserve imported theme metadata 2026-08-08 00:25:57 +00:00
t3-code[bot] 59e1bd230c fix(web): harden community theme workflows 2026-08-08 00:25:57 +00:00
t3-code[bot] bd9e3f953d feat(web): group imported theme variants 2026-08-08 00:25:57 +00:00
t3-code[bot] 7bcd756fc5 fix(web): filter unavailable theme packages 2026-08-08 00:25:57 +00:00
t3-code[bot] 4b78960aff fix(web): harden open vsx theme imports 2026-08-08 00:25:57 +00:00
t3-code[bot] 784493f144 feat(web): integrate theme search with import 2026-08-08 00:25:57 +00:00
t3-code[bot] d11283bac6 fix(web): bound imported theme objects 2026-08-08 00:25:57 +00:00
t3-code[bot] 8779f184bb fix(web): surface malformed theme details 2026-08-08 00:25:57 +00:00
t3-code[bot] 4e5bafcff7 fix(web): address open vsx review findings 2026-08-08 00:25:57 +00:00
t3-code[bot] 64490d4c65 fix(web): harden open vsx responses 2026-08-08 00:25:57 +00:00
t3-code[bot] d1d74f1397 feat(web): add open vsx theme search 2026-08-08 00:25:57 +00:00
Theo BrowneandClaude Fable 5 31891a1a0c feat(web): fold plan mode and token-by-token output into Legacy features (#5664)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 17:17:44 -07:00
Illia Panasenko 45d9aa90ba fix(web): show Stop button while input is pending (#5554) 2026-08-07 17:03:52 -04:00
Henry Zhang 7a84f6cf10 fix(web): reconnect the composer seam for remote non-Git projects (#5633) 2026-08-07 17:03:31 -04:00
maria f0fb406acf feat(web): make sidebar artwork theme-aware (#5636) 2026-08-07 15:41:59 -04:00
t3-code[bot] 82406bce99 chore: vouch chrisdeeming (#5641)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 15:01:39 -04:00
Chris Deeming 72d673a855 feat(desktop): remember recently used sites in the Browser panel (#5270) 2026-08-07 14:45:56 -04:00
t3-code[bot] e2cd2383ce chore(ci): vouch StiensWout (#5637)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-07 14:29:50 -04:00
Theo BrowneandClaude Fable 5 5661c6116c feat(web): drag pinned threads into your own order (#5581)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 06:57:22 -07:00
Theo BrowneandClaude Opus 5 6d70e6d778 fix(mobile): reconnects no longer shift the thread list (#5372)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 06:21:04 -07:00
t3-code[bot] be1a836745 chore(release): prepare v0.0.32 2026-08-07 11:50:54 +00:00
Utkarsh Patil 239ef1c54d fix(web): show the correctly matching shortcut in new thread button's tooltip (#5594) 2026-08-07 12:54:36 +02:00
Utkarsh Patil 61b51ae0e3 feat(web): click the pin icon to unpin a thread (#5578) 2026-08-07 12:54:11 +02:00
Julius Marminge bfc69e4b4d Bump mobile app version to 1.0.2 (#5588) 2026-08-07 12:35:07 +02:00
Gabriel De Andradeandcodex af281c9fc4 fix(mobile): repair Clerk auth navigation headers (#5140)
Co-authored-by: codex <[email protected]>
2026-08-07 12:29:06 +02:00
Pavlo Trinko bd422fd8d1 fix(mobile): keep Android chat text from showing through the composer (#5582) 2026-08-07 10:22:49 +00:00
Tyler Saari 33a03c8a7b fix(mobile): pad scroll views above Android nav bar (#5415) 2026-08-07 10:21:31 +00:00
Justyn Leung a17459e8a9 fix(mobile): avoid iOS terminal reset on clear (#5440) 2026-08-07 10:20:15 +00:00
Theo BrowneandClaude Fable 5 b2ee17d7c1 feat(web): thread actions from the chat header title (#5592)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 10:18:12 +00:00
Theo BrowneandClaude Opus 5 7963cc70f3 feat(server): record runtime mode per turn and on mode changes (#5593)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 03:16:11 -07:00
Jay Meistrichandcodex b792ed9f7b fix(web): stabilize chat timeline positioning (#5449)
Co-authored-by: codex <[email protected]>
2026-08-07 12:12:19 +02:00
Theo BrowneandClaude Fable 5 2e66b1fdfc fix(web): live background-work banner no longer hides behind the update notice (#5595)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 10:10:36 +00:00
Jay Meistrich 8100062a78 fix(mobile): improve keyboard avoiding (#5451) 2026-08-07 09:40:06 +00:00
Theo BrowneandClaude Fable 5 a1762fdd74 fix(dev): Improve instructions for --share (#5586)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 09:28:51 +00:00
Theo BrowneandClaude Fable 5 388b43a27c perf(dev): faster cold-start for dev web serving (#5584)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 02:28:00 -07:00
Theo BrowneandClaude Fable 5 23f0a1ae38 fix(web): reading a thread clears Done; Woke is dismissible (#5579)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 02:09:16 -07:00
85b1734d4d feat(web): add modular theme library (#5226)
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: maria-rcks <[email protected]>
Co-authored-by: Julius Marminge <[email protected]>
2026-08-07 10:37:43 +02:00
Theo BrowneandClaude Opus 5 3ffe84f968 fix(web): stop the sidebar "Working" label from pulsing (#5580)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 01:27:31 -07:00
Mateleo 220efad62b fix: add missing space before 'GitHub releases page' link on download page (#4511) 2026-08-07 01:21:18 -07:00
Theo BrowneandClaude Fable 5 b98a0f0d22 fix(mobile): invisible T3 Connect devices can now be seen and removed (#5563)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 00:58:26 -07:00
Theo BrowneandClaude Opus 5 95305c36fa feat(web): per-device provider settings (#4479)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-07 00:57:22 -07:00
Theo BrowneandClaude Fable 5 48aa875c0e feat(web): remove Build/Plan toggle from the composer (#5551)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 00:42:50 -07:00
Theo BrowneandClaude Fable 5 a8cd2ad2eb fix(web): plans stop hijacking the UI, fold into chat instead (#5558)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-07 00:16:14 -07:00
Theo BrowneandClaude Fable 5 4a07c1ca9d docs: ship production T3 Connect public config in .env.example (#5573)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 23:53:19 -07:00
Theo Browne cf5c9948c8 fix(web): keep agent panel rows stable (#5569) 2026-08-06 23:19:20 -07:00
Theo BrowneandClaude Opus 5 2288d416aa fix(web): stop the "requests are slow" warning from firing on every provider update (#5570)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-06 23:18:34 -07:00
Theo Browne ddfe45c66e test(server): catch client transfer regressions in CI (#5350) 2026-08-06 23:17:49 -07:00
Theo BrowneandClaude 9547cf2463 fix(server): one disconnecting client no longer blocks every reconnect (#5572)
Co-authored-by: Claude <[email protected]>
2026-08-06 23:15:40 -07:00
Theo BrowneandClaude Fable 5 1c7d059f55 fix: scrolling up during a running thread no longer snaps back to the bottom (#5566)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 21:32:01 -07:00
Theo Browne 6fa4576078 fix(server): settle stopped Claude subagents (#5568) 2026-08-06 21:15:59 -07:00
ae7b27de82 fix: prevent reconnect loops during server stalls (#5561)
Co-authored-by: t3-turbo-simulation <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
2026-08-06 21:14:50 -07:00
Theo BrowneandClaude Fable 5 6b73b3defe feat: paginate thread loading with user-anchored turn windows (#5493)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 19:33:49 -07:00
Theo Browne 7aad7911f6 fix(server): let stopped threads settle immediately (#5553) 2026-08-06 18:43:13 -07:00
Theo Browne 6da92244cc fix(web): show one toast when snoozing threads in bulk (#5560) 2026-08-06 18:16:36 -07:00
Theo BrowneandClaude Fable 5 c471145e96 fix(server): stopping a Claude thread no longer shows an ede_diagnostic error (#5557)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:55:20 -07:00
Theo Browne 64a991ad45 fix(web): show remote environment for non-Git projects (#5555) 2026-08-06 17:55:00 -07:00
Theo BrowneandClaude Fable 5 0ec4fbc4a3 fix(server): stop showing commit/push/PR notices as errors in the work log (#5559)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:52:29 -07:00
Theo BrowneandClaude Fable 5 ea50b695a7 fix(web): update tooltip no longer dismisses when scrolling release notes (#5547)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 17:31:12 -07:00
Theo BrowneandClaude Fable 5 331c6dce7f fix(server): skip origin fetch when creating worktrees in repos without an origin remote (#5556)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 20:13:10 -04:00
Wout Stiens 4f5834ba72 fix(web): clear woke state on explicit thread actions (#5486) 2026-08-06 14:08:35 -04:00
Wout Stiens aa16c180e5 fix(web): align composer inline chips with prompt text (#5495) 2026-08-06 12:57:02 -04:00
Carlos Rico-OspinaandClaude Opus 5 470d4eb993 fix(mobile): stop thread messages reading through pending cards (#5450)
Co-authored-by: Claude Opus 5 <[email protected]>
2026-08-06 12:56:01 -04:00
t3-code[bot] 99d91ddaa4 fix(acp): keep unknown approvals actionable (#5430)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:31 -04:00
t3-code[bot] ab3b55e29a fix(web): clarify auto permission fallback (#5431)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-06 12:55:00 -04:00
Theo BrowneandClaude Fable 5 e4abc31f1e docs(server): pin interleaved-collapse divergence as intentional with test
Bugbot flagged that clients collapse only adjacent lifecycle rows, so
dropping a superseded update separated by an interleaved parallel call
diverges from full-history rendering. Measured on a real database: 1.5%
of dropped rows (553/36,581), all pure in-flight state whose final result
the retained completion still shows, and zero dropped rows carry a
client-merged payload field their completion lacks (verified across all
49,515 update rows). Documents the tradeoff and adds a test pinning it.

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

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

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

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

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

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

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-08-06 08:09:51 -04:00
Hugo Blom a483337a02 fix: respect time format for sidebar snooze (#4438) 2026-08-06 11:40:58 +02:00
Theo BrowneandClaude Fable 5 1ffba7093a fix(web): closed plan sidebar stays closed when returning to a thread (#5484)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:37:27 -07:00
Theo BrowneandClaude Fable 5 3da315e7b5 perf(server): stop shipping full MCP tool results in thread payloads (#5482)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 02:34:27 -07:00
Theo BrowneandClaude Fable 5 a2ca89aa10 feat: native subagent & workflow observability (#5219)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-06 00:32:28 -04:00
Theo BrowneandClaude Fable 5 990bb0b689 fix: reconnect faster after remote server updates (#5404)
Co-authored-by: Claude Fable 5 <[email protected]>
2026-08-05 19:12:52 -07:00
Julius Marminge 7251f1a1f1 Prevent terminal loading flash (#5432) 2026-08-05 23:09:23 +02:00
t3-code[bot] 30e471530b fix(web): preserve terminal font size when splitting (#5444)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
2026-08-05 17:02:53 -04:00
Julius Marminge de592a00e8 Enrich terminal font previews (#5428) 2026-08-05 16:03:10 +00:00
Wout Stiens 2a04db134c fix(web): keep terminal font settings reliable (#5397) 2026-08-05 13:42:56 +02:00
Theo Browne 37d3667de4 fix(web): keep model picker shortcuts in sync (#5400) 2026-08-05 04:23:18 -07:00
326 changed files with 33104 additions and 4210 deletions

No files matched your search

+4 -15
View File
@@ -40,7 +40,7 @@ Treat the overall testing or implementation loop—not an assistant turn or one
- Do not stop the server merely because one verification pass completed or because you are yielding a response to the user.
- Before starting another environment, check whether the existing process and browser tab still serve the task. Reuse them when healthy instead of discarding useful state.
- On a later turn, verify that the existing process is alive and reuse its printed ports and base directory. If it exited, restart with the same base directory; create a new pairing token only when the browser session is no longer valid.
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Never include a pairing token.
- Tell the user when a test environment remains available, including its non-secret web URL when useful. Include a pairing token only when the user still needs to pair (see below).
## Authenticate the browser on the first navigation
@@ -50,24 +50,13 @@ Treat the overall testing or implementation loop—not an assistant turn or one
4. Wait for the pairing exchange and redirect to finish before navigating elsewhere.
5. Continue in the same browser context so its stored bearer session remains available.
Treat pairing URLs as secrets. Do not copy them into final responses, screenshots, committed files, or durable logs. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it.
Keep pairing URLs out of screenshots, committed files, and durable logs. When the user asked for a shared environment, the deliverable IS the full pairing URL — paste it in your reply, token and all; a bare origin is useless to them. A pairing token is short-lived and single-use; opening the URL in another browser or opening it twice can consume it, so never open a URL you handed to the user.
## Recover a consumed or expired pairing token
Create another token against the same database and web URL as the running dev server:
Run `node apps/server/src/bin.ts pair` from the repository root. It discovers the running dev server (worktree `.t3` first, same precedence as the dev runner) and prints a fresh `Pair URL` against the server's current web origin, including a `--share` tailnet origin. Pass `--base-dir <base-dir>` only when the server was started with `--home-dir`, using the identical path.
```bash
T3CODE_PORT=<server-port> node apps/server/src/bin.ts auth pairing create \
--base-dir <base-dir> \
--dev-url <web-url> \
--base-url <web-url> \
--ttl 15m \
--label agent-ui-test
```
Use the `Pair URL` from this command once. Derive `<server-port>` and `<web-url>` from the current dev-runner output, including any automatically selected port offset. Setting `T3CODE_PORT` keeps the administrative CLI from probing for an unrelated free port.
Always pass `--dev-url` for a dev-runner environment so the generated pairing URL uses the current web origin. An explicit base directory stores runtime state in `<base-dir>/userdata`; the `<base-dir>/dev` fallback is only used by an implicit dev home. A worktree-local `.t3` counts as explicit, so its state lives in `<worktree>/.t3/userdata`. Use `auth pairing list` to inspect active token metadata; it intentionally cannot reveal token secrets.
Tokens from `pair` carry standard client scopes. The startup pairing URL carries admin scopes; if the user needs Settings → Connections management (`access:write`), restart the server and hand over the new startup URL instead.
## Inspect or seed SQLite state
+12 -9
View File
@@ -1,12 +1,14 @@
# Optional: T3 Connect source builds
# Leave these unset to disable optional T3 Connect features in local source builds.
# Release builds inject their public values at build time. Do not add server-side
# secrets to this file.
# `cp .env.example .env` enables T3 Connect against the production deployment.
# These are the same public identifiers baked into official release builds, not
# secrets. Remove or comment them out to build with cloud features disabled.
# Do not add server-side secrets to this file.
# Get these from the Clerk Dashboard under API keys, JWT templates, and OAuth applications.
# T3CODE_CLERK_PUBLISHABLE_KEY=pk_test_...
# T3CODE_CLERK_JWT_TEMPLATE=t3-relay
# T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=oauthapp_...
# Production Clerk instance. To use your own, get these from the Clerk Dashboard
# under API keys, JWT templates, and OAuth applications.
T3CODE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsudDMuY29kZXMk
T3CODE_CLERK_JWT_TEMPLATE=t3-relay
T3CODE_CLERK_CLI_OAUTH_CLIENT_ID=hzxSgY2cH10sDU2r
# Optional: signed macOS passkey builds. The RP domain defaults to the Frontend API
# hostname encoded in T3CODE_CLERK_PUBLISHABLE_KEY. Set the override only when Clerk
@@ -15,8 +17,9 @@
# T3CODE_MACOS_PROVISIONING_PROFILE=/absolute/path/to/t3code.provisionprofile
# T3CODE_CLERK_PASSKEY_RP_DOMAINS=example.clerk.accounts.dev,clerk.example.com
# Get this from your relay deployment. `infra/relay` deploys update it automatically.
# T3CODE_RELAY_URL=https://relay.example.com
# Production relay. For a self-hosted relay, `infra/relay` deploys update it
# automatically.
T3CODE_RELAY_URL=https://relay.t3.codes
# Optional: hosted app origin used by the CLI's out-of-band OAuth flow.
# Defaults to https://app.t3.codes; override to test against a staging deployment.
+2
View File
@@ -11,6 +11,7 @@
# Keep entries sorted alphabetically.
github:adityavardhansharma
github:binbandit
github:chrisdeeming
github:chuks-qua
github:cursoragent
github:gbarros-dev
@@ -26,6 +27,7 @@ github:notkainoa
github:PatrickBauer
github:realAhmedRoach
github:shiroyasha9
github:StiensWout
github:Yash-Singh1
github:eggfriedrice24
github:Ymit24
+429
View File
@@ -0,0 +1,429 @@
const fs = require("node:fs");
const path = require("node:path");
const ARTIFACT_NAME = "thread-transfer-results";
const RESULT_FILE = "thread-transfer-result.json";
const COMMENT_MARKER = "<!-- t3-thread-transfer-report -->";
const PROVIDERS = ["codex", "claudeAgent"];
const OBSERVED_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"threadSnapshotDecodedBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const CEILING_KEYS = [
"totalWireBytes",
"threadSnapshotWireBytes",
"measuredTurnWebSocketWireBytes",
"measuredTurnWebSocketDecodedBytes",
"measuredTurnWebSocketMessages",
];
const SCENARIO_KEYS = [
"id",
"historyTurns",
"historyCommandToolsPerTurn",
"historyMcpResultBytes",
"measuredCommandTools",
"measuredMcpResultBytes",
];
function resultShaMarker(sha) {
return `<!-- t3-thread-transfer-result-sha:${sha} -->`;
}
function assertObject(value, label) {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
throw new Error(`${label} must be an object`);
}
}
function assertExactKeys(value, expected, label) {
assertObject(value, label);
const actual = Object.keys(value).sort();
const wanted = [...expected].sort();
if (actual.length !== wanted.length || actual.some((key, index) => key !== wanted[index])) {
throw new Error(`${label} has unexpected fields`);
}
}
function assertMetric(value, label) {
if (!Number.isSafeInteger(value) || value < 0 || value > 1_000_000_000) {
throw new Error(`${label} must be a non-negative safe integer below 1,000,000,000`);
}
}
function validateResult(value) {
assertExactKeys(value, ["schemaVersion", "scenario", "providers"], "result");
if (value.schemaVersion !== 1) {
throw new Error("result.schemaVersion must be 1");
}
assertExactKeys(value.scenario, SCENARIO_KEYS, "result.scenario");
if (value.scenario.id !== "thread-transfer-v1") {
throw new Error("result.scenario.id is not supported");
}
for (const key of SCENARIO_KEYS.slice(1)) {
assertMetric(value.scenario[key], `result.scenario.${key}`);
}
assertExactKeys(value.providers, PROVIDERS, "result.providers");
for (const provider of PROVIDERS) {
const entry = value.providers[provider];
assertExactKeys(entry, ["observed", "ceiling"], `result.providers.${provider}`);
assertExactKeys(entry.observed, OBSERVED_KEYS, `result.providers.${provider}.observed`);
assertExactKeys(entry.ceiling, CEILING_KEYS, `result.providers.${provider}.ceiling`);
for (const key of OBSERVED_KEYS) {
assertMetric(entry.observed[key], `result.providers.${provider}.observed.${key}`);
}
for (const key of CEILING_KEYS) {
assertMetric(entry.ceiling[key], `result.providers.${provider}.ceiling.${key}`);
}
}
return value;
}
function readResult(directory) {
if (!directory) return undefined;
const file = path.join(directory, RESULT_FILE);
if (!fs.existsSync(file)) return undefined;
const stat = fs.lstatSync(file);
if (!stat.isFile() || stat.size > 64 * 1_024) {
throw new Error("thread transfer result must be a regular file smaller than 64 KiB");
}
return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
}
function formatBytes(bytes) {
if (bytes < 1_024) return `${bytes} B`;
if (bytes >= 1_024 * 1_024) return `${(bytes / 1_024 / 1_024).toFixed(2)} MiB`;
return `${(bytes / 1_024).toFixed(1)} KiB`;
}
function formatValue(value, kind) {
return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
}
function formatImpact(current, baseline, kind) {
if (baseline === undefined) return "—";
const delta = current - baseline;
const prefix = delta > 0 ? "+" : delta < 0 ? "−" : "";
const magnitude = formatValue(Math.abs(delta), kind);
const percent =
baseline === 0 ? "" : ` (${prefix}${Math.abs((delta / baseline) * 100).toFixed(1)}%)`;
return `${prefix}${magnitude}${percent}`;
}
function sameScenario(left, right) {
return SCENARIO_KEYS.every((key) => left[key] === right[key]);
}
const METRICS = [
{ key: "totalWireBytes", label: "Total thread wire", kind: "bytes" },
{ key: "threadSnapshotWireBytes", label: "Thread snapshot wire", kind: "bytes" },
{
key: "measuredTurnWebSocketWireBytes",
label: "Live turn WebSocket wire",
kind: "bytes",
},
{
key: "measuredTurnWebSocketDecodedBytes",
label: "Live turn WebSocket decoded",
kind: "bytes",
},
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
];
function renderComment(input) {
const current = input.current;
const baseline = input.baseline;
const comparable = baseline !== undefined && sameScenario(current.scenario, baseline.scenario);
const rows = [];
const ceilingChanges = [];
let failed = false;
for (const provider of PROVIDERS) {
for (const metric of METRICS) {
const observed = current.providers[provider].observed[metric.key];
const ceiling = current.providers[provider].ceiling[metric.key];
const baselineObserved = comparable
? baseline.providers[provider].observed[metric.key]
: undefined;
const pass = observed <= ceiling;
failed ||= !pass;
rows.push(
`| ${provider === "codex" ? "Codex" : "Claude"} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
);
if (baseline && baseline.providers[provider].ceiling[metric.key] !== ceiling) {
ceilingChanges.push(
`- ${provider === "codex" ? "Codex" : "Claude"} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
);
}
}
}
const baselineLink = input.baselineRun
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
: "unavailable";
const currentLink = `[\`${input.currentRun.sha.slice(0, 7)}\`](${input.currentRun.url})`;
const notices = [];
if (!baseline) {
notices.push(
"> ℹ️ No successful `main` baseline artifact is available yet. This run establishes the initial measurement.",
);
} else if (!comparable) {
notices.push(
"> ⚠️ The thread fixture changed, so impact percentages are not directly comparable to the `main` baseline.",
);
} else if (!input.baselineRun.matchesBase) {
notices.push(
"> ℹ️ The exact PR base did not have a successful artifact. Baseline uses the latest successful `main` measurement shown below.",
);
}
if (ceilingChanges.length > 0) {
notices.push(
`> ⚠️ **This PR changes transfer ceilings:**\n>\n${ceilingChanges.map((line) => `> ${line}`).join("\n")}`,
);
}
return [
COMMENT_MARKER,
resultShaMarker(input.currentRun.sha),
"## Thread transfer impact",
"",
failed
? "❌ One or more thread transfer ceilings were exceeded."
: "✅ Thread transfer remains within every enforced ceiling.",
...(notices.length > 0 ? ["", ...notices] : []),
"",
"| Provider | Metric | Main baseline | This PR | Impact | PR ceiling | |",
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
...rows,
"",
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
"",
"<details>",
"<summary>Scenario and decoded snapshot size</summary>",
"",
`${current.scenario.historyTurns} historical turns, ${current.scenario.historyCommandToolsPerTurn} command tools per turn, ${formatBytes(current.scenario.historyMcpResultBytes)} retained MCP result per historical turn, and a ${formatBytes(current.scenario.measuredMcpResultBytes)} retained result in the measured turn.`,
"",
...PROVIDERS.map(
(provider) =>
`- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
),
"",
"</details>",
"",
"_Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed._",
].join("\n");
}
async function artifactsForRun(github, owner, repo, runId) {
return github.paginate(github.rest.actions.listWorkflowRunArtifacts, {
owner,
repo,
run_id: runId,
per_page: 100,
});
}
function findResultArtifact(artifacts) {
return artifacts.find((artifact) => artifact.name === ARTIFACT_NAME && !artifact.expired);
}
async function resolve({ github, context, core }) {
const source = context.payload.workflow_run;
const { owner, repo } = context.repo;
if (source.event !== "pull_request") {
core.setOutput("publish", "false");
return;
}
let pullNumber = source.pull_requests?.[0]?.number;
if (!pullNumber) {
const associated = await github.paginate(
github.rest.repos.listPullRequestsAssociatedWithCommit,
{ owner, repo, commit_sha: source.head_sha, per_page: 100 },
);
const matchingPulls = associated.filter(
(pull) =>
pull.state === "open" &&
pull.head.sha === source.head_sha &&
pull.head.ref === source.head_branch,
);
if (matchingPulls.length !== 1) {
core.info(
`Expected one open pull request for ${source.head_repository?.full_name ?? "unknown repository"}:${source.head_branch ?? "unknown branch"} at ${source.head_sha}; found ${matchingPulls.length}.`,
);
core.setOutput("publish", "false");
return;
}
pullNumber = matchingPulls[0].number;
}
if (!pullNumber) {
core.info("No open pull request is associated with the completed CI run.");
core.setOutput("publish", "false");
return;
}
const { data: pull } = await github.rest.pulls.get({ owner, repo, pull_number: pullNumber });
if (pull.head.sha !== source.head_sha) {
core.info(`Skipping stale CI result ${source.head_sha}; PR head is ${pull.head.sha}.`);
core.setOutput("publish", "false");
return;
}
const sourceArtifacts = await artifactsForRun(github, owner, repo, source.id);
const sourceArtifact = findResultArtifact(sourceArtifacts);
const workflowRuns = await github.paginate(github.rest.actions.listWorkflowRuns, {
owner,
repo,
workflow_id: source.workflow_id,
branch: pull.base.ref,
event: "push",
status: "success",
per_page: 100,
});
const orderedRuns = [
...workflowRuns.filter((run) => run.head_sha === pull.base.sha),
...workflowRuns.filter((run) => run.head_sha !== pull.base.sha),
].slice(0, 20);
let baselineRun;
for (const run of orderedRuns) {
const artifacts = await artifactsForRun(github, owner, repo, run.id);
if (findResultArtifact(artifacts)) {
baselineRun = run;
break;
}
}
core.setOutput("publish", "true");
core.setOutput("pull_number", String(pullNumber));
core.setOutput("pr_artifact", sourceArtifact ? "true" : "false");
core.setOutput("pr_run_id", String(source.id));
core.setOutput("pr_sha", source.head_sha);
core.setOutput("pr_conclusion", source.conclusion ?? "unknown");
core.setOutput("baseline_artifact", baselineRun ? "true" : "false");
core.setOutput("baseline_run_id", baselineRun ? String(baselineRun.id) : "");
core.setOutput("baseline_sha", baselineRun?.head_sha ?? "");
core.setOutput(
"baseline_matches_base",
baselineRun?.head_sha === pull.base.sha ? "true" : "false",
);
}
async function upsertComment(github, context, pullNumber, body, options = {}) {
const { owner, repo } = context.repo;
const comments = await github.paginate(github.rest.issues.listComments, {
owner,
repo,
issue_number: pullNumber,
per_page: 100,
});
const existing = comments.find(
(comment) =>
comment.user?.login === "github-actions[bot]" && comment.body?.includes(COMMENT_MARKER),
);
if (
options.preserveResultSha &&
existing?.body?.includes(resultShaMarker(options.preserveResultSha))
) {
return;
}
if (existing) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: pullNumber, body });
}
}
async function upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
expectedSha,
body,
options,
) {
const { owner, repo } = context.repo;
const { data: pull } = await github.rest.pulls.get({
owner,
repo,
pull_number: pullNumber,
});
if (pull.head.sha !== expectedSha) {
core.info(`Skipping stale CI result ${expectedSha}; PR head is ${pull.head.sha}.`);
return false;
}
await upsertComment(github, context, pullNumber, body, options);
return true;
}
async function publish({ github, context, core }) {
const pullNumber = Number(process.env.PR_NUMBER);
if (!Number.isSafeInteger(pullNumber) || pullNumber <= 0) {
throw new Error("PR_NUMBER is invalid");
}
const current = readResult(process.env.PR_RESULT_DIR);
const currentRun = {
sha: process.env.PR_SHA,
conclusion: process.env.PR_CONCLUSION,
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.PR_RUN_ID}`,
};
if (!current) {
await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
[
COMMENT_MARKER,
"## Thread transfer impact",
"",
`⚠️ The latest [CI run](${currentRun.url}) did not produce a thread transfer result for \`${currentRun.sha.slice(0, 7)}\`.`,
"",
"_This comment will update automatically after the next completed run._",
].join("\n"),
{ preserveResultSha: currentRun.sha },
);
return;
}
const baseline = readResult(process.env.BASELINE_RESULT_DIR);
const baselineRun = baseline
? {
sha: process.env.BASELINE_SHA,
matchesBase: process.env.BASELINE_MATCHES_BASE === "true",
url: `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.BASELINE_RUN_ID}`,
}
: undefined;
const body = renderComment({ current, baseline, currentRun, baselineRun });
const published = await upsertCommentForCurrentHead(
github,
context,
core,
pullNumber,
currentRun.sha,
body,
);
if (published) {
core.info(`Updated thread transfer report on PR #${pullNumber}.`);
}
}
module.exports = {
publish,
readResult,
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
};
@@ -0,0 +1,292 @@
const assert = require("node:assert/strict");
const test = require("node:test");
const {
renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
} = require("./thread-transfer-report.cjs");
function result(overrides = {}) {
const observed = {
totalWireBytes: 2_200_000,
threadSnapshotWireBytes: 1_950_000,
threadSnapshotDecodedBytes: 9_100_000,
measuredTurnWebSocketWireBytes: 250_000,
measuredTurnWebSocketDecodedBytes: 1_150_000,
measuredTurnWebSocketMessages: 15,
};
const ceiling = {
totalWireBytes: 2_900_000,
threadSnapshotWireBytes: 2_600_000,
measuredTurnWebSocketWireBytes: 320_000,
measuredTurnWebSocketDecodedBytes: 1_550_000,
measuredTurnWebSocketMessages: 20,
};
return {
schemaVersion: 1,
scenario: {
id: "thread-transfer-v1",
historyTurns: 10,
historyCommandToolsPerTurn: 5,
historyMcpResultBytes: 900_000,
measuredCommandTools: 20,
measuredMcpResultBytes: 1_100_000,
},
providers: {
codex: { observed: { ...observed, ...overrides }, ceiling },
claudeAgent: { observed, ceiling },
},
};
}
test("validates the fixed artifact schema", () => {
assert.equal(validateResult(result()).schemaVersion, 1);
assert.throws(
() => validateResult({ ...result(), injectedMarkdown: "@everyone" }),
/unexpected fields/,
);
assert.throws(
() => validateResult(result({ totalWireBytes: "lots" })),
/non-negative safe integer/,
);
});
test("renders baseline, impact, ceiling, and ceiling changes", () => {
const baseline = result();
const current = result({ measuredTurnWebSocketWireBytes: 260_000 });
current.providers.codex.ceiling = {
...current.providers.codex.ceiling,
measuredTurnWebSocketWireBytes: 330_000,
};
const comment = renderComment({
current,
baseline,
currentRun: {
sha: "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
conclusion: "success",
url: "https://github.com/pingdotgg/t3code/actions/runs/2",
},
baselineRun: {
sha: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
matchesBase: true,
url: "https://github.com/pingdotgg/t3code/actions/runs/1",
},
});
assert.match(comment, /Main baseline \| This PR \| Impact \| PR ceiling/);
assert.match(comment, /\+9\.8 KiB \(\+4\.0%\)/);
assert.match(comment, /This PR changes transfer ceilings/);
assert.match(comment, /312\.5 KiB → 322\.3 KiB/);
assert.match(comment, /<!-- t3-thread-transfer-report -->/);
assert.match(
comment,
/<!-- t3-thread-transfer-result-sha:bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb -->/,
);
});
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
const outputs = {};
const listWorkflowRunArtifacts = () => {};
const listWorkflowRuns = () => {};
const listPullRequestsAssociatedWithCommit = () => {};
const github = {
paginate: async (method, input) => {
if (method === listPullRequestsAssociatedWithCommit) {
return [
{
number: 5350,
state: "open",
head: { sha: "head-sha", ref: "feature-branch", repo: null },
},
];
}
if (method === listWorkflowRunArtifacts) {
return [
{
name: "thread-transfer-results",
expired: false,
runId: input.run_id,
},
];
}
if (method === listWorkflowRuns) {
return [{ id: 1, head_sha: "base-sha" }];
}
throw new Error("unexpected pagination call");
},
rest: {
actions: { listWorkflowRunArtifacts, listWorkflowRuns },
pulls: {
get: async () => ({
data: {
head: { sha: "head-sha" },
base: { sha: "base-sha", ref: "main" },
},
}),
},
repos: { listPullRequestsAssociatedWithCommit },
},
};
await resolve({
github,
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "true");
assert.equal(outputs.pull_number, "5350");
assert.equal(outputs.pr_artifact, "true");
assert.equal(outputs.baseline_run_id, "1");
assert.equal(outputs.baseline_matches_base, "true");
});
test("does not guess when a fallback commit belongs to multiple PRs", async () => {
const outputs = {};
const listPullRequestsAssociatedWithCommit = () => {};
let fetchedPull = false;
await resolve({
github: {
paginate: async (method) => {
assert.equal(method, listPullRequestsAssociatedWithCommit);
return [5350, 5351].map((number) => ({
number,
state: "open",
head: {
sha: "head-sha",
ref: "feature-branch",
repo: { full_name: "pingdotgg/t3code" },
},
}));
},
rest: {
actions: {},
pulls: {
get: async () => {
fetchedPull = true;
},
},
repos: { listPullRequestsAssociatedWithCommit },
},
},
context: {
repo: { owner: "pingdotgg", repo: "t3code" },
payload: {
workflow_run: {
id: 2,
event: "pull_request",
workflow_id: 3,
head_sha: "head-sha",
head_branch: "feature-branch",
head_repository: { full_name: "pingdotgg/t3code" },
conclusion: "success",
pull_requests: [],
},
},
},
core: {
info: () => {},
setOutput: (key, value) => {
outputs[key] = value;
},
},
});
assert.equal(outputs.publish, "false");
assert.equal(fetchedPull, false);
});
test("does not publish a stale result after the PR head advances", async () => {
let listedComments = false;
const info = [];
const published = await upsertCommentForCurrentHead(
{
paginate: async () => {
listedComments = true;
return [];
},
rest: {
issues: {
listComments: () => {},
createComment: () => {
throw new Error("must not create a stale comment");
},
updateComment: () => {
throw new Error("must not update a stale comment");
},
},
pulls: {
get: async () => ({ data: { head: { sha: "new-head-sha" } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: (message) => info.push(message) },
5350,
"old-head-sha",
"stale body",
);
assert.equal(published, false);
assert.equal(listedComments, false);
assert.deepEqual(info, ["Skipping stale CI result old-head-sha; PR head is new-head-sha."]);
});
test("preserves a successful result when a same-SHA rerun has no artifact", async () => {
let updatedComment = false;
const sha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
const published = await upsertCommentForCurrentHead(
{
paginate: async () => [
{
id: 1,
user: { login: "github-actions[bot]" },
body: `<!-- t3-thread-transfer-report -->\n<!-- t3-thread-transfer-result-sha:${sha} -->`,
},
],
rest: {
issues: {
listComments: () => {},
createComment: () => {
updatedComment = true;
},
updateComment: () => {
updatedComment = true;
},
},
pulls: {
get: async () => ({ data: { head: { sha } } }),
},
},
},
{ repo: { owner: "pingdotgg", repo: "t3code" } },
{ info: () => {} },
5350,
sha,
"missing artifact warning",
{ preserveResultSha: sha },
);
assert.equal(published, true);
assert.equal(updatedComment, false);
});
+21
View File
@@ -84,8 +84,29 @@ jobs:
run: vp run --filter @t3tools/desktop ensure:electron
- name: Test
env:
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
run: vp run test
- name: Publish transfer budget report
if: always()
run: |
if test -f "${{ runner.temp }}/t3code-transfer-budget.md"; then
tee -a "$GITHUB_STEP_SUMMARY" < "${{ runner.temp }}/t3code-transfer-budget.md"
else
echo "Transfer budget report was not produced." >> "$GITHUB_STEP_SUMMARY"
fi
- name: Upload thread transfer result
if: always()
uses: actions/upload-artifact@v7
with:
name: thread-transfer-results
path: ${{ runner.temp }}/thread-transfer-result.json
if-no-files-found: ignore
retention-days: 30
- name: Test resource monitor
run: cargo test --locked --manifest-path native/resource-monitor/Cargo.toml
@@ -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 });
+2 -2
View File
@@ -79,8 +79,8 @@ The most common defect in this repo is a change that works on the path you teste
- `vp i` installs. Worktrees get this from the t3.json setup script; if module resolution looks broken, it probably did not run.
- `vp run dev` starts server and web. In a worktree, state defaults to that worktree's gitignored `.t3`, which deliberately outranks an ambient `T3CODE_HOME` so you cannot land on shared state by accident. An explicit `--home-dir` still wins.
- Ports derive from the worktree path and are stable across restarts, but read the real ones from the `[dev-runner]` line since occupied ports shift.
- `--share` publishes over the tailnet. Do not open the URL when you use this, just send it to the user with the pairing code included in url
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to.
- Sharing over the tailnet is three steps: run `vp run dev --share` in the background, wait for the `pairingUrl:` line in its output, paste that full URL (token included) in your reply. Do not wire up `tailscale serve` by hand for this, and do not open the URL yourself.
- The web app requires pairing. Hand over the pairing URL, not the bare origin. A URL without its token is useless to whoever you gave it to. If the token got consumed, mint a fresh one with `node apps/server/src/bin.ts pair` — note it carries standard scopes, while the startup URL carries admin scopes (needed for Settings → Connections management).
- Stop what you started, by the PID you tracked. See rule 1.
## Test data
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@t3tools/desktop",
"version": "0.0.31",
"version": "0.0.32",
"private": true,
"type": "module",
"main": "dist-electron/main.cjs",
@@ -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
View File
@@ -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";
+51
View File
@@ -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: "" })),
);
});
}),
});
+1
View File
@@ -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",
@@ -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,
+1 -1
View File
@@ -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"> &#8599;</span>
</a>
+1 -1
View File
@@ -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))
+5
View File
@@ -138,5 +138,10 @@
"@react-native-menu/menu"
]
}
},
"reanimated": {
"staticFeatureFlags": {
"DISABLE_COMMIT_PAUSING_MECHANISM": true
}
}
}
@@ -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
@@ -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;
@@ -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,
}}
+23 -12
View File
@@ -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}
+49 -41
View File
@@ -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,
};
}
@@ -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>
);
@@ -1,4 +1,11 @@
import { Platform, ScrollView, View, useColorScheme } from "react-native";
import {
Platform,
ScrollView,
type StyleProp,
type TextStyle,
View,
useColorScheme,
} from "react-native";
import { AppText as Text } from "../../../../components/AppText";
import {
@@ -54,14 +61,48 @@ export function TerminalAppearancePreview(props: { readonly fontSize: number })
fontSize: props.fontSize,
lineHeight,
} as const;
// AppText stamps the sans font on every node, so nested spans must
// re-apply the terminal font instead of relying on inheritance, exactly
// like the code preview's tokens below.
const span = (color: string, extra?: TextStyle): StyleProp<TextStyle> => [
lineStyle,
{ color, ...extra },
];
return (
<View className="p-4">
<Text style={[lineStyle, { color: theme.foreground }]}>$ npm run dev</Text>
<Text style={[lineStyle, { color: theme.palette[2] }]}>✓ Ready in 430ms</Text>
<Text style={[lineStyle, { color: theme.foreground }]}>
Local: http://localhost:3000{" "}
<Text style={[lineStyle, { color: theme.cursorForeground }]}>▏</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.palette[6])}>t3code </Text>
<Text style={span(theme.palette[4])}>git:(</Text>
<Text style={span(theme.palette[1])}>main</Text>
<Text style={span(theme.palette[4])}>)</Text>
<Text style={span(theme.palette[3])}> ✗</Text>
<Text style={span(theme.foreground)}> vpr dev</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>VITE v7.1.1</Text>
<Text style={span(theme.mutedForeground)}> ready in</Text>
<Text style={span(theme.foreground)}> 1.24s</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>→ </Text>
<Text style={span(theme.mutedForeground)}>Local: </Text>
<Text style={span(theme.palette[6], { textDecorationLine: "underline" })}>
http://127.0.0.1:5173/
</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.palette[2])}>✓ 85 passed</Text>
<Text style={span(theme.palette[3])}> △ 2 warnings</Text>
<Text style={span(theme.palette[1])}> ✗ 0 failed</Text>
</Text>
<Text style={span(theme.foreground)}>
<Text style={span(theme.background, { backgroundColor: theme.palette[2] })}>
{" READY "}
</Text>
<Text style={span(theme.mutedForeground)}> watching for changes</Text>{" "}
<Text style={span(theme.cursorForeground)}>▏</Text>
</Text>
</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,
}}
@@ -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,
@@ -698,11 +699,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}
@@ -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>
) : (
+88 -55
View File
@@ -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}
@@ -354,6 +354,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 +390,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
onArchiveThread,
onPinThread,
onUnpinThread,
onMovePinnedThread,
onChangeRequestState,
} = props;
const snoozedRow = props.snoozed === true;
@@ -416,6 +425,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 +476,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 +530,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 +548,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
handleSettle,
handleSnooze,
@@ -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";
@@ -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",
@@ -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");
});
});
+93 -1
View File
@@ -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);
+5 -21
View File
@@ -15,10 +15,6 @@ export {
* (environmentId, cwd) by the atom family, so many rows on the same worktree
* or project root share one stream — and virtualization means only visible
* rows subscribe at all.
*
* Keyed by the thread's recorded branch, not the current checkout: the
* streamed status is the fast path while the checkout matches, and a
* branch-keyed lookup keeps the badge alive once the checkout moves away.
*/
export function useThreadPr(
thread: EnvironmentThreadShell,
@@ -33,25 +29,13 @@ export function useThreadPr(
})
: null,
);
const branchPr = useEnvironmentQuery(
thread.branch !== null && cwd !== null
? vcsEnvironment.branchPr({
environmentId: thread.environmentId,
input: { cwd, branch: thread.branch },
})
: null,
);
const status = gitStatus.data;
// When the status describes the thread's own branch it is authoritative
// about that branch's PR — including when it reports none, so this must not
// fall through to a warm branch lookup that would resurrect a stale badge.
if (status !== null && thread.branch !== null && status.refName === thread.branch) {
return status.pr ? presentThreadPr(status.pr, status.sourceControlProvider) : null;
}
const pr = branchPr.data?.pr;
if (!pr) {
if (status === null || thread.branch === null || status.refName !== thread.branch) {
return null;
}
return presentThreadPr(pr, status?.sourceControlProvider);
if (!status.pr) {
return null;
}
return presentThreadPr(status.pr, status.sourceControlProvider);
}
@@ -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";
@@ -54,35 +55,58 @@ 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),
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 +150,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 +185,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 +222,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 +274,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 +326,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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "t3",
"version": "0.0.31",
"version": "0.0.32",
"license": "MIT",
"repository": {
"type": "git",
+1 -1
View File
@@ -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,
@@ -64,7 +65,6 @@ export const RPC_REQUIRED_SCOPES = {
[WS_METHODS.subscribeVcsStatus]: AuthOrchestrationReadScope,
[WS_METHODS.subscribeResourceTelemetry]: AuthOrchestrationReadScope,
[WS_METHODS.vcsRefreshStatus]: AuthOrchestrationReadScope,
[WS_METHODS.vcsBranchPr]: AuthOrchestrationReadScope,
[WS_METHODS.vcsPull]: AuthOrchestrationOperateScope,
[WS_METHODS.gitRunStackedAction]: AuthOrchestrationOperateScope,
[WS_METHODS.gitResolvePullRequest]: AuthOrchestrationOperateScope,
+1 -1
View File
@@ -31,7 +31,7 @@ it("keeps systemd pinned to the stable launcher rather than a versioned server",
});
expect(unit).toContain("ExecStart=/usr/bin/node /home/theo/.t3/runtime/service-launcher.mjs");
expect(unit).toContain("KillMode=control-group");
expect(unit).toContain("KillMode=mixed");
expect(unit).not.toContain("versions/1.2.3");
});
+3 -1
View File
@@ -64,7 +64,9 @@ export function renderBootServiceUnit(plan: BootServicePlan): string {
`Environment=T3CODE_HOME=${quoteSystemdValue(plan.baseDir)}`,
`Environment=${BOOT_SERVICE_UNIT_ENV}=${BOOT_SERVICE_UNIT_FILE}`,
`ExecStart=${quoteSystemdValue(plan.nodePath)} ${quoteSystemdValue(plan.launcherPath)}`,
"KillMode=control-group",
// Let the launcher mark an explicit stop before it signals the server.
// systemd still SIGKILLs the whole cgroup if graceful shutdown times out.
"KillMode=mixed",
"Restart=always",
"RestartSec=5",
`StandardOutput=append:${escapeSystemdSpecifiers(plan.logPath)}`,
+115
View File
@@ -1,7 +1,10 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { describe, expect, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Tracer from "effect/Tracer";
import {
@@ -15,6 +18,14 @@ import { EnvironmentId } from "@t3tools/contracts";
import { RelayClientTracer } from "@t3tools/shared/relayTracing";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import * as ServerConfigModule from "../config.ts";
import { writeServiceState } from "../serviceLauncher.ts";
import {
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
type ServiceUpdateRecord,
} from "./serviceProtocol.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import { CLOUD_CLI_DESIRED_LINK_SECRET } from "./CliState.ts";
import * as CliTokenManager from "./CliTokenManager.ts";
@@ -24,6 +35,7 @@ import {
consumeCloudReplayGuards,
isSupportedLinkProviderKind,
linkProofScopes,
pendingServiceUpdateExists,
reconcileDesiredCloudLink,
releaseManagedTunnelOnShutdown,
} from "./http.ts";
@@ -256,6 +268,23 @@ describe("releaseManagedTunnelOnShutdown", () => {
readonly respond?: () => Response;
}
// Writes the launcher's durable state file into this test's baseDir with
// the launcher's own writer; the release reads it to detect an in-flight
// update handoff.
const writeLauncherState = (update: ServiceUpdateRecord) =>
Effect.gen(function* () {
const path = yield* Path.Path;
const config = yield* ServerConfigModule.ServerConfig;
const statePath = path.join(config.baseDir, "runtime", SERVICE_STATE_FILE);
yield* Effect.promise(() =>
writeServiceState(statePath, {
protocol: SERVICE_LAUNCHER_PROTOCOL,
activeVersion: "0.0.30",
update,
}),
);
});
const provideReleaseHarness =
(harness: ReleaseHarness) =>
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
@@ -306,6 +335,14 @@ describe("releaseManagedTunnelOnShutdown", () => {
}),
),
),
// The release consults the launcher state file under the configured
// baseDir, so every harness run gets a scoped temp baseDir.
Effect.provide(
ServerConfigModule.layerTest("/", { prefix: "t3-http-release-test-" }).pipe(
Layer.provideMerge(NodeServices.layer),
),
),
Effect.scoped,
);
// The persisted state of a CLI-managed link whose tunnel is releasable.
@@ -390,6 +427,84 @@ describe("releaseManagedTunnelOnShutdown", () => {
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("keeps the tunnel when shutdown hands off to a pending update", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
dbPath: "/tmp/state.sqlite",
status: "pending",
});
const released = yield* releaseManagedTunnelOnShutdown();
// The launcher restarts a server immediately, so the tunnel is not
// orphaned; keeping it avoids the hostname route re-propagation that
// dominates update downtime. The stored config must survive so the
// next boot respawns the connector against the same tunnel.
expect(released).toBe(false);
expect(applyConfigCalls).toEqual([]);
expect(requests).toEqual([]);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(true);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("still releases a pending update when the launcher is stopping", () => {
// `t3 service uninstall` or `systemctl stop` during the pending window:
// the launcher writes its stop marker before signalling the child, so no
// replacement server is coming and the tunnel must not be kept.
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
dbPath: "/tmp/state.sqlite",
status: "pending",
});
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfigModule.ServerConfig;
yield* fs.writeFileString(path.join(config.baseDir, "runtime", SERVICE_STOP_MARKER_FILE), "");
expect(yield* pendingServiceUpdateExists).toBe(true);
const released = yield* releaseManagedTunnelOnShutdown();
expect(released).toBe(true);
expect(requests).toHaveLength(1);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("still releases when the recorded update already settled", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
const requests: Array<HttpClientRequest.HttpClientRequest> = [];
return Effect.gen(function* () {
yield* writeLauncherState({
id: "update-1",
fromVersion: "0.0.30",
targetVersion: "0.0.31",
status: "committed",
});
const released = yield* releaseManagedTunnelOnShutdown();
expect(released).toBe(true);
expect(requests).toHaveLength(1);
expect(values.has(CLOUD_ENDPOINT_RUNTIME_CONFIG)).toBe(false);
}).pipe(provideReleaseHarness({ store, applyConfigCalls, requests }));
});
it.effect("keeps a runtime config that a fast restart replaced mid-release", () => {
const { store, values } = makeMemorySecretStore(managedLinkSecrets);
const applyConfigCalls: Array<unknown> = [];
+52
View File
@@ -46,7 +46,9 @@ import * as DateTime from "effect/DateTime";
import * as Crypto from "effect/Crypto";
import * as Duration from "effect/Duration";
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 HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
@@ -56,8 +58,14 @@ import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
import { requireEnvironmentScope } from "../auth/http.ts";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
import * as ManagedEndpointRuntime from "./ManagedEndpointRuntime.ts";
import {
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
serviceStateHasPendingUpdate,
} from "./serviceProtocol.ts";
import {
CLOUD_ENDPOINT_RUNTIME_CONFIG,
CLOUD_LINKED_USER_ID,
@@ -627,6 +635,37 @@ export const reconcileDesiredCloudLink = Effect.fn("environment.cloud.reconcileD
},
);
// The launcher owns this durable state, so read it directly both when a trial
// decides whether it owns pre-activation cleanup and while a server tears down.
export const pendingServiceUpdateExists = Effect.gen(function* () {
const config = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runtimeDir = path.join(config.baseDir, "runtime");
const stateText = yield* fs
.readFileString(path.join(runtimeDir, SERVICE_STATE_FILE))
.pipe(Effect.option);
return Option.isSome(stateText) && serviceStateHasPendingUpdate(stateText.value);
});
// A pending update alone is not proof a replacement server is coming: an
// explicit launcher stop (`t3 service uninstall`, `systemctl stop`) during
// the pending window also tears this server down. The launcher marks that case
// just before it signals the child, so pending + no marker is the handoff.
const pendingUpdateHandoffExists = Effect.gen(function* () {
if (!(yield* pendingServiceUpdateExists)) {
return false;
}
const config = yield* ServerConfig.ServerConfig;
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const runtimeDir = path.join(config.baseDir, "runtime");
const stopping = yield* fs
.exists(path.join(runtimeDir, SERVICE_STOP_MARKER_FILE))
.pipe(Effect.orElseSucceed(() => false));
return !stopping;
});
// Cloudflare bills per provisioned tunnel, so an environment that goes offline
// must not leave its tunnel behind. Releasing deletes only the tunnel — the
// relay keeps the link and its hostname reservation, and the next startup's
@@ -649,6 +688,19 @@ export const releaseManagedTunnelOnShutdown = Effect.fn(
if (!(yield* readCliDesiredCloudLink) || (yield* readCliDesiredLinkMode) !== "managed") {
return false;
}
// A shutdown that hands off to a pending remote update is not the
// environment going offline: the launcher immediately brings a server back
// (the new version, or the old one after a rollback). Deleting the tunnel
// here forces that server to provision a replacement UUID, and the public
// hostname's route to the new tunnel takes 1-2 minutes to propagate — the
// dominant cost of an update restart. Keep the tunnel instead: the next
// boot respawns the connector from the stored config and is reachable as
// soon as it connects, and the reconcile confirms the still-live tunnel
// without replacing it.
if (yield* pendingUpdateHandoffExists) {
yield* Effect.logInfo("Keeping the managed tunnel across the update restart");
return false;
}
const token = yield* dependencies.cliTokenManager.getExisting;
if (Option.isNone(token)) {
return false;
+4
View File
@@ -5,6 +5,10 @@ export const SERVICE_LAUNCHER_PROTOCOL = 2 as const;
export const SERVICE_LAUNCHER_CONTEXT_ENV = "T3_SERVICE_LAUNCHER_CONTEXT";
export const SERVICE_LAUNCHER_FILE = "service-launcher.mjs";
export const SERVICE_STATE_FILE = "service-state.json";
/** Written by the launcher just before an explicit stop kills its child, so
the child can tell "the service is going away" from "the launcher is about
to start my replacement" while a pending update is recorded. */
export const SERVICE_STOP_MARKER_FILE = ".service-stopping";
export interface PendingServiceUpdate {
readonly id: string;
@@ -146,6 +146,7 @@ export const make = Effect.gen(function* () {
threadSettlement: true,
threadSnooze: true,
threadPinning: true,
threadPinReorder: true,
threadTitleRegeneration: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
-43
View File
@@ -23,8 +23,6 @@ import {
GitRunStackedActionInput,
GitRunStackedActionResult,
GitStackedAction,
type VcsBranchPrInput,
type VcsBranchPrResult,
VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
@@ -89,9 +87,6 @@ export class GitManager extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly branchPr: (
input: VcsBranchPrInput,
) => Effect.Effect<VcsBranchPrResult, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -1689,43 +1684,6 @@ export const make = Effect.gen(function* () {
});
return mergeGitStatusParts(local, remote);
});
// PR lookup for a branch that is not necessarily checked out. Threads keep
// a recorded branch, and their PR badge must survive the checkout moving
// elsewhere — so this derives the branch's upstream from git config instead
// of HEAD and funnels into the same cached lookup as status.
const branchPr: GitManager["Service"]["branchPr"] = Effect.fn("branchPr")(function* (input) {
const cwd = yield* normalizeStatusCacheKey(input.cwd);
const branch = input.branch;
const [remoteName, mergeRef, originHead] = yield* Effect.all(
[
readConfigValueNullable(cwd, `branch.${branch}.remote`),
readConfigValueNullable(cwd, `branch.${branch}.merge`),
gitCore
.execute({
operation: "GitManager.branchPr.defaultBranch",
cwd,
args: ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"],
allowNonZeroExit: true,
})
.pipe(Effect.orElseSucceed(() => null)),
],
{ concurrency: "unbounded" },
);
const upstreamRef =
remoteName !== null && mergeRef !== null && mergeRef.startsWith("refs/heads/")
? `${remoteName}/${mergeRef.slice("refs/heads/".length)}`
: null;
const originHeadBranch =
originHead !== null && originHead.exitCode === 0
? (originHead.stdout.trim().split("/").slice(1).join("/") ?? "")
: "";
const isDefaultBranch =
originHeadBranch.length > 0
? branch === originHeadBranch
: branch === "main" || branch === "master";
const pr = yield* lookupStatusPr(cwd, { branch, upstreamRef, isDefaultBranch });
return { branch, pr } satisfies VcsBranchPrResult;
});
const invalidateLocalStatus: GitManager["Service"]["invalidateLocalStatus"] = Effect.fn(
"invalidateLocalStatus",
)(function* (cwd) {
@@ -2178,7 +2136,6 @@ export const make = Effect.gen(function* () {
return GitManager.of({
localStatus,
remoteStatus,
branchPr,
status,
invalidateLocalStatus,
invalidateRemoteStatus,
+8 -13
View File
@@ -22,8 +22,6 @@ import {
type GitResolvePullRequestResult,
type GitRunStackedActionInput,
type GitRunStackedActionResult,
type VcsBranchPrInput,
type VcsBranchPrResult,
type VcsStatusInput,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
@@ -47,9 +45,6 @@ export class GitWorkflowService extends Context.Service<
input: VcsStatusInput,
options?: GitVcsDriver.GitRemoteStatusOptions,
) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
readonly branchPr: (
input: VcsBranchPrInput,
) => Effect.Effect<VcsBranchPrResult, GitManagerServiceError>;
readonly invalidateLocalStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect<void, never>;
readonly invalidateStatus: (cwd: string) => Effect.Effect<void, never>;
@@ -74,6 +69,10 @@ export class GitWorkflowService extends Context.Service<
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<void, GitCommandError>;
readonly remoteExists: (input: {
readonly cwd: string;
readonly remoteName: string;
}) => Effect.Effect<boolean, GitCommandError>;
readonly resolveRemoteTrackingCommit: (input: {
readonly cwd: string;
readonly refName: string;
@@ -275,14 +274,6 @@ export const make = Effect.gen(function* () {
isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null),
),
),
branchPr: (input) =>
detectGitRepositoryForStatus("GitWorkflowService.branchPr", input.cwd).pipe(
Effect.flatMap((isGitRepository) =>
isGitRepository
? gitManager.branchPr(input)
: Effect.succeed({ branch: input.branch, pr: null }),
),
),
invalidateLocalStatus: gitManager.invalidateLocalStatus,
invalidateRemoteStatus: gitManager.invalidateRemoteStatus,
invalidateStatus: gitManager.invalidateStatus,
@@ -316,6 +307,10 @@ export const make = Effect.gen(function* () {
ensureGitCommand("GitWorkflowService.fetchRemote", input.cwd).pipe(
Effect.andThen(git.fetchRemote(input)),
),
remoteExists: (input) =>
ensureGitCommand("GitWorkflowService.remoteExists", input.cwd).pipe(
Effect.andThen(git.remoteExists(input)),
),
resolveRemoteTrackingCommit: (input) =>
ensureGitCommand("GitWorkflowService.resolveRemoteTrackingCommit", input.cwd).pipe(
Effect.andThen(git.resolveRemoteTrackingCommit(input)),
+1
View File
@@ -198,6 +198,7 @@ it.layer(NodeServices.layer)("keybindings", (it) => {
assert.equal(defaultsByCommand.get("thread.jump.1"), "mod+1");
assert.equal(defaultsByCommand.get("thread.jump.9"), "mod+9");
assert.equal(defaultsByCommand.get("modelPicker.toggle"), "mod+shift+m");
assert.equal(defaultsByCommand.get("themeEditor.toggle"), "mod+alt+shift+t");
assert.equal(defaultsByCommand.get("filePicker.toggle"), "mod+p");
assert.equal(defaultsByCommand.get("projectSearch.toggle"), "mod+shift+f");
assert.equal(defaultsByCommand.get("sidebar.toggle"), "mod+b");
@@ -0,0 +1,117 @@
import { describe, expect, it } from "vite-plus/test";
import type { OrchestrationThreadActivity } from "@t3tools/contracts";
import { projectActivityPayload } from "./ActivityPayloadProjection.ts";
function activity(payload: Record<string, unknown>): OrchestrationThreadActivity {
return {
id: "activity-1",
tone: "tool",
kind: "tool.completed",
summary: "Tool",
payload,
turnId: null,
createdAt: "2026-08-01T10:00:00.000Z",
} as unknown as OrchestrationThreadActivity;
}
/**
* Wire-survival regression: the slimming pass rewrites payload.data but must
* never strip the top-level per-agent fields the subagent fold depends on.
* If slimming ever moves to an allowlist over the whole payload, these
* assertions are the tripwire.
*/
describe("projectActivityPayload agent-field survival", () => {
it("preserves tool attribution (agentId/parentToolUseId) through data slimming", () => {
const projected = projectActivityPayload(
activity({
itemType: "command_execution",
agentId: "task-123",
parentToolUseId: "toolu_abc",
data: {
toolName: "Bash",
input: { command: "ls" },
command: "ls",
rawOutput: { content: "x".repeat(10) },
somethingClientNeverReads: { big: "blob" },
},
}),
);
const payload = projected.payload as Record<string, unknown>;
expect(payload.agentId).toBe("task-123");
expect(payload.parentToolUseId).toBe("toolu_abc");
// Slimming itself still applies to data.
const data = payload.data as Record<string, unknown>;
expect(data.somethingClientNeverReads).toBeUndefined();
});
it("slims Codex-shaped mcp_tool_call items to rendered fields plus a result summary", () => {
const projected = projectActivityPayload(
activity({
itemType: "mcp_tool_call",
data: {
item: {
type: "mcpToolCall",
id: "item-1",
tool: "fetch_pr",
server: "github",
status: "completed",
arguments: { pr: 42 },
durationMs: 1200,
result: {
content: [{ type: "text", text: `PR body line one\n${"x".repeat(5000)}` }],
structuredContent: { huge: "y".repeat(5000) },
},
_meta: { internal: true },
},
},
}),
);
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
const item = data.item as Record<string, unknown>;
expect(item.tool).toBe("fetch_pr");
expect(item.server).toBe("github");
expect(item.arguments).toEqual({ pr: 42 });
expect(item._meta).toBeUndefined();
expect(item.result).toEqual({ content: "PR body line one" });
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
});
it("slims Claude-shaped mcp_tool_call data (toolName/input/result block)", () => {
const projected = projectActivityPayload(
activity({
itemType: "mcp_tool_call",
data: {
toolName: "mcp__github__fetch_pr",
input: { pr: 42 },
result: {
type: "tool_result",
tool_use_id: "toolu_1",
content: [{ type: "text", text: `first line of output\n${"z".repeat(5000)}` }],
},
},
}),
);
const data = (projected.payload as Record<string, unknown>).data as Record<string, unknown>;
expect(data.toolName).toBe("mcp__github__fetch_pr");
expect(data.input).toEqual({ pr: 42 });
expect(data.result).toEqual({ content: "first line of output" });
expect(JSON.stringify(projected.payload).length).toBeLessThan(500);
});
it("passes task lifecycle payloads (no data field) through untouched", () => {
const source = activity({
taskId: "task-9",
title: "Audit auth",
role: "explorer",
model: "opus",
effort: "high",
workflowName: "audit-flow",
phases: [{ index: 0, title: "Audit" }],
typedUsage: { totalTokens: 1200 },
runHandles: { runId: "run-1", scriptPath: "/tmp/wf.js" },
timelineBypass: true,
});
const projected = projectActivityPayload(source);
expect(projected.payload).toEqual(source.payload);
});
});
@@ -123,6 +123,114 @@ function summarizeToolTextOutput(value: string): string | null {
return null;
}
/**
* Fields of an MCP tool-call item both clients render in the expanded
* work-log row. Everything else — notably `result`, which carries the full
* tool output and dominates wire size on MCP-heavy threads — is summarized
* or dropped. Full payloads remain in persistence.
*/
const MCP_ITEM_KEPT_FIELDS = [
"type",
"id",
"tool",
"server",
"status",
"arguments",
"appContext",
"error",
"durationMs",
] as const;
/**
* Pulls renderable text out of an MCP tool result: either a Codex-style
* `{content: [{type: "text", text}, ...]}` record or a raw Claude
* `tool_result` block whose `content` is a string or block array.
*/
function extractMcpResultText(result: unknown): string | null {
const record = asRecord(result);
if (!record) {
return typeof result === "string" ? result : null;
}
if (typeof record.content === "string") {
return record.content;
}
if (Array.isArray(record.content)) {
const texts: string[] = [];
for (const entry of record.content) {
const text = asRecord(entry)?.text;
if (typeof text === "string" && text.trim().length > 0) {
texts.push(text);
}
}
if (texts.length > 0) {
return texts.join("\n");
}
}
return null;
}
function summarizeMcpResult(result: unknown): Record<string, unknown> | undefined {
if (result === undefined || result === null) {
return undefined;
}
const text = extractMcpResultText(result);
const summary = text ? summarizeToolTextOutput(text) : null;
return summary ? { content: summary } : undefined;
}
/**
* MCP tool calls carry full tool results (`data.item.result` on Codex,
* `data.result` on Claude/OpenCode) that used to bypass slimming entirely to
* keep the expanded-row UI working. Keep the fields the UI actually renders
* and summarize the result like regular tool output.
*/
function projectMcpToolCallData(data: Record<string, unknown>): Record<string, unknown> {
const projectedData: Record<string, unknown> = {};
const item = asRecord(data.item);
if (item) {
const projectedItem: Record<string, unknown> = {};
for (const key of MCP_ITEM_KEPT_FIELDS) {
if (key in item) {
projectedItem[key] = item[key];
}
}
const result = summarizeMcpResult(item.result);
if (result) {
projectedItem.result = result;
}
projectedData.item = projectedItem;
}
if ("toolName" in data) {
projectedData.toolName = data.toolName;
}
if ("input" in data) {
projectedData.input = data.input;
}
if (!item) {
const result = summarizeMcpResult(data.result);
if (result) {
projectedData.result = result;
}
}
if ("toolCallId" in data) {
projectedData.toolCallId = data.toolCallId;
}
if ("kind" in data) {
projectedData.kind = data.kind;
}
const changedFiles: string[] = [];
collectChangedFiles(data, changedFiles, new Set<string>(), 0);
if (changedFiles.length > 0) {
projectedData.files = changedFiles.map((path) => ({ path }));
}
return projectedData;
}
function projectRawOutput(value: unknown): Record<string, unknown> | undefined {
const rawOutput = asRecord(value);
if (!rawOutput) {
@@ -160,10 +268,20 @@ export function projectActivityPayload(
): OrchestrationThreadActivity {
const payload = asRecord(activity.payload);
const data = asRecord(payload?.data);
if (!payload || !data || payload.itemType === "mcp_tool_call") {
if (!payload || !data) {
return activity;
}
if (payload.itemType === "mcp_tool_call") {
return {
...activity,
payload: {
...payload,
data: projectMcpToolCallData(data),
},
};
}
const projectedData: Record<string, unknown> = {};
const item = projectCommandData(data);
if (item) {
@@ -247,6 +365,107 @@ function dropStaleContextWindowActivities(
);
}
/**
* Identity both clients use to fold a tool lifecycle row into the call it
* belongs to (`deriveToolLifecycleCollapseKey` in web's `session-logic` and
* mobile's `threadActivity`): an explicit `data.toolCallId` when the adapter
* emits one, otherwise the itemType/title/detail triple. Returns null for rows
* with no identity at all — those never collapse on the client either, so they
* must not be dropped here.
*/
function toolLifecycleIdentity(activity: OrchestrationThreadActivity): string | null {
const payload = asRecord(activity.payload);
if (!payload) {
return null;
}
const toolCallId = asTrimmedString(asRecord(payload.data)?.toolCallId);
if (toolCallId) {
return `id:${toolCallId}`;
}
const itemType = asTrimmedString(payload.itemType) ?? "";
// Mirrors the clients' `normalizeCompactToolLabel`: a completion's title may
// gain a trailing "complete"/"completed" the in-flight updates lack.
const label = (asTrimmedString(payload.title) ?? activity.summary)
.replace(/\s+(?:complete|completed)\s*$/iu, "")
.trim();
const detail = asTrimmedString(payload.detail) ?? "";
if (itemType.length === 0 && label.length === 0 && detail.length === 0) {
return null;
}
return [itemType, label, detail].join("");
}
/**
* Drops `tool.updated` rows a `tool.completed` row already supersedes. An
* update is the in-flight snapshot of a call; once the call completes, the
* completion carries the final state and the clients fold every matching
* update into it, so shipping the updates buys nothing — 47k such rows exist
* in one real database, and a single thread carries 2,291 of them totalling
* ~1MB post-slimming.
*
* Matching is per turn for the same reason `dropStaleContextWindowActivities`
* retains per turn: a live `thread.reverted` makes the client discard whole
* turns, so a completion in a different turn could vanish and leave the
* dropped update unrepresented. The completion must also come *after* the
* update within the turn — a later update belongs to a subsequent call that
* reuses the same identity and is still in flight. Rows without a lifecycle
* identity pass through, matching the clients, which never collapse them.
* Live `thread.activity-appended` events are untouched: updates still stream
* in real time and the completion supersedes them on the client as before.
*
* Deliberate divergence from client collapse: clients fold only *adjacent*
* lifecycle rows, so a superseded update separated from its completion by an
* interleaved parallel call renders as its own row today, and this drop
* removes it. Measured against a real database, that affects 1.5% of dropped
* rows (553 of 36,581), all pure in-flight state whose final result the
* retained completion still shows. Dropping them is intentional; matching
* adjacency server-side would forfeit most of the win for parallel-heavy
* threads, which are exactly the heavy ones. Superseding completions always
* carry a payload superset of their updates (verified across all 49,515
* update rows: zero dropped rows held a client-merged field — detail, title,
* command, item, kind, files — their completion lacked), so no expanded-row
* content is lost.
*/
function dropSupersededToolUpdatedActivities(
activities: ReadonlyArray<OrchestrationThreadActivity>,
): ReadonlyArray<OrchestrationThreadActivity> {
const completionIndicesByKey = new Map<string, number[]>();
for (let index = 0; index < activities.length; index += 1) {
const activity = activities[index]!;
if (activity.kind !== "tool.completed") {
continue;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
continue;
}
const key = `${activity.turnId ?? ""}${identity}`;
const indices = completionIndicesByKey.get(key);
if (indices) {
indices.push(index);
} else {
completionIndicesByKey.set(key, [index]);
}
}
if (completionIndicesByKey.size === 0) {
return activities;
}
return activities.filter((activity, index) => {
if (activity.kind !== "tool.updated") {
return true;
}
const identity = toolLifecycleIdentity(activity);
if (!identity) {
return true;
}
const indices = completionIndicesByKey.get(`${activity.turnId ?? ""}${identity}`);
return !indices?.some((completionIndex) => completionIndex > index);
});
}
export function projectThreadDetailSnapshot(
snapshot: OrchestrationThreadDetailSnapshot,
): OrchestrationThreadDetailSnapshot {
@@ -254,9 +473,9 @@ export function projectThreadDetailSnapshot(
...snapshot,
thread: {
...snapshot.thread,
activities: dropStaleContextWindowActivities(snapshot.thread.activities).map(
projectActivityPayload,
),
activities: dropSupersededToolUpdatedActivities(
dropStaleContextWindowActivities(snapshot.thread.activities),
).map(projectActivityPayload),
},
};
}
@@ -39,6 +39,8 @@ import { CheckpointReactorLive } from "./CheckpointReactor.ts";
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { RuntimeReceiptBusLive } from "./RuntimeReceiptBus.ts";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { OrchestrationCommandReceiptRepositoryLive } from "../../persistence/Layers/OrchestrationCommandReceipts.ts";
@@ -294,6 +296,8 @@ describe("CheckpointReactor", () => {
);
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -301,6 +305,8 @@ describe("CheckpointReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -31,6 +31,8 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import {
OrchestrationProjectionPipeline,
@@ -55,6 +57,8 @@ async function createOrchestrationSystem() {
),
OrchestrationProjectionSnapshotQueryLive,
).pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
Layer.provide(RepositoryIdentityResolver.layer),
@@ -817,6 +821,8 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(Layer.succeed(OrchestrationEventStore, flakyStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -922,6 +928,8 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -1065,6 +1073,8 @@ describe("OrchestrationEngine", () => {
const runtime = ManagedRuntime.make(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(Layer.succeed(OrchestrationProjectionPipeline, flakyProjectionPipeline)),
Layer.provide(Layer.succeed(OrchestrationEventStore, nonTransactionalStore)),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -31,6 +31,8 @@ import {
OrchestrationProjectionPipelineLive,
} from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { ServerConfig } from "../../config.ts";
@@ -1429,6 +1431,13 @@ it.layer(BaseTestLayer)("OrchestrationProjectionPipeline", (it) => {
assert.deepEqual(settledRows, [
{ state: "completed", completedAt: "2026-01-01T00:01:00.000Z" },
]);
const threadRows = yield* sql<{ readonly latestTurnId: string | null }>`
SELECT latest_turn_id AS "latestTurnId"
FROM projection_threads
WHERE thread_id = ${threadId}
`;
assert.deepEqual(threadRows, [{ latestTurnId: turnId }]);
}),
);
@@ -2664,6 +2673,8 @@ it.effect("restores pending turn-start metadata across projection pipeline resta
const engineLayer = it.layer(
OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -612,6 +612,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
pinOrderKey: null,
titleRegenerationRequestId: null,
titleRegenerationStartedAt: null,
latestUserMessageAt: null,
@@ -728,6 +729,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: event.payload.pinnedAt,
...(event.payload.pinOrderKey !== undefined
? { pinOrderKey: event.payload.pinOrderKey }
: {}),
updatedAt: event.payload.updatedAt,
});
return;
@@ -743,6 +747,22 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinnedAt: null,
pinOrderKey: null,
updatedAt: event.payload.updatedAt,
});
return;
}
case "thread.pin-reordered": {
const existingRow = yield* projectionThreadRepository.getById({
threadId: event.payload.threadId,
});
if (Option.isNone(existingRow)) {
return;
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
pinOrderKey: event.payload.orderKey,
updatedAt: event.payload.updatedAt,
});
return;
@@ -850,7 +870,8 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
}
yield* projectionThreadRepository.upsert({
...existingRow.value,
latestTurnId: event.payload.session.activeTurnId,
// activeTurnId describes current work; a terminal session must not erase history.
latestTurnId: event.payload.session.activeTurnId ?? existingRow.value.latestTurnId,
updatedAt: event.occurredAt,
});
yield* refreshThreadShellSummary(event.payload.threadId);
@@ -17,7 +17,10 @@ import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import { encodeThreadDetailPageCursor } from "../threadDetailCursor.ts";
const asProjectId = (value: string): ProjectId => ProjectId.make(value);
const asTurnId = (value: string): TurnId => TurnId.make(value);
@@ -27,6 +30,8 @@ const asCheckpointRef = (value: string): CheckpointRef => CheckpointRef.make(val
const projectionSnapshotLayer = it.layer(
OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provideMerge(RepositoryIdentityResolver.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
@@ -82,6 +87,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
pending_approval_count,
pending_user_input_count,
has_actionable_proposed_plan,
pinned_at,
pin_order_key,
created_at,
updated_at,
deleted_at
@@ -100,6 +107,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
1,
0,
0,
'2026-02-24T00:00:01.000Z',
'gm',
'2026-02-24T00:00:02.000Z',
'2026-02-24T00:00:03.000Z',
NULL
@@ -312,7 +321,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
titleRegeneration: null,
deletedAt: null,
messages: [
@@ -428,7 +438,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
pinnedAt: null,
pinnedAt: "2026-02-24T00:00:01.000Z",
pinOrderKey: "gm",
titleRegeneration: null,
session: {
threadId: ThreadId.make("thread-1"),
@@ -443,6 +454,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
backgroundLiveness: null,
planProgress: null,
},
]);
@@ -1825,6 +1838,8 @@ it.effect(
() => {
const resolveCalls: string[] = [];
const layer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provideMerge(
Layer.succeed(RepositoryIdentityResolver.RepositoryIdentityResolver, {
resolve: (cwd: string) =>
@@ -1913,3 +1928,407 @@ it.effect(
}).pipe(Effect.provide(layer));
},
);
projectionSnapshotLayer("ProjectionSnapshotQuery windowed thread detail", (it) => {
// A thread shaped like real fan-out usage: user turns interleaved with
// subagent turns (no user pending message), plus a turnless straggler user
// message and a turnless activity anchored between turns.
//
// row turn pending msg anchor (requested_at)
// 1 turn-1 user-msg-1 T00
// 2 turn-2 (subagent) T01
// 3 turn-3 (subagent) T02
// 4 turn-4 user-msg-4 T03
// 5 turn-5 user-msg-5 T04
//
// Straggler user message at T03.5 (turn_id NULL, not any pending_message_id)
// and a turnless activity at T03.6 — both belong to the page containing T03+.
const seedFanOutThread = Effect.fnUntraced(function* () {
const sql = yield* SqlClient.SqlClient;
// Tests in this block share one in-memory database; reset before seeding.
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at
)
VALUES ('project-w', 'Windowed', '/tmp/project-w', '[]',
'2026-03-01T00:00:00.000Z', '2026-03-01T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
latest_turn_id, pending_approval_count, pending_user_input_count,
has_actionable_proposed_plan, created_at, updated_at, deleted_at
)
VALUES ('thread-w', 'project-w', 'Windowed thread',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
'turn-5', 0, 0, 0, '2026-03-01T00:00:00.000Z', '2026-03-01T00:00:10.000Z', NULL)
`;
const turns: ReadonlyArray<{
turn: string;
pendingMessage: string | null;
at: string;
}> = [
{ turn: "turn-1", pendingMessage: "user-msg-1", at: "2026-03-01T00:00:00.000Z" },
{ turn: "turn-2", pendingMessage: null, at: "2026-03-01T00:01:00.000Z" },
{ turn: "turn-3", pendingMessage: null, at: "2026-03-01T00:02:00.000Z" },
{ turn: "turn-4", pendingMessage: "user-msg-4", at: "2026-03-01T00:03:00.000Z" },
{ turn: "turn-5", pendingMessage: "user-msg-5", at: "2026-03-01T00:04:00.000Z" },
];
for (const { turn, pendingMessage, at } of turns) {
yield* sql`
INSERT INTO projection_turns (
thread_id, turn_id, pending_message_id, state, requested_at, started_at, completed_at,
checkpoint_files_json
)
VALUES ('thread-w', ${turn}, ${pendingMessage}, 'completed', ${at}, ${at}, ${at}, '[]')
`;
if (pendingMessage !== null) {
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES (${pendingMessage}, 'thread-w', NULL, 'user', ${"prompt for " + turn}, 0, ${at}, ${at})
`;
}
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES (${turn + "-reply"}, 'thread-w', ${turn}, 'assistant', ${"reply from " + turn}, 0, ${at}, ${at})
`;
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
)
VALUES (${turn + "-activity"}, 'thread-w', ${turn}, 'tool', 'tool.completed',
'ran tool', '{"ok":true}', ${at})
`;
}
// Straggler user message sent while turn-4 ran: turn_id NULL and not any
// turn's pending_message_id.
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES ('user-msg-straggler', 'thread-w', NULL, 'user', 'while you are at it',
0, '2026-03-01T00:03:30.000Z', '2026-03-01T00:03:30.000Z')
`;
// Turnless activity in the same time range.
yield* sql`
INSERT INTO projection_thread_activities (
activity_id, thread_id, turn_id, tone, kind, summary, payload_json, created_at
)
VALUES ('turnless-activity', 'thread-w', NULL, 'info', 'context-window.updated',
'usage', '{"usedTokens":1}', '2026-03-01T00:03:36.000Z')
`;
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES (${projector}, 42, '2026-03-01T00:00:10.000Z')
`;
}
});
const threadW = ThreadId.make("thread-w");
const messageIds = (snapshot: { thread: { messages: ReadonlyArray<{ id: string }> } }) =>
snapshot.thread.messages.map((message) => message.id).toSorted();
const activityIds = (snapshot: { thread: { activities: ReadonlyArray<{ id: string }> } }) =>
snapshot.thread.activities.map((activity) => activity.id).toSorted();
it.effect("returns the full thread with no page metadata when no window is requested", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW);
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.page, undefined);
assert.equal(snapshot.value.thread.messages.length, 9);
assert.equal(snapshot.value.thread.activities.length, 6);
assert.equal(snapshot.value.snapshotSequence, 42);
}
}),
);
it.effect("windows to the last N user-anchored turns with subagent turns riding along", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// turnLimit 2 walks back: turn-5 (user), turn-4 (user) -> window is
// rows 4..5. Subagent turns 2-3 are older than the 2nd user turn and
// stay out; the straggler message and turnless activity (T03.5/T03.6,
// after turn-4's anchor) ride along.
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), [
"turn-4-reply",
"turn-5-reply",
"user-msg-4",
"user-msg-5",
"user-msg-straggler",
]);
assert.deepEqual(activityIds(snapshot.value), [
"turn-4-activity",
"turn-5-activity",
"turnless-activity",
]);
assert.equal(snapshot.value.page?.hasMore, true);
assert.notEqual(snapshot.value.page?.beforeCursor, null);
assert.equal(snapshot.value.page?.snapshotSequence, 42);
}
}),
);
it.effect("subagent turns between user turns ride along inside the window", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// turnLimit 3 reaches user turn-1, dragging subagent turns 2-3 along:
// the full thread, so no further pages.
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 3 });
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.thread.messages.length, 9);
assert.equal(snapshot.value.thread.activities.length, 6);
assert.equal(snapshot.value.page?.hasMore, false);
assert.equal(snapshot.value.page?.beforeCursor, null);
}
}),
);
it.effect("cursors survive a projection rewrite that reassigns turn row ids", () =>
Effect.gen(function* () {
// The revert projector (and any projection rebuild) deletes and
// re-upserts projection_turns, assigning fresh autoincrement row ids.
// The keyset cursor is derived from event content, so a page cursor
// minted before the rewrite must keep working after it.
yield* seedFanOutThread();
const sql = yield* SqlClient.SqlClient;
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const cursor = firstPage.value.page?.beforeCursor;
assert.notEqual(cursor, null);
if (cursor === null || cursor === undefined) return;
// Simulate the rewrite: delete and re-insert every turn row with the
// same content, which reassigns all row ids.
const turnRows = yield* sql`
SELECT thread_id, turn_id, pending_message_id, state, requested_at, started_at,
completed_at, checkpoint_files_json
FROM projection_turns WHERE thread_id = 'thread-w' ORDER BY row_id
`;
yield* sql`DELETE FROM projection_turns WHERE thread_id = 'thread-w'`;
for (const row of turnRows) {
yield* sql`
INSERT INTO projection_turns (
thread_id, turn_id, pending_message_id, state, requested_at, started_at,
completed_at, checkpoint_files_json
)
VALUES (${row.thread_id as string}, ${row.turn_id as string},
${row.pending_message_id as string | null}, ${row.state as string},
${row.requested_at as string}, ${row.started_at as string},
${row.completed_at as string}, ${row.checkpoint_files_json as string})
`;
}
const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
beforeCursor: cursor,
});
assert.equal(olderPage._tag, "Some");
if (olderPage._tag === "Some") {
// Identical older slice to what the pre-rewrite cursor would return.
assert.deepEqual(messageIds(olderPage.value), [
"turn-1-reply",
"turn-2-reply",
"turn-3-reply",
"user-msg-1",
]);
assert.equal(olderPage.value.page?.hasMore, false);
}
}),
);
it.effect("beforeCursor returns the disjoint adjacent older slice", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const cursor = firstPage.value.page?.beforeCursor;
assert.notEqual(cursor, null);
assert.notEqual(cursor, undefined);
if (cursor === null || cursor === undefined) return;
// Older page: user turn-1 plus subagent turns 2-3 riding along. Disjoint
// from the first page: no turn-4/5 rows, no straggler.
const olderPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
beforeCursor: cursor,
});
assert.equal(olderPage._tag, "Some");
if (olderPage._tag === "Some") {
assert.deepEqual(messageIds(olderPage.value), [
"turn-1-reply",
"turn-2-reply",
"turn-3-reply",
"user-msg-1",
]);
assert.deepEqual(activityIds(olderPage.value), [
"turn-1-activity",
"turn-2-activity",
"turn-3-activity",
]);
assert.equal(olderPage.value.page?.hasMore, false);
assert.equal(olderPage.value.page?.beforeCursor, null);
}
}),
);
it.effect("a cursor for a different thread degrades to the first page", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const firstPage = yield* snapshotQuery.getThreadDetailSnapshot(threadW, { turnLimit: 2 });
assert.equal(firstPage._tag, "Some");
if (firstPage._tag !== "Some") return;
const foreign = encodeThreadDetailPageCursor({
threadId: ThreadId.make("thread-other"),
beforeAnchorAt: "2026-03-01T00:01:00.000Z",
beforeTurnId: "turn-2",
});
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 2,
beforeCursor: foreign,
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), messageIds(firstPage.value));
}
}),
);
it.effect("a malformed cursor degrades to the first page instead of failing", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 2,
beforeCursor: "not-a-cursor",
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.equal(snapshot.value.page?.hasMore, true);
assert.equal(snapshot.value.thread.messages.length, 5);
}
}),
);
it.effect("windows never split below the raw-turn ceiling boundary contiguously", () =>
Effect.gen(function* () {
yield* seedFanOutThread();
const snapshotQuery = yield* ProjectionSnapshotQuery;
// Page repeatedly with turnLimit 1 and assert the union of all pages is
// exactly the full thread with no duplicates (disjointness + coverage).
const seenMessages: string[] = [];
const seenActivities: string[] = [];
let cursor: string | undefined;
for (let page = 0; page < 10; page += 1) {
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(threadW, {
turnLimit: 1,
...(cursor !== undefined ? { beforeCursor: cursor } : {}),
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag !== "Some") return;
seenMessages.push(...snapshot.value.thread.messages.map((message) => message.id));
seenActivities.push(...snapshot.value.thread.activities.map((activity) => activity.id));
const next = snapshot.value.page?.beforeCursor;
if (next === null || next === undefined) break;
cursor = next;
}
assert.equal(new Set(seenMessages).size, seenMessages.length);
assert.equal(new Set(seenActivities).size, seenActivities.length);
assert.equal(seenMessages.length, 9);
assert.equal(seenActivities.length, 6);
}),
);
it.effect("a thread with no turns returns its content unwindowed on the first page", () =>
Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const snapshotQuery = yield* ProjectionSnapshotQuery;
yield* sql`DELETE FROM projection_projects`;
yield* sql`DELETE FROM projection_threads`;
yield* sql`DELETE FROM projection_turns`;
yield* sql`DELETE FROM projection_thread_messages`;
yield* sql`DELETE FROM projection_thread_activities`;
yield* sql`DELETE FROM projection_state`;
yield* sql`
INSERT INTO projection_projects (
project_id, title, workspace_root, scripts_json, created_at, updated_at, deleted_at
)
VALUES ('project-e', 'Empty', '/tmp/project-e', '[]',
'2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_threads (
thread_id, project_id, title, model_selection_json, runtime_mode, interaction_mode,
pending_approval_count, pending_user_input_count, has_actionable_proposed_plan,
created_at, updated_at, deleted_at
)
VALUES ('thread-e', 'project-e', 'Turnless thread',
'{"provider":"codex","model":"gpt-5-codex"}', 'full-access', 'default',
0, 0, 0, '2026-03-02T00:00:00.000Z', '2026-03-02T00:00:00.000Z', NULL)
`;
yield* sql`
INSERT INTO projection_thread_messages (
message_id, thread_id, turn_id, role, text, is_streaming, created_at, updated_at
)
VALUES ('pre-turn-msg', 'thread-e', NULL, 'user', 'first prompt', 0,
'2026-03-02T00:00:01.000Z', '2026-03-02T00:00:01.000Z')
`;
for (const projector of Object.values(ORCHESTRATION_PROJECTOR_NAMES)) {
yield* sql`
INSERT INTO projection_state (projector, last_applied_sequence, updated_at)
VALUES (${projector}, 7, '2026-03-02T00:00:01.000Z')
`;
}
const snapshot = yield* snapshotQuery.getThreadDetailSnapshot(ThreadId.make("thread-e"), {
turnLimit: 5,
});
assert.equal(snapshot._tag, "Some");
if (snapshot._tag === "Some") {
assert.deepEqual(messageIds(snapshot.value), ["pre-turn-msg"]);
assert.equal(snapshot.value.page?.hasMore, false);
assert.equal(snapshot.value.page?.beforeCursor, null);
}
}),
);
});
@@ -43,6 +43,8 @@ import {
type ProjectionRepositoryError,
} from "../../persistence/Errors.ts";
import { ProjectionCheckpoint } from "../../persistence/Services/ProjectionCheckpoints.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
import { ProjectionProject } from "../../persistence/Services/ProjectionProjects.ts";
import { ProjectionState } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
@@ -50,6 +52,10 @@ import { ProjectionThreadMessage } from "../../persistence/Services/ProjectionTh
import { ProjectionThreadProposedPlan } from "../../persistence/Services/ProjectionThreadProposedPlans.ts";
import { ProjectionThreadSession } from "../../persistence/Services/ProjectionThreadSessions.ts";
import { ProjectionThread } from "../../persistence/Services/ProjectionThreads.ts";
import {
decodeThreadDetailPageCursor,
encodeThreadDetailPageCursor,
} from "../threadDetailCursor.ts";
import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityResolver.ts";
import { ORCHESTRATION_PROJECTOR_NAMES } from "./ProjectionPipeline.ts";
import {
@@ -129,6 +135,36 @@ const ProjectIdLookupInput = Schema.Struct({
const ThreadIdLookupInput = Schema.Struct({
threadId: ThreadId,
});
// Windowed reads order turns by the stable keyset (anchor, turn key), where
// anchor is requested_at and turn key is
// COALESCE(turn_id, ''). Both are event-derived, so cursors survive the
// revert projector's row-id rewrite and full projection rebuilds.
const ThreadTurnWindowLookupInput = Schema.Struct({
threadId: ThreadId,
// Exclusive keyset upper bound. Sentinels "~"/"" mean unbounded ("~" sorts
// after every ISO timestamp).
beforeAnchorAt: Schema.String,
beforeTurnKey: Schema.String,
userTurnLimit: Schema.Number,
maxRawTurns: Schema.Number,
});
const ProjectionTurnWindowRowSchema = Schema.Struct({
// The turn's timeline anchor, used to bound rows that have no turn linkage
// (user messages and turnless activities) to the same page window.
anchorAt: Schema.String,
turnKey: Schema.String,
});
const ThreadTurnRangeLookupInput = Schema.Struct({
threadId: ThreadId,
// Turn-linked rows are bounded by the keyset range [min, before) over
// (anchor, turn key); turnless rows by the matching [minAnchorAt,
// beforeAnchorAt) time range. Unbounded ends use sentinels: "" for the
// lower bound, "~" (sorts after ISO dates) for the upper bound.
minAnchorAt: Schema.String,
minTurnKey: Schema.String,
beforeAnchorAt: Schema.String,
beforeTurnKey: Schema.String,
});
const ProjectionProjectLookupRowSchema = ProjectionProjectDbRowSchema;
const ProjectionThreadIdLookupRowSchema = Schema.Struct({
threadId: ThreadId,
@@ -308,6 +344,8 @@ function toPersistenceSqlOrDecodeError(sqlOperation: string, decodeOperation: st
}
const makeProjectionSnapshotQuery = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const threadPlanProgress = yield* ThreadPlanProgressService;
const sql = yield* SqlClient.SqlClient;
const repositoryIdentityResolver = yield* RepositoryIdentityResolver.RepositoryIdentityResolver;
const repositoryIdentityResolutionConcurrency = 4;
@@ -385,6 +423,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -420,6 +459,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -457,6 +497,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -894,6 +935,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -1041,6 +1083,197 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
`,
});
// Resolves a page of recent turns for a windowed thread detail read. Walks
// back from the exclusive (beforeAnchorAt, beforeTurnKey) keyset boundary
// (sentinels "~"/"" mean unbounded, i.e. the first page) until it has seen
// `userTurnLimit` user-anchored turns — turns whose pending message is a
// user message; subagent/fan-out turns between them ride along — or hits the
// `maxRawTurns` ceiling that bounds pathological fan-out. The `candidates`
// CTE applies the keyset bound and LIMIT before the window functions run;
// its ORDER BY uses raw columns so the migration-037
// (thread_id, requested_at, turn_id) index serves both range and order with
// no temp B-tree — the scan is genuinely bounded by the LIMIT. (Raw
// turn_id DESC places NULLs exactly where COALESCE-to-'' would, below every
// real id.) The caller derives the continuation cursor from the oldest
// returned row.
// Highest thread-DETAIL event sequence for this thread that the projection
// has applied (bounded by the global snapshot sequence read in the same
// transaction). This is the thread-scoped watermark a windowed page carries
// so clients can defer merging until their live subscription has caught up;
// the global sequence is not waitable per-thread. The event_type filter
// must match ws.ts's isThreadDetailEvent exactly: the subscription only
// delivers these types, so a watermark counting any other event could
// never be reached by the client and would park the page forever. Served
// by the event store's (aggregate_kind, stream_id, sequence) index.
const getThreadEventWatermarkRow = SqlSchema.findOneOption({
Request: Schema.Struct({ threadId: ThreadId, maxSequence: Schema.Number }),
Result: Schema.Struct({ threadSequence: Schema.NullOr(Schema.Number) }),
execute: ({ threadId, maxSequence }) =>
sql`
SELECT MAX(sequence) AS "threadSequence"
FROM orchestration_events
WHERE aggregate_kind = 'thread'
AND stream_id = ${threadId}
AND sequence <= ${maxSequence}
AND event_type IN (
'thread.message-sent',
'thread.proposed-plan-upserted',
'thread.activity-appended',
'thread.turn-diff-completed',
'thread.reverted',
'thread.session-set'
)
`,
});
const listTurnWindowRows = SqlSchema.findAll({
Request: ThreadTurnWindowLookupInput,
Result: ProjectionTurnWindowRowSchema,
execute: ({ threadId, beforeAnchorAt, beforeTurnKey, userTurnLimit, maxRawTurns }) =>
sql`
WITH candidates AS (
SELECT
turns.requested_at AS anchor_at,
COALESCE(turns.turn_id, '') AS turn_key,
turns.pending_message_id
FROM projection_turns AS turns
WHERE turns.thread_id = ${threadId}
AND (
turns.requested_at < ${beforeAnchorAt}
OR (
turns.requested_at = ${beforeAnchorAt}
AND COALESCE(turns.turn_id, '') < ${beforeTurnKey}
)
)
ORDER BY turns.requested_at DESC, turns.turn_id DESC
LIMIT ${maxRawTurns}
),
walked AS (
SELECT
candidates.anchor_at,
candidates.turn_key,
CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END AS is_user_turn,
SUM(CASE WHEN messages.role = 'user' THEN 1 ELSE 0 END) OVER (
ORDER BY candidates.anchor_at DESC, candidates.turn_key DESC
) AS user_turns_seen
FROM candidates
LEFT JOIN projection_thread_messages AS messages
ON messages.message_id = candidates.pending_message_id
)
SELECT
anchor_at AS "anchorAt",
turn_key AS "turnKey"
FROM walked
WHERE user_turns_seen < ${userTurnLimit}
OR (user_turns_seen = ${userTurnLimit} AND is_user_turn = 1)
ORDER BY anchor_at ASC, turn_key ASC
`,
});
// Windowed variants of the two heavy collections. Turn-linked rows are
// bounded by the page's (anchor, turn key) keyset range over
// projection_turns; rows with no turn linkage (user messages always, and
// turnless activities like pre-turn context-window updates) are bounded by
// the matching turn-anchor time range so they land on the same page as the
// turns around them. Proposed plans and checkpoints stay unwindowed: they
// are metadata-scale.
const listThreadMessageRowsByThreadWindow = SqlSchema.findAll({
Request: ThreadTurnRangeLookupInput,
Result: ProjectionThreadMessageDbRowSchema,
execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>
sql`
SELECT
message_id AS "messageId",
thread_id AS "threadId",
turn_id AS "turnId",
role,
text,
attachments_json AS "attachments",
is_streaming AS "isStreaming",
created_at AS "createdAt",
updated_at AS "updatedAt"
FROM projection_thread_messages
WHERE thread_id = ${threadId}
AND (
turn_id IN (
SELECT turn_id FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NOT NULL
AND (
requested_at > ${minAnchorAt}
OR (
requested_at = ${minAnchorAt}
AND turn_id >= ${minTurnKey}
)
)
AND (
requested_at < ${beforeAnchorAt}
OR (
requested_at = ${beforeAnchorAt}
AND turn_id < ${beforeTurnKey}
)
)
)
OR (
turn_id IS NULL
AND created_at >= ${minAnchorAt}
AND created_at < ${beforeAnchorAt}
)
)
ORDER BY created_at ASC, message_id ASC
`,
});
const listThreadActivityRowsByThreadWindow = SqlSchema.findAll({
Request: ThreadTurnRangeLookupInput,
Result: ProjectionThreadActivityDbRowSchema,
execute: ({ threadId, minAnchorAt, minTurnKey, beforeAnchorAt, beforeTurnKey }) =>
sql`
SELECT
activity_id AS "activityId",
thread_id AS "threadId",
turn_id AS "turnId",
tone,
kind,
summary,
payload_json AS "payload",
sequence,
created_at AS "createdAt"
FROM projection_thread_activities
WHERE thread_id = ${threadId}
AND (
turn_id IN (
SELECT turn_id FROM projection_turns
WHERE thread_id = ${threadId}
AND turn_id IS NOT NULL
AND (
requested_at > ${minAnchorAt}
OR (
requested_at = ${minAnchorAt}
AND turn_id >= ${minTurnKey}
)
)
AND (
requested_at < ${beforeAnchorAt}
OR (
requested_at = ${beforeAnchorAt}
AND turn_id < ${beforeTurnKey}
)
)
)
OR (
turn_id IS NULL
AND created_at >= ${minAnchorAt}
AND created_at < ${beforeAnchorAt}
)
)
ORDER BY
sequence ASC,
created_at ASC,
activity_id ASC
`,
});
const getFullThreadDiffContextRow = SqlSchema.findOneOption({
Request: FullThreadDiffContextLookupInput,
Result: ProjectionFullThreadDiffContextRowSchema,
@@ -1333,6 +1566,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: messagesByThread.get(row.threadId) ?? [],
@@ -1537,6 +1771,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
deletedAt: row.deletedAt,
messages: [],
@@ -1672,12 +1907,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
} satisfies OrchestrationThreadShell)
: Result.failVoid,
),
@@ -1812,12 +2052,17 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: row.snoozedUntil,
snoozedAt: row.snoozedAt,
pinnedAt: row.pinnedAt,
pinOrderKey: row.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(row),
session: sessionByThread.get(row.threadId) ?? null,
latestUserMessageAt: row.latestUserMessageAt,
hasPendingApprovals: row.pendingApprovalCount > 0,
hasPendingUserInput: row.pendingUserInputCount > 0,
hasActionableProposedPlan: row.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
row.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(row.threadId),
}),
),
updatedAt: updatedAt ?? "1970-01-01T00:00:00.000Z",
@@ -2084,16 +2329,31 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
session: Option.isSome(sessionRow) ? mapSessionRow(sessionRow.value) : null,
latestUserMessageAt: threadRow.value.latestUserMessageAt,
hasPendingApprovals: threadRow.value.pendingApprovalCount > 0,
hasPendingUserInput: threadRow.value.pendingUserInputCount > 0,
hasActionableProposedPlan: threadRow.value.hasActionableProposedPlan > 0,
backgroundLiveness: threadBackgroundLiveness.getThreadBackgroundLiveness(
threadRow.value.threadId,
),
planProgress: threadPlanProgress.getThreadPlanProgress(threadRow.value.threadId),
} satisfies OrchestrationThreadShell);
});
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
// Contiguous turn range bounding a windowed detail read; undefined loads the
// full thread. Resolved from a window request inside the snapshot
// transaction (see getThreadDetailSnapshot).
interface ThreadDetailBounds {
readonly minAnchorAt: string;
readonly minTurnKey: string;
readonly beforeAnchorAt: string;
readonly beforeTurnKey: string;
}
const getThreadDetailByIdBounded = (threadId: ThreadId, bounds: ThreadDetailBounds | undefined) =>
Effect.gen(function* () {
const [
threadRow,
@@ -2112,7 +2372,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadMessageRowsByThread({ threadId }).pipe(
(bounds === undefined
? listThreadMessageRowsByThread({ threadId })
: listThreadMessageRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listMessages:query",
@@ -2128,7 +2391,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadActivityRowsByThread({ threadId }).pipe(
(bounds === undefined
? listThreadActivityRowsByThread({ threadId })
: listThreadActivityRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
@@ -2184,6 +2450,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
snoozedUntil: threadRow.value.snoozedUntil,
snoozedAt: threadRow.value.snoozedAt,
pinnedAt: threadRow.value.pinnedAt,
pinOrderKey: threadRow.value.pinOrderKey ?? null,
titleRegeneration: mapTitleRegeneration(threadRow.value),
deletedAt: null,
messages: messageRows.map((row) => {
@@ -2238,23 +2505,139 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
);
});
const getThreadDetailById: ProjectionSnapshotQueryShape["getThreadDetailById"] = (threadId) =>
getThreadDetailByIdBounded(threadId, undefined);
// Bounds pathological fan-out: one user turn that spawned hundreds of
// subagent turns still pages in bounded chunks, at the cost of splitting the
// fan-out group across pages (the cursor continues the same group). Also
// structurally bounds the window scan via the candidates CTE's LIMIT.
const THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE = 150;
// Sentinels for unbounded keyset ends; "~" sorts after any ISO timestamp.
const ANCHOR_UNBOUNDED = "~";
const getThreadDetailSnapshot: ProjectionSnapshotQueryShape["getThreadDetailSnapshot"] = (
threadId,
window,
) =>
// Read the thread detail and the snapshot sequence within a single
// transaction so the sequence is consistent with the returned state; a
// projector update landing between two separate reads could otherwise return
// a sequence ahead of the thread detail, causing the client to resume from
// too far and drop events.
// too far and drop events. Window resolution runs inside the same
// transaction so the page boundary is consistent with the returned rows.
sql
.withTransaction(
Effect.gen(function* () {
const thread = yield* getThreadDetailById(threadId);
if (window?.turnLimit === undefined) {
const thread = yield* getThreadDetailById(threadId);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
}
// A malformed or foreign-thread cursor falls back to the first page
// rather than failing: the client's stale cursor after a revert or
// reconnect should degrade to "reload recent history", not error.
const decodedCursor =
window.beforeCursor === undefined
? null
: decodeThreadDetailPageCursor(window.beforeCursor);
const cursor = decodedCursor?.threadId === threadId ? decodedCursor : null;
const windowRows = yield* listTurnWindowRows({
threadId,
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
beforeTurnKey: cursor?.beforeTurnId ?? "",
userTurnLimit: window.turnLimit,
maxRawTurns: THREAD_DETAIL_MAX_RAW_TURNS_PER_PAGE,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:listTurnWindow:decodeRows",
),
),
);
const oldest = windowRows[0];
// An empty window (no turns before the cursor, or a thread with no
// turns at all) still returns thread metadata with empty collections
// for turn-linked rows; turnless rows are bounded to the same empty
// range. The first page of a turnless thread stays unwindowed so
// pre-turn content (e.g. a just-created thread) is not hidden.
const bounds: ThreadDetailBounds | undefined =
oldest === undefined && cursor === null
? undefined
: {
minAnchorAt: oldest?.anchorAt ?? "",
minTurnKey: oldest?.turnKey ?? "",
beforeAnchorAt: cursor?.beforeAnchorAt ?? ANCHOR_UNBOUNDED,
beforeTurnKey: cursor?.beforeTurnId ?? "",
};
// Empty window behind a cursor: nothing older remains.
const emptyBounds =
oldest === undefined && cursor !== null
? { minAnchorAt: "", minTurnKey: "", beforeAnchorAt: "", beforeTurnKey: "" }
: undefined;
const thread = yield* getThreadDetailByIdBounded(threadId, emptyBounds ?? bounds);
if (Option.isNone(thread)) {
return Option.none<OrchestrationThreadDetailSnapshot>();
}
const hasMore =
oldest !== undefined &&
(yield* listTurnWindowRows({
threadId,
beforeAnchorAt: oldest.anchorAt,
beforeTurnKey: oldest.turnKey,
userTurnLimit: 1,
maxRawTurns: 1,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:probeOlder:decodeRows",
),
),
)).length > 0;
const { snapshotSequence } = yield* getSnapshotSequence();
return Option.some({ snapshotSequence, thread: thread.value });
const watermarkRow = yield* getThreadEventWatermarkRow({
threadId,
maxSequence: snapshotSequence,
}).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:query",
"ProjectionSnapshotQuery.getThreadDetailSnapshot:threadWatermark:decodeRow",
),
),
);
const threadSequence = Option.match(watermarkRow, {
onNone: () => 0,
onSome: (row) => row.threadSequence ?? 0,
});
return Option.some({
snapshotSequence,
thread: thread.value,
page: {
beforeCursor:
hasMore && oldest !== undefined
? encodeThreadDetailPageCursor({
threadId,
beforeAnchorAt: oldest.anchorAt,
beforeTurnId: oldest.turnKey,
})
: null,
hasMore,
snapshotSequence,
threadSequence,
},
});
}),
)
.pipe(
@@ -48,6 +48,8 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import {
providerErrorLabel,
providerErrorLabelFromInstanceHint,
@@ -345,6 +347,8 @@ describe("ProviderCommandReactor", () => {
const orchestrationLayer = OrchestrationEngineLive.pipe(
Layer.provide(OrchestrationProjectionSnapshotQueryLive),
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(OrchestrationProjectionPipelineLive),
Layer.provide(OrchestrationEventStoreLive),
Layer.provide(OrchestrationCommandReceiptRepositoryLive),
@@ -352,6 +356,8 @@ describe("ProviderCommandReactor", () => {
Layer.provide(SqlitePersistenceMemory),
);
const projectionSnapshotLayer = OrchestrationProjectionSnapshotQueryLive.pipe(
Layer.provide(ThreadBackgroundLiveness.layer),
Layer.provide(ThreadPlanProgress.layer),
Layer.provide(RepositoryIdentityResolver.layer),
Layer.provide(SqlitePersistenceMemory),
);
@@ -0,0 +1,84 @@
import {
EventId,
ProviderDriverKind,
RuntimeTaskId,
ThreadId,
type ProviderRuntimeEvent,
} from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { runtimeEventToActivities } from "./ProviderRuntimeIngestion.ts";
const base = {
provider: ProviderDriverKind.make("codex"),
createdAt: "2026-08-06T00:00:00.000Z",
threadId: ThreadId.make("thread-1"),
};
describe("runtimeEventToActivities task progress", () => {
it("persists usage independently from replaceable activity", () => {
const taskId = RuntimeTaskId.make("agent-1");
const usageOnly = {
...base,
type: "task.progress",
eventId: EventId.make("evt-usage"),
payload: {
taskId,
description: "Agent one",
typedUsage: { totalTokens: 73_700_000 },
},
} satisfies ProviderRuntimeEvent;
const command = {
...base,
type: "task.progress",
eventId: EventId.make("evt-command"),
payload: {
taskId,
description: "Agent one",
summary: "Running tests",
lastToolName: "exec_command",
},
} satisfies ProviderRuntimeEvent;
const usageActivities = runtimeEventToActivities(usageOnly);
const commandActivities = runtimeEventToActivities(command);
expect(usageActivities.map((activity) => activity.id)).toEqual(["task-usage:thread-1:agent-1"]);
expect(commandActivities.map((activity) => activity.id)).toEqual([
"task-progress:thread-1:agent-1",
]);
const usagePayload = usageActivities[0]?.payload as Record<string, unknown> | undefined;
expect(usagePayload?.typedUsage).toEqual({ totalTokens: 73_700_000 });
expect(usagePayload?.usageSnapshot).toBe(true);
});
it("splits combined progress and usage into their independent snapshots", () => {
const event = {
...base,
type: "task.progress",
eventId: EventId.make("evt-combined"),
payload: {
taskId: RuntimeTaskId.make("agent-2"),
description: "Agent two",
summary: "Inspecting the panel",
typedUsage: { totalTokens: 4_200, toolUses: 7 },
status: "running",
},
} satisfies ProviderRuntimeEvent;
const activities = runtimeEventToActivities(event);
const progressPayload = activities[0]?.payload as Record<string, unknown>;
const usagePayload = activities[1]?.payload as Record<string, unknown>;
expect(activities.map((activity) => activity.id)).toEqual([
"task-progress:thread-1:agent-2",
"task-usage:thread-1:agent-2",
]);
expect(progressPayload.summary).toBe("Inspecting the panel");
expect(progressPayload.status).toBe("running");
expect(progressPayload).not.toHaveProperty("typedUsage");
expect(usagePayload.typedUsage).toEqual({ totalTokens: 4_200, toolUses: 7 });
expect(usagePayload.usageSnapshot).toBe(true);
expect(usagePayload).not.toHaveProperty("status");
});
});
@@ -44,6 +44,8 @@ import * as RepositoryIdentityResolver from "../../project/RepositoryIdentityRes
import { OrchestrationEngineLive } from "./OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "../ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "../ThreadPlanProgress.ts";
import { ProviderRuntimeIngestionLive } from "./ProviderRuntimeIngestion.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProviderRuntimeIngestionService } from "../Services/ProviderRuntimeIngestion.ts";
@@ -237,6 +239,10 @@ describe("ProviderRuntimeIngestion", () => {
const layer = ProviderRuntimeIngestionLive.pipe(
Layer.provideMerge(orchestrationLayer),
Layer.provideMerge(projectionSnapshotLayer),
// Single shared liveness instance across ingestion (writer), the
// engine, and the snapshot query (reader).
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(ThreadPlanProgress.layer),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(Layer.succeed(ProviderService, provider.service)),
Layer.provideMerge(makeTestServerSettingsLayer(options?.serverSettings)),
@@ -2193,7 +2199,7 @@ describe("ProviderRuntimeIngestion", () => {
});
it("starts a new streaming assistant message segment after approval", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
const startedAt = "2026-03-28T07:00:00.000Z";
const pausedAt = "2026-03-28T07:00:01.000Z";
const resumedAt = "2026-03-28T07:00:02.000Z";
@@ -2300,7 +2306,7 @@ describe("ProviderRuntimeIngestion", () => {
});
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
const now = "2026-01-01T00:00:00.000Z";
await Effect.runPromise(
@@ -3143,7 +3149,8 @@ describe("ProviderRuntimeIngestion", () => {
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-started",
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:turn-task-1",
);
const completed = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-task-completed",
@@ -3227,7 +3234,8 @@ describe("ProviderRuntimeIngestion", () => {
);
const progress = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:named-task-1",
);
const completed = thread.activities.find(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-named-task-completed",
@@ -3318,7 +3326,8 @@ describe("ProviderRuntimeIngestion", () => {
await waitForThread(harness.readModel, (entry) =>
entry.activities.some(
(activity: ProviderRuntimeTestActivity) => activity.id === "evt-swept-task-progress",
(activity: ProviderRuntimeTestActivity) =>
activity.id === "task-progress:thread-1:swept-task-1",
),
);
@@ -7,6 +7,8 @@ import {
type OrchestrationMessage,
type OrchestrationProposedPlanId,
CheckpointRef,
classifyTaskAgentKind,
EventId,
isToolLifecycleItemType,
ThreadId,
type ThreadTokenUsageSnapshot,
@@ -32,6 +34,8 @@ import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionT
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ThreadBackgroundLivenessService } from "../ThreadBackgroundLiveness.ts";
import { ThreadPlanProgressService } from "../ThreadPlanProgress.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
import {
ProviderRuntimeIngestionService,
@@ -307,6 +311,52 @@ function requestKindFromCanonicalRequestType(
}
}
/**
* Copies the optional TaskAgentLinkage bundle from a task.* runtime payload
* into the persisted activity payload. Identity fields ride on every row so
* client folds survive activity retention; absent fields stay absent.
*/
function taskLinkageActivityFields(payload: Record<string, unknown>): Record<string, unknown> {
const fields: Record<string, unknown> = {
// Server-stamped classification: persisted rows are self-describing, so
// clients trust the stamp instead of re-deriving agent-vs-background
// from taskType denylists and marker heuristics (legacy rows without a
// stamp keep the client fallback).
agentKind: classifyTaskAgentKind({
taskType: typeof payload.taskType === "string" ? payload.taskType : undefined,
agentId: typeof payload.agentId === "string" ? payload.agentId : undefined,
}),
};
for (const key of [
"taskType",
"agentId",
"title",
"role",
"model",
"effort",
"toolUseId",
"parentAgentId",
"workflowName",
"agentIndex",
"phaseIndex",
"phaseTitle",
"phases",
"attempt",
"runHandles",
"outputFile",
"agentPath",
"timelineBypass",
"typedUsage",
"status",
"error",
] as const) {
if (payload[key] !== undefined) {
fields[key] = payload[key];
}
}
return fields;
}
export function runtimeEventToActivities(
event: ProviderRuntimeEvent,
taskTitle?: string,
@@ -505,6 +555,7 @@ export function runtimeEventToActivities(
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -513,25 +564,140 @@ export function runtimeEventToActivities(
}
case "task.progress": {
const linkage = taskLinkageActivityFields(event.payload as Record<string, unknown>);
// Usage and activity are independent latest-state streams. Keeping them
// under separate stable ids prevents a command/reasoning update from
// replacing the last known token count (and prevents a usage-only tick
// from blanking the last meaningful activity).
const identityLinkage = { ...linkage };
delete identityLinkage.typedUsage;
delete identityLinkage.status;
delete identityLinkage.error;
const title =
event.payload.description.trim().length > 0
? { title: truncateDetail(event.payload.description, 120) }
: {};
const hasProgressState =
event.payload.typedUsage === undefined ||
event.payload.summary !== undefined ||
event.payload.lastToolName !== undefined ||
event.payload.status !== undefined ||
event.payload.error !== undefined;
return [
...(hasProgressState
? [
{
// Stable per-task id: activity is "latest state", not
// history, so each meaningful tick replaces the last. This
// bounds a large fleet to one activity row per task.
id: EventId.make(`task-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info" as const,
kind: "task.progress" as const,
summary:
event.payload.description.trim().length > 0
? truncateDetail(event.payload.description, 120)
: "Reasoning update",
payload: {
taskId: event.payload.taskId,
...title,
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary
? { summary: truncateDetail(event.payload.summary) }
: {}),
...(event.payload.lastToolName
? { lastToolName: event.payload.lastToolName }
: {}),
...(event.payload.status ? { status: event.payload.status } : {}),
...(event.payload.error ? { error: event.payload.error } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...identityLinkage,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
]
: []),
...(event.payload.typedUsage !== undefined
? [
{
id: EventId.make(`task-usage:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info" as const,
kind: "task.progress" as const,
summary: "Task usage updated",
payload: {
taskId: event.payload.taskId,
...title,
...identityLinkage,
usageSnapshot: true,
typedUsage: event.payload.typedUsage,
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
]
: []),
];
}
case "task.updated": {
return [
{
id: event.eventId,
createdAt: event.createdAt,
tone: "info",
kind: "task.progress",
tone: event.payload.status === "failed" ? "error" : "info",
kind: "task.updated",
summary:
event.payload.description.trim().length > 0
? truncateDetail(event.payload.description, 120)
: "Reasoning update",
event.payload.status === "failed"
? "Task failed"
: event.payload.status
? `Task ${event.payload.status}`
: "Task updated",
payload: {
taskId: event.payload.taskId,
...(event.payload.description.trim().length > 0
? { title: truncateDetail(event.payload.description, 120) }
...(event.payload.description
? { detail: truncateDetail(event.payload.description) }
: {}),
...(event.payload.endedAt ? { endedAt: event.payload.endedAt } : {}),
...(event.payload.isBackgrounded !== undefined
? { isBackgrounded: event.payload.isBackgrounded }
: {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
},
];
}
case "tool.progress": {
// Only agent-owned heartbeats are persisted: they feed the owning
// agent's activity line. Parent-conversation tool progress stays
// ephemeral (item lifecycle already covers it).
if (event.payload.taskId === undefined) {
return [];
}
return [
{
// Same stable-id treatment as task.progress: a heartbeat is
// "what is this agent doing right now", so one row per task
// (thread-scoped for the same global-PK collision reason).
id: EventId.make(`tool-progress:${event.threadId}:${event.payload.taskId}`),
createdAt: event.createdAt,
tone: "info",
kind: "tool.progress",
summary: event.payload.toolName ?? "Tool progress",
payload: {
taskId: event.payload.taskId,
...(event.payload.toolName ? { toolName: event.payload.toolName } : {}),
...(event.payload.toolUseId ? { toolUseId: event.payload.toolUseId } : {}),
...(event.payload.elapsedSeconds !== undefined
? { elapsedSeconds: event.payload.elapsedSeconds }
: {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
detail: truncateDetail(event.payload.summary ?? event.payload.description),
...(event.payload.summary ? { summary: truncateDetail(event.payload.summary) } : {}),
...(event.payload.lastToolName ? { lastToolName: event.payload.lastToolName } : {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -565,6 +731,7 @@ export function runtimeEventToActivities(
}
: {}),
...(event.payload.usage !== undefined ? { usage: event.payload.usage } : {}),
...taskLinkageActivityFields(event.payload as Record<string, unknown>),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -630,6 +797,10 @@ export function runtimeEventToActivities(
...(event.payload.status ? { status: event.payload.status } : {}),
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -652,6 +823,10 @@ export function runtimeEventToActivities(
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.data !== undefined ? { data: event.payload.data } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -673,6 +848,10 @@ export function runtimeEventToActivities(
payload: {
itemType: event.payload.itemType,
...(event.payload.detail ? { detail: truncateDetail(event.payload.detail) } : {}),
...(event.payload.agentId ? { agentId: event.payload.agentId } : {}),
...(event.payload.parentToolUseId
? { parentToolUseId: event.payload.parentToolUseId }
: {}),
},
turnId: toTurnId(event.turnId) ?? null,
...maybeSequence,
@@ -688,6 +867,8 @@ export function runtimeEventToActivities(
}
const make = Effect.gen(function* () {
const threadBackgroundLiveness = yield* ThreadBackgroundLivenessService;
const threadPlanProgress = yield* ThreadPlanProgressService;
const crypto = yield* Crypto.Crypto;
const orchestrationEngine = yield* OrchestrationEngineService;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
@@ -1474,7 +1655,7 @@ const make = Effect.gen(function* () {
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
);
if (assistantDeliveryMode === "buffered") {
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
@@ -1510,7 +1691,7 @@ const make = Effect.gen(function* () {
const detailedThread = yield* getLoadedThreadDetail();
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
serverSettingsService.getSettings,
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
);
const flushedMessageIds =
assistantDeliveryMode === "buffered"
@@ -1756,6 +1937,58 @@ const make = Effect.gen(function* () {
yield* rememberTaskDescription(thread.id, event.payload.taskId, description);
}
}
// Working-indicator plan progress: current step while the turn runs,
// cleared on settle so a finished plan never lingers as stale UI.
// Events carrying a turn id that conflicts with the active turn are
// stale (superseded turn) and must neither overwrite nor clear the
// active turn's progress; session.exited always clears.
if (event.type === "session.exited") {
threadPlanProgress.clearThreadPlanProgress(thread.id);
} else if (!conflictsWithActiveTurn) {
if (event.type === "turn.plan.updated") {
threadPlanProgress.recordPlanProgress(thread.id, event.payload.plan);
} else if (event.type === "turn.completed" || event.type === "turn.aborted") {
threadPlanProgress.clearThreadPlanProgress(thread.id);
}
}
// Sidebar background liveness: fed from the same lifecycle stream,
// read by the shell query at mapping time (no persistence).
switch (event.type) {
case "task.started":
case "task.progress":
case "task.updated":
case "task.completed": {
const payload = event.payload as {
taskId: string;
taskType?: string;
status?: string;
agentId?: string;
};
threadBackgroundLiveness.recordTaskLiveness({
threadId: thread.id,
taskId: payload.taskId,
taskType: payload.taskType,
status: payload.status,
agentId: payload.agentId,
kind:
event.type === "task.started"
? "started"
: event.type === "task.progress"
? "progress"
: event.type === "task.updated"
? "updated"
: "completed",
});
break;
}
case "session.exited":
threadBackgroundLiveness.clearThreadLiveness(thread.id);
break;
default:
break;
}
let taskTitle: string | undefined;
if (event.type === "task.completed") {
taskTitle = yield* lookupTaskDescription(thread.id, event.payload.taskId);
+2
View File
@@ -15,6 +15,7 @@ import {
ThreadUnsnoozedPayload as ContractsThreadUnsnoozedPayloadSchema,
ThreadPinnedPayload as ContractsThreadPinnedPayloadSchema,
ThreadUnpinnedPayload as ContractsThreadUnpinnedPayloadSchema,
ThreadPinReorderedPayload as ContractsThreadPinReorderedPayloadSchema,
ThreadMessageSentPayload as ContractsThreadMessageSentPayloadSchema,
ThreadProposedPlanUpsertedPayload as ContractsThreadProposedPlanUpsertedPayloadSchema,
ThreadSessionSetPayload as ContractsThreadSessionSetPayloadSchema,
@@ -46,6 +47,7 @@ export const ThreadSnoozedPayload = ContractsThreadSnoozedPayloadSchema;
export const ThreadUnsnoozedPayload = ContractsThreadUnsnoozedPayloadSchema;
export const ThreadPinnedPayload = ContractsThreadPinnedPayloadSchema;
export const ThreadUnpinnedPayload = ContractsThreadUnpinnedPayloadSchema;
export const ThreadPinReorderedPayload = ContractsThreadPinReorderedPayloadSchema;
export const MessageSentPayloadSchema = ContractsThreadMessageSentPayloadSchema;
export const ThreadProposedPlanUpsertedPayload = ContractsThreadProposedPlanUpsertedPayloadSchema;
@@ -17,6 +17,7 @@ import type {
OrchestrationShellSnapshot,
OrchestrationThread,
OrchestrationThreadDetailSnapshot,
OrchestrationThreadDetailWindow,
OrchestrationThreadShell,
ProjectId,
ThreadId,
@@ -174,9 +175,16 @@ export interface ProjectionSnapshotQueryShape {
* sequence in one consistent transaction, so the returned `snapshotSequence`
* exactly matches the state reflected in `thread` (no interleaving projector
* update between the two reads).
*
* When `window` is provided, the thread's messages, activities, proposed
* plans, and checkpoints are bounded to a page of recent turns and the
* response carries `page` metadata (see `OrchestrationThreadDetailWindow`).
* Without a window the full thread is returned with no `page` field —
* pagination is strictly opt-in.
*/
readonly getThreadDetailSnapshot: (
threadId: ThreadId,
window?: OrchestrationThreadDetailWindow,
) => Effect.Effect<Option.Option<OrchestrationThreadDetailSnapshot>, ProjectionRepositoryError>;
}
@@ -0,0 +1,173 @@
import { describe, expect, it } from "vite-plus/test";
import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
describe("ThreadBackgroundLiveness", () => {
it("agents present as working; monitors as monitoring; agents win", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-1";
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: undefined,
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
liveness.recordTaskLiveness({
threadId,
taskId: "a1",
taskType: "subagent",
status: undefined,
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "a1",
taskType: "subagent",
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("terminal rows without a taskType still clear monitor entries", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-2";
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: "local_bash",
status: undefined,
kind: "started",
});
// Terminal tick arrives with no taskType (common on task.completed).
liveness.recordTaskLiveness({
threadId,
taskId: "m1",
taskType: undefined,
status: "completed",
kind: "completed",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("nested agents (agentId + agent taskType) still count toward liveness", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-nested";
liveness.recordTaskLiveness({
threadId,
taskId: "n1",
taskType: "local_agent",
status: undefined,
kind: "started",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "n1",
taskType: "local_agent",
status: "completed",
kind: "completed",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("untyped rows count as agents; idle is not live; agent-owned tasks are ignored", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-3";
liveness.recordTaskLiveness({
threadId,
taskId: "wf:1",
taskType: undefined,
status: "running",
kind: "progress",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
liveness.recordTaskLiveness({
threadId,
taskId: "wf:1",
taskType: undefined,
status: "idle",
kind: "updated",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
liveness.recordTaskLiveness({
threadId,
taskId: "sh:1",
taskType: "local_bash",
status: undefined,
kind: "started",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("reclassification moves a task between buckets instead of duplicating it", () => {
const liveness = ThreadBackgroundLiveness.make();
const threadId = "t-live-reclass";
// First seen without a taskType: counts as an agent.
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: undefined,
status: "running",
kind: "started",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("working");
// Later transition reveals it's a shell: downgrade to monitoring, not
// a stale duplicate pinning "working".
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: "local_bash",
status: "running",
kind: "progress",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBe("monitoring");
// Turning out to be inert or agent-owned drops the prior entry too.
liveness.recordTaskLiveness({
threadId,
taskId: "x1",
taskType: "local_bash",
status: "running",
kind: "progress",
agentId: "owner",
});
expect(liveness.getThreadBackgroundLiveness(threadId)).toBeNull();
});
it("plan tasks are inert; clear removes everything; instances are isolated", () => {
const a = ThreadBackgroundLiveness.make();
const b = ThreadBackgroundLiveness.make();
a.recordTaskLiveness({
threadId: "t",
taskId: "p1",
taskType: "plan",
status: undefined,
kind: "started",
});
expect(a.getThreadBackgroundLiveness("t")).toBeNull();
a.recordTaskLiveness({
threadId: "t",
taskId: "a1",
taskType: "local_workflow",
status: undefined,
kind: "started",
});
expect(a.getThreadBackgroundLiveness("t")).toBe("working");
expect(b.getThreadBackgroundLiveness("t")).toBeNull();
a.clearThreadLiveness("t");
expect(a.getThreadBackgroundLiveness("t")).toBeNull();
});
});
@@ -0,0 +1,160 @@
/**
* ThreadBackgroundLivenessService - in-memory per-thread background liveness
* for the sidebar status pill.
*
* The turn can settle while native background work runs on (subagent fleets,
* workflow runs, Monitor watch loops); the shell previously showed nothing.
* Ingestion records task lifecycle transitions and the shell query reads the
* derived state at mapping time — no persistence, no migration. After a
* server restart the registry is empty until new task events arrive, which
* matches reality: orphaned background work is not live.
*
* "monitoring" is reserved for watch loops (monitor tasks and background
* shells) when they are the ONLY live work; any agent work presents as
* "working".
*
* @module ThreadBackgroundLivenessService
*/
import { INERT_TASK_TYPES, MONITOR_TASK_TYPES } from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export type ThreadBackgroundLiveness = "working" | "monitoring" | null;
interface ThreadLivenessState {
readonly agents: Set<string>;
readonly monitors: Set<string>;
}
// Classification sets are the shared contracts copies (MONITOR_TASK_TYPES:
// watch loops — monitor tasks plus background shells, which in practice are
// PR babysitting/log tails since pacing sleeps complete inside the turn;
// INERT_TASK_TYPES: plan-mode bookkeeping) so this registry, ingestion's
// agentKind stamp, and the client fold can never drift apart.
const TERMINAL_STATUSES: ReadonlySet<string> = new Set([
"completed",
"failed",
"stopped",
"cancelled",
"interrupted",
]);
export class ThreadBackgroundLivenessService extends Context.Service<
ThreadBackgroundLivenessService,
{
/**
* Feed one task lifecycle transition. taskType may be absent on
* synthesized rows (workflow members, Codex children) — those count as
* agents. agentId marks a task launched from inside a subagent: its
* internal shells are covered by the owning agent's liveness, but a
* NESTED AGENT (agentId + agent-flavored taskType) still counts — it
* can outlive its parent and must keep the thread Working.
*/
readonly recordTaskLiveness: (input: {
readonly threadId: string;
readonly taskId: string;
readonly taskType: string | undefined;
readonly status: string | undefined;
readonly kind: "started" | "progress" | "updated" | "completed";
readonly agentId?: string | undefined;
}) => void;
/** Session death orphans all of a thread's background work. */
readonly clearThreadLiveness: (threadId: string) => void;
/**
* Two-state vocabulary by design: any live agent work is "working";
* "monitoring" only when watch loops are the ONLY live work.
*/
readonly getThreadBackgroundLiveness: (threadId: string) => ThreadBackgroundLiveness;
}
>()("t3/orchestration/ThreadBackgroundLiveness/ThreadBackgroundLivenessService") {}
export function make(): ThreadBackgroundLivenessService["Service"] {
const stateByThreadId = new Map<string, ThreadLivenessState>();
const stateFor = (threadId: string): ThreadLivenessState => {
const existing = stateByThreadId.get(threadId);
if (existing) {
return existing;
}
const created: ThreadLivenessState = { agents: new Set(), monitors: new Set() };
stateByThreadId.set(threadId, created);
return created;
};
// Classification is per-transition, not sticky: a task first seen without
// a taskType may later reveal itself as a shell, become inert, or turn out
// to be agent-owned. Every path drops any prior entry for the taskId so a
// stale bucket assignment can't pin the thread's status (review finding).
const drop = (threadId: string, taskId: string) => {
const state = stateByThreadId.get(threadId);
if (!state) {
return;
}
state.agents.delete(taskId);
state.monitors.delete(taskId);
if (state.agents.size === 0 && state.monitors.size === 0) {
stateByThreadId.delete(threadId);
}
};
return {
recordTaskLiveness: (input) => {
const taskType = input.taskType;
if (taskType !== undefined && INERT_TASK_TYPES.has(taskType)) {
drop(input.threadId, input.taskId);
return;
}
// A subagent's internal non-agent work (its own shells/monitors) is
// covered by the owning agent's liveness. Nested agents fall through:
// they can outlive their parent (review finding).
if (
input.agentId !== undefined &&
(taskType === undefined || MONITOR_TASK_TYPES.has(taskType))
) {
drop(input.threadId, input.taskId);
return;
}
// Idle counts as not-live: a resting (resumable) Codex child isn't
// doing anything, and an all-idle fleet must not pin Working.
const terminal =
input.kind === "completed" ||
input.status === "idle" ||
(input.status !== undefined && TERMINAL_STATUSES.has(input.status));
if (terminal) {
drop(input.threadId, input.taskId);
return;
}
drop(input.threadId, input.taskId);
const state = stateFor(input.threadId);
const bucket =
taskType !== undefined && MONITOR_TASK_TYPES.has(taskType) ? state.monitors : state.agents;
bucket.add(input.taskId);
},
clearThreadLiveness: (threadId) => {
stateByThreadId.delete(threadId);
},
getThreadBackgroundLiveness: (threadId) => {
const state = stateByThreadId.get(threadId);
if (!state) {
return null;
}
if (state.agents.size > 0) {
return "working";
}
if (state.monitors.size > 0) {
return "monitoring";
}
return null;
},
};
}
export const layer = Layer.effect(ThreadBackgroundLivenessService, Effect.sync(make));
@@ -0,0 +1,44 @@
import { describe, expect, it } from "vite-plus/test";
import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";
describe("ThreadPlanProgress", () => {
it("tracks the in-progress step and clears when the plan completes", () => {
const progress = ThreadPlanProgress.make();
const threadId = "t-plan-1";
progress.recordPlanProgress(threadId, [
{ step: "Audit failure paths", status: "completed" },
{ step: "Implement the fix", status: "inProgress" },
{ step: "Run targeted tests", status: "pending" },
]);
expect(progress.getThreadPlanProgress(threadId)).toEqual({
step: "Implement the fix",
completedSteps: 1,
totalSteps: 3,
});
progress.recordPlanProgress(threadId, [
{ step: "Audit failure paths", status: "completed" },
{ step: "Implement the fix", status: "completed" },
{ step: "Run targeted tests", status: "completed" },
]);
expect(progress.getThreadPlanProgress(threadId)).toBeNull();
});
it("falls back to the first non-completed step when nothing is in progress", () => {
const progress = ThreadPlanProgress.make();
const threadId = "t-plan-2";
progress.recordPlanProgress(threadId, [
{ step: "First", status: "pending" },
{ step: "Second", status: "pending" },
]);
expect(progress.getThreadPlanProgress(threadId)?.step).toBe("First");
});
it("clearThreadPlanProgress removes the entry (turn settled / session died)", () => {
const progress = ThreadPlanProgress.make();
const threadId = "t-plan-3";
progress.recordPlanProgress(threadId, [{ step: "Only step", status: "inProgress" }]);
progress.clearThreadPlanProgress(threadId);
expect(progress.getThreadPlanProgress(threadId)).toBeNull();
});
});
@@ -0,0 +1,76 @@
/**
* ThreadPlanProgressService - in-memory per-thread plan progress for the
* Working indicators (sidebar rows, in-chat working line).
*
* Plans are a progress annotation, not a surface of their own: the useful
* kernel of a turn.plan.updated event is "which step is the agent on right
* now". Ingestion records the current step here and the shell query reads it
* at mapping time — no persistence, no migration (same pattern as
* ThreadBackgroundLivenessService). Cleared when the turn settles or the
* session dies, so a finished plan never lingers as stale UI.
*
* @module ThreadPlanProgressService
*/
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
export interface ThreadPlanProgress {
readonly step: string;
readonly completedSteps: number;
readonly totalSteps: number;
}
interface PlanStepInput {
readonly step: string;
readonly status: string;
}
export class ThreadPlanProgressService extends Context.Service<
ThreadPlanProgressService,
{
/**
* Feed one turn.plan.updated payload. An all-completed plan clears the
* entry (the turn is wrapping up; nothing is "in progress" anymore).
*/
readonly recordPlanProgress: (threadId: string, plan: ReadonlyArray<PlanStepInput>) => void;
/** Turn settled or session died: the working indicator reverts to plain. */
readonly clearThreadPlanProgress: (threadId: string) => void;
readonly getThreadPlanProgress: (threadId: string) => ThreadPlanProgress | null;
}
>()("t3/orchestration/ThreadPlanProgress/ThreadPlanProgressService") {}
export function make(): ThreadPlanProgressService["Service"] {
const progressByThreadId = new Map<string, ThreadPlanProgress>();
return {
recordPlanProgress: (threadId, plan) => {
const totalSteps = plan.length;
const completedSteps = plan.filter((step) => step.status === "completed").length;
// Current step: the in-progress one, else the first pending one (a
// plan that was just written has no in-progress step yet).
const current =
plan.find((step) => step.status === "inProgress") ??
plan.find((step) => step.status !== "completed");
if (totalSteps === 0 || completedSteps === totalSteps || current === undefined) {
progressByThreadId.delete(threadId);
return;
}
progressByThreadId.set(threadId, {
step: current.step,
completedSteps,
totalSteps,
});
},
clearThreadPlanProgress: (threadId) => {
progressByThreadId.delete(threadId);
},
getThreadPlanProgress: (threadId) => progressByThreadId.get(threadId) ?? null,
};
}
export const layer = Layer.effect(ThreadPlanProgressService, Effect.sync(make));
@@ -16,6 +16,7 @@ const PINNED_AT = "1969-12-30T00:00:00.000Z";
function makeReadModel(input: {
readonly pinnedAt?: string | null;
readonly pinOrderKey?: string | null;
readonly archivedAt?: string | null;
readonly settledOverride?: "settled" | "active" | null;
readonly settledAt?: string | null;
@@ -44,6 +45,7 @@ function makeReadModel(input: {
snoozedUntil: input.snoozedUntil ?? null,
snoozedAt: input.snoozedAt ?? (input.snoozedUntil != null ? PINNED_AT : null),
pinnedAt: input.pinnedAt ?? null,
pinOrderKey: input.pinOrderKey ?? null,
deletedAt: null,
messages: [],
proposedPlans: [],
@@ -223,4 +225,100 @@ it.layer(NodeServices.layer)("pinned thread decider", (it) => {
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
it.effect("a fresh pin carries the client's order key", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-keyed"),
threadId: ThreadId.make("thread-1"),
orderKey: "g",
},
readModel: makeReadModel({}),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinOrderKey).toBe("g");
}
}),
);
it.effect(
"re-pinning ignores the incoming order key so raced pins cannot move a placed thread",
() =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin",
commandId: CommandId.make("cmd-pin-keyed-again"),
threadId: ThreadId.make("thread-1"),
orderKey: "t",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pinned");
if (events[0]?.type === "thread.pinned") {
expect(events[0].payload.pinOrderKey).toBeUndefined();
}
}),
);
it.effect("reorders a pinned thread, stamping the new key", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder"),
threadId: ThreadId.make("thread-1"),
orderKey: "m",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pin-reordered");
if (events[0]?.type === "thread.pin-reordered") {
expect(events[0].payload.orderKey).toBe("m");
// A real move stamps the command time (the test clock), not the
// thread's previous updatedAt.
expect(events[0].payload.updatedAt).not.toBe(NOW);
}
}),
);
it.effect("reordering onto the same key preserves updatedAt", () =>
Effect.gen(function* () {
const event = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder-noop"),
threadId: ThreadId.make("thread-1"),
orderKey: "g",
},
readModel: makeReadModel({ pinnedAt: PINNED_AT, pinOrderKey: "g" }),
});
const events = Array.isArray(event) ? event : [event];
expect(events[0]?.type).toBe("thread.pin-reordered");
if (events[0]?.type === "thread.pin-reordered") {
expect(events[0].payload.updatedAt).toBe(NOW);
}
}),
);
it.effect("rejects reordering an unpinned thread", () =>
Effect.gen(function* () {
const error = yield* decideOrchestrationCommand({
command: {
type: "thread.pin.reorder",
commandId: CommandId.make("cmd-reorder-unpinned"),
threadId: ThreadId.make("thread-1"),
orderKey: "m",
},
readModel: makeReadModel({}),
}).pipe(Effect.flip);
expect(error._tag).toBe("OrchestrationCommandInvariantError");
}),
);
});
+43
View File
@@ -676,6 +676,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
payload: {
threadId: command.threadId,
pinnedAt: existingPinnedAt ?? occurredAt,
// A fresh pin takes the client's slot in the arranged order; on a
// re-pin the existing key wins so raced duplicates cannot move a
// thread the user already placed.
...(existingPinnedAt === null && command.orderKey !== undefined
? { pinOrderKey: command.orderKey }
: {}),
updatedAt: existingPinnedAt !== null ? thread.updatedAt : occurredAt,
},
};
@@ -745,6 +751,43 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.pin.reorder": {
const thread = yield* requireThreadNotArchived({
readModel,
command,
threadId: command.threadId,
});
// Only pinned threads have a slot in the arranged order. Rejecting
// (rather than silently pinning) keeps a raced reorder-after-unpin
// from resurrecting a pin the user just cleared.
if (thread.pinnedAt == null) {
return yield* Effect.fail(
new OrchestrationCommandInvariantError({
commandType: command.type,
detail: `thread ${command.threadId} is not pinned and cannot be reordered`,
}),
);
}
// Idempotent by re-emission (see thread.settle): a duplicate drop on
// the same slot keeps the existing updatedAt so it projects as a no-op.
const keyUnchanged = thread.pinOrderKey === command.orderKey;
const occurredAt = yield* nowIso;
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt,
commandId: command.commandId,
})),
type: "thread.pin-reordered",
payload: {
threadId: command.threadId,
orderKey: command.orderKey,
updatedAt: keyUnchanged ? thread.updatedAt : occurredAt,
},
};
}
case "thread.meta.update": {
const thread = yield* requireThread({
readModel,
+11 -1
View File
@@ -66,7 +66,17 @@ export const orchestrationHttpApiLayer = HttpApiBuilder.group(
yield* annotateEnvironmentRequest(args.endpoint.name);
yield* requireEnvironmentScope(AuthOrchestrationReadScope);
const snapshot = yield* projectionSnapshotQuery
.getThreadDetailSnapshot(args.params.threadId)
.getThreadDetailSnapshot(
args.params.threadId,
args.payload.turnLimit === undefined
? undefined
: {
turnLimit: args.payload.turnLimit,
...(args.payload.beforeCursor !== undefined
? { beforeCursor: args.payload.beforeCursor }
: {}),
},
)
.pipe(
Effect.catch((cause) =>
failEnvironmentInternal("orchestration_thread_snapshot_failed", cause),
@@ -75,3 +75,80 @@ it.effect("projects pin lifecycle events", () =>
expect(unpinned.threads[0]?.pinnedAt).toBeNull();
}),
);
it.effect("projects pin order key lifecycle", () =>
Effect.gen(function* () {
const now = "2026-01-01T00:00:00.000Z";
const created = yield* projectEvent(
createEmptyReadModel(now),
makeEvent({
sequence: 1,
type: "thread.created",
payload: {
threadId: ThreadId.make("thread-1"),
projectId: ProjectId.make("project-1"),
title: "Thread",
modelSelection: { provider: "codex", model: "gpt-5.4" },
runtimeMode: "full-access",
interactionMode: "default",
branch: null,
worktreePath: null,
createdAt: now,
updatedAt: now,
},
}),
);
expect(created.threads[0]?.pinOrderKey ?? null).toBeNull();
// Fresh pin carries the client's slot in the arranged order.
const pinned = yield* projectEvent(
created,
makeEvent({
sequence: 2,
type: "thread.pinned",
payload: {
threadId: ThreadId.make("thread-1"),
pinnedAt: now,
pinOrderKey: "g",
updatedAt: now,
},
}),
);
expect(pinned.threads[0]?.pinOrderKey).toBe("g");
// Re-pins and events from pre-reorder servers omit the field entirely;
// the existing key must survive rather than being nulled out.
const repinned = yield* projectEvent(
pinned,
makeEvent({
sequence: 3,
type: "thread.pinned",
payload: { threadId: ThreadId.make("thread-1"), pinnedAt: now, updatedAt: now },
}),
);
expect(repinned.threads[0]?.pinOrderKey).toBe("g");
// A drag persists the new slot.
const reordered = yield* projectEvent(
repinned,
makeEvent({
sequence: 4,
type: "thread.pin-reordered",
payload: { threadId: ThreadId.make("thread-1"), orderKey: "m", updatedAt: now },
}),
);
expect(reordered.threads[0]?.pinOrderKey).toBe("m");
// Unpin clears the slot: re-pinning is "pin again", not "restore an
// ancient position".
const unpinned = yield* projectEvent(
reordered,
makeEvent({
sequence: 5,
type: "thread.unpinned",
payload: { threadId: ThreadId.make("thread-1"), updatedAt: now },
}),
);
expect(unpinned.threads[0]?.pinOrderKey).toBeNull();
}),
);
@@ -24,6 +24,7 @@ import {
ThreadRuntimeModeSetPayload,
ThreadSettledPayload,
ThreadPinnedPayload,
ThreadPinReorderedPayload,
ThreadSnoozedPayload,
ThreadUnpinnedPayload,
ThreadUnarchivedPayload,
@@ -402,6 +403,7 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: payload.pinnedAt,
...(payload.pinOrderKey !== undefined ? { pinOrderKey: payload.pinOrderKey } : {}),
updatedAt: payload.updatedAt,
}),
})),
@@ -413,6 +415,20 @@ export function projectEvent(
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinnedAt: null,
// Unpin clears the slot: re-pinning is "pin again", not "restore
// an ancient position".
pinOrderKey: null,
updatedAt: payload.updatedAt,
}),
})),
);
case "thread.pin-reordered":
return decodeForEvent(ThreadPinReorderedPayload, event.payload, event.type, "payload").pipe(
Effect.map((payload) => ({
...nextBase,
threads: updateThread(nextBase.threads, payload.threadId, {
pinOrderKey: payload.orderKey,
updatedAt: payload.updatedAt,
}),
})),
@@ -5,6 +5,8 @@ import { OrchestrationEventStoreLive } from "../persistence/Layers/Orchestration
import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
import * as ThreadBackgroundLiveness from "./ThreadBackgroundLiveness.ts";
import * as ThreadPlanProgress from "./ThreadPlanProgress.ts";
export const OrchestrationEventInfrastructureLayerLive = Layer.mergeAll(
OrchestrationEventStoreLive,
@@ -19,6 +21,13 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
// Shared background-liveness and plan-progress registries: written by
// runtime ingestion, read by the snapshot query. provideMerge feeds the
// same instance to the snapshot query here and re-exports it for runtime
// ingestion.
).pipe(
Layer.provideMerge(ThreadBackgroundLiveness.layer),
Layer.provideMerge(ThreadPlanProgress.layer),
);
export const OrchestrationLayerLive = Layer.mergeAll(
@@ -0,0 +1,44 @@
import { ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "@effect/vitest";
import {
decodeThreadDetailPageCursor,
encodeThreadDetailPageCursor,
} from "./threadDetailCursor.ts";
describe("threadDetailCursor", () => {
it("round-trips a cursor", () => {
const cursor = {
threadId: ThreadId.make("thread-1"),
beforeAnchorAt: "2026-08-01T00:00:00.000Z",
beforeTurnId: "turn-9",
};
expect(decodeThreadDetailPageCursor(encodeThreadDetailPageCursor(cursor))).toEqual(cursor);
});
it("round-trips empty boundary values", () => {
// The anchor is COALESCE(requested_at, started_at, '') and the turn key
// is COALESCE(turn_id, ''), so a server-minted cursor can legitimately
// carry empty strings; rejecting them would degrade a valid cursor to a
// first-page request that repeats recent history (review finding).
const cursor = {
threadId: ThreadId.make("thread-1"),
beforeAnchorAt: "",
beforeTurnId: "",
};
expect(decodeThreadDetailPageCursor(encodeThreadDetailPageCursor(cursor))).toEqual(cursor);
});
it("rejects malformed input", () => {
expect(decodeThreadDetailPageCursor("not-base64-json")).toBeNull();
expect(decodeThreadDetailPageCursor(Buffer.from("[]").toString("base64url"))).toBeNull();
expect(
decodeThreadDetailPageCursor(Buffer.from(JSON.stringify({ t: "" })).toString("base64url")),
).toBeNull();
expect(
decodeThreadDetailPageCursor(
Buffer.from(JSON.stringify({ t: "thread-1", a: 5, i: "x" })).toString("base64url"),
),
).toBeNull();
});
});
@@ -0,0 +1,62 @@
import type { ThreadId } from "@t3tools/contracts";
/**
* Opaque, exclusive cursor for windowed thread detail reads. Encodes the thread
* id and the keyset boundary of an already-delivered page: the boundary turn's
* anchor timestamp (`COALESCE(requested_at, started_at, '')`) and turn id.
* Passing it back requests the adjacent disjoint slice of strictly older turns
* under `(anchor, turn_id)` ordering.
*
* The boundary is deliberately NOT a `projection_turns.row_id`: row ids are
* rewritten by the revert projector (delete + re-upsert) and by projection
* rebuilds, which would silently invalidate every persisted cursor with no
* event emitted. The (anchor, turnId) pair is derived from event content, so
* cursors survive both and no client-side refresh machinery is needed. The
* anchor doubles as the time bound for rows with no turn linkage (straggler
* user messages, turnless activities). The thread id is embedded so a cursor
* can never be replayed against a different thread. Clients must treat the
* string as opaque.
*/
export interface ThreadDetailPageCursor {
readonly threadId: ThreadId;
readonly beforeAnchorAt: string;
/** Boundary turn id; "" for the rare turn row with a null turn_id. */
readonly beforeTurnId: string;
}
export function encodeThreadDetailPageCursor(cursor: ThreadDetailPageCursor): string {
return Buffer.from(
JSON.stringify({ t: cursor.threadId, a: cursor.beforeAnchorAt, i: cursor.beforeTurnId }),
).toString("base64url");
}
/**
* Returns null for anything that is not a well-formed cursor. Callers degrade
* a malformed or foreign-thread cursor to a first-page request.
*/
export function decodeThreadDetailPageCursor(encoded: string): ThreadDetailPageCursor | null {
let parsed: unknown;
try {
parsed = JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
} catch {
return null;
}
if (parsed === null || typeof parsed !== "object") {
return null;
}
const record = parsed as Record<string, unknown>;
if (typeof record.t !== "string" || record.t.length === 0) {
return null;
}
// Empty strings are valid boundary values, not malformed input: the anchor
// is COALESCE(requested_at, started_at, ''), so a boundary turn with no
// timestamps encodes a: "" (and sorts before every real anchor, correctly
// ending the walk); the turn key is "" for a null turn_id.
if (typeof record.a !== "string") {
return null;
}
if (typeof record.i !== "string") {
return null;
}
return { threadId: record.t as ThreadId, beforeAnchorAt: record.a, beforeTurnId: record.i };
}
@@ -0,0 +1,75 @@
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { it as effectIt } from "@effect/vitest";
import * as Effect from "effect/Effect";
import { afterAll, assert, describe } from "vite-plus/test";
import { readWorkflowScript } from "./workflowScriptQuery.ts";
const root = NodePath.join(NodeOS.homedir(), ".claude", "projects", "__wf_script_test__");
NodeFS.mkdirSync(root, { recursive: true });
const scriptPath = NodePath.join(root, "run.js");
NodeFS.writeFileSync(scriptPath, "export const meta = {};\n");
const outside = NodePath.join(NodeOS.tmpdir(), "wf-outside.js");
NodeFS.writeFileSync(outside, "evil\n");
const link = NodePath.join(root, "sneaky.js");
try {
NodeFS.symlinkSync(outside, link);
} catch (error) {
// Tolerate only "already exists" from a prior run — any other failure
// (EPERM etc.) must fail setup, or the escape test below would pass
// vacuously on "not-found" without testing containment.
if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
throw error;
}
}
if (!NodeFS.lstatSync(link).isSymbolicLink()) {
throw new Error("test setup: sneaky.js must be a symlink");
}
afterAll(() => {
NodeFS.rmSync(root, { recursive: true, force: true });
NodeFS.rmSync(outside, { force: true });
});
describe("readWorkflowScript containment", () => {
effectIt.effect("serves a real script under the projects root", () =>
Effect.gen(function* () {
const result = yield* readWorkflowScript({ scriptPath });
assert.include(result.contents, "export const meta");
assert.equal(result.truncated, false);
}),
);
effectIt.effect("rejects relative and non-js paths", () =>
Effect.gen(function* () {
const relative = yield* Effect.exit(readWorkflowScript({ scriptPath: "run.js" }));
assert.equal(relative._tag, "Failure");
const nonJs = yield* Effect.exit(
readWorkflowScript({ scriptPath: scriptPath.replace(".js", ".ts") }),
);
assert.equal(nonJs._tag, "Failure");
}),
);
effectIt.effect("rejects paths outside the root and symlink escapes", () =>
Effect.gen(function* () {
const escaped = yield* Effect.exit(readWorkflowScript({ scriptPath: outside }));
assert.equal(escaped._tag, "Failure");
// A symlink INSIDE the root pointing outside must fail specifically on
// realpath re-containment — a "not-found" would mean the link was
// never exercised and the assertion proves nothing.
const sneaky = yield* Effect.exit(
readWorkflowScript({ scriptPath: link }).pipe(
Effect.flip,
Effect.map((error) => error.reason),
),
);
assert.equal(sneaky._tag, "Success");
if (sneaky._tag === "Success") {
assert.equal(sneaky.value, "outside-root");
}
}),
);
});
@@ -0,0 +1,124 @@
// @effect-diagnostics nodeBuiltinImport:off
/**
* Read-only access to persisted workflow scripts for the Agents surface's
* "{} script" affordance.
*
* Containment rules (lifted from the reviewed #3650 inspection service):
* - the resolved realpath must live under ~/.claude/projects (where the
* Claude harness persists workflow scripts) — realpath re-containment
* defeats symlink escapes, including a symlinked leaf file;
* - only .js leaf files are served;
* - reads are size-capped rather than failed, with a truncation marker.
*
* The client-supplied path is a hint from the workflow's runHandles; it is
* never trusted beyond these checks.
*/
import * as NodeFSP from "node:fs/promises";
import * as NodeOS from "node:os";
import * as NodePath from "node:path";
import { OrchestrationGetWorkflowScriptError } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
const SCRIPT_BYTE_CAP = 256 * 1024;
function scriptsRoot(): string {
return NodePath.join(NodeOS.homedir(), ".claude", "projects");
}
export const readWorkflowScript = Effect.fn("orchestration.readWorkflowScript")(function* (input: {
readonly scriptPath: string;
}) {
const requested = input.scriptPath;
if (!NodePath.isAbsolute(requested) || NodePath.extname(requested) !== ".js") {
return yield* Effect.fail(
new OrchestrationGetWorkflowScriptError({ reason: "invalid-path", scriptPath: requested }),
);
}
const root = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(scriptsRoot()),
catch: (cause) =>
new OrchestrationGetWorkflowScriptError({
reason: "root-unavailable",
scriptPath: requested,
cause,
}),
});
// Realpath the FILE itself (not just its directory): a symlink named
// like a script inside a contained directory must not escape.
const resolved = yield* Effect.tryPromise({
try: () => NodeFSP.realpath(requested),
catch: (cause) =>
new OrchestrationGetWorkflowScriptError({
reason: "not-found",
scriptPath: requested,
cause,
}),
});
if (resolved !== root && !resolved.startsWith(`${root}${NodePath.sep}`)) {
return yield* Effect.fail(
new OrchestrationGetWorkflowScriptError({ reason: "outside-root", scriptPath: resolved }),
);
}
if (NodePath.extname(resolved) !== ".js") {
return yield* Effect.fail(
new OrchestrationGetWorkflowScriptError({ reason: "not-js", scriptPath: resolved }),
);
}
// TOCTOU-safe read (review finding): open FIRST, then verify what was
// actually opened via the file descriptor. Re-checking the path after
// open would race against a swap; fstat on the handle cannot. The two
// containment checks fail with their own tagged reasons (not manufactured
// Errors folded into read-failed); "read-failed" is reserved for genuine
// platform failures with the real cause attached.
const read = yield* Effect.tryPromise({
try: async () => {
const handle = await NodeFSP.open(resolved, "r");
try {
const stat = await handle.stat();
if (!stat.isFile()) {
return { failure: "not-regular-file" as const };
}
// The opened inode must be the same one realpath resolved to: a
// process swapping the path between realpath and open changes the
// inode, which this comparison catches.
const pathStat = await NodeFSP.lstat(resolved);
if (stat.ino !== pathStat.ino || stat.dev !== pathStat.dev) {
return { failure: "changed-during-read" as const };
}
const truncated = stat.size > SCRIPT_BYTE_CAP;
const buffer = Buffer.alloc(Math.min(stat.size, SCRIPT_BYTE_CAP));
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
return {
contents: buffer.subarray(0, bytesRead).toString("utf8"),
truncated,
};
} finally {
await handle.close();
}
},
catch: (cause) =>
new OrchestrationGetWorkflowScriptError({
reason: "read-failed",
scriptPath: resolved,
cause,
}),
});
if ("failure" in read) {
return yield* new OrchestrationGetWorkflowScriptError({
reason: read.failure,
scriptPath: resolved,
});
}
return {
scriptPath: resolved,
contents: read.contents,
truncated: read.truncated,
};
});
@@ -48,6 +48,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until,
snoozed_at,
pinned_at,
pin_order_key,
title_regeneration_request_id,
title_regeneration_started_at,
latest_user_message_at,
@@ -74,6 +75,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
${row.snoozedUntil},
${row.snoozedAt},
${row.pinnedAt},
${row.pinOrderKey ?? null},
${row.titleRegenerationRequestId ?? null},
${row.titleRegenerationStartedAt ?? null},
${row.latestUserMessageAt},
@@ -100,6 +102,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until = excluded.snoozed_until,
snoozed_at = excluded.snoozed_at,
pinned_at = excluded.pinned_at,
pin_order_key = excluded.pin_order_key,
title_regeneration_request_id = excluded.title_regeneration_request_id,
title_regeneration_started_at = excluded.title_regeneration_started_at,
latest_user_message_at = excluded.latest_user_message_at,
@@ -133,6 +136,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -168,6 +172,7 @@ const makeProjectionThreadRepository = Effect.gen(function* () {
snoozed_until AS "snoozedUntil",
snoozed_at AS "snoozedAt",
pinned_at AS "pinnedAt",
pin_order_key AS "pinOrderKey",
title_regeneration_request_id AS "titleRegenerationRequestId",
title_regeneration_started_at AS "titleRegenerationStartedAt",
latest_user_message_at AS "latestUserMessageAt",
@@ -49,6 +49,8 @@ import Migration0033 from "./Migrations/033_ProjectionThreadsSettled.ts";
import Migration0034 from "./Migrations/034_ProjectionThreadsSnoozed.ts";
import Migration0035 from "./Migrations/035_ProjectionThreadTitleRegeneration.ts";
import Migration0036 from "./Migrations/036_ProjectionThreadsPinned.ts";
import Migration0037 from "./Migrations/037_ProjectionTurnsKeysetIndex.ts";
import Migration0038 from "./Migrations/038_ProjectionThreadsPinOrderKey.ts";
/**
* Migration loader with all migrations defined inline.
@@ -97,6 +99,8 @@ export const migrationEntries = [
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
[37, "ProjectionTurnsKeysetIndex", Migration0037],
[38, "ProjectionThreadsPinOrderKey", Migration0038],
] as const;
export const migrationManifest = migrationEntries.map(([id, name]) => [id, name] as const);
@@ -0,0 +1,17 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
/**
* Composite index for windowed thread detail reads. Pagination orders turns by
* the stable keyset (requested_at, turn_id); the pre-existing
* (thread_id, requested_at) index cannot serve the tiebreak order, forcing a
* temp B-tree over all of a thread's turns before the page LIMIT applies.
* With this index the candidates scan is genuinely bounded by the page size.
*/
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_turns_thread_keyset
ON projection_turns(thread_id, requested_at, turn_id)
`;
});
@@ -0,0 +1,16 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const columns = yield* sql<{ readonly name: string }>`
PRAGMA table_info(projection_threads)
`;
if (!columns.some((column) => column.name === "pin_order_key")) {
yield* sql`
ALTER TABLE projection_threads
ADD COLUMN pin_order_key TEXT
`;
}
});
@@ -42,6 +42,7 @@ export const ProjectionThread = Schema.Struct({
snoozedUntil: Schema.NullOr(IsoDateTime),
snoozedAt: Schema.NullOr(IsoDateTime),
pinnedAt: Schema.NullOr(IsoDateTime),
pinOrderKey: Schema.optional(Schema.NullOr(Schema.String)),
titleRegenerationRequestId: Schema.optional(Schema.NullOr(CommandId)),
titleRegenerationStartedAt: Schema.optional(Schema.NullOr(IsoDateTime)),
latestUserMessageAt: Schema.NullOr(IsoDateTime),
@@ -2,11 +2,13 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Sink from "effect/Sink";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
@@ -155,6 +157,130 @@ it.effect("discovers editors through the service API", () =>
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
it.effect("memoizes editor discovery and refreshes after the cache window", () => {
let statCalls = 0;
const fileInfo = { type: "File" } as FileSystem.File.Info;
const launcherLayer = ExternalLauncher.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
stat: () =>
Effect.sync(() => {
statCalls += 1;
return fileInfo;
}),
}),
Path.layer,
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
),
),
),
);
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const first = yield* launcher.resolveAvailableEditors();
assert.equal(first.includes("vscode"), true);
const statCallsAfterFirstScan = statCalls;
assert.isAbove(statCallsAfterFirstScan, 0);
// Past the shared command-resolution cache TTL (30s) but within the
// discovery cache window: the memoized set is reused without any scan.
yield* TestClock.adjust("31 seconds");
const second = yield* launcher.resolveAvailableEditors();
assert.deepEqual([...second], [...first]);
assert.equal(statCalls, statCallsAfterFirstScan);
// Past the discovery cache window the next call rescans.
yield* TestClock.adjust("30 seconds");
yield* launcher.resolveAvailableEditors();
assert.isAbove(statCalls, statCallsAfterFirstScan);
}).pipe(
Effect.provide(
Layer.mergeAll(
launcherLayer,
Layer.succeed(HostProcessPlatform, "win32"),
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
PATH: "C:\\t3-editor-discovery-cache-test",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
}),
),
TestClock.layer(),
),
),
);
});
// A client that disconnects mid-scan interrupts the shared discovery effect on
// the connection fiber. The cache must not retain that interrupt: doing so
// replayed it to every later connect for the whole TTL, so `server.getConfig`
// failed and no client could reconnect until the server restarted.
it.effect("rescans after an interrupted discovery instead of caching the interrupt", () => {
const fileInfo = { type: "File" } as FileSystem.File.Info;
let blockFirstScan = true;
let scans = 0;
const launcherLayer = ExternalLauncher.layer.pipe(
Layer.provide(
Layer.mergeAll(
FileSystem.layerNoop({
// The first scan parks inside `stat` so the interrupt lands while
// discovery is in flight, which is what a client disconnecting
// mid-connect does to the shared effect.
stat: () =>
Effect.gen(function* () {
scans += 1;
if (blockFirstScan) {
return yield* Effect.never;
}
return fileInfo;
}),
}),
Path.layer,
Layer.succeed(
ChildProcessSpawner.ChildProcessSpawner,
ChildProcessSpawner.make(() => Effect.sync(() => makeMockDetachedHandle())),
),
),
),
);
return Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
const fiber = yield* Effect.forkChild(launcher.resolveAvailableEditors());
yield* Effect.yieldNow;
yield* Fiber.interrupt(fiber);
// The next connect must still get a real answer well inside the TTL.
blockFirstScan = false;
scans = 0;
const editors = yield* launcher.resolveAvailableEditors();
assert.equal(editors.includes("vscode"), true);
assert.isAbove(scans, 0);
}).pipe(
Effect.provide(
Layer.mergeAll(
launcherLayer,
Layer.succeed(HostProcessPlatform, "win32"),
ConfigProvider.layer(
ConfigProvider.fromEnv({
env: {
PATH: "C:\\t3-editor-discovery-interrupt-test",
PATHEXT: ".COM;.EXE;.BAT;.CMD",
},
}),
),
),
),
);
});
it.effect("rejects unknown editors through the service API", () =>
Effect.gen(function* () {
const launcher = yield* ExternalLauncher.ExternalLauncher;
Loaded 100 of 326 files, more files were not shown because too many files have changed in this diff. Show more