Compare commits

..
Author SHA1 Message Date
Theo Browne 082c598716 refactor(clients): share thread list v2 ordering 2026-08-07 03:39:42 -07:00
Theo Browne 8717043ff7 Keep woke threads active after visits 2026-08-07 03:39:42 -07:00
Theo Browne 8d9b77b131 Make sidebar v2 attention states harder to miss 2026-08-07 03:39:42 -07: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
265 changed files with 27766 additions and 3466 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.
+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
@@ -1,10 +1,6 @@
name: Mobile Showcase Screenshots
on:
push:
branches:
- t3bot/mobile-pending-card-glass
- t3bot/mobile-pending-card-glass-before
workflow_dispatch:
inputs:
platform:
@@ -35,7 +31,7 @@ env:
jobs:
ios:
name: iPhone 6.9, iPhone 6.5, and iPad 13
if: github.event_name == 'push' || inputs.platform == 'all' || inputs.platform == 'ios'
if: inputs.platform == 'all' || inputs.platform == 'ios'
runs-on: blacksmith-12vcpu-macos-26
timeout-minutes: 60
steps:
@@ -66,10 +62,10 @@ jobs:
"$vp_pnpm_bin/pnpm" --version
- name: Capture iOS showcase
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance || 'dark' }}"
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}"
- name: Validate App Store Connect assets
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance || 'dark' }}" --validate-only
run: pnpm screenshots:mobile --platform ios --appearance "${{ inputs.appearance }}" --validate-only
- name: Upload iOS screenshots
if: always()
@@ -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
@@ -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
}
}
}
@@ -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,
}}
+2 -2
View File
@@ -68,7 +68,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
const iconColor = useThemeColor("--color-icon");
const mutedColor = useThemeColor("--color-foreground-muted");
const stageLabel = resolveMobileStageLabel(Constants.expoConfig?.extra?.appVariant);
// Thread List v2 lays the list out in fixed creation order, so the
// Thread List v2 owns ordering (attention priority, then creation), so the
// sort/group filter controls would be silently ignored — hide them and
// key the "customized" icon state off the environment filter alone.
const threadListV2Enabled = useThreadListV2Enabled();
@@ -290,7 +290,7 @@ function AndroidHomeHeader(props: HomeHeaderProps) {
function IosHomeHeader(props: HomeHeaderProps) {
const searchBarRef = useRef<SearchBarCommands>(null);
const iconColor = useThemeColor("--color-icon");
// Thread List v2 lays the list out in fixed creation order, so the
// Thread List v2 owns ordering (attention priority, then creation), so the
// sort/group filter controls would be silently ignored — hide them and
// key the "customized" icon state off the environment filter alone.
const threadListV2Enabled = useThreadListV2Enabled();
+2 -1
View File
@@ -475,7 +475,8 @@ export function HomeScreen(props: HomeScreenProps) {
),
[v2ScopedProjectGroup],
);
// Thread List v2 (beta): one flat list in creation order, no grouping.
// Thread List v2 (beta): one flat list, attention priority then creation
// order, with no grouping.
// Settled threads collapse into a recency tail below the card block.
// Settled threads stay in the live shell stream (settled ≠ archived), so
// the partition works directly off live shells — no snapshot merging or
@@ -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>
);
@@ -556,8 +556,8 @@ function BetaSettingsSection() {
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
One flat thread list in creation order. Active work renders as cards; settled threads
collapse to compact rows. Switch back any time.
One flat thread list. Woke and un-settled work comes first; settled threads collapse to
compact rows. Switch back any time.
</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,
}}
@@ -3,7 +3,6 @@ import { Pressable, View } from "react-native";
import { AppText as Text } from "../../components/AppText";
import type { PendingApproval } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingApprovalCardProps {
readonly approval: PendingApproval;
@@ -15,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 (
<PendingCardSurface>
<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>
@@ -53,6 +54,6 @@ export function PendingApprovalCard(props: PendingApprovalCardProps) {
<Text className="font-t3-bold text-sm text-rose-700 dark:text-rose-300">Decline</Text>
</Pressable>
</View>
</PendingCardSurface>
</View>
);
}
@@ -1,35 +0,0 @@
import { isLiquidGlassSupported, LiquidGlassView } from "@callstack/liquid-glass";
import type { ReactNode } from "react";
import { useColorScheme, View, type ViewStyle } from "react-native";
const SURFACE_STYLE: ViewStyle = {
borderRadius: 20,
overflow: "hidden",
};
export function PendingCardSurface(props: { readonly children: ReactNode }) {
const isDarkMode = useColorScheme() === "dark";
const content = <View className="gap-2.5 p-4">{props.children}</View>;
if (isLiquidGlassSupported) {
return (
<LiquidGlassView
effect="regular"
interactive
colorScheme={isDarkMode ? "dark" : "light"}
style={SURFACE_STYLE}
>
{content}
</LiquidGlassView>
);
}
return (
<View
className="rounded-[20px] border border-neutral-200 bg-neutral-100 dark:border-white/6 dark:bg-neutral-900"
style={SURFACE_STYLE}
>
{content}
</View>
);
}
@@ -4,7 +4,6 @@ import { Pressable, View } from "react-native";
import { AppText as Text, AppTextInput as TextInput } from "../../components/AppText";
import { cn } from "../../lib/cn";
import type { PendingUserInput, PendingUserInputDraftAnswer } from "../../lib/threadActivity";
import { PendingCardSurface } from "./PendingCardSurface";
export interface PendingUserInputCardProps {
readonly pendingUserInput: PendingUserInput;
@@ -25,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 (
<PendingCardSurface>
<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>
@@ -101,6 +103,6 @@ export function PendingUserInputCard(props: PendingUserInputCardProps) {
>
<Text className="font-t3-extrabold text-sm text-white">Submit answers</Text>
</Pressable>
</PendingCardSurface>
</View>
);
}
@@ -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,
@@ -644,8 +644,8 @@ function ThreadNavigationSidebarPane(
],
},
] satisfies MenuAction[])),
// v2 lays the list out in fixed creation order — offering sort/group
// controls it silently ignores would be a lie. Environment still
// v2 owns ordering (attention priority, then creation) — offering
// sort/group controls it silently ignores would be a lie. Environment still
// scopes the v2 partition, so it stays.
...(threadListV2Enabled
? []
@@ -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}
@@ -4,6 +4,7 @@ import type {
} from "@t3tools/client-runtime/state/shell";
import type { EnvironmentThreadSearchMatch } from "@t3tools/client-runtime/state/thread-search";
import { canSnooze, resolveSnoozePresets } from "@t3tools/client-runtime/state/thread-settled";
import { resolveSettledTimestamp } from "@t3tools/client-runtime/state/thread-sort";
import type { MenuAction } from "@react-native-menu/menu";
import { memo, useCallback, useEffect, useMemo, useState, type ComponentProps } from "react";
import {
@@ -812,7 +813,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
>
{snoozedRow && props.snoozeWakeLabelText !== undefined
? props.snoozeWakeLabelText
: relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt)}
: relativeTime(resolveSettledTimestamp(thread) ?? thread.createdAt)}
</Text>
</View>
</Pressable>
@@ -21,7 +21,6 @@ import {
resolveThreadListV2SnoozeGateExpiryMs,
resolveThreadListV2Status,
resolveThreadListV2SwipeActions,
sortThreadsForListV2,
} from "./threadListV2";
const environmentId = EnvironmentId.make("environment-1");
@@ -247,17 +246,6 @@ describe("resolveThreadListV2SnoozeGateExpiryMs", () => {
});
});
describe("sortThreadsForListV2", () => {
it("orders by creation time, newest first, ignoring activity", () => {
const sorted = sortThreadsForListV2([
{ id: "oldest", createdAt: "2026-06-01T08:00:00.000Z" },
{ id: "newest", createdAt: "2026-06-01T12:00:00.000Z" },
{ id: "middle", createdAt: "2026-06-01T10:00:00.000Z" },
]);
expect(sorted.map((thread) => thread.id)).toEqual(["newest", "middle", "oldest"]);
});
});
describe("buildThreadListV2Items", () => {
it("hides snoozed threads and counts them — visibility parity with web", () => {
const layout = buildThreadListV2Items({
@@ -282,12 +270,53 @@ describe("buildThreadListV2Items", () => {
now: NOW,
});
// Same createdAt → static sort tiebreaks by id; the point is the woken
// thread is BACK in the card block and the snoozed one is gone.
expect(layout.items.map((item) => item.thread.id)).toEqual(["active", "woken"]);
expect(layout.items.map((item) => item.thread.id)).toEqual(["woken", "active"]);
expect(layout.snoozedCount).toBe(1);
});
it("shares web attention priority while preserving the pinned block", () => {
const layout = buildThreadListV2Items({
threads: [
makeThread({
id: ThreadId.make("woke"),
title: "Woke",
createdAt: "2026-05-01T00:00:00.000Z",
latestUserMessageAt: "2026-05-01T00:00:00.000Z",
snoozedAt: "2026-05-29T00:00:00.000Z",
snoozedUntil: "2026-05-30T00:00:00.000Z",
}),
makeThread({
id: ThreadId.make("unsettled"),
title: "Un-settled",
createdAt: "2026-06-01T08:00:00.000Z",
settledOverride: "active",
}),
makeThread({
id: ThreadId.make("default"),
title: "Default",
createdAt: "2026-06-01T12:00:00.000Z",
}),
makeThread({
id: ThreadId.make("pinned"),
title: "Pinned",
createdAt: "2026-04-01T00:00:00.000Z",
pinnedAt: "2026-06-01T12:00:00.000Z",
}),
],
environmentId: null,
searchQuery: "",
autoSettleAfterDays: 3,
now: NOW,
});
expect(layout.items.map((item) => [item.thread.id, item.variant])).toEqual([
["pinned", "card"],
["woke", "card"],
["unsettled", "card"],
["default", "card"],
]);
});
it("renders pinned threads first and exempts them from auto-settle — parity with web", () => {
const layout = buildThreadListV2Items({
threads: [
@@ -678,7 +707,7 @@ describe("buildThreadListV2Items settled paging", () => {
id: ThreadId.make(`settled-${index}`),
title: `Settled ${index}`,
settledOverride: "settled",
settledAt: NOW,
settledAt: `2026-06-01T0${index}:20:00.000Z`,
latestUserMessageAt: `2026-06-01T0${index}:00:00.000Z`,
// A turn adopted the message (same requestedAt): without it the
// thread reads as a queued turn start, which never settles.
@@ -5,8 +5,14 @@ import {
QUEUED_TURN_START_GRACE_MS,
resolveSnoozePresets,
snoozeWakeLabel,
threadWokeAt,
} from "@t3tools/client-runtime/state/thread-settled";
import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled";
import {
sortSettledThreadsForListV2,
sortThreadsForListV2,
threadListV2Priority,
} from "@t3tools/client-runtime/state/thread-sort";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";
import type { EnvironmentId, ProjectId } from "@t3tools/contracts";
@@ -146,35 +152,6 @@ function parseTimestampMs(isoDate: string): number {
return Number.isNaN(parsed) ? 0 : parsed;
}
/** First VALID timestamp wins: a present-yet-malformed string falls through
to the next candidate rather than sinking the row to the epoch. */
function firstValidTimestampMs(...candidates: ReadonlyArray<string | null | undefined>): number {
for (const candidate of candidates) {
if (candidate == null) continue;
const parsed = Date.parse(candidate);
if (!Number.isNaN(parsed)) return parsed;
}
return 0;
}
/**
* v2 sort: static creation order, newest thread on top. Activity NEVER
* reorders the list — a row holds its position from open until settled, so
* the screen only moves at lifecycle transitions. Mirrors web's
* sortThreadsForSidebarV2.
*/
export function sortThreadsForListV2<T extends { readonly id: string; readonly createdAt: string }>(
threads: readonly T[],
): T[] {
// .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023
// change-by-copy array methods.
return [...threads].sort(
(left, right) =>
parseTimestampMs(right.createdAt) - parseTimestampMs(left.createdAt) ||
left.id.localeCompare(right.id),
);
}
export interface ThreadListV2Item {
readonly thread: EnvironmentThreadShell;
readonly variant: "card" | "slim";
@@ -304,8 +281,9 @@ export function buildThreadListV2ListItems(input: {
}
/**
* Partitions visible threads into the active card block (creation order) and
* the settled recency tail, matching the web v2 list. `autoSettleAfterDays`
* Partitions visible threads into the active card block (attention priority,
* then creation order) and the settled recency tail, matching web v2.
* `autoSettleAfterDays`
* mirrors the web default of 3 — mobile has no client-settings sync yet, so
* the default is fixed here rather than user-configurable.
*/
@@ -357,6 +335,7 @@ export function buildThreadListV2Items(input: {
const active: EnvironmentThreadShell[] = [];
const settled: EnvironmentThreadShell[] = [];
const snoozed: EnvironmentThreadShell[] = [];
const wokeAtByThreadKey = new Map<string, string>();
let nextSnoozeWakeAt: string | null = null;
for (const thread of input.threads) {
// Callers pass live (unarchived) shells; settled threads are among them
@@ -381,6 +360,16 @@ export function buildThreadListV2Items(input: {
const supportsSnooze = input.snoozeEnvironmentIds?.has(thread.environmentId) ?? true;
const changeRequestState =
input.changeRequestStateByKey?.get(`${thread.environmentId}:${thread.id}`) ?? null;
const wokeAt = supportsSnooze ? threadWokeAt(thread, { now: snoozeNow }) : null;
if (wokeAt !== null) {
wokeAtByThreadKey.set(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
wokeAt,
);
}
// 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
@@ -404,7 +393,12 @@ export function buildThreadListV2Items(input: {
}
if (
supportsSettlement &&
effectiveSettled(thread, { now, autoSettleAfterDays, changeRequestState })
effectiveSettled(thread, {
now,
autoSettleAfterDays,
changeRequestState,
suppressAutoSettle: wokeAt !== null,
})
) {
settled.push(thread);
} else {
@@ -412,7 +406,17 @@ export function buildThreadListV2Items(input: {
}
}
const orderedActive = sortThreadsForListV2(active);
const orderedActive = sortThreadsForListV2(active, (thread) =>
threadListV2Priority(thread, {
wokeAt:
wokeAtByThreadKey.get(
threadSearchMatchKey({
environmentId: thread.environmentId,
threadId: thread.id,
}),
) ?? null,
}),
);
const orderedSnoozed = [...snoozed].sort(
(left, right) =>
parseTimestampMs(left.snoozedUntil ?? "") - parseTimestampMs(right.snoozedUntil ?? ""),
@@ -424,11 +428,7 @@ export function buildThreadListV2Items(input: {
: orderedSnoozed.filter(
(thread) => `${thread.environmentId}:${thread.id}` === selectedThreadKey,
);
const orderedSettled = [...settled].sort(
(left, right) =>
firstValidTimestampMs(right.latestUserMessageAt, right.updatedAt) -
firstValidTimestampMs(left.latestUserMessageAt, left.updatedAt),
);
const orderedSettled = sortSettledThreadsForListV2(settled);
const settledLimit = input.settledLimit ?? Number.POSITIVE_INFINITY;
const pagedSettled =
orderedSettled.length > settledLimit ? orderedSettled.slice(0, settledLimit) : orderedSettled;
@@ -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);
@@ -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
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,
+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;
@@ -69,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;
@@ -303,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),
@@ -850,7 +850,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),
@@ -443,6 +448,8 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
hasPendingApprovals: true,
hasPendingUserInput: false,
hasActionableProposedPlan: false,
backgroundLiveness: null,
planProgress: null,
},
]);
@@ -1825,6 +1832,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 +1922,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;
@@ -1041,6 +1079,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,
@@ -1678,6 +1907,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
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,
),
@@ -1818,6 +2051,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
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",
@@ -2090,10 +2327,24 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
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 +2363,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 +2382,10 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
),
),
),
listThreadActivityRowsByThread({ threadId }).pipe(
(bounds === undefined
? listThreadActivityRowsByThread({ threadId })
: listThreadActivityRowsByThreadWindow({ threadId, ...bounds })
).pipe(
Effect.mapError(
toPersistenceSqlOrDecodeError(
"ProjectionSnapshotQuery.getThreadDetailById:listActivities:query",
@@ -2238,23 +2495,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)),
@@ -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;
@@ -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);
@@ -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));
+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),
@@ -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,
};
});
@@ -49,6 +49,7 @@ 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";
/**
* Migration loader with all migrations defined inline.
@@ -97,6 +98,7 @@ export const migrationEntries = [
[34, "ProjectionThreadsSnoozed", Migration0034],
[35, "ProjectionThreadTitleRegeneration", Migration0035],
[36, "ProjectionThreadsPinned", Migration0036],
[37, "ProjectionTurnsKeysetIndex", Migration0037],
] 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)
`;
});
@@ -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;
+45 -1
View File
@@ -19,6 +19,7 @@ import {
} from "@t3tools/contracts";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { isCommandAvailable, resolveSpawnCommand } from "@t3tools/shared/shell";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
@@ -27,6 +28,7 @@ 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 Ref from "effect/Ref";
import * as ChildProcess from "effect/unstable/process/ChildProcess";
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
@@ -298,6 +300,28 @@ const resolveAvailableEditors = Effect.fn("externalLauncher.resolveAvailableEdit
return yield* buildAvailableEditors(platform, env);
});
// Editor discovery walks PATH for every known editor and runs for every
// client connect (the server config embeds the available editors). Memoize
// the discovered set for a bounded window so repeat connects skip even the
// per-command cache lookups in @t3tools/shared/shell.
//
// This deliberately does not use `Effect.cachedWithTTL`: that memoizes the
// first caller's Exit whatever it is, including an interrupt. Callers run this
// on the connection fiber under a timeout (`resolveAvailableEditorsForConfig`),
// so one client disconnecting mid-scan would cache the interrupt and replay it
// to every later connect for the whole TTL, breaking `server.getConfig`
// permanently. Storing only on success means an interrupted scan leaves the
// cache untouched and the next connect simply rescans.
// Expiry uses the monotonic clock (Clock.currentTimeNanos), matching the
// command-resolution cache in @t3tools/shared/shell, so a backward wall-clock
// adjustment cannot keep an expired entry alive.
const EDITOR_DISCOVERY_CACHE_TTL_NANOS = 60_000_000_000n;
interface EditorDiscoveryCacheEntry {
readonly editors: ReadonlyArray<EditorId>;
readonly expiresAtNanos: bigint;
}
/**
* ExternalLauncher - Service tag for browser/editor launch operations.
*/
@@ -443,8 +467,28 @@ export const make = Effect.gen(function* () {
Effect.provideService(Path.Path, path),
);
const editorDiscoveryCache = yield* Ref.make<Option.Option<EditorDiscoveryCacheEntry>>(
Option.none(),
);
const cachedAvailableEditors = Effect.gen(function* () {
const nowNanos = yield* Clock.currentTimeNanos;
const entry = yield* Ref.get(editorDiscoveryCache);
if (Option.isSome(entry) && entry.value.expiresAtNanos > nowNanos) {
return entry.value.editors;
}
const editors = yield* provideCommandResolutionServices(resolveAvailableEditors());
yield* Ref.set(
editorDiscoveryCache,
Option.some({
editors,
expiresAtNanos: nowNanos + EDITOR_DISCOVERY_CACHE_TTL_NANOS,
}),
);
return editors;
});
return ExternalLauncher.of({
resolveAvailableEditors: () => provideCommandResolutionServices(resolveAvailableEditors()),
resolveAvailableEditors: () => cachedAvailableEditors,
launchBrowser: (target) =>
launchBrowser(target).pipe(
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
@@ -55,6 +55,7 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
private failure: unknown | undefined;
public readonly interruptCalls: Array<void> = [];
public readonly stopTaskCalls: Array<string> = [];
public readonly setModelCalls: Array<string | undefined> = [];
public readonly setPermissionModeCalls: Array<string> = [];
public readonly setMaxThinkingTokensCalls: Array<number | null> = [];
@@ -98,6 +99,10 @@ class FakeClaudeQuery implements AsyncIterable<SDKMessage> {
this.interruptCalls.push(undefined);
};
readonly stopTask = async (taskId: string): Promise<void> => {
this.stopTaskCalls.push(taskId);
};
readonly setModel = async (model?: string): Promise<void> => {
this.setModelCalls.push(model);
};
@@ -1445,6 +1450,321 @@ describe("ClaudeAdapterLive", () => {
);
});
it.effect("treats aborted_tools results as interrupted and hides ede_diagnostic errors", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
const turn = yield* adapter.sendTurn({
threadId: session.threadId,
input: "hello",
attachments: [],
});
// Exact shape the CLI emits when Stop lands mid-tool-call: is_error
// is true and the only error is internal diagnostic telemetry.
harness.query.emit({
type: "result",
subtype: "error_during_execution",
is_error: true,
errors: ["[ede_diagnostic] result_type=user last_content_type=n/a stop_reason=tool_use"],
stop_reason: "tool_use",
terminal_reason: "aborted_tools",
session_id: "sdk-session-abort-tools",
uuid: "result-abort-tools",
} as unknown as SDKMessage);
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
assert.deepEqual(
runtimeEvents.map((event) => event.type),
[
"session.started",
"session.configured",
"session.state.changed",
"turn.started",
"thread.started",
"turn.completed",
],
);
const turnCompleted = runtimeEvents[runtimeEvents.length - 1];
assert.equal(turnCompleted?.type, "turn.completed");
if (turnCompleted?.type === "turn.completed") {
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
assert.equal(turnCompleted.payload.state, "interrupted");
assert.equal(turnCompleted.payload.errorMessage, undefined);
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("interruptTurn settles every acknowledged live task before interrupting", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
// Wait for the three task.* runtime events to prove the lifecycle
// handlers processed the emissions (no wall-clock sleeps under the
// test clock).
const taskEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type.startsWith("task.")),
Stream.take(3),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "spawn agents",
attachments: [],
});
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "task-live",
description: "Agent A",
task_type: "local_agent",
uuid: "task-live-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "task-settled",
description: "Agent B",
task_type: "local_agent",
uuid: "task-settled-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_notification",
task_id: "task-settled",
status: "completed",
output_file: "/tmp/task-settled.jsonl",
summary: "done",
uuid: "task-settled-done-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
yield* Fiber.join(taskEventsFiber);
const stoppedTaskEventFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type === "task.completed"),
Stream.take(1),
Stream.runCollect,
Effect.forkChild,
);
yield* adapter.interruptTurn(session.threadId);
// Only the still-live task is stopped; interrupt always fires after.
assert.deepEqual(harness.query.stopTaskCalls, ["task-live"]);
assert.equal(harness.query.interruptCalls.length, 1);
const stoppedTaskEvents = Array.from(yield* Fiber.join(stoppedTaskEventFiber));
assert.equal(stoppedTaskEvents.length, 1);
const stoppedTaskEvent = stoppedTaskEvents[0];
assert.equal(stoppedTaskEvent?.type, "task.completed");
if (stoppedTaskEvent?.type === "task.completed") {
assert.equal(String(stoppedTaskEvent.payload.taskId), "task-live");
assert.equal(stoppedTaskEvent.payload.status, "stopped");
assert.equal(stoppedTaskEvent.payload.taskType, "local_agent");
assert.equal(stoppedTaskEvent.payload.title, "Agent A");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("workflow member coalescing: identical snapshots suppress, changes emit", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
// Collect task.progress until member-0's tick-3 emission lands, then
// evaluate member emissions.
const progressFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type === "task.progress"),
Stream.takeUntil(
// Sentinel: member-0's tick-3 emission (tokens 20) — members are
// emitted after the coordinator row within a tick.
(event) =>
(event.payload as { taskId?: string }).taskId === "wf-coalesce:wf:0" &&
(event.payload as { typedUsage?: { totalTokens?: number } }).typedUsage?.totalTokens ===
20,
),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "run workflow",
attachments: [],
});
const memberSnapshot = (tokens: number) => [
{ type: "workflow_phase", index: 0, title: "Work" },
{
type: "workflow_agent",
index: 0,
state: "running",
label: "member-0",
phaseIndex: 0,
tokens,
},
{
type: "workflow_agent",
index: 1,
state: "running",
label: "member-1",
phaseIndex: 0,
tokens: 50,
},
];
const tick = (usageTotal: number, snapshot: ReturnType<typeof memberSnapshot>) =>
harness.query.emit({
type: "system",
subtype: "task_progress",
task_id: "wf-coalesce",
description: "Coalescing workflow",
usage: { total_tokens: usageTotal, tool_uses: 1, duration_ms: 10 },
workflow_progress: snapshot,
uuid: `wf-tick-${usageTotal}`,
session_id: "sdk-session",
} as unknown as SDKMessage);
// Tick 1: both members are new -> 2 member events.
tick(100, memberSnapshot(10));
// Tick 2: IDENTICAL member snapshot -> 0 member events (coordinator
// usage changed, but members did not).
tick(200, memberSnapshot(10));
// Tick 3: member-0's tokens advanced -> exactly 1 member event.
tick(300, memberSnapshot(20));
const progressEvents = Array.from(yield* Fiber.join(progressFiber));
const byMember = new Map<string, number>();
for (const event of progressEvents) {
const taskId = (event.payload as { taskId: string }).taskId;
if (!taskId.includes(":wf:")) continue;
byMember.set(taskId, (byMember.get(taskId) ?? 0) + 1);
}
// member-0: tick 1 + tick 3. member-1: tick 1 only (tick 2 identical,
// tick 3 unchanged).
assert.equal(byMember.get("wf-coalesce:wf:0"), 2);
assert.equal(byMember.get("wf-coalesce:wf:1"), 1);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("task.started carries model/effort; subagent snapshots refine the model", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const adapter = yield* ClaudeAdapter;
const taskEventsFiber = yield* adapter.streamEvents.pipe(
Stream.filter((event) => event.type.startsWith("task.")),
Stream.take(2),
Stream.runCollect,
Effect.forkChild,
);
const session = yield* adapter.startSession({
threadId: THREAD_ID,
provider: ProviderDriverKind.make("claudeAgent"),
modelSelection: createModelSelection(
ProviderInstanceId.make("claudeAgent"),
"claude-opus-4-6",
[{ id: "effort", value: "max" }],
),
runtimeMode: "full-access",
});
yield* adapter.sendTurn({
threadId: session.threadId,
input: "spawn an agent",
attachments: [],
});
// No explicit model/effort on the launch input: the task inherits the
// session's selection.
harness.query.emit({
type: "system",
subtype: "task_started",
task_id: "task-model",
description: "Agent M",
task_type: "local_agent",
tool_use_id: "toolu_agent_m",
uuid: "task-model-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
// The subagent's assistant snapshot carries the authoritative API
// model id, which refines the linkage on later rows.
harness.query.emit({
type: "assistant",
parent_tool_use_id: "toolu_agent_m",
message: {
model: "claude-sonnet-5[1m]",
content: [],
},
uuid: "subagent-snapshot-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
harness.query.emit({
type: "system",
subtype: "task_progress",
task_id: "task-model",
description: "Agent M",
usage: { total_tokens: 100, tool_uses: 1, duration_ms: 10 },
uuid: "task-model-progress-uuid",
session_id: "sdk-session",
} as unknown as SDKMessage);
const taskEvents = Array.from(yield* Fiber.join(taskEventsFiber));
const started = taskEvents[0];
assert.equal(started?.type, "task.started");
if (started?.type === "task.started") {
assert.equal(started.payload.model, "claude-opus-4-6");
assert.equal(started.payload.effort, "max");
}
const progress = taskEvents[1];
assert.equal(progress?.type, "task.progress");
if (progress?.type === "task.progress") {
assert.equal(progress.payload.model, "claude-sonnet-5[1m]");
assert.equal(progress.payload.effort, "max");
}
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});
it.effect("closes the session when the Claude stream aborts after a turn starts", () => {
const harness = makeHarness();
return Effect.gen(function* () {
@@ -1779,6 +2099,24 @@ describe("ClaudeAdapterLive", () => {
session_id: "session",
uuid: "roster",
},
{
type: "system",
subtype: "vcs_state_changed",
kind: "push",
cwd: "/tmp/worktree",
session_id: "session",
uuid: "vcs",
},
{
type: "system",
subtype: "code_change_published",
provider: "github",
url: "https://github.com/pingdotgg/t3code/pull/1",
repo: "pingdotgg/t3code",
identifier: "1",
session_id: "session",
uuid: "ccp",
},
{
type: "system",
subtype: "task_updated",
+649 -17
View File
@@ -42,6 +42,10 @@ import {
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
type RuntimeTaskStatus,
type RuntimeTaskUsage,
type TaskAgentLinkage,
type TaskRunHandles,
ThreadId,
TurnId,
type UserInputQuestion,
@@ -61,6 +65,7 @@ import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Fiber from "effect/Fiber";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
@@ -169,6 +174,9 @@ interface ToolInFlight {
readonly input: Record<string, unknown>;
readonly partialInputJson: string;
readonly lastEmittedInputFingerprint?: string;
/** Owning agent when this tool ran inside a subagent (see attribution note). */
readonly agentId?: string;
readonly parentToolUseId?: string;
}
interface ClaudeTaskState {
@@ -178,6 +186,28 @@ interface ClaudeTaskState {
readonly blockedBy: Set<string>;
}
/**
* Agent identity captured from task_started and repeated on every subsequent
* task.* payload, so client folds can reconstruct an agent even when its
* start row aged out of activity retention.
*/
interface ClaudeTaskAgentState {
readonly taskId: string;
toolUseId: string | undefined;
description: string | undefined;
subagentType: string | undefined;
taskType: string | undefined;
workflowName: string | undefined;
skipTranscript: boolean;
runHandles: TaskRunHandles | undefined;
/** Set when this task was launched from inside a subagent. */
owningAgentId: string | undefined;
/** Seeded from the launching tool's input; refined by the subagent's own
* assistant snapshots (authoritative API model). */
model: string | undefined;
effort: string | undefined;
}
interface ClaudeSessionContext {
session: ProviderSession;
readonly promptQueue: Queue.Queue<PromptQueueItem>;
@@ -186,6 +216,9 @@ interface ClaudeSessionContext {
readonly startedAt: string;
readonly basePermissionMode: PermissionMode | undefined;
currentApiModelId: string | undefined;
/** Effective effort for the session's turns; subagents without an explicit
* effort override inherit this. */
currentEffort: string | undefined;
resumeSessionId: string | undefined;
readonly pendingApprovals: Map<ApprovalRequestId, PendingApproval>;
readonly pendingUserInputs: Map<ApprovalRequestId, PendingUserInput>;
@@ -195,6 +228,17 @@ interface ClaudeSessionContext {
}>;
readonly inFlightTools: Map<number, ToolInFlight>;
readonly claudeTasks: Map<string, ClaudeTaskState>;
readonly taskAgents: Map<string, ClaudeTaskAgentState>;
/**
* Last emitted workflow-member fingerprint per member slot. A coordinator
* task_progress repeats the FULL member array every tick; without a
* material-transition filter one provider tick fans out into up to 100
* runtime events (event-log writes, queue pressure, client reducer work)
* even when nothing changed for most members.
*/
readonly workflowMemberFingerprints: Map<string, string>;
/** Task ids that have started and not yet reached a terminal state. */
readonly liveTaskIds: Set<string>;
turnState: ClaudeTurnState | undefined;
lastKnownContextWindow: number | undefined;
lastKnownTokenUsage: ThreadTokenUsageSnapshot | undefined;
@@ -206,6 +250,8 @@ interface ClaudeSessionContext {
interface ClaudeQueryRuntime extends AsyncIterable<SDKMessage> {
readonly interrupt: () => Promise<void>;
/** SDK Query.stopTask — present on real queries; optional for test doubles. */
readonly stopTask?: (taskId: string) => Promise<void>;
readonly setModel: (model?: string) => Promise<void>;
readonly setPermissionMode: (mode: PermissionMode) => Promise<void>;
readonly setMaxThinkingTokens: (maxThinkingTokens: number | null) => Promise<void>;
@@ -303,7 +349,29 @@ function resultErrorsText(result: SDKResultMessage): string {
: "";
}
/**
* First user-facing error from a non-success result. "[ede_diagnostic] ..."
* entries are CLI-internal telemetry (the CLI hides them from its own UI too),
* so they must never become the error banner.
*/
function resultUserFacingError(result: SDKResultMessage): string | undefined {
if (result.subtype === "success" || !Array.isArray(result.errors)) {
return undefined;
}
return result.errors.find((error) => !error.startsWith("[ede_diagnostic]"));
}
function isInterruptedResult(result: SDKResultMessage): boolean {
// The CLI stamps user aborts explicitly: interrupting mid-tool-call yields
// "aborted_tools" (with an internal "[ede_diagnostic] ..." error and
// is_error: true), interrupting mid-stream yields "aborted_streaming".
if (
result.terminal_reason === "aborted_tools" ||
result.terminal_reason === "aborted_streaming"
) {
return true;
}
const errors = resultErrorsText(result);
if (errors.includes("interrupt")) {
return true;
@@ -826,6 +894,225 @@ function planStepsFromClaudeTasks(tasks: Map<string, ClaudeTaskState>): PlanStep
});
}
/** Only http/https survive; anything else (javascript:, file:, …) is dropped. */
function sanitizeSessionUrl(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const trimmed = value.trim();
if (!/^https?:\/\//i.test(trimmed)) {
return undefined;
}
return trimmed;
}
function nonNegativeInt(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) && value >= 0
? Math.floor(value)
: undefined;
}
function trimmedString(value: unknown): string | undefined {
if (typeof value !== "string") {
return undefined;
}
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
/**
* SDK task usage ({total_tokens, tool_uses, duration_ms}, sometimes with
* input/output/cache breakdowns) → the typed contract shape. Unknown or
* malformed input yields undefined rather than a partial guess.
*/
function normalizeTaskUsage(usage: unknown): RuntimeTaskUsage | undefined {
if (typeof usage !== "object" || usage === null) {
return undefined;
}
const record = usage as Record<string, unknown>;
const totalTokens = nonNegativeInt(record.total_tokens);
if (totalTokens === undefined) {
return undefined;
}
const inputTokens = nonNegativeInt(record.input_tokens);
const cachedInputTokens = nonNegativeInt(record.cache_read_input_tokens);
const outputTokens = nonNegativeInt(record.output_tokens);
const toolUses = nonNegativeInt(record.tool_uses);
const durationMs = nonNegativeInt(record.duration_ms);
return {
totalTokens,
...(inputTokens !== undefined ? { inputTokens } : {}),
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
...(outputTokens !== undefined ? { outputTokens } : {}),
...(toolUses !== undefined ? { toolUses } : {}),
...(durationMs !== undefined ? { durationMs } : {}),
};
}
/** SDK task_updated patch status → the shared wire vocabulary. */
const CLAUDE_TASK_PATCH_STATUS: Record<string, RuntimeTaskStatus> = {
pending: "pending",
running: "running",
completed: "completed",
failed: "failed",
killed: "cancelled",
paused: "idle",
};
/**
* Resolves a stream message's parent_tool_use_id to the owning agent's
* taskId. The Task tool's tool_use_id is remembered on task_started; any
* subagent-forwarded block carries that id as its parent. Returns undefined
* for parent-conversation traffic.
*/
function agentIdForParentToolUse(
agents: Map<string, ClaudeTaskAgentState>,
parentToolUseId: string | null | undefined,
): string | undefined {
if (parentToolUseId === null || parentToolUseId === undefined) {
return undefined;
}
for (const agent of agents.values()) {
if (agent.toolUseId === parentToolUseId) {
return agent.taskId;
}
}
return undefined;
}
/**
* Linkage bundle repeated on every task.* payload for `taskId`. Reads the
* remembered identity (from task_started) so progress/terminal rows are
* self-describing even when the start row ages out of activity retention.
*/
function taskLinkageFor(
agents: Map<string, ClaudeTaskAgentState>,
taskId: string,
): TaskAgentLinkage {
const agent = agents.get(taskId);
if (!agent) {
return {};
}
return {
...(agent.taskType ? { taskType: agent.taskType } : {}),
...(agent.owningAgentId ? { agentId: agent.owningAgentId } : {}),
...(agent.description ? { title: agent.description } : {}),
...(agent.subagentType ? { role: agent.subagentType } : {}),
...(agent.model ? { model: agent.model } : {}),
...(agent.effort ? { effort: agent.effort } : {}),
...(agent.toolUseId ? { toolUseId: agent.toolUseId } : {}),
...(agent.workflowName ? { workflowName: agent.workflowName } : {}),
...(agent.runHandles ? { runHandles: agent.runHandles } : {}),
};
}
const WORKFLOW_PHASE_CAP = 64;
const WORKFLOW_AGENT_CAP = 100;
interface ClaudeWorkflowAgentEntry {
readonly index: number;
readonly state: string;
readonly label: string | undefined;
readonly phaseIndex: number | undefined;
readonly phaseTitle: string | undefined;
readonly model: string | undefined;
readonly attempt: number | undefined;
readonly lastToolName: string | undefined;
readonly startedAt: string | undefined;
readonly error: string | undefined;
readonly tokens: number | undefined;
readonly toolCalls: number | undefined;
}
interface ClaudeWorkflowProgress {
readonly phases: ReadonlyArray<{ index: number; title: string }>;
readonly agents: ReadonlyArray<ClaudeWorkflowAgentEntry>;
}
/**
* Defensive parse of the SDK's undeclared-but-real workflow_progress array on
* task_progress messages (wire-confirmed; absent from sdk.d.ts). Unknown
* shapes are skipped per-entry; phases and agents dedupe by index before
* caps; a vanished field never throws. If the array disappears upstream the
* caller keeps the coordinator row and plain task lifecycle.
*/
function parseWorkflowProgress(value: unknown): ClaudeWorkflowProgress | undefined {
if (!Array.isArray(value) || value.length === 0) {
return undefined;
}
const phasesByIndex = new Map<number, string>();
const agentsByIndex = new Map<number, ClaudeWorkflowAgentEntry>();
for (const entry of value) {
if (typeof entry !== "object" || entry === null) {
continue;
}
const record = entry as Record<string, unknown>;
const entryType = trimmedString(record.type);
if (entryType === "workflow_phase") {
const index = nonNegativeInt(record.index);
const title = trimmedString(record.title);
if (index !== undefined && title && !phasesByIndex.has(index)) {
phasesByIndex.set(index, title);
}
continue;
}
if (entryType !== "workflow_agent") {
continue;
}
const index = nonNegativeInt(record.index);
const state = trimmedString(record.state);
if (index === undefined || !state || agentsByIndex.has(index)) {
continue;
}
agentsByIndex.set(index, {
index,
state,
label: trimmedString(record.label),
phaseIndex: nonNegativeInt(record.phaseIndex),
phaseTitle: trimmedString(record.phaseTitle),
model: trimmedString(record.model),
attempt: nonNegativeInt(record.attempt),
lastToolName: trimmedString(record.lastToolName),
startedAt: trimmedString(record.startedAt),
error: trimmedString(record.error),
tokens: nonNegativeInt(record.tokens),
toolCalls: nonNegativeInt(record.toolCalls),
});
}
if (phasesByIndex.size === 0 && agentsByIndex.size === 0) {
return undefined;
}
const phases = Array.from(phasesByIndex.entries())
.map(([index, title]) => ({ index, title }))
.toSorted((a, b) => a.index - b.index)
.slice(0, WORKFLOW_PHASE_CAP);
const agents = Array.from(agentsByIndex.values())
.toSorted((a, b) => a.index - b.index)
.slice(0, WORKFLOW_AGENT_CAP);
return { phases, agents };
}
/**
* Workflow member states from workflow_progress → shared task status.
* Unknown states read running after startedAt, pending before it.
*/
function workflowAgentStatus(entry: ClaudeWorkflowAgentEntry): RuntimeTaskStatus {
switch (entry.state) {
case "queued":
case "pending":
return "pending";
case "start":
case "running":
return entry.startedAt === undefined ? "pending" : "running";
case "done":
return "completed";
case "error":
return "failed";
default:
return entry.startedAt === undefined ? "pending" : "running";
}
}
function summarizeToolRequest(toolName: string, input: Record<string, unknown>): string {
const commandValue = input.command ?? input.cmd;
const command = typeof commandValue === "string" ? commandValue : undefined;
@@ -833,17 +1120,17 @@ function summarizeToolRequest(toolName: string, input: Record<string, unknown>):
return `${toolName}: ${command.trim().slice(0, 400)}`;
}
// For agent/subagent tools, prefer human-readable description or prompt over raw JSON
// For agent/subagent tools, prefer the human-readable description or prompt
// over raw JSON. The structured subagent_type is carried separately on the
// task.* payloads (role) — the label is display-only.
const itemType = classifyToolItemType(toolName);
if (itemType === "collab_agent_tool_call") {
const description =
typeof input.description === "string" ? input.description.trim() : undefined;
const prompt = typeof input.prompt === "string" ? input.prompt.trim() : undefined;
const subagentType =
typeof input.subagent_type === "string" ? input.subagent_type.trim() : undefined;
const label = description || (prompt ? prompt.slice(0, 200) : undefined);
if (label) {
return subagentType ? `${subagentType}: ${label}` : label;
return label;
}
}
@@ -2078,6 +2365,32 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const { event } = message;
// Subagent-owned stream traffic (parent_tool_use_id set) must not write
// into the parent transcript: with forwardSubagentText off the SDK still
// forwards subagent tool_use/tool_result blocks and their wrapping
// text/thinking deltas, and emitting them interleaved N subagents'
// narration into the chat (live-test finding). Their results reach the
// UI via the task.* lifecycle; their tool blocks are attributed and
// re-homed by the quiet-timeline filter.
const streamParentToolUseId = (message as { parent_tool_use_id?: string | null })
.parent_tool_use_id;
if (streamParentToolUseId !== null && streamParentToolUseId !== undefined) {
// Drop only the subagent's narration (text/thinking); tool_use blocks
// and their input_json_delta frames must flow so attributed tool items
// keep their inputs (review finding: dropping deltas emptied inputs).
const dropStart =
event.type === "content_block_start" &&
event.content_block.type !== "tool_use" &&
event.content_block.type !== "server_tool_use" &&
event.content_block.type !== "mcp_tool_use";
const dropDelta =
event.type === "content_block_delta" &&
(event.delta.type === "text_delta" || event.delta.type === "thinking_delta");
if (dropStart || dropDelta) {
return;
}
}
if (event.type === "message_delta") {
if (message.parent_tool_use_id !== null && message.parent_tool_use_id !== undefined) {
return;
@@ -2205,6 +2518,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: "inProgress",
title: nextTool.title,
...(nextTool.detail ? { detail: nextTool.detail } : {}),
...(nextTool.agentId ? { agentId: nextTool.agentId } : {}),
...(nextTool.parentToolUseId ? { parentToolUseId: nextTool.parentToolUseId } : {}),
data: {
toolName: nextTool.toolName,
input: nextTool.input,
@@ -2274,6 +2589,14 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const inputFingerprint =
Object.keys(toolInput).length > 0 ? toolInputFingerprint(toolInput) : undefined;
// Attribute tools that ran inside a subagent to their owning agent so
// clients can re-home them out of the main timeline (quiet-timeline
// guarantee): the SDK forwards subagent tool_use blocks tagged with the
// spawning Task tool's id as parent_tool_use_id.
const parentToolUseId =
(message as { parent_tool_use_id?: string | null }).parent_tool_use_id ?? undefined;
const owningAgentId = agentIdForParentToolUse(context.taskAgents, parentToolUseId);
const tool: ToolInFlight = {
itemId,
itemType,
@@ -2283,6 +2606,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
input: toolInput,
partialInputJson: "",
...(inputFingerprint ? { lastEmittedInputFingerprint: inputFingerprint } : {}),
...(owningAgentId ? { agentId: owningAgentId } : {}),
...(parentToolUseId ? { parentToolUseId } : {}),
};
context.inFlightTools.set(index, tool);
@@ -2300,6 +2625,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: "inProgress",
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
...(tool.agentId ? { agentId: tool.agentId } : {}),
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
data: {
toolName: tool.toolName,
input: toolInput,
@@ -2378,6 +2705,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: toolResult.isError ? "failed" : "inProgress",
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
...(tool.agentId ? { agentId: tool.agentId } : {}),
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
@@ -2430,6 +2759,8 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: itemStatus,
title: tool.title,
...(tool.detail ? { detail: tool.detail } : {}),
...(tool.agentId ? { agentId: tool.agentId } : {}),
...(tool.parentToolUseId ? { parentToolUseId: tool.parentToolUseId } : {}),
data: toolData,
},
providerRefs: nativeProviderRefs(context, {
@@ -2442,6 +2773,43 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
// The Workflow tool's result carries the run handles (runId, scriptPath,
// transcriptDir, sessionUrl). Attach them to the workflow's task agent so
// the next task.* payload advertises them to clients.
if (!toolResult.isError && tool.toolName.toLowerCase() === "workflow" && toolUseResult) {
const workflowTaskId = trimmedString(toolUseResult.taskId);
if (workflowTaskId) {
const runHandles: TaskRunHandles = {
...(trimmedString(toolUseResult.runId)
? { runId: trimmedString(toolUseResult.runId) }
: {}),
...(trimmedString(toolUseResult.scriptPath)
? { scriptPath: trimmedString(toolUseResult.scriptPath) }
: {}),
...(trimmedString(toolUseResult.transcriptDir)
? { transcriptDir: trimmedString(toolUseResult.transcriptDir) }
: {}),
...(sanitizeSessionUrl(toolUseResult.sessionUrl)
? { sessionUrl: sanitizeSessionUrl(toolUseResult.sessionUrl) }
: {}),
};
const existing = context.taskAgents.get(workflowTaskId);
context.taskAgents.set(workflowTaskId, {
taskId: workflowTaskId,
toolUseId: existing?.toolUseId ?? tool.itemId,
description: existing?.description,
subagentType: existing?.subagentType,
taskType: existing?.taskType ?? "local_workflow",
workflowName: existing?.workflowName,
skipTranscript: existing?.skipTranscript ?? false,
runHandles,
owningAgentId: existing?.owningAgentId,
model: existing?.model,
effort: existing?.effort,
});
}
}
if (
!toolResult.isError &&
applyClaudeTaskToolResult(context.claudeTasks, tool, toolUseResult)
@@ -2465,6 +2833,26 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
return;
}
// Subagent-owned assistant snapshots (parent_tool_use_id set) are the
// subagent's own conversation, not the parent's. Emitting them created
// interleaved "Agent N done"-adjacent leak messages and spawned synthetic
// turns per subagent completion (which also reset the Working timer).
const assistantParentToolUseId = (message as { parent_tool_use_id?: string | null })
.parent_tool_use_id;
if (assistantParentToolUseId !== null && assistantParentToolUseId !== undefined) {
// The snapshot's message.model is the authoritative API model the
// subagent actually ran on — refine the seeded launch-time value.
const owningTaskId = agentIdForParentToolUse(context.taskAgents, assistantParentToolUseId);
const snapshotModel = trimmedString(message.message.model);
const owningAgent = owningTaskId ? context.taskAgents.get(owningTaskId) : undefined;
if (owningAgent && snapshotModel) {
owningAgent.model = snapshotModel;
}
context.lastAssistantUuid = message.uuid;
yield* updateResumeCursor(context);
return;
}
// Auto-start a synthetic turn for assistant messages that arrive without
// an active turn (e.g., background agent/subagent responses between user prompts).
if (!context.turnState) {
@@ -2554,7 +2942,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
}
const status = turnStatusFromResult(message);
const errorMessage = message.subtype === "success" ? undefined : message.errors[0];
const errorMessage = resultUserFacingError(message);
if (status === "failed") {
yield* emitRuntimeError(context, errorMessage ?? "Claude turn failed.");
@@ -2563,6 +2951,82 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
yield* completeTurn(context, status, errorMessage, message);
});
/**
* Synthesizes per-member task.progress rows from the coordinator's
* workflow_progress array. Member identity is the stable slot
* `<coordinatorTaskId>:wf:<index>` (never the per-attempt agent id, which
* changes on retry and would split one member into duplicate rows).
* timelineBypass keeps these out of the parent chat; the Agents surface and
* workflow card consume them.
*/
const emitWorkflowMemberProgress = Effect.fn("emitWorkflowMemberProgress")(function* (
context: ClaudeSessionContext,
base: Omit<ProviderRuntimeEvent, "type" | "payload">,
message: Extract<SDKMessage, { type: "system"; subtype: "task_progress" }>,
) {
const progress = parseWorkflowProgress(
(message as unknown as Record<string, unknown>).workflow_progress,
);
if (!progress) {
return;
}
const coordinatorId = message.task_id;
for (const entry of progress.agents) {
const memberTaskId = `${coordinatorId}:wf:${entry.index}`;
const status = workflowAgentStatus(entry);
// Material-transition filter: the wire repeats every member each tick.
// Emit only when something the client renders actually changed, so a
// 100-agent fleet costs ~1 event per changed member instead of 100
// per tick (review finding: unbounded event amplification).
const fingerprint = [
status,
entry.label ?? "",
entry.model ?? "",
entry.lastToolName ?? "",
entry.error ?? "",
entry.tokens ?? "",
entry.toolCalls ?? "",
entry.phaseIndex ?? "",
entry.phaseTitle ?? "",
entry.attempt ?? "",
].join("\u001f");
if (context.workflowMemberFingerprints.get(memberTaskId) === fingerprint) {
continue;
}
context.workflowMemberFingerprints.set(memberTaskId, fingerprint);
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
...base,
eventId: stamp.eventId,
createdAt: stamp.createdAt,
type: "task.progress",
payload: {
taskId: RuntimeTaskId.make(memberTaskId),
description: entry.label ?? `agent ${entry.index}`,
status,
...(entry.error ? { error: entry.error } : {}),
...(entry.label ? { title: entry.label } : {}),
...(entry.model ? { model: entry.model } : {}),
...(entry.lastToolName ? { lastToolName: entry.lastToolName } : {}),
...(entry.tokens !== undefined
? {
typedUsage: {
totalTokens: entry.tokens,
...(entry.toolCalls !== undefined ? { toolUses: entry.toolCalls } : {}),
},
}
: {}),
parentAgentId: coordinatorId,
agentIndex: entry.index,
...(entry.phaseIndex !== undefined ? { phaseIndex: entry.phaseIndex } : {}),
...(entry.phaseTitle ? { phaseTitle: entry.phaseTitle } : {}),
...(entry.attempt !== undefined ? { attempt: entry.attempt } : {}),
timelineBypass: true,
},
});
}
});
const handleSystemMessage = Effect.fn("handleSystemMessage")(function* (
context: ClaudeSessionContext,
message: SDKMessage,
@@ -2593,9 +3057,15 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
// error rows in client work logs. `background_tasks_changed` is a roster
// snapshot ({tasks: [...]}) — the task_* lifecycle events carry the
// authoritative per-agent data and the typed background_tasks control
// request is the reconciliation source.
if ((message.subtype as string) === "background_tasks_changed") {
return;
// request is the reconciliation source. `vcs_state_changed`
// ({kind: commit|push|rebase}) and `code_change_published`
// ({provider, url, repo}) are informational CLI notices; the work log
// already shows the underlying git/gh tool calls.
switch (message.subtype as string) {
case "background_tasks_changed":
case "vcs_state_changed":
case "code_change_published":
return;
}
switch (message.subtype) {
@@ -2678,7 +3148,46 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
},
});
return;
case "task_started":
case "task_started": {
// A task launched by a tool that itself ran inside a subagent (the
// in-flight tool carries agentId from parent_tool_use_id) is
// agent-internal: a subagent's background shell, not parent work.
const launchingTool = message.tool_use_id
? Array.from(context.inFlightTools.values()).find(
(tool) => tool.itemId === message.tool_use_id,
)
: undefined;
const owningAgentId = launchingTool?.agentId;
// Model/effort: the Agent tool's input carries explicit overrides;
// absent ones inherit the session's selection (SDK behavior).
// Subagent assistant snapshots later refine model with the
// authoritative API id. AgentInput.effort may be a named level or an
// integer.
const launchInput = launchingTool?.input;
const model =
trimmedString(launchInput?.model) ?? trimmedString(context.session.model ?? undefined);
const rawLaunchEffort = launchInput?.effort;
const effort =
trimmedString(rawLaunchEffort) ??
(typeof rawLaunchEffort === "number" && Number.isFinite(rawLaunchEffort)
? String(rawLaunchEffort)
: context.currentEffort);
// Remember the agent identity so every later task.* payload for this
// taskId is self-describing (identity must survive activity retention).
context.taskAgents.set(message.task_id, {
taskId: message.task_id,
toolUseId: message.tool_use_id,
description: message.description,
subagentType: message.subagent_type,
taskType: message.task_type,
workflowName: message.workflow_name,
skipTranscript: message.skip_transcript === true,
runHandles: context.taskAgents.get(message.task_id)?.runHandles,
owningAgentId,
model,
effort,
});
context.liveTaskIds.add(message.task_id);
yield* offerRuntimeEvent({
...base,
type: "task.started",
@@ -2686,10 +3195,18 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
taskId: RuntimeTaskId.make(message.task_id),
description: message.description,
...(message.task_type ? { taskType: message.task_type } : {}),
...(owningAgentId ? { agentId: owningAgentId } : {}),
...(message.description ? { title: message.description } : {}),
...(message.subagent_type ? { role: message.subagent_type } : {}),
...(model ? { model } : {}),
...(effort ? { effort } : {}),
...(message.tool_use_id ? { toolUseId: message.tool_use_id } : {}),
...(message.workflow_name ? { workflowName: message.workflow_name } : {}),
},
});
return;
case "task_progress":
}
case "task_progress": {
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2698,6 +3215,15 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
rawPayload: message,
},
);
const linkage = taskLinkageFor(context.taskAgents, message.task_id);
const typedUsage = normalizeTaskUsage(message.usage);
// Phases ride on the coordinator's ONE progress row per tick. A
// separate phases-only row shared the stable ingestion activity id
// with this full row, and the thinner upsert overwrote usage and
// progress text (review finding).
const workflowPhases = parseWorkflowProgress(
(message as unknown as Record<string, unknown>).workflow_progress,
)?.phases;
yield* offerRuntimeEvent({
...base,
type: "task.progress",
@@ -2706,16 +3232,48 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
description: message.description,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(typedUsage ? { typedUsage } : {}),
...(message.last_tool_name ? { lastToolName: message.last_tool_name } : {}),
...(workflowPhases && workflowPhases.length > 0 ? { phases: workflowPhases } : {}),
...linkage,
...(message.subagent_type ? { role: message.subagent_type } : {}),
},
});
yield* emitWorkflowMemberProgress(context, base, message);
return;
}
case "task_updated": {
// Status patch (killed/paused/backgrounded/end_time/error) — main
// previously dropped this on the floor, losing all transitions.
const patch = message.patch;
const status =
patch.status !== undefined ? CLAUDE_TASK_PATCH_STATUS[patch.status] : undefined;
if (status === "completed" || status === "failed" || status === "cancelled") {
context.liveTaskIds.delete(message.task_id);
}
const endedAt =
typeof patch.end_time === "number" && Number.isFinite(patch.end_time)
? DateTime.formatIso(DateTime.makeUnsafe(patch.end_time))
: undefined;
yield* offerRuntimeEvent({
...base,
type: "task.updated",
payload: {
taskId: RuntimeTaskId.make(message.task_id),
...(status ? { status } : {}),
...(patch.description ? { description: patch.description } : {}),
...(patch.error ? { error: patch.error } : {}),
...(endedAt ? { endedAt } : {}),
...(patch.is_backgrounded !== undefined
? { isBackgrounded: patch.is_backgrounded }
: {}),
...taskLinkageFor(context.taskAgents, message.task_id),
},
});
return;
// Task state patch (status/backgrounded/end_time). No runtime mapping
// yet — the terminal task_notification reports the outcome — but it
// must not surface as an unknown-subtype warning row.
case "task_updated":
return;
case "task_notification":
}
case "task_notification": {
context.liveTaskIds.delete(message.task_id);
yield* emitThreadTokenUsage(
context,
normalizeClaudeTaskProgressTokenUsage(message.usage, context),
@@ -2724,6 +3282,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
rawPayload: message,
},
);
const typedUsage = normalizeTaskUsage(message.usage);
yield* offerRuntimeEvent({
...base,
type: "task.completed",
@@ -2732,9 +3291,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
status: message.status,
...(message.summary ? { summary: message.summary } : {}),
...(message.usage ? { usage: message.usage } : {}),
...(typedUsage ? { typedUsage } : {}),
...(message.output_file ? { outputFile: message.output_file } : {}),
...taskLinkageFor(context.taskAgents, message.task_id),
},
});
return;
}
case "files_persisted":
yield* offerRuntimeEvent({
...base,
@@ -2870,7 +3433,10 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
toolUseId: message.tool_use_id,
toolName: message.tool_name,
elapsedSeconds: message.elapsed_time_seconds,
...(message.task_id ? { summary: `task:${message.task_id}` } : {}),
...(message.task_id ? { taskId: RuntimeTaskId.make(message.task_id) } : {}),
...(message.parent_tool_use_id !== null
? { parentToolUseId: message.parent_tool_use_id }
: {}),
},
});
return;
@@ -3192,6 +3758,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const pendingUserInputs = new Map<ApprovalRequestId, PendingUserInput>();
const inFlightTools = new Map<number, ToolInFlight>();
const claudeTasks = new Map<string, ClaudeTaskState>();
const taskAgents = new Map<string, ClaudeTaskAgentState>();
const workflowMemberFingerprints = new Map<string, string>();
const liveTaskIds = new Set<string>();
const contextRef = yield* Ref.make<ClaudeSessionContext | undefined>(undefined);
@@ -3628,12 +4197,16 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
startedAt,
basePermissionMode: permissionMode,
currentApiModelId: apiModelId,
currentEffort: effectiveEffort ?? undefined,
resumeSessionId: sessionId,
pendingApprovals,
pendingUserInputs,
turns: [],
inFlightTools,
claudeTasks,
taskAgents,
workflowMemberFingerprints,
liveTaskIds,
turnState: undefined,
lastKnownContextWindow: initialContextWindow,
lastKnownTokenUsage: undefined,
@@ -3750,6 +4323,13 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
...context.session,
model: modelSelection.model,
};
const turnCaps = getClaudeModelCapabilities(modelSelection.model);
const turnEffort = resolveClaudeEffort(
turnCaps,
getModelSelectionStringOptionValue(modelSelection, "effort"),
);
context.currentEffort =
getEffectiveClaudeAgentEffort(turnEffort ?? null, modelSelection.model) ?? undefined;
}
// Apply interaction mode by switching the SDK's permission mode.
@@ -3825,6 +4405,58 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const interruptTurn: ClaudeAdapterShape["interruptTurn"] = Effect.fn("interruptTurn")(
function* (threadId, _turnId) {
const context = yield* requireSession(threadId);
// Stop-everything semantics: users reach for Stop precisely when a
// fleet ran away. interrupt() alone only ends the parent turn —
// background subagents/shells keep running and keep burning tokens.
// Stop every live task first (best-effort per task: one refusal must
// not strand the rest or block the turn interrupt), then interrupt.
if (context.query.stopTask && context.liveTaskIds.size > 0) {
const liveIds = Array.from(context.liveTaskIds);
// Bounded: a wedged child's stopTask promise may never settle
// (Effect.ignore handles rejection, not non-resolution), and the
// parent interrupt below MUST still run — Stop matters most during
// runaway fleets (review finding). Per-task timeout keeps one hung
// child from consuming the whole budget.
yield* Effect.forEach(
liveIds,
(taskId) =>
Effect.gen(function* () {
const stopAcknowledged = yield* Effect.tryPromise({
// Invoke through the query object: SDK methods rely on `this`.
try: () => context.query.stopTask!(taskId),
catch: () => undefined,
}).pipe(
Effect.timeoutOption("3 seconds"),
Effect.orElseSucceed(() => Option.none()),
);
if (Option.isNone(stopAcknowledged) || !context.liveTaskIds.delete(taskId)) {
return;
}
// stopTask only acknowledges the control request. Its separate
// task_notification can lose the race with interrupt(), so make
// the acknowledged stop authoritative for the durable UI state.
const stamp = yield* makeEventStamp();
yield* offerRuntimeEvent({
type: "task.completed",
eventId: stamp.eventId,
provider: PROVIDER,
createdAt: stamp.createdAt,
threadId: context.session.threadId,
...(context.turnState
? { turnId: asCanonicalTurnId(context.turnState.turnId) }
: {}),
payload: {
taskId: RuntimeTaskId.make(taskId),
status: "stopped",
...taskLinkageFor(context.taskAgents, taskId),
},
providerRefs: nativeProviderRefs(context),
});
}).pipe(Effect.ignore),
{ concurrency: 8, discard: true },
).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);
}
yield* Effect.tryPromise({
try: () => context.query.interrupt(),
catch: (cause) => toRequestError(threadId, "turn/interrupt", cause),
@@ -20,6 +20,8 @@ import {
type ProviderUserInputAnswers,
RuntimeItemId,
RuntimeRequestId,
RuntimeTaskId,
type RuntimeTaskUsage,
ProviderApprovalDecision,
ThreadId,
ProviderSendTurnInput,
@@ -494,10 +496,276 @@ function mapItemLifecycle(
};
}
/**
* Maps the session runtime's synthetic `collabAgent/*` events (native
* multi-agent v2 child-thread signals) into the shared task.* lifecycle.
* Agent identity = child thread id; nickname is the display title, role is
* agentRole (fallback: last agentPath segment, then "general-purpose").
* A completed child turn is idle (resumable), not terminal. timelineBypass
* keeps these rows out of the parent chat.
*/
function mapCollabAgentEvent(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): ReadonlyArray<ProviderRuntimeEvent> {
const payload =
typeof event.payload === "object" && event.payload !== null
? (event.payload as Record<string, unknown>)
: undefined;
const agentThreadId = typeof payload?.agentThreadId === "string" ? payload.agentThreadId : "";
if (!payload || agentThreadId.length === 0) {
return [];
}
const base = runtimeEventBase(event, canonicalThreadId);
const taskId = RuntimeTaskId.make(agentThreadId);
const agentPath = typeof payload.agentPath === "string" ? payload.agentPath : undefined;
const pathLeaf = agentPath?.split("/").findLast((segment) => segment.length > 0);
const nickname = typeof payload.nickname === "string" ? payload.nickname : undefined;
const role =
(typeof payload.role === "string" ? payload.role : undefined) ?? pathLeaf ?? "general-purpose";
// A bare thread id is not a name. Omitting the title lets the client fold
// keep the real one from task.started instead of clobbering it (probe
// finding: progress rows renamed math_one to its UUID).
const knownName = nickname ?? pathLeaf;
const title = knownName ?? agentThreadId;
// Identity repeated on every status patch so rows are self-describing when
// the start row ages out of activity retention (review finding: a
// reconstructed agent had a UUID name and no role/path).
const statusLinkage = {
role,
...(knownName ? { title: knownName } : {}),
...(agentPath ? { agentPath } : {}),
timelineBypass: true,
} as const;
switch (event.method) {
case "collabAgent/started":
return [
{
...base,
type: "task.started",
payload: {
taskId,
description: title,
title,
role,
...(agentPath ? { agentPath } : {}),
...(typeof payload.parentThreadId === "string"
? { parentAgentId: payload.parentThreadId }
: {}),
timelineBypass: true,
},
},
];
case "collabAgent/activity": {
const activityKind = typeof payload.activityKind === "string" ? payload.activityKind : "";
if (activityKind === "interrupted") {
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "interrupted", ...statusLinkage },
},
];
}
if (activityKind === "started") {
// Wire-probe finding: children often register via subAgentActivity
// alone (no thread/started with a spawn source), so this is the one
// shot at a task.started with a real name — agentPath leaf beats a
// bare thread-id title.
return [
{
...base,
type: "task.started",
payload: {
taskId,
description: title,
title,
role,
...(agentPath ? { agentPath } : {}),
timelineBypass: true,
},
},
];
}
// interacted → the child is (again) actively driven.
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "running", ...statusLinkage },
},
];
}
case "collabAgent/turnStarted":
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "running", ...statusLinkage },
},
];
case "collabAgent/turnCompleted": {
// Idle, not terminal: the identity is resumable via sendInput/resume.
const turn =
typeof payload.turn === "object" && payload.turn !== null
? (payload.turn as Record<string, unknown>)
: undefined;
const turnStatus = typeof turn?.status === "string" ? turn.status : undefined;
const status =
turnStatus === "failed"
? ("failed" as const)
: turnStatus === "interrupted"
? ("interrupted" as const)
: ("idle" as const);
return [
{
...base,
type: "task.updated",
payload: { taskId, status, ...statusLinkage },
},
];
}
case "collabAgent/statusChanged": {
const status =
typeof payload.status === "object" && payload.status !== null
? (payload.status as Record<string, unknown>)
: undefined;
const statusType = typeof status?.type === "string" ? status.type : undefined;
if (statusType === "systemError") {
// Silently dropping this once left children stuck running forever.
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "failed", ...statusLinkage },
},
];
}
if (statusType === "active") {
const flags = Array.isArray(status?.activeFlags) ? status.activeFlags : [];
const waiting = flags.some(
(flag) => flag === "waitingOnApproval" || flag === "waitingOnUserInput",
);
return [
{
...base,
type: "task.updated",
payload: { taskId, status: waiting ? "waiting" : "running", ...statusLinkage },
},
];
}
if (statusType === "idle") {
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "idle", ...statusLinkage },
},
];
}
return [];
}
case "collabAgent/tokenUsage": {
// Cumulative per child thread: always the `total` breakdown, never
// `last` (which shrinks on follow-ups). Client folds max-merge.
const tokenUsage =
typeof payload.tokenUsage === "object" && payload.tokenUsage !== null
? (payload.tokenUsage as Record<string, unknown>)
: undefined;
const total =
typeof tokenUsage?.total === "object" && tokenUsage.total !== null
? (tokenUsage.total as Record<string, unknown>)
: undefined;
const count = (value: unknown): number | undefined =>
typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
// Same validation as every other field: RuntimeTaskUsage.totalTokens
// is NonNegativeInt, so NaN/Infinity/negative wire values must miss.
const totalTokens = count(total?.totalTokens);
if (totalTokens === undefined) {
return [];
}
const typedUsage: RuntimeTaskUsage = {
totalTokens,
...(count(total?.inputTokens) !== undefined
? { inputTokens: count(total?.inputTokens) }
: {}),
...(count(total?.cachedInputTokens) !== undefined
? { cachedInputTokens: count(total?.cachedInputTokens) }
: {}),
...(count(total?.outputTokens) !== undefined
? { outputTokens: count(total?.outputTokens) }
: {}),
...(count(total?.reasoningOutputTokens) !== undefined
? { reasoningOutputTokens: count(total?.reasoningOutputTokens) }
: {}),
};
return [
{
...base,
type: "task.progress",
payload: {
taskId,
description: title,
...(knownName ? { title: knownName } : {}),
typedUsage,
timelineBypass: true,
},
},
];
}
case "collabAgent/item": {
const item =
typeof payload.item === "object" && payload.item !== null
? (payload.item as Record<string, unknown>)
: undefined;
const itemTypeRaw = typeof item?.type === "string" ? item.type : undefined;
if (!itemTypeRaw) {
return [];
}
// A loose summary from the raw item: the child stream is untyped at
// this boundary (synthetic event payload), so read best-effort fields
// rather than force a schema decode.
const looseSummary =
(typeof item?.command === "string" ? item.command : undefined) ??
(typeof item?.title === "string" ? item.title : undefined) ??
(typeof item?.query === "string" ? item.query : undefined);
const canonical = toCanonicalItemType(itemTypeRaw);
const summary = looseSummary ?? canonical.replaceAll("_", " ");
return [
{
...base,
type: "task.progress",
payload: {
taskId,
description: title,
...(knownName ? { title: knownName } : {}),
summary,
timelineBypass: true,
},
},
];
}
case "collabAgent/closed":
return [
{
...base,
type: "task.updated",
payload: { taskId, status: "interrupted", ...statusLinkage },
},
];
default:
return [];
}
}
function mapToRuntimeEvents(
event: ProviderEvent,
canonicalThreadId: ThreadId,
): ReadonlyArray<ProviderRuntimeEvent> {
if (event.kind === "notification" && event.method.startsWith("collabAgent/")) {
return mapCollabAgentEvent(event, canonicalThreadId);
}
if (event.kind === "error") {
if (!event.message) {
return [];
@@ -0,0 +1,248 @@
/**
* Runtime-level collab regression: boots the REAL CodexSessionRuntime against
* a scripted mock app-server peer that replays the captured multi-agent wire
* sequence (codexMultiAgentWire.json) plus the shapes the capture alone can't
* script (receiver-turn bookkeeping via collabAgentToolCall, child terminal
* lifecycle, approval pass-through). This is the layer the pure routing-table
* test can't reach: ordering between the legacy receiver-turn suppressor and
* v2 interception, registration state, and synthetic event emission.
*/
// @effect-diagnostics nodeBuiltinImport:off
import * as NodeFS from "node:fs";
import * as NodePath from "node:path";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { it } from "@effect/vitest";
import { ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Stream from "effect/Stream";
import { assert, describe } from "vite-plus/test";
import wireFixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
import { makeCodexSessionRuntime } from "./CodexSessionRuntime.ts";
const ROOT = wireFixture.rootThreadId;
const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
/**
* The captured sequence, extended with the shapes the live capture didn't
* include: a collabAgentToolCall with receiverThreadIds (feeds the legacy
* receiver-turn map, so ordering vs. v2 interception is exercised), child
* terminal lifecycle, and a serverRequest/resolved addressed to a child
* (must pass through to the parent path, not vanish).
*/
function buildScript() {
const captured = wireFixture.notifications;
const extras = [
{
method: "item/completed",
params: {
threadId: ROOT,
item: {
type: "collabAgentToolCall",
id: "call_fixture_wait",
tool: "wait",
status: "completed",
senderThreadId: ROOT,
receiverThreadIds: [CHILD_A, CHILD_B],
},
},
},
// Child terminal lifecycle AFTER the receiver map knows the children —
// pre-fix, the legacy suppressor dropped these before interception saw
// them, so no synthetic agent events were emitted.
{
method: "turn/completed",
params: {
threadId: CHILD_A,
turn: { id: `${CHILD_A}-turn-1`, status: "completed", items: [] },
},
},
{ method: "thread/closed", params: { threadId: CHILD_B } },
// Parent-owned traffic addressed to a child conversation: must reach the
// parent path (approval correlation cleanup), not be swallowed.
{ method: "serverRequest/resolved", params: { threadId: CHILD_A, requestId: "req-1" } },
];
return {
rootThreadId: ROOT,
notifications: [...captured.filter((entry) => entry.method !== "turn/completed"), ...extras],
};
}
const scriptPath = NodePath.join(import.meta.dirname, "../testFixtures/.collab-script.json");
const peerPath = NodePath.join(import.meta.dirname, "../testFixtures/codexCollabMockPeer.sh");
describe("CodexSessionRuntime collab integration", () => {
it.effect("replays the captured fan-out into synthetic agent events without child leaks", () =>
Effect.gen(function* () {
// @effect-diagnostics-next-line preferSchemaOverJson:off
NodeFS.writeFileSync(scriptPath, JSON.stringify(buildScript()), "utf8");
yield* Effect.addFinalizer(() =>
Effect.sync(() => NodeFS.rmSync(scriptPath, { force: true })),
);
const runtime = yield* makeCodexSessionRuntime({
threadId: ThreadId.make("thread-collab-integration"),
binaryPath: peerPath,
cwd: "/tmp",
runtimeMode: "full-access",
environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
});
const eventsFiber = yield* runtime.events.pipe(
Stream.takeUntil((event) => event.method === "turn/completed"),
Stream.runCollect,
Effect.forkScoped,
);
yield* runtime.start();
yield* runtime.sendTurn({ input: "fan out" });
const events = Array.from(yield* Fiber.join(eventsFiber));
const methods = events.map((event) => event.method);
// Children registered from subAgentActivity become synthetic agent
// lifecycle — including terminal rows that arrive AFTER the receiver
// map knows them (the ordering this test exists to pin).
assert.include(methods, "collabAgent/activity");
assert.include(methods, "collabAgent/turnCompleted");
assert.include(methods, "collabAgent/closed");
const childTurnCompleted = events.find(
(event) =>
event.method === "collabAgent/turnCompleted" &&
(event.payload as { agentThreadId?: string }).agentThreadId === CHILD_A,
);
assert.isDefined(childTurnCompleted, "child A's turn completion becomes an agent event");
const childClosed = events.find(
(event) =>
event.method === "collabAgent/closed" &&
(event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
);
assert.isDefined(childClosed, "child B's close becomes an agent event");
// Parent-owned resolution passes through — not swallowed, not
// re-labelled as an agent event.
assert.include(methods, "serverRequest/resolved");
// The root's own subAgentActivity about "/root" must NOT register the
// root as a child: the parent turn completion still flows.
assert.include(methods, "turn/completed");
// No raw child conversation methods leak onto the parent stream.
const leaked = events.filter((event) => {
const payload = event.payload as { threadId?: string } | undefined;
const addressedToChild = payload?.threadId === CHILD_A || payload?.threadId === CHILD_B;
return addressedToChild && (event.method?.startsWith("thread/") ?? false);
});
assert.deepEqual(
leaked.map((event) => event.method),
[],
"child thread/* lifecycle must not appear as parent events",
);
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
// it.live: the runtime talks to a real child process; under it.effect's
// TestClock the internal timers freeze and the join never completes.
it.live("Stop interrupts every live child regardless of registration timing", () =>
Effect.gen(function* () {
// Ordering + liveness torture for stop-everything: child A's
// turn/started arrives BEFORE anything registers it (foreign
// suppression path must record the live turn); child B's arrives after
// registration; child A's interrupt HANGS (RPC never settles — worse
// than rejecting) and the bounded deadline must still deliver B's and
// the parent's interrupts. The turn stays open so children are live
// when Stop fires.
// Build from REAL captured rows (hand-written shapes fail notification
// schema validation and are silently dropped): reorder so child A's
// turn/started precedes its registration, and drop terminal rows so
// children stay live when Stop fires.
const byIndex = wireFixture.notifications;
const isTurnStarted = (entry: (typeof byIndex)[number], child: string) =>
entry.method === "turn/started" &&
(entry.params as { threadId?: string }).threadId === child;
const isRegistration = (entry: (typeof byIndex)[number], child: string) => {
const item = (entry.params as { item?: { type?: string; agentThreadId?: string } }).item;
return item?.type === "subAgentActivity" && item.agentThreadId === child;
};
const turnStartedA = byIndex.find((entry) => isTurnStarted(entry, CHILD_A));
const turnStartedB = byIndex.find((entry) => isTurnStarted(entry, CHILD_B));
const registrationA = byIndex.find((entry) => isRegistration(entry, CHILD_A));
const registrationB = byIndex.find((entry) => isRegistration(entry, CHILD_B));
assert.isDefined(turnStartedA);
assert.isDefined(turnStartedB);
assert.isDefined(registrationA);
assert.isDefined(registrationB);
const script = {
rootThreadId: ROOT,
holdTurnOpen: true,
hangInterruptFor: CHILD_A,
notifications: [turnStartedA, registrationA, registrationB, turnStartedB],
};
// @effect-diagnostics-next-line preferSchemaOverJson:off
NodeFS.writeFileSync(scriptPath, JSON.stringify(script), "utf8");
const interruptsPath = `${scriptPath}.interrupts`;
NodeFS.rmSync(interruptsPath, { force: true });
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
NodeFS.rmSync(scriptPath, { force: true });
NodeFS.rmSync(interruptsPath, { force: true });
}),
);
const runtime = yield* makeCodexSessionRuntime({
threadId: ThreadId.make("thread-collab-stop"),
binaryPath: peerPath,
cwd: "/tmp",
runtimeMode: "full-access",
environment: { ...process.env, T3_CODEX_COLLAB_SCRIPT: scriptPath },
});
// Wait for both children's turnStarted signals to be processed before
// stopping (B via the registered-child path; A only produces live-turn
// bookkeeping, so key on B's synthetic event).
const childBStartedFiber = yield* runtime.events.pipe(
Stream.filter(
(event) =>
event.method === "collabAgent/turnStarted" &&
(event.payload as { agentThreadId?: string }).agentThreadId === CHILD_B,
),
Stream.take(1),
Stream.runCollect,
Effect.forkScoped,
);
yield* runtime.start();
yield* runtime.sendTurn({ input: "fan out and hang" });
const childBStarted = yield* Fiber.join(childBStartedFiber).pipe(
Effect.timeoutOption("15 seconds"),
);
assert.isTrue(childBStarted._tag === "Some", "child B turnStarted never arrived");
// Stop everything. A's interrupt hangs forever — the bounded child
// deadline must expire and the parent interrupt must still be sent.
yield* runtime.interruptTurn();
const parseInterruptLine = (line: string) => JSON.parse(line) as { threadId?: string };
const interrupted = NodeFS.readFileSync(interruptsPath, "utf8")
.trim()
.split("\n")
.filter((line) => line.length > 0)
.map(parseInterruptLine);
const interruptedThreads = new Set(interrupted.map((entry) => entry.threadId));
assert.isTrue(
interruptedThreads.has(CHILD_A),
"pre-registration child A must still receive the interrupt RPC",
);
assert.isTrue(interruptedThreads.has(CHILD_B), "registered child B must be interrupted");
assert.isTrue(interruptedThreads.has(ROOT), "parent turn must be interrupted last");
yield* runtime.close;
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
});
@@ -0,0 +1,180 @@
/**
* Codex multi-agent wire fixtures.
*
* The child-interception path is the highest-blast-radius code in the
* subagent stack: it decides, per notification, whether traffic reaches the
* parent timeline at all. Three shipped bugs came from that decision being
* implicit (root thread registered as its own child; `error` and
* `serverRequest/resolved` swallowed by a catch-all). These tests pin the
* decision against a REAL capture rather than hand-written shapes.
*
* Fixture provenance: codex-cli 0.145.0 driven directly over stdio with
* gpt-5.6-luna at low effort, prompting a two-child fan-out (alpha, beta).
* See codexMultiAgentWire.json.
*/
import { assert, describe, it } from "vite-plus/test";
import fixture from "../testFixtures/codexMultiAgentWire.json" with { type: "json" };
import { routeCodexChildNotification } from "./CodexSessionRuntime.ts";
interface WireNotification {
readonly method: string;
readonly params: Record<string, unknown>;
}
const notifications = fixture.notifications as ReadonlyArray<WireNotification>;
const rootThreadId = fixture.rootThreadId;
const childThreadIds = new Set(fixture.childThreadIds);
/** Mirrors readNotificationThreadId's addressing for the captured methods. */
function notificationThreadId(entry: WireNotification): string | undefined {
const params = entry.params;
const thread = params.thread;
if (
typeof thread === "object" &&
thread !== null &&
typeof (thread as { id?: unknown }).id === "string"
) {
return (thread as { id: string }).id;
}
return typeof params.threadId === "string" ? params.threadId : undefined;
}
function subAgentActivityItems(): ReadonlyArray<Record<string, unknown>> {
return notifications.flatMap((entry) => {
const item = entry.params.item;
if (typeof item !== "object" || item === null) return [];
const record = item as Record<string, unknown>;
return record.type === "subAgentActivity" ? [record] : [];
});
}
describe("codex multi-agent wire capture", () => {
it("captures a real two-child fan-out", () => {
assert.equal(fixture.capturedWith.model, "gpt-5.6-luna");
assert.equal(childThreadIds.size, 2);
const paths = subAgentActivityItems().map((item) => item.agentPath);
assert.include(paths, "/root/alpha");
assert.include(paths, "/root/beta");
});
it("emits child traffic BEFORE the item that registers the child", () => {
// Ordering hazard: the child's own thread/status/changed arrives before
// the parent-side subAgentActivity naming it. Registration must tolerate
// child-first arrival, so unregistered child traffic passes through
// rather than being eaten (no regression vs. pre-feature behavior).
const firstChildTraffic = notifications.findIndex((entry) => {
const threadId = notificationThreadId(entry);
return threadId !== undefined && childThreadIds.has(threadId);
});
const firstRegistration = notifications.findIndex((entry) => {
const item = entry.params.item;
if (typeof item !== "object" || item === null) return false;
const record = item as Record<string, unknown>;
return record.type === "subAgentActivity" && record.kind === "started";
});
assert.isAtLeast(firstChildTraffic, 0);
assert.isAtLeast(firstRegistration, 0);
assert.isBelow(
firstChildTraffic,
firstRegistration,
"capture should exercise child-first ordering",
);
});
it("contains a /root self-activity emitted from a CHILD thread", () => {
// The bug this guards: the wire reports subAgentActivity about the ROOT
// (agentPath "/root"). Registering it made the runtime intercept the
// parent's own final message and turn/completed, so the thread hung
// "working" forever. The root guard must key on agentPath/thread id,
// never on which thread the notification arrived from.
const rootSelfActivity = subAgentActivityItems().find((item) => item.agentPath === "/root");
assert.isDefined(rootSelfActivity, "capture should contain a /root self-activity");
assert.equal(rootSelfActivity?.agentThreadId, rootThreadId);
});
it("routes every captured child method to a defined disposition", () => {
const childMethods = new Set(
notifications
.filter((entry) => {
const threadId = notificationThreadId(entry);
return threadId !== undefined && childThreadIds.has(threadId);
})
.map((entry) => entry.method),
);
assert.isAbove(childMethods.size, 0);
for (const method of childMethods) {
const route = routeCodexChildNotification(method);
// Child lifecycle traffic must become agent events — never silently
// dropped, never leaked to the parent timeline.
assert.equal(route, "agent-event", `${method} should map to an agent event`);
}
});
});
describe("routeCodexChildNotification", () => {
it("maps child lifecycle to agent events", () => {
for (const method of [
"turn/started",
"turn/completed",
"thread/status/changed",
"thread/tokenUsage/updated",
"item/started",
"item/completed",
"thread/closed",
"error",
]) {
assert.equal(routeCodexChildNotification(method), "agent-event", method);
}
});
it("drops only enumerated child chatter", () => {
for (const method of [
"item/agentMessage/delta",
"item/reasoning/textDelta",
"item/commandExecution/outputDelta",
"turn/plan/updated",
"thread/name/updated",
]) {
assert.equal(routeCodexChildNotification(method), "drop", method);
}
});
it("never routes child-owned thread lifecycle to the parent", () => {
// These mutate PARENT thread state in CodexAdapter (archived/compacted),
// so a child emitting them must never reach the parent path. This list
// mirrors shouldSuppressChildConversationNotification (the v1 collab
// suppressor) — the two must not drift (review finding: the router
// initially omitted them and they leaked).
for (const method of [
"thread/started",
"thread/status/changed",
"thread/archived",
"thread/unarchived",
"thread/closed",
"thread/compacted",
"thread/name/updated",
"thread/tokenUsage/updated",
"turn/started",
"turn/completed",
"turn/plan/updated",
"item/plan/delta",
]) {
assert.notEqual(
routeCodexChildNotification(method),
"parent",
`${method} is child-owned and must not reach the parent path`,
);
}
});
it("sends parent-owned and UNKNOWN methods to the parent path", () => {
// serverRequest/resolved clears the parent's approval correlation:
// swallowing it left approvals stuck (shipped bug). Unknown methods take
// the same route by design — a codex update that adds a notification
// must degrade to "parent sees it", never to silent loss.
assert.equal(routeCodexChildNotification("serverRequest/resolved"), "parent");
assert.equal(routeCodexChildNotification("thread/somethingBrandNew"), "parent");
assert.equal(routeCodexChildNotification("account/rateLimits/updated"), "parent");
});
});
@@ -600,6 +600,71 @@ function readRouteFields(notification: CodexServerNotification): {
}
}
/**
* Native collab child-agent tracking (multi-agent v2). Under v2 subagents are
* full app-server threads: identity arrives on `thread/started` with
* source.subAgent.thread_spawn, lifecycle on `subAgentActivity` items and the
* child thread's own turn/status/tokenUsage notifications. The runtime
* registers children from those explicit signals, intercepts their
* notifications before parent-timeline mapping, and re-emits them as
* synthetic `collabAgent/*` provider events the adapter turns into task.*
* runtime events (timelineBypass keeps them out of the parent chat).
*
* WIP, probe-gated: registration is deliberately explicit-signals-only. The
* spec's "provisionally treat unknown foreign thread ids as v2 children" rule
* needs a live wire capture of the packaged binary before it lands — blind
* capture risks eating unrelated traffic. Until then a child whose first
* notification precedes registration passes through as today (no regression
* vs main, which passes everything through).
*/
interface CollabChildAgentState {
readonly agentThreadId: string;
readonly nickname: string | undefined;
readonly role: string | undefined;
readonly agentPath: string | undefined;
readonly depth: number | undefined;
readonly parentThreadId: string | undefined;
/**
* Parent canonical turn active when the child registered. Stamped on every
* synthetic collabAgent/* event so clients can batch a fleet by its spawn
* turn — without it, separate fleets in one thread collapsed into a single
* "direct:no-turn" CTA (review finding).
*/
readonly spawnTurnId: TurnId | undefined;
}
function readThreadSpawnSource(thread: { readonly source: unknown }):
| {
nickname: string | undefined;
role: string | undefined;
agentPath: string | undefined;
depth: number | undefined;
parentThreadId: string | undefined;
}
| undefined {
const source = thread.source;
if (typeof source !== "object" || source === null || !("subAgent" in source)) {
return undefined;
}
const subAgent = (source as { subAgent: unknown }).subAgent;
if (typeof subAgent !== "object" || subAgent === null || !("thread_spawn" in subAgent)) {
return undefined;
}
const spawn = (subAgent as { thread_spawn: unknown }).thread_spawn;
if (typeof spawn !== "object" || spawn === null) {
return undefined;
}
const record = spawn as Record<string, unknown>;
return {
nickname: typeof record.agent_nickname === "string" ? record.agent_nickname : undefined,
role: typeof record.agent_role === "string" ? record.agent_role : undefined,
agentPath: typeof record.agent_path === "string" ? record.agent_path : undefined,
depth: typeof record.depth === "number" ? record.depth : undefined,
parentThreadId:
typeof record.parent_thread_id === "string" ? record.parent_thread_id : undefined,
};
}
function rememberCollabReceiverTurns(
collabReceiverTurns: Map<string, TurnId>,
notification: CodexServerNotification,
@@ -641,6 +706,72 @@ function shouldSuppressChildConversationNotification(
);
}
/**
* How a notification addressed to a REGISTERED child thread is handled.
*
* Exported and pure so the routing table can be asserted against captured
* wire traces (see codexMultiAgentWire.json) rather than only read.
*
* - "agent-event": map to a synthetic collabAgent/* event (Agents surface).
* - "parent": pass through to the parent path — it carries state the parent
* still owns (approval correlation cleanup).
* - "drop": genuine child chatter with no parent meaning (deltas, name and
* plan updates).
*
* Default is "drop" ONLY for the enumerated chatter; anything unrecognized
* routes to "parent" so new wire methods surface instead of vanishing
* (two shipped bugs came from a catch-all that swallowed everything).
*/
export type CodexChildNotificationRoute = "agent-event" | "parent" | "drop";
const CHILD_AGENT_EVENT_METHODS: ReadonlySet<string> = new Set([
"turn/started",
"turn/completed",
"thread/status/changed",
"thread/tokenUsage/updated",
"item/started",
"item/completed",
"thread/closed",
"error",
]);
const CHILD_CHATTER_METHODS: ReadonlySet<string> = new Set([
"item/agentMessage/delta",
"item/reasoning/textDelta",
"item/reasoning/summaryTextDelta",
"item/reasoning/summaryPartAdded",
"item/commandExecution/outputDelta",
"item/fileChange/outputDelta",
"item/fileChange/patchUpdated",
"item/plan/delta",
"turn/plan/updated",
"turn/diff/updated",
"thread/name/updated",
"thread/settings/updated",
"rawResponseItem/completed",
// Child-owned thread lifecycle: the parent adapter maps these onto the
// PARENT thread (archived/compacted state), so a child compacting would
// rewrite the parent. Mirrors the v1 suppressor list — dropping them is
// the pre-existing behavior for collab children (review finding).
"thread/archived",
"thread/unarchived",
"thread/compacted",
// Registration path 1 handles a child's first thread/started; a repeat
// must not reach the parent (it would restart the parent's thread state).
"thread/started",
]);
export function routeCodexChildNotification(method: string): CodexChildNotificationRoute {
if (CHILD_AGENT_EVENT_METHODS.has(method)) {
return "agent-event";
}
if (CHILD_CHATTER_METHODS.has(method)) {
return "drop";
}
// Unknown or parent-owned (serverRequest/resolved, approvals, …).
return "parent";
}
function toCodexUserInputAnswer(
questionId: string,
value: ProviderUserInputAnswers[string],
@@ -723,6 +854,9 @@ export const makeCodexSessionRuntime = (
const approvalCorrelationsRef = yield* Ref.make(new Map<string, ApprovalCorrelation>());
const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgentState>());
/** Child provider-thread id → its currently running provider turn id. */
const collabChildLiveTurnsRef = yield* Ref.make(new Map<string, string>());
const closedRef = yield* Ref.make(false);
// `~` is not shell-expanded when env vars are set via
@@ -839,6 +973,280 @@ export const makeCodexSessionRuntime = (
),
);
/**
* Registers v2 collab children and re-emits their notifications as
* synthetic `collabAgent/*` events for the adapter's task.* synthesis.
* Returns true when the notification was fully handled (must not reach
* parent-timeline mapping).
*/
const interceptCollabChildNotification = (notification: CodexServerNotification) =>
Effect.gen(function* () {
// Registration path 1: child thread announces itself with a
// subAgent thread_spawn source.
if (notification.method === "thread/started") {
const thread = notification.params.thread;
const spawn = readThreadSpawnSource(thread);
if (!spawn) {
return false;
}
// Merge with any subAgentActivity registration that got here
// first. spawnTurnId is REGISTRATION-time-only on both paths: for
// an already-known child we keep its value (set or unset) — a
// later thread/started during an unrelated parent turn must not
// backfill that turn as the spawn batch, which would stamp an old
// child onto a new fleet's CTA (review finding). Only a genuinely
// new registration captures the current turn.
const existingChild = (yield* Ref.get(collabChildAgentsRef)).get(thread.id);
const spawnTurnId = existingChild
? existingChild.spawnTurnId
: ((yield* Ref.get(sessionRef)).activeTurnId ?? undefined);
const state: CollabChildAgentState = {
agentThreadId: thread.id,
nickname: spawn.nickname ?? thread.agentNickname ?? existingChild?.nickname,
role: spawn.role ?? thread.agentRole ?? existingChild?.role,
agentPath: spawn.agentPath ?? existingChild?.agentPath,
depth: spawn.depth ?? existingChild?.depth,
parentThreadId:
spawn.parentThreadId ?? thread.parentThreadId ?? existingChild?.parentThreadId,
spawnTurnId,
};
yield* Ref.update(collabChildAgentsRef, (current) => {
const next = new Map(current);
next.set(thread.id, state);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
method: "collabAgent/started",
...(state.spawnTurnId ? { turnId: state.spawnTurnId } : {}),
payload: {
agentThreadId: state.agentThreadId,
...(state.nickname ? { nickname: state.nickname } : {}),
...(state.role ? { role: state.role } : {}),
...(state.agentPath ? { agentPath: state.agentPath } : {}),
...(state.depth !== undefined ? { depth: state.depth } : {}),
...(state.parentThreadId ? { parentThreadId: state.parentThreadId } : {}),
},
});
return true;
}
// Registration path 2: parent-side subAgentActivity item names the
// child thread (may arrive before or after thread/started).
if (
(notification.method === "item/started" || notification.method === "item/completed") &&
notification.params.item.type === "subAgentActivity"
) {
const item = notification.params.item;
// Never register the session's ROOT thread as its own child. The
// wire emits subAgentActivity {agentPath: "/root", interacted}
// about the root during collab runs; registering it intercepted
// every subsequent root notification — including the final
// assistant message and turn/completed — so the thread hung
// "working" after all subagents finished (live-probe finding).
const rootProviderThreadId = currentProviderThreadId(yield* Ref.get(sessionRef));
if (
item.agentThreadId === rootProviderThreadId ||
item.agentPath === "/root" ||
item.agentPath === "/"
) {
return false;
}
const activitySpawnTurnId = (yield* Ref.get(sessionRef)).activeTurnId ?? undefined;
yield* Ref.update(collabChildAgentsRef, (current) => {
const existing = current.get(item.agentThreadId);
const next = new Map(current);
// Merge-late semantics: when thread/started registered first, a
// later subAgentActivity still carries the real agentPath (and a
// derived nickname) — fill missing fields, never clobber known
// ones. spawnTurnId is registration-time-only: for an already
// registered child, a later activity during an UNRELATED turn
// must not backfill that turn as the spawn batch (review
// finding); an unset spawn turn stays unset.
next.set(item.agentThreadId, {
agentThreadId: item.agentThreadId,
nickname:
existing?.nickname ??
item.agentPath.split("/").findLast((segment) => segment.length > 0),
role: existing?.role,
agentPath: existing?.agentPath ?? item.agentPath,
depth: existing?.depth,
parentThreadId: existing?.parentThreadId,
spawnTurnId: existing ? existing.spawnTurnId : activitySpawnTurnId,
});
return next;
});
const registeredChild = (yield* Ref.get(collabChildAgentsRef)).get(item.agentThreadId);
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
method: "collabAgent/activity",
...(registeredChild?.spawnTurnId ? { turnId: registeredChild.spawnTurnId } : {}),
payload: {
agentThreadId: item.agentThreadId,
agentPath: item.agentPath,
activityKind: item.kind,
},
});
return true;
}
// Interception: notifications addressed to a registered child thread
// become agent-scoped synthetic events instead of parent chatter.
const providerConversationId = readNotificationThreadId(notification);
if (!providerConversationId) {
return false;
}
// Belt-and-braces: the root thread's traffic must never be
// intercepted, whatever the registry says.
const interceptRootId = currentProviderThreadId(yield* Ref.get(sessionRef));
if (providerConversationId === interceptRootId) {
return false;
}
const children = yield* Ref.get(collabChildAgentsRef);
const child = children.get(providerConversationId);
if (!child) {
return false;
}
const childIdentity = {
agentThreadId: child.agentThreadId,
...(child.nickname ? { nickname: child.nickname } : {}),
...(child.role ? { role: child.role } : {}),
...(child.agentPath ? { agentPath: child.agentPath } : {}),
};
switch (notification.method) {
case "turn/started": {
const childTurnId =
typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === "string"
? ((notification.params as { turn: { id: string } }).turn.id as string)
: undefined;
if (childTurnId) {
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.set(child.agentThreadId, childTurnId);
return next;
});
}
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/turnStarted",
payload: childIdentity,
});
return true;
}
case "turn/completed":
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/turnCompleted",
payload: {
...childIdentity,
turn: notification.params.turn,
},
});
return true;
case "thread/status/changed":
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/statusChanged",
payload: {
...childIdentity,
status: notification.params.status,
},
});
return true;
case "thread/tokenUsage/updated":
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/tokenUsage",
payload: {
...childIdentity,
tokenUsage: notification.params.tokenUsage,
},
});
return true;
case "item/started":
case "item/completed":
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/item",
payload: {
...childIdentity,
item: notification.params.item,
},
});
return true;
case "thread/closed":
// The child is gone: drop its live-turn entry so a later Stop
// doesn't waste a turn/interrupt RPC on a closed thread before
// reaching the parent (review finding).
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/closed",
payload: childIdentity,
});
return true;
case "error": {
// A child error must surface as a failed agent, not vanish into
// the default swallow (review finding: the child stayed
// "running" forever). Retryable errors (willRetry) keep the
// child RUNNING and interruptible — mirroring the root error
// handler; settling it would orphan a still-live child from
// Stop (review finding). Terminal errors clean up the live turn
// like thread/closed and reuse the statusChanged systemError
// path.
const willRetry = (notification.params as { willRetry?: boolean }).willRetry === true;
if (willRetry) {
return true;
}
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(child.agentThreadId);
return next;
});
yield* emitEvent({
kind: "notification",
threadId: options.threadId,
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
method: "collabAgent/statusChanged",
payload: {
...childIdentity,
status: { type: "systemError" },
},
});
return true;
}
default:
// Routing table decides (single source of truth, asserted
// against captured wire traces): enumerated chatter is dropped,
// everything else — including methods this build has never seen
// — falls through to the parent path rather than vanishing.
return routeCodexChildNotification(notification.method) === "drop";
}
});
const handleRawNotification = (notification: CodexServerNotification) =>
Effect.gen(function* () {
const payload = notification.params;
@@ -852,7 +1260,68 @@ export const makeCodexSessionRuntime = (
})();
rememberCollabReceiverTurns(collabReceiverTurns, notification, route.turnId);
if (childParentTurnId && shouldSuppressChildConversationNotification(notification.method)) {
// Interception FIRST: a registered v2 child is usually also in the
// receiver-turn map (collabAgentToolCall.receiverThreadIds), and the
// legacy suppressor below would drop its lifecycle before it could
// become synthetic collabAgent events (review finding). The
// suppressor still covers UNREGISTERED children.
if (yield* interceptCollabChildNotification(notification)) {
yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
return;
}
// Suppression applies to receiver-map children (v1) AND to any
// conversation that is not the root thread. The live capture
// (codexMultiAgentWire.json) shows a child's thread/status/changed
// arriving BEFORE anything registers the child — pre-registration
// lifecycle must not reach the parent path, where the adapter maps
// thread/* onto parent session state. Root-id-known guard keeps the
// root's own early notifications flowing during session open.
const suppressRootId = currentProviderThreadId(yield* Ref.get(sessionRef));
const foreignConversation = (() => {
const providerConversationId = readNotificationThreadId(notification);
return (
providerConversationId !== undefined &&
suppressRootId !== undefined &&
providerConversationId !== suppressRootId
);
})();
if (
(childParentTurnId !== undefined || foreignConversation) &&
shouldSuppressChildConversationNotification(notification.method)
) {
// Stop-everything must not depend on registration timing: a
// child's turn/started can arrive before the subAgentActivity that
// registers it (captured ordering), and suppressing it without
// remembering the live turn would leave that child running after
// Stop (review finding). Track live turns for ANY foreign
// conversation; interrupts are best-effort per child, so a
// false-positive entry costs one ignored RPC at worst.
const foreignThreadId = readNotificationThreadId(notification);
if (foreignThreadId !== undefined) {
if (notification.method === "turn/started") {
const foreignTurnId =
typeof (notification.params as { turn?: { id?: unknown } }).turn?.id === "string"
? (notification.params as { turn: { id: string } }).turn.id
: undefined;
if (foreignTurnId) {
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.set(foreignThreadId, foreignTurnId);
return next;
});
}
} else if (
notification.method === "turn/completed" ||
notification.method === "thread/closed"
) {
yield* Ref.update(collabChildLiveTurnsRef, (current) => {
const next = new Map(current);
next.delete(foreignThreadId);
return next;
});
}
}
yield* Ref.set(collabReceiverTurnsRef, collabReceiverTurns);
return;
}
@@ -1331,6 +1800,26 @@ export const makeCodexSessionRuntime = (
Effect.gen(function* () {
const providerThreadId = yield* readProviderThreadId;
const session = yield* Ref.get(sessionRef);
// Stop-everything: children are full threads with their own turns;
// interrupting only the parent leaves the fleet running. Interrupt
// each live child turn first, best-effort per child, BOUNDED: the
// transport awaits an unbounded Deferred per request, so a wedged
// child would otherwise block the parent interrupt forever —
// exactly during the runaway fleet where Stop matters most
// (review finding). Per-child and overall deadlines guarantee the
// parent interrupt below always runs.
const liveChildTurns = yield* Ref.get(collabChildLiveTurnsRef);
yield* Effect.forEach(
Array.from(liveChildTurns.entries()),
([childThreadId, childTurnId]) =>
client
.request("turn/interrupt", {
threadId: childThreadId,
turnId: childTurnId,
})
.pipe(Effect.timeoutOption("3 seconds"), Effect.ignore),
{ concurrency: 8, discard: true },
).pipe(Effect.timeoutOption("10 seconds"), Effect.ignore);
const effectiveTurnId = turnId ?? session.activeTurnId;
if (!effectiveTurnId) {
return;
@@ -459,6 +459,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
adapter,
instanceId,
threadId: input.threadId,
runtimeMode: binding.runtimeMode,
isActive: true,
} as const;
}
@@ -468,6 +469,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
adapter,
instanceId,
threadId: input.threadId,
runtimeMode: binding.runtimeMode,
isActive: false,
} as const;
}
@@ -480,6 +482,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
adapter: recovered.adapter,
instanceId,
threadId: input.threadId,
runtimeMode: recovered.session.runtimeMode,
isActive: true,
} as const;
});
@@ -629,6 +632,19 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
input.modelSelection.model.trim().length > 0,
});
// Changing runtime mode restarts the session, so the transition is only
// observable here, by diffing against the mode the previous session for
// this thread was bound to. Recording it separately is what makes the
// "started supervised, switched to full access" funnel answerable.
const previousRuntimeMode = persistedBinding?.runtimeMode;
if (previousRuntimeMode !== undefined && previousRuntimeMode !== input.runtimeMode) {
yield* analytics.record("provider.runtime_mode.changed", {
provider: sessionWithInstance.provider,
from: previousRuntimeMode,
to: input.runtimeMode,
});
}
return sessionWithInstance;
}).pipe(
withMetrics({
@@ -703,6 +719,10 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
provider: routed.adapter.provider,
model: input.modelSelection?.model,
interactionMode: input.interactionMode,
// Session-start events alone skew runtime mode toward users who toggle
// often, since every toggle restarts the session. Recording it per turn
// gives a usage-weighted view and lets it cross with interactionMode.
runtimeMode: routed.runtimeMode,
attachmentCount: input.attachments.length,
hasInput: typeof input.input === "string" && input.input.trim().length > 0,
});
@@ -68,6 +68,46 @@ describe("AcpCoreRuntimeEvents", () => {
});
});
it("maps generic ACP permission kinds to dynamic tool approvals", () => {
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
for (const kind of ["search", "fetch", "other", "unknown", "future-tool-kind"]) {
const permissionRequest = { kind };
const request = {
stamp,
provider: ProviderDriverKind.make("cursor"),
threadId: "thread-1" as never,
turnId: TurnId.make("turn-1"),
requestId: RuntimeRequestId.make(`request-${kind}`),
permissionRequest,
};
expect(
makeAcpRequestOpenedEvent({
...request,
detail: kind,
args: {},
source: "acp.jsonrpc",
method: "session/request_permission",
rawPayload: { sessionId: "session-1" },
}),
).toMatchObject({
type: "request.opened",
payload: { requestType: "dynamic_tool_call" },
});
expect(
makeAcpRequestResolvedEvent({
...request,
decision: "accept",
}),
).toMatchObject({
type: "request.resolved",
payload: { requestType: "dynamic_tool_call" },
});
}
});
it("maps ACP core plan, tool-call, and content updates", () => {
const stamp = { eventId: "event-1" as never, createdAt: "2026-03-27T00:00:00.000Z" };
const turnId = TurnId.make("turn-1");
@@ -26,7 +26,7 @@ interface AcpEventStamp {
type AcpCanonicalRequestType = Extract<
CanonicalRequestType,
"exec_command_approval" | "file_read_approval" | "file_change_approval" | "unknown"
"exec_command_approval" | "file_read_approval" | "file_change_approval" | "dynamic_tool_call"
>;
function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonicalRequestType {
@@ -40,7 +40,7 @@ function canonicalRequestTypeFromAcpKind(kind: string | "unknown"): AcpCanonical
case "move":
return "file_change_approval";
default:
return "unknown";
return "dynamic_tool_call";
}
}
@@ -0,0 +1,93 @@
// Minimal codex app-server stand-in for runtime-level collab tests.
// Speaks just enough of the protocol for CodexSessionRuntime to start a
// session, using REAL captured responses (codexMultiAgentWire.json), then
// replays a scripted multi-agent notification sequence read from the
// T3_CODEX_COLLAB_SCRIPT env var (a JSON file path) when the first turn
// starts. Runs as a plain Node process — stdlib only.
import * as NodeFS from "node:fs";
import * as NodeReadline from "node:readline";
import * as NodePath from "node:path";
import * as NodeURL from "node:url";
const here = NodePath.dirname(NodeURL.fileURLToPath(import.meta.url));
const fixture = JSON.parse(
NodeFS.readFileSync(NodePath.join(here, "codexMultiAgentWire.json"), "utf8"),
);
const script = JSON.parse(NodeFS.readFileSync(process.env.T3_CODEX_COLLAB_SCRIPT, "utf8"));
const write = (message) => process.stdout.write(`${JSON.stringify(message)}\n`);
const rl = NodeReadline.createInterface({ input: process.stdin });
rl.on("line", (line) => {
let message;
try {
message = JSON.parse(line);
} catch {
return;
}
const { id, method } = message;
if (method === "initialize") {
write({
id,
result: {
userAgent: "t3-collab-mock/0.0.0",
codexHome: "/tmp",
platformFamily: "unix",
platformOs: "linux",
},
});
return;
}
if (method === "thread/start" || method === "thread/resume") {
write({ id, result: fixture.responses.threadStart });
return;
}
if (method === "turn/start") {
write({ id, result: fixture.responses.turnStart });
const rootThreadId = script.rootThreadId;
const turn = fixture.responses.turnStart.turn;
write({
jsonrpc: "2.0",
method: "turn/started",
params: { threadId: rootThreadId, turn },
});
for (const notification of script.notifications) {
write({ jsonrpc: "2.0", method: notification.method, params: notification.params });
}
if (script.holdTurnOpen !== true) {
write({
jsonrpc: "2.0",
method: "turn/completed",
params: {
threadId: rootThreadId,
turn: { ...turn, status: "completed" },
},
});
}
return;
}
if (method === "turn/interrupt") {
// Record which thread/turn was interrupted (append-only sidecar file the
// test reads) so Stop coverage can assert every live child was reached.
// failInterruptFor simulates a dead child whose interrupt errors.
const target = message.params?.threadId;
NodeFS.appendFileSync(
`${process.env.T3_CODEX_COLLAB_SCRIPT}.interrupts`,
`${JSON.stringify({ threadId: target, turnId: message.params?.turnId })}\n`,
);
if (script.failInterruptFor && script.failInterruptFor === target) {
write({ id, error: { code: -32000, message: "thread already closed" } });
return;
}
if (script.hangInterruptFor && script.hangInterruptFor === target) {
// Never respond: simulates a wedged child whose RPC neither resolves
// nor rejects. The runtime's bounded deadline must move on.
return;
}
write({ id, result: {} });
return;
}
if (id !== undefined) {
write({ id, result: {} });
}
});
@@ -0,0 +1,6 @@
#!/usr/bin/env bash
# Wrapper so CodexSessionRuntime can spawn the mock peer: the runtime always
# passes "app-server" as the first argument (real codex CLI subcommand);
# discard it and exec node on the .mjs peer.
shift
exec node "$(dirname "$0")/codexCollabMockPeer.mjs" "$@"
@@ -0,0 +1,445 @@
{
"capturedWith": {
"cli": "codex-cli 0.145.0",
"model": "gpt-5.6-luna",
"effort": "low"
},
"rootThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"childThreadIds": [
"019fcfd6-2883-77e0-9013-4410ede70371",
"019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf"
],
"notifications": [
{
"method": "thread/started",
"params": {
"thread": {
"id": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"extra": null,
"sessionId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"forkedFromId": null,
"parentThreadId": null,
"preview": "",
"ephemeral": false,
"historyMode": "legacy",
"modelProvider": "openai",
"createdAt": 1785898342,
"updatedAt": 1785898342,
"recencyAt": 1785898342,
"status": {
"type": "idle"
},
"path": "/fixtures/codex/rollout.jsonl",
"cwd": "/workspace/repo",
"cliVersion": "0.145.0",
"source": "vscode",
"canAcceptDirectInput": true,
"threadSource": null,
"agentNickname": null,
"agentRole": null,
"gitInfo": null,
"name": null,
"turns": []
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"status": {
"type": "active",
"activeFlags": []
}
}
},
{
"method": "turn/started",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turn": {
"id": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": 1785898342,
"completedAt": null,
"durationMs": null
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"status": {
"type": "idle"
}
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "subAgentActivity",
"id": "call_S2JPiq0sMnJYS7kswVdvzEjB",
"kind": "started",
"agentThreadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"agentPath": "/root/alpha"
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"completedAtMs": 1785898346687
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"tokenUsage": {
"total": {
"totalTokens": 18261,
"inputTokens": 18228,
"cachedInputTokens": 11008,
"cacheWriteInputTokens": 0,
"outputTokens": 33,
"reasoningOutputTokens": 0
},
"last": {
"totalTokens": 18261,
"inputTokens": 18228,
"cachedInputTokens": 11008,
"cacheWriteInputTokens": 0,
"outputTokens": 33,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"status": {
"type": "active",
"activeFlags": []
}
}
},
{
"method": "turn/started",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turn": {
"id": "019fcfd6-28bf-7e00-a873-4554526dc845",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": 1785898346,
"completedAt": null,
"durationMs": null
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"status": {
"type": "idle"
}
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "subAgentActivity",
"id": "call_A2U7sfjmdGlUn5bn6gUNI0rl",
"kind": "started",
"agentThreadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"agentPath": "/root/beta"
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"completedAtMs": 1785898348329
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"status": {
"type": "active",
"activeFlags": []
}
}
},
{
"method": "turn/started",
"params": {
"threadId": "019fcfd6-2ef7-7932-9ff5-dea6ad6f4daf",
"turn": {
"id": "019fcfd6-2f29-79e3-aa6a-c5836a519d3f",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": 1785898348,
"completedAt": null,
"durationMs": null
}
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"tokenUsage": {
"total": {
"totalTokens": 36576,
"inputTokens": 36510,
"cachedInputTokens": 28160,
"cacheWriteInputTokens": 0,
"outputTokens": 66,
"reasoningOutputTokens": 0
},
"last": {
"totalTokens": 18315,
"inputTokens": 18282,
"cachedInputTokens": 17152,
"cacheWriteInputTokens": 0,
"outputTokens": 33,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "subAgentActivity",
"id": "call_2W1NboHClVo0VqAf1y3ZFinO",
"kind": "interacted",
"agentThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"agentPath": "/root"
},
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",
"completedAtMs": 1785898349265
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",
"tokenUsage": {
"total": {
"totalTokens": 20756,
"inputTokens": 20713,
"cachedInputTokens": 5888,
"cacheWriteInputTokens": 0,
"outputTokens": 43,
"reasoningOutputTokens": 11
},
"last": {
"totalTokens": 20756,
"inputTokens": 20713,
"cachedInputTokens": 5888,
"cacheWriteInputTokens": 0,
"outputTokens": 43,
"reasoningOutputTokens": 11
},
"modelContextWindow": 258400
}
}
},
{
"method": "item/started",
"params": {
"item": {
"type": "collabAgentToolCall",
"id": "call_XGMDYMm4O8ne7vg3Y6p4eSqz",
"tool": "wait",
"status": "inProgress",
"senderThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"receiverThreadIds": [],
"prompt": null,
"model": null,
"reasoningEffort": null,
"agentsStates": {}
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"startedAtMs": 1785898349931
}
},
{
"method": "item/completed",
"params": {
"item": {
"type": "collabAgentToolCall",
"id": "call_XGMDYMm4O8ne7vg3Y6p4eSqz",
"tool": "wait",
"status": "completed",
"senderThreadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"receiverThreadIds": [],
"prompt": null,
"model": null,
"reasoningEffort": null,
"agentsStates": {}
},
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"completedAtMs": 1785898349931
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"turnId": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"tokenUsage": {
"total": {
"totalTokens": 54933,
"inputTokens": 54846,
"cachedInputTokens": 45312,
"cacheWriteInputTokens": 0,
"outputTokens": 87,
"reasoningOutputTokens": 0
},
"last": {
"totalTokens": 18357,
"inputTokens": 18336,
"cachedInputTokens": 17152,
"cacheWriteInputTokens": 0,
"outputTokens": 21,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "thread/tokenUsage/updated",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turnId": "019fcfd6-28bf-7e00-a873-4554526dc845",
"tokenUsage": {
"total": {
"totalTokens": 41529,
"inputTokens": 41481,
"cachedInputTokens": 26112,
"cacheWriteInputTokens": 0,
"outputTokens": 48,
"reasoningOutputTokens": 11
},
"last": {
"totalTokens": 20773,
"inputTokens": 20768,
"cachedInputTokens": 20224,
"cacheWriteInputTokens": 0,
"outputTokens": 5,
"reasoningOutputTokens": 0
},
"modelContextWindow": 258400
}
}
},
{
"method": "thread/status/changed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"status": {
"type": "idle"
}
}
},
{
"method": "turn/completed",
"params": {
"threadId": "019fcfd6-2883-77e0-9013-4410ede70371",
"turn": {
"id": "019fcfd6-28bf-7e00-a873-4554526dc845",
"items": [],
"itemsView": "notLoaded",
"status": "completed",
"error": null,
"startedAt": 1785898346,
"completedAt": 1785898350,
"durationMs": 3792
}
}
}
],
"responses": {
"threadStart": {
"thread": {
"id": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"extra": null,
"sessionId": "019fcfd6-17bb-72f0-ae12-a1f2dee6e3e5",
"forkedFromId": null,
"parentThreadId": null,
"preview": "",
"ephemeral": false,
"historyMode": "legacy",
"modelProvider": "openai",
"createdAt": 1785898342,
"updatedAt": 1785898342,
"recencyAt": 1785898342,
"status": {
"type": "idle"
},
"path": "/fixtures/codex/rollout.jsonl",
"cwd": "/workspace/repo",
"cliVersion": "0.145.0",
"source": "vscode",
"canAcceptDirectInput": true,
"threadSource": null,
"agentNickname": null,
"agentRole": null,
"gitInfo": null,
"name": null,
"turns": []
},
"model": "gpt-5.6-sol",
"modelProvider": "openai",
"serviceTier": "default",
"cwd": "/workspace/repo",
"runtimeWorkspaceRoots": ["/workspace/repo"],
"instructionSources": ["/fixtures/scrubbed", "/workspace/repo/AGENTS.md"],
"approvalPolicy": "on-request",
"approvalsReviewer": "auto_review",
"sandbox": {
"type": "workspaceWrite",
"writableRoots": [],
"networkAccess": false,
"excludeTmpdirEnvVar": false,
"excludeSlashTmp": false
},
"activePermissionProfile": null,
"reasoningEffort": "high",
"multiAgentMode": "explicitRequestOnly"
},
"turnStart": {
"turn": {
"id": "019fcfd6-1806-7de1-8564-de69fd55bffb",
"items": [],
"itemsView": "notLoaded",
"status": "inProgress",
"error": null,
"startedAt": null,
"completedAt": null,
"durationMs": null
}
}
}
}
+359 -25
View File
@@ -2,7 +2,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeSocket from "@effect/platform-node/NodeSocket";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeCrypto from "node:crypto";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import {
AuthAccessTokenType,
@@ -16,6 +16,8 @@ import {
KeybindingRule,
MessageId,
ExternalLauncherCommandNotFoundError,
OrchestrationThreadDetailSnapshot,
type OrchestrationThreadStreamItem,
type OrchestrationThreadShell,
TerminalNotRunningError,
type OrchestrationCommand,
@@ -41,6 +43,7 @@ import * as RelayClient from "@t3tools/shared/relayClient";
import { assert, it } from "@effect/vitest";
import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils";
import * as Clock from "effect/Clock";
import * as Config from "effect/Config";
import * as Deferred from "effect/Deferred";
import * as DateTime from "effect/DateTime";
import * as Duration from "effect/Duration";
@@ -52,6 +55,8 @@ import * as ManagedRuntime from "effect/ManagedRuntime";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PubSub from "effect/PubSub";
import * as Queue from "effect/Queue";
import * as Schema from "effect/Schema";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";
import { ChildProcessSpawner } from "effect/unstable/process";
@@ -70,11 +75,34 @@ import * as Socket from "effect/unstable/socket/Socket";
import { vi } from "vite-plus/test";
const TEST_EPOCH = DateTime.makeUnsafe("1970-01-01T00:00:00.000Z");
const decodeTransferThreadSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(OrchestrationThreadDetailSnapshot),
);
const collectQueueUntil = Effect.fn("TransferBudget.collectQueueUntil")(function* <A>(
queue: Queue.Queue<A>,
predicate: (value: A) => boolean,
waitDescription: string,
) {
return yield* Effect.gen(function* () {
const values: A[] = [];
while (true) {
const value = yield* Queue.take(queue);
values.push(value);
if (predicate(value)) return values;
}
}).pipe(
Effect.timeoutOrElse({
duration: "10 seconds",
orElse: () => Effect.die(new Error(`Timed out waiting for ${waitDescription}`)),
}),
);
});
import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
import * as ServerConfig from "./config.ts";
import { makeRoutesLayer } from "./server.ts";
import { resolveAvailableEditorsForConfig } from "./ws.ts";
import { isThreadDetailEvent, resolveAvailableEditorsForConfig } from "./ws.ts";
import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
import * as GitManager from "./git/GitManager.ts";
import * as Keybindings from "./keybindings.ts";
@@ -123,6 +151,32 @@ import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts
import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
import * as Data from "effect/Data";
import { makeOrchestrationIntegrationHarness } from "../integration/OrchestrationEngineHarness.integration.ts";
import {
countingWsRpcProtocolLayer,
makeCountingWsRpcClient,
makeWebSocketTransferRecorder,
measureHttpGet,
transferDelta,
} from "../integration/NetworkTransferMeasurement.integration.ts";
import {
expectedMeasuredAssistantText,
queueMeasuredTransferTurn,
seedTransferBudgetHistory,
TRANSFER_HISTORY_TURN_COUNT,
TRANSFER_MEASURED_TURN_CREATED_AT,
TRANSFER_MEASURED_TURN_INDEX,
TRANSFER_THREAD_ID,
transferModelSelection,
waitForTurnQuiesced,
} from "../integration/TransferBudgetScenario.integration.ts";
import {
formatTransferBudgetReport,
formatTransferBudgetResult,
type TransferBudgetRun,
transferBudgetViolations,
} from "../integration/TransferBudgetReport.integration.ts";
const defaultProjectId = ProjectId.make("project-default");
const defaultThreadId = ThreadId.make("thread-default");
const defaultDesktopBootstrapToken = "test-desktop-bootstrap-token";
@@ -549,9 +603,12 @@ const buildAppUnderTest = (options?: {
),
),
);
const serviceLauncherClientLayer = ServiceLauncherClient.layer.pipe(
Layer.provide(Layer.succeed(HostProcessEnvironment, {})),
);
const servedRoutesLayer = HttpRouter.serve(
makeRoutesLayer.pipe(Layer.provide(ServiceLauncherClient.layer)),
makeRoutesLayer.pipe(Layer.provide(serviceLauncherClientLayer)),
{
disableListenLog: true,
disableLogger: true,
@@ -1319,6 +1376,28 @@ const getWsServerUrl = (
);
});
// Mirrors NodeHttpServer.layerTest, which does not expose server options,
// with the production `websocket: { perMessageDeflate: true }` setting.
const NodeHttpServerTestWithWsDeflate = HttpServer.layerTestClient.pipe(
Layer.provide(
Layer.fresh(FetchHttpClient.layer).pipe(
Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false })),
),
),
Layer.provideMerge(
Layer.unwrap(
Effect.map(
Effect.promise(() => import("node:http")),
(NodeHttp) =>
NodeHttpServer.layer(NodeHttp.createServer, {
port: 0,
websocket: { perMessageDeflate: true },
}),
),
),
),
);
it.layer(NodeServices.layer)("server router seam", (it) => {
it.effect("parks HTTP ingress until command readiness", () =>
Effect.gen(function* () {
@@ -3219,28 +3298,6 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
// Mirrors NodeHttpServer.layerTest, which does not expose server options,
// with the production `websocket: { perMessageDeflate: true }` setting.
const NodeHttpServerTestWithWsDeflate = HttpServer.layerTestClient.pipe(
Layer.provide(
Layer.fresh(FetchHttpClient.layer).pipe(
Layer.provide(Layer.succeed(FetchHttpClient.RequestInit)({ keepalive: false })),
),
),
Layer.provideMerge(
Layer.unwrap(
Effect.map(
Effect.promise(() => import("node:http")),
(NodeHttp) =>
NodeHttpServer.layer(NodeHttp.createServer, {
port: 0,
websocket: { perMessageDeflate: true },
}),
),
),
),
);
it.effect("negotiates permessage-deflate with clients that offer it", () =>
Effect.gen(function* () {
yield* buildAppUnderTest();
@@ -7134,6 +7191,13 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
pr: null,
}),
);
const remoteExists = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["remoteExists"]>[0]) =>
Effect.sync(() => {
bootstrapGitOperations.push("remote-exists");
return true;
}),
);
const fetchRemote = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"]>[0]) =>
Effect.sync(() => {
@@ -7181,6 +7245,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
yield* buildAppUnderTest({
layers: {
gitVcsDriver: {
remoteExists,
fetchRemote,
resolveRemoteTrackingCommit,
createWorktree,
@@ -7271,6 +7336,7 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
fallbackRemoteName: "origin",
});
assert.deepEqual(bootstrapGitOperations, [
"remote-exists",
"fetch",
"resolve-remote-commit",
"create-worktree",
@@ -7299,6 +7365,110 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect(
"falls back to the local base branch when startFromOrigin is set but no origin remote exists",
() =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
const remoteExists = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["remoteExists"]>[0]) =>
Effect.succeed(false),
);
const fetchRemote = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["fetchRemote"]>[0]) => Effect.void,
);
const resolveRemoteTrackingCommit = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["resolveRemoteTrackingCommit"]>[0]) =>
Effect.succeed({
commitSha: "0123456789abcdef0123456789abcdef01234567",
remoteRefName: "origin/main",
}),
);
const createWorktree = vi.fn(
(_: Parameters<GitVcsDriver.GitVcsDriver["Service"]["createWorktree"]>[0]) =>
Effect.succeed({
worktree: {
refName: "t3code/bootstrap-refName",
path: "/tmp/bootstrap-worktree",
},
}),
);
yield* buildAppUnderTest({
layers: {
gitVcsDriver: {
remoteExists,
fetchRemote,
resolveRemoteTrackingCommit,
createWorktree,
},
orchestrationEngine: {
dispatch: (command) =>
Effect.sync(() => {
dispatchedCommands.push(command);
return { sequence: dispatchedCommands.length };
}),
readEvents: () => Stream.empty,
},
},
});
const createdAt = "2026-01-01T00:00:00.000Z";
const wsUrl = yield* getWsServerUrl("/ws");
yield* Effect.scoped(
withWsRpcClient(wsUrl, (client) =>
client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.make("cmd-bootstrap-turn-start-no-origin"),
threadId: ThreadId.make("thread-bootstrap-no-origin"),
message: {
messageId: MessageId.make("msg-bootstrap-no-origin"),
role: "user",
text: "hello",
attachments: [],
},
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
bootstrap: {
createThread: {
projectId: defaultProjectId,
title: "Bootstrap Thread",
modelSelection: defaultModelSelection,
runtimeMode: "full-access",
interactionMode: "default",
branch: "main",
worktreePath: null,
createdAt,
},
prepareWorktree: {
projectCwd: "/tmp/project",
baseBranch: "main",
branch: "t3code/bootstrap-refName",
startFromOrigin: true,
},
},
createdAt,
}),
),
);
assert.deepEqual(remoteExists.mock.calls[0]?.[0], {
cwd: "/tmp/project",
remoteName: "origin",
});
assert.equal(fetchRemote.mock.calls.length, 0);
assert.equal(resolveRemoteTrackingCommit.mock.calls.length, 0);
assert.deepEqual(createWorktree.mock.calls[0]?.[0], {
cwd: "/tmp/project",
refName: "main",
newRefName: "t3code/bootstrap-refName",
baseRefName: "main",
path: null,
});
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("records setup-script failures without aborting bootstrap turn start", () =>
Effect.gen(function* () {
const dispatchedCommands: Array<OrchestrationCommand> = [];
@@ -7726,3 +7896,167 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
});
it.live(
"reports thread HTTP and WebSocket transfer budgets",
() =>
Effect.gen(function* () {
const providers = [
ProviderDriverKind.make("codex"),
ProviderDriverKind.make("claudeAgent"),
] as const;
const runs = yield* Effect.forEach(
providers,
(provider) =>
Effect.acquireUseRelease(
makeOrchestrationIntegrationHarness({ provider }),
(harness) =>
Effect.gen(function* () {
yield* seedTransferBudgetHistory(harness, provider);
yield* buildAppUnderTest({
layers: {
orchestrationEngine: harness.engine,
projectionSnapshotQuery: harness.snapshotQuery,
},
});
const baseUrl = yield* getHttpServerUrl();
const cookie = yield* getAuthenticatedSessionCookieHeader();
const recorder = makeWebSocketTransferRecorder();
const wsUrl = baseUrl.replace(/^http:/, "ws:") + "/ws";
const protocolLayer = countingWsRpcProtocolLayer({
url: wsUrl,
cookie,
recorder,
});
return yield* Effect.scoped(
Effect.gen(function* () {
const client = yield* makeCountingWsRpcClient;
const threadSnapshot = yield* measureHttpGet({
url: `${baseUrl}/api/orchestration/threads/${TRANSFER_THREAD_ID}`,
headers: { cookie },
});
assert.equal(threadSnapshot.status, 200);
assert.equal(threadSnapshot.contentEncoding, "gzip");
const decodedThread = yield* decodeTransferThreadSnapshot(
Buffer.from(threadSnapshot.decodedBody).toString("utf8"),
);
assert.equal(
decodedThread.thread.messages.length,
TRANSFER_HISTORY_TURN_COUNT * 2,
);
const threadItems = yield* Queue.unbounded<OrchestrationThreadStreamItem>();
yield* client[ORCHESTRATION_WS_METHODS.subscribeThread]({
threadId: TRANSFER_THREAD_ID,
afterSequence: decodedThread.snapshotSequence,
requestCompletionMarker: true,
}).pipe(
Stream.runForEach((item) =>
Queue.offer(threadItems, item).pipe(Effect.asVoid),
),
Effect.forkScoped,
);
const initialThreadItems = yield* collectQueueUntil(
threadItems,
(item) => item.kind === "synchronized",
`${provider} thread subscription to synchronize`,
);
assert.isFalse(initialThreadItems.some((item) => item.kind === "snapshot"));
assert.include(recorder.negotiatedExtensions(), "permessage-deflate");
yield* queueMeasuredTransferTurn(harness, provider);
const turnStartTotals = recorder.totals();
yield* client[ORCHESTRATION_WS_METHODS.dispatchCommand]({
type: "thread.turn.start",
commandId: CommandId.make(`transfer:${provider}:measured-turn`),
threadId: TRANSFER_THREAD_ID,
message: {
messageId: MessageId.make("transfer-user-measured"),
role: "user",
text: "Measure the client-bound transfer for this turn.",
attachments: [],
},
modelSelection: transferModelSelection(provider),
runtimeMode: "approval-required",
interactionMode: "default",
createdAt: TRANSFER_MEASURED_TURN_CREATED_AT,
});
yield* waitForTurnQuiesced(harness, TRANSFER_MEASURED_TURN_INDEX + 1);
const finalThreadSequence = yield* harness.engine
.readEvents(decodedThread.snapshotSequence, 10_000)
.pipe(
Stream.runFold(
() => decodedThread.snapshotSequence,
(sequence, event) =>
event.aggregateId === TRANSFER_THREAD_ID && isThreadDetailEvent(event)
? Math.max(sequence, event.sequence)
: sequence,
),
);
assert.isAbove(finalThreadSequence, decodedThread.snapshotSequence);
yield* collectQueueUntil(
threadItems,
(item) =>
item.kind === "event" && item.event.sequence === finalThreadSequence,
`${provider} thread stream to reach sequence ${finalThreadSequence}`,
);
const measuredTurnWebSocket = transferDelta(turnStartTotals, recorder.totals());
const finalThreadSnapshot = yield* harness.snapshotQuery
.getThreadDetailSnapshot(TRANSFER_THREAD_ID)
.pipe(Effect.map(Option.getOrThrow));
const expectedAssistantText = expectedMeasuredAssistantText(provider);
const measuredAssistant = finalThreadSnapshot.thread.messages.find(
(message) =>
message.role === "assistant" && message.text === expectedAssistantText,
);
assert.isDefined(measuredAssistant);
assert.isTrue(
finalThreadSnapshot.thread.messages.length >= TRANSFER_HISTORY_TURN_COUNT * 2,
);
assert.equal(measuredAssistant?.streaming, false);
assert.equal(finalThreadSnapshot.thread.session?.status, "ready");
assert.equal(
finalThreadSnapshot.thread.checkpoints.length,
TRANSFER_HISTORY_TURN_COUNT + 1,
);
return {
provider,
threadSnapshot,
measuredTurnWebSocket,
} satisfies TransferBudgetRun;
}).pipe(Effect.provide(protocolLayer)),
);
}),
(harness) => harness.dispose,
).pipe(Effect.provide(NodeHttpServerTestWithWsDeflate)),
{ concurrency: 1 },
);
const report = formatTransferBudgetReport(runs);
yield* Effect.logInfo(`\n${report}`);
const reportPath = yield* Config.string("T3CODE_TRANSFER_BUDGET_REPORT_PATH").pipe(
Config.option,
);
if (Option.isSome(reportPath)) {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(reportPath.value, report);
}
const resultPath = yield* Config.string("T3CODE_TRANSFER_BUDGET_RESULT_PATH").pipe(
Config.option,
);
if (Option.isSome(resultPath)) {
const fileSystem = yield* FileSystem.FileSystem;
yield* fileSystem.writeFileString(resultPath.value, formatTransferBudgetResult(runs));
}
assert.deepEqual(transferBudgetViolations(runs), []);
}).pipe(Effect.provide(NodeServices.layer)),
120_000,
);
+27 -18
View File
@@ -83,6 +83,7 @@ import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
connectHttpApiLayer,
pendingServiceUpdateExists,
reconcileDesiredCloudLink,
releaseManagedTunnelOnShutdown,
} from "./cloud/http.ts";
@@ -559,26 +560,34 @@ export const makeServerLayer = Layer.unwrap(
yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
return;
}
const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
),
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to release the managed tunnel on shutdown; the next link reuses it",
{ cause },
),
),
Effect.asVoid,
);
// A launcher trial can be stopped before activation. The previous
// server is already gone, so the trial owns cleanup immediately; the
// pending-state check keeps the tunnel for normal commit or rollback,
// while the launcher's explicit-stop marker allows it to be released.
// Other runtimes wait for activation so a failed standby cannot tear
// down the active runtime's tunnel.
const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
if (cleanupBeforeActivation) {
yield* Effect.addFinalizer(() => releaseManagedTunnel);
}
yield* forkParked(
Effect.gen(function* () {
// Only an activated runtime owns the tunnel cleanup finalizer.
yield* Effect.addFinalizer(() =>
releaseManagedTunnelOnShutdown().pipe(
Effect.timeout("10 seconds"),
Effect.tap((released) =>
released
? Effect.logInfo("Released the managed tunnel on shutdown")
: Effect.void,
),
Effect.catchCause((cause) =>
Effect.logWarning(
"Failed to release the managed tunnel on shutdown; the next link reuses it",
{ cause },
),
),
Effect.asVoid,
),
);
if (!cleanupBeforeActivation) {
yield* Effect.addFinalizer(() => releaseManagedTunnel);
}
if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
const server = yield* HttpServer.HttpServer;
const address = server.address;
+7 -1
View File
@@ -10,6 +10,7 @@ import {
decodeServiceState,
isExactServiceVersion,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STOP_MARKER_FILE,
} from "./cloud/serviceProtocol.ts";
it("accepts only exact semantic versions", () => {
@@ -111,7 +112,12 @@ it.layer(NodeServices.layer)("service state persistence", (it) => {
const launcher = new Launcher(root, yield* Effect.promise(() => readServiceState(statePath)));
const running = launcher.run();
yield* Effect.promise(() => launcher.stop("SIGTERM"));
const stopping = launcher.stop("SIGTERM");
// An explicit stop leaves the marker that tells a child shutting down
// mid-update that no replacement server is coming. It is present as
// soon as stop() returns its promise, before queued transitions run.
assert.isTrue(yield* fs.exists(path.join(root, "runtime", SERVICE_STOP_MARKER_FILE)));
yield* Effect.promise(() => stopping);
yield* Effect.promise(() => running);
}),
);
+25 -2
View File
@@ -5,6 +5,7 @@
// `t3 service update`. Keep runtime imports limited to Node built-ins.
import * as NodeChildProcess from "node:child_process";
import * as NodeCrypto from "node:crypto";
import * as NodeFS from "node:fs";
import * as NodeFSP from "node:fs/promises";
import * as NodePath from "node:path";
@@ -24,6 +25,7 @@ import {
SERVICE_LAUNCHER_CONTEXT_ENV,
SERVICE_LAUNCHER_PROTOCOL,
SERVICE_STATE_FILE,
SERVICE_STOP_MARKER_FILE,
} from "./cloud/serviceProtocol.ts";
const HANDOFF_DELAY_MS = 2_000;
@@ -257,6 +259,9 @@ async function terminateChild(
}
}
const stopMarkerPath = (baseDir: string) =>
NodePath.join(baseDir, "runtime", SERVICE_STOP_MARKER_FILE);
export class Launcher {
readonly #baseDir: string;
readonly #statePath: string;
@@ -264,6 +269,7 @@ export class Launcher {
#child: ManagedChild | null = null;
#timer: NodeJS.Timeout | undefined;
#transitions: Promise<void> = Promise.resolve();
#stopRequested = false;
#stopping = false;
#done = false;
readonly #completion = Promise.withResolvers<void>();
@@ -308,13 +314,26 @@ export class Launcher {
}
async stop(signal: NodeJS.Signals): Promise<void> {
if (this.#stopping) {
// This must happen synchronously at signal receipt. A queued update
// transition may already be terminating the active child, and that child
// needs to see the marker in its shutdown finalizer. KillMode=mixed also
// ensures systemd signals the launcher before the rest of the cgroup.
try {
NodeFS.writeFileSync(stopMarkerPath(this.#baseDir), "", { mode: 0o600 });
} catch {
// Err toward keeping the tunnel; the next link or unlink reconciles it.
}
if (this.#stopRequested || this.#stopping) {
await this.#completion.promise.catch(() => undefined);
return;
}
this.#stopping = true;
this.#stopRequested = true;
this.#clearTimer();
this.#enqueue(async () => {
// Let an update transition already in progress start its replacement
// before this queued stop tears it down. That replacement owns the
// pre-activation tunnel cleanup path and observes the marker above.
this.#stopping = true;
const child = this.#child?.process;
this.#child = null;
if (child !== undefined) await terminateChild(child, signal);
@@ -330,6 +349,10 @@ export class Launcher {
}
async #recover(): Promise<void> {
// A fresh launcher means servers are running again: any stop marker from
// a previous explicit stop is stale and must not make a future update
// handoff release its tunnel.
await NodeFSP.rm(stopMarkerPath(this.#baseDir), { force: true }).catch(() => undefined);
const update = this.#state.update;
if (update?.status !== "pending") {
if (update !== undefined) {
+6
View File
@@ -168,6 +168,11 @@ export interface GitFetchRemoteInput {
remoteName: string;
}
export interface GitRemoteExistsInput {
cwd: string;
remoteName: string;
}
export interface GitResolveRemoteTrackingCommitInput {
cwd: string;
refName: string;
@@ -243,6 +248,7 @@ export class GitVcsDriver extends Context.Service<
readonly ensureRemote: (input: GitEnsureRemoteInput) => Effect.Effect<string, GitCommandError>;
readonly resolvePrimaryRemoteName: (cwd: string) => Effect.Effect<string, GitCommandError>;
readonly fetchRemote: (input: GitFetchRemoteInput) => Effect.Effect<void, GitCommandError>;
readonly remoteExists: (input: GitRemoteExistsInput) => Effect.Effect<boolean, GitCommandError>;
readonly resolveRemoteTrackingCommit: (
input: GitResolveRemoteTrackingCommitInput,
) => Effect.Effect<GitResolveRemoteTrackingCommitResult, GitCommandError>;
Loaded 100 of 265 files, more files were not shown because too many files have changed in this diff. Show more