diff --git a/.github/scripts/thread-transfer-report.cjs b/.github/scripts/thread-transfer-report.cjs
index 09b25131e4c48..304b56d57e400 100644
--- a/.github/scripts/thread-transfer-report.cjs
+++ b/.github/scripts/thread-transfer-report.cjs
@@ -3,6 +3,7 @@ const path = require("node:path");
const ARTIFACT_NAME = "thread-transfer-results";
const RESULT_FILE = "thread-transfer-result.json";
+const SCENARIOS_FILE = "thread-transfer-scenarios.json";
const COMMENT_MARKER = "";
const PROVIDERS = ["codex", "claudeAgent"];
const OBSERVED_KEYS = [
@@ -29,6 +30,12 @@ const SCENARIO_KEYS = [
"measuredMcpResultBytes",
];
+const SCENARIO_ROW_KEYS = ["phase", "metric", "unit", "observed", "ceiling"];
+// These labels come from the PR and reach a comment the bot posts: no markup, links or mentions.
+// GitHub still links plain text such as `GH-26`, so they are rendered as code spans.
+const SCENARIO_LABEL = /^[A-Za-z0-9][A-Za-z0-9 ,-]{0,79}$/;
+const MAX_SCENARIO_ROWS = 100;
+
function resultShaMarker(sha) {
return ``;
}
@@ -85,15 +92,63 @@ function validateResult(value) {
return value;
}
-function readResult(directory) {
+function validateScenarios(value) {
+ assertExactKeys(value, ["schemaVersion", "providers"], "scenarios");
+ if (value.schemaVersion !== 1) {
+ throw new Error("scenarios.schemaVersion must be 1");
+ }
+ assertExactKeys(value.providers, PROVIDERS, "scenarios.providers");
+ for (const provider of PROVIDERS) {
+ const rows = value.providers[provider];
+ if (!Array.isArray(rows) || rows.length > MAX_SCENARIO_ROWS) {
+ throw new Error(
+ `scenarios.providers.${provider} must list at most ${MAX_SCENARIO_ROWS} rows`,
+ );
+ }
+ const seen = new Set();
+ for (const [index, row] of rows.entries()) {
+ const label = `scenarios.providers.${provider}[${index}]`;
+ assertExactKeys(row, SCENARIO_ROW_KEYS, label);
+ for (const key of ["phase", "metric"]) {
+ if (typeof row[key] !== "string" || !SCENARIO_LABEL.test(row[key])) {
+ throw new Error(`${label}.${key} must be a short plain label`);
+ }
+ }
+ if (row.unit !== "bytes" && row.unit !== "count") {
+ throw new Error(`${label}.unit must be bytes or count`);
+ }
+ assertMetric(row.observed, `${label}.observed`);
+ assertMetric(row.ceiling, `${label}.ceiling`);
+ const key = scenarioKey(row);
+ if (seen.has(key)) throw new Error(`${label} repeats an earlier row`);
+ seen.add(key);
+ }
+ }
+ return value;
+}
+
+function scenarioKey(row) {
+ return `${row.phase}|${row.metric}`;
+}
+
+function readArtifactFile(directory, name, validate) {
if (!directory) return undefined;
- const file = path.join(directory, RESULT_FILE);
+ const file = path.join(directory, name);
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");
+ throw new Error(`${name} must be a regular file smaller than 64 KiB`);
}
- return validateResult(JSON.parse(fs.readFileSync(file, "utf8")));
+ return validate(JSON.parse(fs.readFileSync(file, "utf8")));
+}
+
+function readResult(directory) {
+ return readArtifactFile(directory, RESULT_FILE, validateResult);
+}
+
+// Older runs upload only the result file, so a run without scenarios is still a valid run.
+function readScenarios(directory) {
+ return readArtifactFile(directory, SCENARIOS_FILE, validateScenarios);
}
function formatBytes(bytes) {
@@ -103,7 +158,7 @@ function formatBytes(bytes) {
}
function formatValue(value, kind) {
- return kind === "messages" ? value.toLocaleString("en-US") : formatBytes(value);
+ return kind === "bytes" ? formatBytes(value) : value.toLocaleString("en-US");
}
function formatImpact(current, baseline, kind) {
@@ -136,6 +191,77 @@ const METRICS = [
{ key: "measuredTurnWebSocketMessages", label: "Live turn messages", kind: "messages" },
];
+function providerLabel(provider) {
+ return provider === "codex" ? "Codex" : "Claude";
+}
+
+/**
+ * The scenario rows of a run against the same rows on `main`. Rows that fail or differ from
+ * `main` are listed in the open; the full table is collapsed below them.
+ */
+function renderScenarios(current, baseline, ceilingChanges) {
+ if (!current) return { lines: [], failed: false };
+ const header = [
+ "| Provider | Scenario | Metric | Main baseline | This PR | Impact | PR ceiling | |",
+ "| --- | --- | --- | ---: | ---: | ---: | ---: | --- |",
+ ];
+ const all = [];
+ const notable = [];
+ let failed = false;
+ let withoutBaseline = 0;
+
+ for (const provider of PROVIDERS) {
+ const baselineRows = new Map(
+ (baseline?.providers[provider] ?? []).map((row) => [scenarioKey(row), row]),
+ );
+ for (const row of current.providers[provider]) {
+ const before = baselineRows.get(scenarioKey(row));
+ const beforeObserved = before?.unit === row.unit ? before.observed : undefined;
+ const pass = row.observed <= row.ceiling;
+ failed ||= !pass;
+ if (beforeObserved === undefined) withoutBaseline += 1;
+ const line = `| ${providerLabel(provider)} | \`${row.phase}\` | \`${row.metric}\` | ${beforeObserved === undefined ? "—" : formatValue(beforeObserved, row.unit)} | ${formatValue(row.observed, row.unit)} | ${formatImpact(row.observed, beforeObserved, row.unit)} | ${formatValue(row.ceiling, row.unit)} | ${pass ? "✅" : "❌"} |`;
+ all.push(line);
+ if (!pass || (beforeObserved !== undefined && beforeObserved !== row.observed)) {
+ notable.push(line);
+ }
+ if (beforeObserved !== undefined && before.ceiling !== row.ceiling) {
+ ceilingChanges.push(
+ `- ${providerLabel(provider)} \`${row.phase}\` \`${row.metric}\`: ${formatValue(before.ceiling, row.unit)} → ${formatValue(row.ceiling, row.unit)}`,
+ );
+ }
+ }
+ }
+
+ const compared = all.length - withoutBaseline;
+ const summary = !baseline
+ ? `No \`main\` baseline exists yet for these ${all.length} scenario measurements.`
+ : [
+ notable.length > 0
+ ? `${notable.length} of ${all.length} scenario measurements changed or failed.`
+ : `${compared === all.length ? "All " : ""}${compared} scenario measurements match \`main\`.`,
+ ...(withoutBaseline > 0 ? [`${withoutBaseline} have no \`main\` baseline.`] : []),
+ ].join(" ");
+ return {
+ failed,
+ lines: [
+ "### Other scenarios",
+ "",
+ summary,
+ ...(notable.length > 0 ? ["", ...header, ...notable] : []),
+ "",
+ "",
+ `All ${all.length} scenario measurements
`,
+ "",
+ ...header,
+ ...all,
+ "",
+ " ",
+ "",
+ ],
+ };
+}
+
function renderComment(input) {
const current = input.current;
const baseline = input.baseline;
@@ -154,16 +280,22 @@ function renderComment(input) {
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 ? "✅" : "❌"} |`,
+ `| ${providerLabel(provider)} | ${metric.label} | ${baselineObserved === undefined ? "—" : formatValue(baselineObserved, metric.kind)} | ${formatValue(observed, metric.kind)} | ${formatImpact(observed, baselineObserved, metric.kind)} | ${formatValue(ceiling, metric.kind)} | ${pass ? "✅" : "❌"} |`,
);
if (comparable && 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)}`,
+ `- ${providerLabel(provider)} ${metric.label}: ${formatValue(baseline.providers[provider].ceiling[metric.key], metric.kind)} → ${formatValue(ceiling, metric.kind)}`,
);
}
}
}
+ const scenarios = renderScenarios(
+ input.currentScenarios,
+ input.baselineScenarios,
+ ceilingChanges,
+ );
+ failed ||= scenarios.failed;
const baselineLink = input.baselineRun
? `[\`${input.baselineRun.sha.slice(0, 7)}\`](${input.baselineRun.url})`
@@ -203,6 +335,7 @@ function renderComment(input) {
"| --- | --- | ---: | ---: | ---: | ---: | --- |",
...rows,
"",
+ ...scenarios.lines,
`Baseline: ${baselineLink} · PR result: ${currentLink} · Source CI: ${input.currentRun.conclusion}`,
"",
"",
@@ -212,7 +345,7 @@ function renderComment(input) {
"",
...PROVIDERS.map(
(provider) =>
- `- ${provider === "codex" ? "Codex" : "Claude"} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
+ `- ${providerLabel(provider)} decoded thread snapshot: ${formatBytes(current.providers[provider].observed.threadSnapshotDecodedBytes)}`,
),
"",
" ",
@@ -437,7 +570,14 @@ async function publish({ github, context, core }) {
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 body = renderComment({
+ current,
+ baseline,
+ currentScenarios: readScenarios(process.env.PR_RESULT_DIR),
+ baselineScenarios: readScenarios(process.env.BASELINE_RESULT_DIR),
+ currentRun,
+ baselineRun,
+ });
const published = await upsertCommentForCurrentHead(
github,
context,
@@ -458,4 +598,5 @@ module.exports = {
resolve,
upsertCommentForCurrentHead,
validateResult,
+ validateScenarios,
};
diff --git a/.github/scripts/thread-transfer-report.test.cjs b/.github/scripts/thread-transfer-report.test.cjs
index 8c4595ccf0c6a..3a953a8bfc16b 100644
--- a/.github/scripts/thread-transfer-report.test.cjs
+++ b/.github/scripts/thread-transfer-report.test.cjs
@@ -2,9 +2,11 @@ const assert = require("node:assert/strict");
const test = require("node:test");
const {
+ renderComment,
resolve,
upsertCommentForCurrentHead,
validateResult,
+ validateScenarios,
} = require("./thread-transfer-report.cjs");
function result(overrides = {}) {
@@ -40,6 +42,29 @@ function result(overrides = {}) {
};
}
+function scenarios(overrides = {}) {
+ const rows = [
+ {
+ phase: "long turn finished, cold open",
+ metric: "HTTP decoded",
+ unit: "bytes",
+ observed: 390_000,
+ ceiling: 420_000,
+ },
+ {
+ phase: "idle thread resume",
+ metric: "WebSocket messages",
+ unit: "count",
+ observed: 1,
+ ceiling: 1,
+ },
+ ];
+ return {
+ schemaVersion: 1,
+ providers: { codex: [{ ...rows[0], ...overrides }, rows[1]], claudeAgent: rows },
+ };
+}
+
test("validates the fixed artifact schema", () => {
assert.equal(validateResult(result()).schemaVersion, 1);
assert.throws(
@@ -50,6 +75,60 @@ test("validates the fixed artifact schema", () => {
() => validateResult(result({ totalWireBytes: "lots" })),
/non-negative safe integer/,
);
+
+ assert.equal(validateScenarios(scenarios()).schemaVersion, 1);
+ for (const phase of ["@everyone", "[link](https://example.com)", "a | b", "
", ""]) {
+ assert.throws(() => validateScenarios(scenarios({ phase })), /short plain label/);
+ }
+ assert.throws(() => validateScenarios(scenarios({ note: "extra" })), /unexpected fields/);
+ assert.throws(() => validateScenarios(scenarios({ ceiling: null })), /non-negative safe integer/);
+ assert.throws(
+ () =>
+ validateScenarios(scenarios({ phase: "idle thread resume", metric: "WebSocket messages" })),
+ /repeats an earlier row/,
+ );
+});
+
+test("lists scenario rows that changed or failed above the collapsed table", () => {
+ const run = { sha: "abcdef1234", url: "https://example.com/run", conclusion: "success" };
+ const render = (currentScenarios, baselineScenarios) =>
+ renderComment({
+ current: result(),
+ baseline: result(),
+ currentScenarios,
+ baselineScenarios,
+ currentRun: run,
+ baselineRun: { ...run, matchesBase: true },
+ });
+ const open = (body) => body.slice(0, body.indexOf(""));
+
+ const unchanged = render(scenarios(), scenarios());
+ assert.match(unchanged, /✅ Thread transfer remains within every enforced ceiling/);
+ assert.match(open(unchanged), /All 4 scenario measurements match `main`/);
+ assert.doesNotMatch(open(unchanged), /long turn finished, cold open/);
+
+ const grown = render(scenarios({ observed: 400_000 }), scenarios());
+ assert.match(open(grown), /1 of 4 scenario measurements changed or failed/);
+ assert.match(
+ open(grown),
+ /\| Codex \| `long turn finished, cold open` \| `HTTP decoded` \| 380\.9 KiB \| 390\.6 KiB \| \+9\.8 KiB \(\+2\.6%\) \| 410\.2 KiB \| ✅ \|/,
+ );
+
+ const over = render(scenarios({ observed: 430_000, ceiling: 425_000 }), scenarios());
+ assert.match(over, /❌ One or more thread transfer ceilings were exceeded/);
+ assert.match(
+ over,
+ /Codex `long turn finished, cold open` `HTTP decoded`: 410\.2 KiB → 415\.0 KiB/,
+ );
+
+ // A row `main` does not have is not reported as matching it.
+ const added = render(scenarios({ phase: "GH-26" }), scenarios());
+ assert.match(open(added), /3 scenario measurements match `main`\. 1 have no `main` baseline\./);
+ assert.match(added, /\| Codex \| `GH-26` \|/);
+
+ // A main run from before the scenario file has nothing to compare; a PR run from before it has no section.
+ assert.match(open(render(scenarios(), undefined)), /No `main` baseline exists yet/);
+ assert.doesNotMatch(render(undefined, scenarios()), /Other scenarios/);
});
test("resolves a fallback PR with a redacted head repo and exact main baseline", async () => {
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 653a81c84a210..2854a53a7b124 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -503,6 +503,7 @@ jobs:
env:
T3CODE_TRANSFER_BUDGET_REPORT_PATH: ${{ runner.temp }}/t3code-transfer-budget.md
T3CODE_TRANSFER_BUDGET_RESULT_PATH: ${{ runner.temp }}/thread-transfer-result.json
+ T3CODE_TRANSFER_BUDGET_SCENARIOS_PATH: ${{ runner.temp }}/thread-transfer-scenarios.json
run: >-
vp run test:cached -- --shard ${{ matrix.shard }}/${{ strategy.job-total }}
--uncached apps/server/integration/transferBudgetV2.integration.test.ts
@@ -543,7 +544,9 @@ jobs:
uses: actions/upload-artifact@v7
with:
name: thread-transfer-results
- path: ${{ runner.temp }}/thread-transfer-result.json
+ path: |
+ ${{ runner.temp }}/thread-transfer-result.json
+ ${{ runner.temp }}/thread-transfer-scenarios.json
if-no-files-found: ignore
retention-days: 30
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 8827876b3829f..ec5ec6b15a6ba 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -48,9 +48,11 @@ jobs:
# triggering commit. Manual stable releases build the commit of the latest
# published nightly, so stable only ever ships a build that nightly users
# have already run. Scheduled runs also decide here whether a nightly is due.
+ # The PAUSE_NIGHTLY repository variable skips scheduled runs only; every later
+ # job needs this one, so a skip here skips the whole run.
resolve_commit:
name: Resolve release commit
- if: github.repository == 'pingdotgg/t3code'
+ if: github.repository == 'pingdotgg/t3code' && (github.event_name != 'schedule' || vars.PAUSE_NIGHTLY != 'true')
runs-on: blacksmith-8vcpu-ubuntu-2404
timeout-minutes: 5
outputs:
diff --git a/apps/desktop/src/app/DesktopObservability.test.ts b/apps/desktop/src/app/DesktopObservability.test.ts
index ab8ea0b8e9d6e..ceb29b149e3d6 100644
--- a/apps/desktop/src/app/DesktopObservability.test.ts
+++ b/apps/desktop/src/app/DesktopObservability.test.ts
@@ -281,6 +281,27 @@ describe("DesktopObservability", () => {
),
);
+ it.effect("startup prunes only canonical rotation suffixes", () =>
+ Effect.gen(function* () {
+ const fileSystem = yield* FileSystem.FileSystem;
+ const directory = yield* fileSystem.makeTempDirectoryScoped({
+ prefix: "t3-desktop-rotating-prune-test-",
+ });
+ const filePath = `${directory}/server-child.log`;
+ const retained = ["1", "3", "04", "4.0", "4e0", "0x4", "+4", "notes"];
+ for (const suffix of [...retained, "4", "50"]) {
+ yield* fileSystem.writeFileString(`${filePath}.${suffix}`, suffix);
+ }
+
+ yield* DesktopObservability.makeRotatingLogFileWriter({ filePath, maxFiles: 3 });
+
+ assert.deepEqual(
+ (yield* fileSystem.readDirectory(directory)).sort(),
+ retained.map((suffix) => `server-child.log.${suffix}`).sort(),
+ );
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+ );
+
it.effect("stops every export when the OpenTelemetry SDK is disabled", () => {
const requests: Array = [];
return Effect.gen(function* () {
diff --git a/apps/desktop/src/app/DesktopObservability.ts b/apps/desktop/src/app/DesktopObservability.ts
index e9b0ab9379dfe..16192fff46de8 100644
--- a/apps/desktop/src/app/DesktopObservability.ts
+++ b/apps/desktop/src/app/DesktopObservability.ts
@@ -263,8 +263,10 @@ export const makeRotatingLogFileWriter = Effect.fn("makeRotatingLogFileWriter")(
const entries = yield* fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed(() => []));
for (const entry of entries) {
if (!entry.startsWith(`${baseName}.`)) continue;
- const suffix = Number(entry.slice(baseName.length + 1));
- if (!Number.isInteger(suffix) || suffix <= maxFiles) continue;
+ const suffixText = entry.slice(baseName.length + 1);
+ const suffix = Number(suffixText);
+ if (!Number.isInteger(suffix) || String(suffix) !== suffixText || suffix <= maxFiles)
+ continue;
yield* fileSystem.remove(path.join(directory, entry), { force: true }).pipe(Effect.ignore);
}
});
diff --git a/apps/desktop/src/preview/PickPreload.test.ts b/apps/desktop/src/preview/PickPreload.test.ts
index 8a080183b3830..34beb7f4c8011 100644
--- a/apps/desktop/src/preview/PickPreload.test.ts
+++ b/apps/desktop/src/preview/PickPreload.test.ts
@@ -62,3 +62,25 @@ it("keeps the tool while typing a tool key in the comment", () => {
expect(document.documentElement.getAttribute("data-t3code-annotation-tool")).toBe("select");
});
+
+it("keeps comment keystrokes away from the page's capture-phase shortcuts", () => {
+ const pageShortcut = vi.fn((event: KeyboardEvent) => event.preventDefault());
+ window.addEventListener("keydown", pageShortcut, { capture: true });
+ const shadowRoot = startAnnotation();
+ const comment = shadowRoot.querySelector("textarea");
+ if (!comment) throw new Error("comment textarea not found");
+
+ comment.focus();
+ const space = new KeyboardEvent("keydown", {
+ key: " ",
+ code: "Space",
+ bubbles: true,
+ cancelable: true,
+ composed: true,
+ });
+ comment.dispatchEvent(space);
+ window.removeEventListener("keydown", pageShortcut, { capture: true });
+
+ expect(pageShortcut).not.toHaveBeenCalled();
+ expect(space.defaultPrevented).toBe(false);
+});
diff --git a/apps/desktop/src/preview/PickPreload.ts b/apps/desktop/src/preview/PickPreload.ts
index a9f479d32b81a..0784b21a5308b 100644
--- a/apps/desktop/src/preview/PickPreload.ts
+++ b/apps/desktop/src/preview/PickPreload.ts
@@ -149,6 +149,7 @@ interface AnnotationSession {
teardown: (notifyMain: boolean) => void;
applyTheme: (theme: DesktopPreviewAnnotationTheme) => void;
setSendEnabled: (enabled: boolean) => void;
+ handleOverlayKey: (event: KeyboardEvent) => void;
}
let activeSession: AnnotationSession | null = null;
@@ -225,6 +226,18 @@ const reportUnhandledShortcut = (event: KeyboardEvent): void => {
window.addEventListener("keydown", reportUnhandledShortcut, true);
+// Registered before page scripts so their capture listeners never see keys typed into the
+// overlay; the closed shadow root retargets those to the host, hiding that they edit text.
+const isolateOverlayKey = (event: KeyboardEvent): void => {
+ if (!activeSession || !(event.target instanceof Element) || !isAnnotationNode(event.target))
+ return;
+ activeSession.handleOverlayKey(event);
+ event.stopImmediatePropagation();
+};
+
+for (const type of ["keydown", "keypress", "keyup"] as const)
+ window.addEventListener(type, isolateOverlayKey, true);
+
const MOUSE_BUTTON_BACK = 3;
const MOUSE_BUTTON_FORWARD = 4;
@@ -1762,15 +1775,17 @@ function startAnnotation(
});
};
submit.addEventListener("click", () => submitAnnotation("attach"));
- root.addEventListener("keydown", (event) => {
+ const handleOverlayKey = (event: KeyboardEvent): void => {
+ if (event.type === "keyup") onVoiceKeyUp(event);
+ if (event.type !== "keydown") return;
+ onKeyDown(event);
+ if (event.cancelBubble) return;
const submission =
- event.target === comment ? resolveAnnotationSubmission(event, sendEnabled) : null;
- // Bubble phase lets editor inputs handle events before hiding them from the page.
- event.stopImmediatePropagation();
+ shadowRoot.activeElement === comment ? resolveAnnotationSubmission(event, sendEnabled) : null;
if (!submission) return;
event.preventDefault();
submitAnnotation(submission);
- });
+ };
window.addEventListener("pointermove", onPointerMove, { capture: true, passive: false });
window.addEventListener("pointerdown", onPointerDown, { capture: true, passive: false });
@@ -1806,6 +1821,7 @@ function startAnnotation(
sendEnabled = enabled;
updateSendHint();
},
+ handleOverlayKey,
};
}
diff --git a/apps/desktop/src/updates/releaseNotes.test.ts b/apps/desktop/src/updates/releaseNotes.test.ts
index 6f05b1e9e94ab..a8fcc70ea355c 100644
--- a/apps/desktop/src/updates/releaseNotes.test.ts
+++ b/apps/desktop/src/updates/releaseNotes.test.ts
@@ -241,14 +241,20 @@ describe("normalizeDesktopUpdateReleaseNotes", () => {
});
});
- it("does not throw on out-of-range numeric entities and keeps the literal", () => {
+ it("keeps unsupported entities literal, including out-of-range and Object.prototype names", () => {
const result = normalizeDesktopUpdateReleaseNotes(
- "- Broken entity ",
+ "- Broken entity \n- Mentions &constructor; and &toString;",
"1.0.0",
"latest",
);
expect(result).toEqual({
- releaseNotes: [{ version: "1.0.0", items: ["Broken entity "], totalItems: 1 }],
+ releaseNotes: [
+ {
+ version: "1.0.0",
+ items: ["Mentions &constructor; and &toString;", "Broken entity "],
+ totalItems: 2,
+ },
+ ],
omittedReleaseCount: 0,
});
});
diff --git a/apps/desktop/src/updates/releaseNotes.ts b/apps/desktop/src/updates/releaseNotes.ts
index 715c1767e6a04..30bfb9ace64b8 100644
--- a/apps/desktop/src/updates/releaseNotes.ts
+++ b/apps/desktop/src/updates/releaseNotes.ts
@@ -20,14 +20,14 @@ const MAX_RELEASE_NOTE_GROUPS = 6;
const MAX_RELEASE_NOTE_ITEMS_PER_GROUP = 8;
const MAX_RELEASE_NOTE_ITEM_LENGTH = 220;
-const HTML_ENTITY_REPLACEMENTS: Readonly> = {
- amp: "&",
- apos: "'",
- gt: ">",
- lt: "<",
- nbsp: " ",
- quot: '"',
-};
+const HTML_ENTITY_REPLACEMENTS: ReadonlyMap = new Map([
+ ["amp", "&"],
+ ["apos", "'"],
+ ["gt", ">"],
+ ["lt", "<"],
+ ["nbsp", " "],
+ ["quot", '"'],
+]);
function decodeCodePoint(codePoint: number, entity: string): string {
if (!Number.isInteger(codePoint) || codePoint < 0 || codePoint > 0x10ffff) {
@@ -37,7 +37,7 @@ function decodeCodePoint(codePoint: number, entity: string): string {
}
function decodeHtmlEntity(entity: string): string {
- const named = HTML_ENTITY_REPLACEMENTS[entity];
+ const named = HTML_ENTITY_REPLACEMENTS.get(entity);
if (named) return named;
if (entity.startsWith("#x")) {
return decodeCodePoint(Number.parseInt(entity.slice(2), 16), entity);
diff --git a/apps/mobile/src/App.tsx b/apps/mobile/src/App.tsx
index 6287a05956519..d2577b07c004f 100644
--- a/apps/mobile/src/App.tsx
+++ b/apps/mobile/src/App.tsx
@@ -4,7 +4,7 @@ import { installThreadOutboxDelivery } from "./state/threadOutboxDelivery";
import * as Linking from "expo-linking";
import * as SplashScreen from "expo-splash-screen";
import { requireNativeModule } from "expo";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
import { Platform, StatusBar } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";
import { KeyboardProvider } from "react-native-keyboard-controller";
@@ -21,7 +21,7 @@ import {
import { pipe } from "effect/Function";
import { DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
-import { RegistryContext } from "@effect/atom-react";
+import { RegistryContext, useAtomValue } from "@effect/atom-react";
import { ProjectChipIconRasterizer } from "./native/ProjectChipIconImages";
import { ThreadArrangementHost } from "./features/threads/ThreadArrangementSheet";
import * as Dialog from "./components/ui/Dialog";
@@ -50,7 +50,7 @@ import { RootStack, rootPathnameFromState, workspaceLocationFromState } from "./
import { appAtomRegistry } from "./state/atom-registry";
import { subscribeComposerDraftModelReconciliation } from "./state/use-composer-drafts";
import { environmentThreadShells, threadEnvironment } from "./state/threads";
-import { environmentShell } from "./state/shell";
+import { environmentShell, shellCachesReadAtom } from "./state/shell";
import { OverlayPortalHost } from "./components/ui/OverlayPortal";
import { shouldHandleAppLink, restoreDraftLinkState } from "./lib/appLinking";
import { hasCloudPublicConfig } from "./features/cloud/publicConfig";
@@ -204,13 +204,28 @@ disposeOnFoundationReplace(typeof module === "undefined" ? undefined : module.ho
for (const dispose of appServiceDisposers) dispose();
});
+// Cached shells are local reads that end in a fraction of this time; the limit only keeps a
+// failed read from holding the splash screen.
+const SPLASH_SHELL_CACHE_WAIT_MS = 1_500;
+
function SplashScreenCoordinator() {
const { isReady } = useAppearancePreferences();
+ const shellCachesRead = useAtomValue(shellCachesReadAtom);
+ const [waitEnded, setWaitEnded] = useState(false);
+
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts the limit on how long the native splash screen waits for cached shells
+ useEffect(() => {
+ const timer = setTimeout(() => setWaitEnded(true), SPLASH_SHELL_CACHE_WAIT_MS);
+ return () => clearTimeout(timer);
+ }, []);
- // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once appearance preferences have loaded
+ // The thread list paints every environment's cached rows at once when the splash hides
+ // after they are read.
+ const canHide = isReady && (shellCachesRead || waitEnded);
+ // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- hides the native splash screen once preferences and cached shells have loaded
useEffect(() => {
- if (isReady) void SplashScreen.hide();
- }, [isReady]);
+ if (canHide) void SplashScreen.hide();
+ }, [canHide]);
return null;
}
diff --git a/apps/mobile/src/Stack.tsx b/apps/mobile/src/Stack.tsx
index d93bf076a78e0..b2ad65cf05374 100644
--- a/apps/mobile/src/Stack.tsx
+++ b/apps/mobile/src/Stack.tsx
@@ -493,11 +493,11 @@ const RootStackConfig = createWorkspaceStackNavigator({
Home: createNativeStackScreen({
screen: WorkspaceRootScreen,
linking: "",
- listeners: {
+ listeners: ({ navigation }) => ({
transitionStart: ({ data }) => recordHomeTransitionStart(data.closing),
- transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing),
+ transitionEnd: ({ data }) => recordHomeTransitionEnd(data.closing, navigation.isFocused()),
focus: recordHomeFocus,
- },
+ }),
options: {
...pageRoute({ duoMinimize: "never", root: true }),
contentStyle: { backgroundColor: "transparent" },
diff --git a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
index d83852f260466..b312eeb645346 100644
--- a/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
+++ b/apps/mobile/src/features/browser/BrowserPreviewRouteScreen.tsx
@@ -35,16 +35,33 @@ type BrowserPreviewRouteScreenProps = StaticScreenProps<{
export function BrowserPreviewRouteScreen({ route }: BrowserPreviewRouteScreenProps) {
const navigation = useNavigation();
const onClose = () => navigation.goBack();
+ const { environmentId, threadId } = route.params;
+ if (!environmentId?.trim() || !threadId?.trim()) {
+ return ;
+ }
return (
);
}
+function BrowserUnavailableScreen({ onClose }: { readonly onClose: () => void }) {
+ const insets = useSafeAreaInsets();
+ const contentTopInset = useContentTopInset();
+ return (
+
+
+
+ );
+}
+
function BrowserPreviewScreen({
environmentId,
threadId,
diff --git a/apps/mobile/src/features/home/HomeRouteScreen.tsx b/apps/mobile/src/features/home/HomeRouteScreen.tsx
index a2db3d14d45fd..78b4eca22a47d 100644
--- a/apps/mobile/src/features/home/HomeRouteScreen.tsx
+++ b/apps/mobile/src/features/home/HomeRouteScreen.tsx
@@ -15,7 +15,7 @@ import {
} from "@t3tools/client-runtime/state/project-grouping";
import { useProjects } from "../../state/entities";
-import { environmentThreadShells } from "../../state/threads";
+import { steadyNavigationThreadShellsAtom } from "../../state/threads";
import { useLaunchingThreads, usePendingNewTasks } from "../../state/use-pending-new-tasks";
import { useWorkspaceState } from "../../state/workspace";
import { useSavedRemoteConnections } from "../../state/use-remote-environment-registry";
@@ -47,7 +47,7 @@ export function HomeRouteScreen() {
// Stop rebuilding the streaming thread list while Thread covers Home.
const visible = useHomeRouteVisible();
const threads = useLaunchingThreads(
- useAtomValueWhileVisible(environmentThreadShells.navigationThreadShellsAtom, visible),
+ useAtomValueWhileVisible(steadyNavigationThreadShellsAtom, visible),
);
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
diff --git a/apps/mobile/src/features/home/home-route-visibility.test.tsx b/apps/mobile/src/features/home/home-route-visibility.test.tsx
index b720bbae033ac..dae399420944a 100644
--- a/apps/mobile/src/features/home/home-route-visibility.test.tsx
+++ b/apps/mobile/src/features/home/home-route-visibility.test.tsx
@@ -4,7 +4,10 @@ import { act, useLayoutEffect } from "react";
import { createRoot } from "react-dom/client";
import { expect, it, vi } from "vite-plus/test";
-import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
+import {
+ NativePrimaryColumnContext,
+ NativeWorkspaceTabActivityContext,
+} from "../../native/v5-workspace-context";
// The Thread in the detail column is the focused route on iPad split view.
vi.mock("@react-navigation/native", () => ({
@@ -12,6 +15,7 @@ vi.mock("@react-navigation/native", () => ({
}));
import {
+ recordHomeFocus,
recordHomeTransitionEnd,
recordHomeTransitionStart,
useAtomValueWhileVisible,
@@ -54,6 +58,18 @@ function setup() {
),
);
},
+ /** A phone has no primary column: Home is the root page of its tab's slot. */
+ showHomeInTabSlot(active: boolean) {
+ act(() =>
+ root.render(
+
+ active }}>
+
+
+ ,
+ ),
+ );
+ },
[Symbol.dispose]() {
act(() => root.unmount());
registry.dispose();
@@ -71,11 +87,51 @@ it("keeps the sidebar thread list live after switching tabs beside a focused Thr
// Chats → PRs → Chats: Chats' column will-appear, then the PRs column's did-disappear.
act(() => {
- recordHomeTransitionEnd(true);
+ recordHomeTransitionEnd(true, false);
recordHomeTransitionStart(false);
- recordHomeTransitionEnd(true);
+ recordHomeTransitionEnd(true, false);
});
act(() => home.registry.set(shellsAtom, 2));
expect(home.latest, "new thread shells reach the sidebar list").toBe(2);
});
+
+// Each phone tab slot shows its own copy of the Home route. PRs keeps Home focused; Settings
+// is a route of its own.
+it.each([
+ { tab: "PRs", homeFocusedUnderTab: true },
+ { tab: "Settings", homeFocusedUnderTab: false },
+])(
+ "keeps the phone thread list live after a round trip through $tab",
+ ({ homeFocusedUnderTab }) => {
+ using home = setup();
+ recordHomeFocus();
+ home.showHomeInTabSlot(true);
+ act(() => home.registry.set(shellsAtom, 1));
+ expect(home.latest).toBe(1);
+
+ // To the other tab: its slot will-appear, then the Chats slot's did-disappear.
+ act(() => {
+ recordHomeTransitionStart(false);
+ recordHomeTransitionEnd(true, homeFocusedUnderTab);
+ });
+ home.showHomeInTabSlot(false);
+ act(() => home.registry.set(shellsAtom, 2));
+ expect(home.latest, "the list under another tab holds its rows").toBe(1);
+
+ // Back to Chats: its slot will-appear, then the other slot's did-disappear comes last.
+ act(() => {
+ recordHomeFocus();
+ recordHomeTransitionStart(false);
+ recordHomeTransitionEnd(true, true);
+ });
+ home.showHomeInTabSlot(true);
+ act(() => home.registry.set(shellsAtom, 3));
+ expect(home.latest, "a server rename reaches the list").toBe(3);
+
+ // A pushed Thread takes the focus and still stops the list.
+ act(() => recordHomeTransitionEnd(true, false));
+ act(() => home.registry.set(shellsAtom, 4));
+ expect(home.latest, "the list under a Thread holds its rows").toBe(3);
+ },
+);
diff --git a/apps/mobile/src/features/home/home-route-visibility.ts b/apps/mobile/src/features/home/home-route-visibility.ts
index 532053f8f8d07..7a8837b582a11 100644
--- a/apps/mobile/src/features/home/home-route-visibility.ts
+++ b/apps/mobile/src/features/home/home-route-visibility.ts
@@ -3,7 +3,10 @@ import { useNavigation } from "@react-navigation/native";
import { useContext, useRef, useSyncExternalStore } from "react";
import type { Atom } from "effect/reactivity";
-import { NativePrimaryColumnContext } from "../../native/v5-workspace-context";
+import {
+ NativePrimaryColumnContext,
+ NativeWorkspaceTabActivityContext,
+} from "../../native/v5-workspace-context";
/**
* Home stays mounted under a pushed Thread, and native-stack never freezes the
@@ -34,8 +37,12 @@ export function recordHomeTransitionStart(closing: boolean): void {
if (!closing) setHomeVisible(true);
}
-export function recordHomeTransitionEnd(closing: boolean): void {
- if (closing) setHomeVisible(false);
+/**
+ * Each iOS tab slot shows its own copy of the Home route, and the slot a tab switch leaves
+ * disappears last. So a disappear hides Home only when another route has the focus.
+ */
+export function recordHomeTransitionEnd(closing: boolean, homeFocused: boolean): void {
+ if (closing && !homeFocused) setHomeVisible(false);
}
/** Popping a sheet or a deep-linked route above Home has no appear event. */
@@ -46,10 +53,13 @@ export function recordHomeFocus(): void {
export function useHomeRouteVisible(): boolean {
const navigation = useNavigation();
const primaryColumn = useContext(NativePrimaryColumnContext);
+ const tabActive = useContext(NativeWorkspaceTabActivityContext)?.active ?? true;
const visible = useSyncExternalStore(subscribeHomeVisibility, () => homeVisible);
// Every tab slot's primary column reports to the one Home route, so a tab
// switch can end on the leaving slot's disappear. Trust this column instead.
if (primaryColumn) return primaryColumn.presented;
+ // The store is true for the Home route of every tab; this list shows in one of them.
+ if (!tabActive) return false;
// Before Home's first navigation event: a cold deep link mounts Home under
// its Thread without ever showing it.
return visible ?? navigation.isFocused();
diff --git a/apps/mobile/src/features/home/useThreadListActions.test.ts b/apps/mobile/src/features/home/useThreadListActions.test.ts
index 18cd5363d3c0a..b0f0ce78d0a89 100644
--- a/apps/mobile/src/features/home/useThreadListActions.test.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.test.ts
@@ -16,6 +16,7 @@ const state = vi.hoisted(() => ({
connectedEnvironmentIds: [] as EnvironmentId[],
pendingOrder: null as object | null,
dropBusy: false,
+ holdingRows: false,
failedAction: null as string | null,
archivedRefreshes: [] as string[],
scopes: new Map>(),
@@ -78,26 +79,28 @@ vi.mock("../../state/atom-registry", () => ({
? state.connectedEnvironmentIds
: atom === "thread-drop-busy"
? state.dropBusy
- : atom === "thread-shells"
- ? state.shells
- : atom === "queued-thread-keys"
- ? new Set()
- : new Map(
- [...state.scopes.keys()].map((environmentId) => [
- environmentId,
- {
- environment: {
- capabilities: {
- threadSettlement: true,
- threadSnooze: true,
- threadPinning: true,
- threadPinReorder: true,
- threadTitleRegeneration: true,
+ : atom === "steady-shells-holding"
+ ? state.holdingRows
+ : atom === "thread-shells"
+ ? state.shells
+ : atom === "queued-thread-keys"
+ ? new Set()
+ : new Map(
+ [...state.scopes.keys()].map((environmentId) => [
+ environmentId,
+ {
+ environment: {
+ capabilities: {
+ threadSettlement: true,
+ threadSnooze: true,
+ threadPinning: true,
+ threadPinReorder: true,
+ threadTitleRegeneration: true,
+ },
},
},
- },
- ]),
- ),
+ ]),
+ ),
},
}));
vi.mock("../../state/use-atom-command", () => ({
@@ -121,10 +124,9 @@ vi.mock("../../state/thread-order", () => ({
},
}));
vi.mock("../../state/threads", () => ({
- environmentThreadShells: {
- threadShellsAtom: "thread-shells",
- navigationThreadShellsAtom: "thread-shells",
- },
+ environmentThreadShells: { threadShellsAtom: "thread-shells" },
+ steadyNavigationThreadShellsAtom: "thread-shells",
+ steadyShellsHoldingAtom: "steady-shells-holding",
threadEnvironment: Object.fromEntries(
[
"archive",
@@ -193,6 +195,7 @@ beforeEach(() => {
state.archivedRefreshes = [];
state.pendingOrder = null;
state.dropBusy = false;
+ state.holdingRows = false;
state.scopes = new Map([
[primaryEnvironmentId, new Set([AuthOrchestrationOperateScope])],
[otherEnvironmentId, new Set()],
@@ -274,6 +277,12 @@ describe("pinned thread operation permissions", () => {
}),
];
+ // Rows that wait to show can hold order keys the server has replaced.
+ state.holdingRows = true;
+ expect(await useThreadListActions().moveThread(moved, "up")).toBe(false);
+ expect(state.requests).toEqual([]);
+ state.holdingRows = false;
+
expect(await useThreadListActions().moveThread(moved, "up")).toBe(true);
expect(state.requests).toEqual([
expect.objectContaining({ action: "reorderPin", environmentId: primaryEnvironmentId }),
@@ -494,6 +503,25 @@ describe("thread action undo", () => {
},
);
+ it.each(["settleThread", "unpinThread"] as const)(
+ "%s plans its undo from the live row when the list holds an older one",
+ async (handler) => {
+ const held = makeThread({ pinnedAt: "2026-09-02T00:00:00.000Z", pinOrderKey: "m" });
+ const live = makeThread({
+ pinnedAt: "2026-09-02T00:00:00.000Z",
+ pinOrderKey: "t",
+ snoozedUntil: "2099-01-01T09:00:00.000Z",
+ });
+ state.shells = [live];
+ await useThreadListActions()[handler](held);
+ await readThreadUndoNotice()!.undo();
+ expect(state.requests.slice(-2)).toMatchObject([
+ { action: "pin", input: { threadId: live.id, orderKey: "t" } },
+ { action: "snooze", input: { threadId: live.id, snoozedUntil: live.snoozedUntil } },
+ ]);
+ },
+ );
+
// regression: #21401 restore archive and thread action undo
it("does not restore snooze if undoing an unpin fails", async () => {
const thread = makeThread({
@@ -570,5 +598,10 @@ describe("thread archive guard", () => {
expect(state.requests).toEqual([]);
expect(state.archivedRefreshes).toEqual([]);
expect(state.alerts.at(-1)?.title).toBe("Could not archive thread");
+
+ // A list can hold a row from before the run started.
+ state.shells = [thread];
+ expect(await useThreadListActions().archiveThread(makeThread())).toBe(false);
+ expect(state.requests).toEqual([]);
});
});
diff --git a/apps/mobile/src/features/home/useThreadListActions.ts b/apps/mobile/src/features/home/useThreadListActions.ts
index 9d44d971c1f03..aaba12dd8f419 100644
--- a/apps/mobile/src/features/home/useThreadListActions.ts
+++ b/apps/mobile/src/features/home/useThreadListActions.ts
@@ -17,7 +17,12 @@ import { appAtomRegistry } from "../../state/atom-registry";
import { environmentServerConfigsAtom } from "../../state/server";
import { connectedEnvironmentIdsAtom } from "../../state/presentation";
import { readEnvironmentScope } from "../../state/session";
-import { environmentThreadShells, threadEnvironment } from "../../state/threads";
+import {
+ environmentThreadShells,
+ steadyNavigationThreadShellsAtom,
+ steadyShellsHoldingAtom,
+ threadEnvironment,
+} from "../../state/threads";
import { queuedThreadKeysAtom } from "../../state/use-thread-outbox";
import { useAtomCommand } from "../../state/use-atom-command";
import {
@@ -83,6 +88,19 @@ function checkThreadOperationPermission(thread: EnvironmentThreadShell, title: s
return false;
}
+/**
+ * The live row of a thread that a list passes to an action. A list holds its rows while an
+ * environment synchronizes (`steadyNavigationThreadShellsAtom`), so its row can be older than
+ * the client's data: an undo plan or a guard read from it would use replaced state.
+ */
+function liveThread(thread: EnvironmentThreadShell): EnvironmentThreadShell {
+ return (
+ appAtomRegistry
+ .get(environmentThreadShells.threadShellsAtom)
+ .find((row) => row.id === thread.id && row.environmentId === thread.environmentId) ?? thread
+ );
+}
+
function useThreadActionExecutor(
onCompleted?: (action: ThreadListAction, thread: EnvironmentThreadShell) => void,
) {
@@ -572,7 +590,10 @@ export function useThreadListActions(): {
const moveThread = async (thread: EnvironmentThreadShell, direction: ThreadMoveDestination) => {
if (!checkThreadOperationPermission(thread, "Could not move thread")) return false;
if (getPendingThreadOrder() !== null || appAtomRegistry.get(threadDropBusyAtom)) return false;
- const shells = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom);
+ // The rows on screen can be older than the server's while they wait to show. A move
+ // planned from them could act on a pin or an order key that the server has replaced.
+ if (appAtomRegistry.get(steadyShellsHoldingAtom)) return false;
+ const shells = appAtomRegistry.get(steadyNavigationThreadShellsAtom);
const current = shells.find(
(row) => row.id === thread.id && row.environmentId === thread.environmentId,
);
@@ -708,19 +729,20 @@ export function useThreadListActions(): {
const confirmDeleteThread = (thread: EnvironmentThreadShell) =>
confirmThreadDeletion(executeAction, thread);
+ // `moveThread` looks up its own row, and refuses while a list holds older rows.
return {
- archiveThread,
- confirmDeleteThread,
- settleThread,
- snoozeThread,
- unsnoozeThread,
- unsettleThread,
- pinThread,
- unpinThread,
- setThreadAutoSettle,
+ archiveThread: (thread) => archiveThread(liveThread(thread)),
+ confirmDeleteThread: (thread) => confirmDeleteThread(liveThread(thread)),
+ settleThread: (thread) => settleThread(liveThread(thread)),
+ snoozeThread: (thread, snoozedUntil) => snoozeThread(liveThread(thread), snoozedUntil),
+ unsnoozeThread: (thread) => unsnoozeThread(liveThread(thread)),
+ unsettleThread: (thread) => unsettleThread(liveThread(thread)),
+ pinThread: (thread) => pinThread(liveThread(thread)),
+ unpinThread: (thread) => unpinThread(liveThread(thread)),
+ setThreadAutoSettle: (thread, enabled) => setThreadAutoSettle(liveThread(thread), enabled),
moveThread,
- renameThread,
- regenerateThreadTitle,
+ renameThread: (thread) => renameThread(liveThread(thread)),
+ regenerateThreadTitle: (thread) => regenerateThreadTitle(liveThread(thread)),
};
}
diff --git a/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx b/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx
index de3041c06b57e..747b9a9fc1867 100644
--- a/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx
+++ b/apps/mobile/src/features/threads/McpAppFullscreenScreen.tsx
@@ -56,6 +56,41 @@ function descendsFrom(
/** Resolve apps from stored tool calls so links cannot supply apps the call never produced. */
export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
+ const navigation = useNavigation();
+ const { environmentId, threadId, itemId } = route.params;
+ if (!environmentId?.trim() || !threadId?.trim() || !itemId?.trim()) {
+ return (
+
+ navigation.goBack()}
+ closeAccessibilityLabel="Exit full screen"
+ />
+ This app cannot be shown.
+
+ );
+ }
+ return (
+
+ );
+}
+
+function McpAppFullscreen({
+ params,
+ environmentId,
+ threadId,
+ itemId,
+}: {
+ readonly params: McpAppFullscreenScreenProps["route"]["params"];
+ readonly environmentId: EnvironmentId;
+ readonly threadId: ThreadId;
+ readonly itemId: TurnItemId;
+}) {
const navigation = useNavigation();
const insets = useSafeAreaInsets();
// Wait for focus before goBack; an exit under another screen must not pop that screen.
@@ -74,10 +109,6 @@ export function McpAppFullscreenScreen({ route }: McpAppFullscreenScreenProps) {
});
};
const [size, setSize] = useState({ width: 0, height: 0 });
- const params = route.params;
- const environmentId = EnvironmentId.make(params.environmentId);
- const threadId = ThreadId.make(params.threadId);
- const itemId = TurnItemId.make(params.itemId);
const conversationThreadId = useConversationThreadId(
environmentId,
threadId,
diff --git a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
index 2ebbad63577e6..1b4614a81f472 100644
--- a/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
+++ b/apps/mobile/src/features/threads/ThreadArrangementSheet.tsx
@@ -18,7 +18,7 @@ import { scopedThreadKey } from "../../lib/scopedEntities";
import { deriveThreadArrangementSizing } from "../../lib/layout";
import { environmentServerConfigsAtom } from "../../state/server";
import { threadListEnvironmentsAtom } from "../../state/presentation";
-import { environmentThreadShells } from "../../state/threads";
+import { steadyNavigationThreadShellsAtom, steadyShellsHoldingAtom } from "../../state/threads";
import { sortSettledThreads } from "@t3tools/client-runtime/state/thread-sort";
import { useOlderSettledShelf, useOlderSettledShelfGrowth } from "../../state/olderSettledShelf";
import {
@@ -170,12 +170,13 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {
baseFontSize: appearance.baseFontSize,
fontScale,
});
- const threads = useAtomValue(environmentThreadShells.navigationThreadShellsAtom);
+ const threads = useAtomValue(steadyNavigationThreadShellsAtom);
const configs = useAtomValue(environmentServerConfigsAtom);
const listEnvironments = useAtomValue(threadListEnvironmentsAtom);
const queuedThreadKeys = useAtomValue(queuedThreadKeysAtom);
const pendingOrder = useAtomValue(pendingThreadOrderAtom);
const dropBusy = useAtomValue(threadDropBusyAtom);
+ const holdingRows = useAtomValue(steadyShellsHoldingAtom);
const { moveThread } = useThreadListActions();
const { workingShelfEnabled } = useThreadListV2ShelfPreferences();
const now = useThreadListNow(threads);
@@ -489,6 +490,7 @@ function ThreadArrangementSheet(props: { onClose: () => void }) {
disabled={
dropBusy ||
pendingOrder !== null ||
+ holdingRows ||
(!listEnvironments.pinReorderEnvironmentIds.has(
thread.environmentId,
) &&
diff --git a/apps/mobile/src/features/threads/ThreadFeed.tsx b/apps/mobile/src/features/threads/ThreadFeed.tsx
index dbbcaa1fd9cff..39cc885e4d2e3 100644
--- a/apps/mobile/src/features/threads/ThreadFeed.tsx
+++ b/apps/mobile/src/features/threads/ThreadFeed.tsx
@@ -3326,7 +3326,7 @@ export const ThreadFeed = memo(function ThreadFeed(props: ThreadFeedProps) {
const jumpRunId =
jumpReady &&
!presentedFeed.some((entry) => entry.type === "message" && entry.id === jumpToMessageId)
- ? messageFoldRunId(props.feed, jumpToMessageId)
+ ? messageFoldRunId(props.feed, jumpToMessageId, presentedFeed)
: null;
if (jumpRunId && !expandedTurnIds.has(jumpRunId)) {
setInteractionState((current) => ({
diff --git a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
index 1f0a84a71154b..e1c51b7f524b5 100644
--- a/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
+++ b/apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx
@@ -27,7 +27,8 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
import { AppText as Text } from "../../components/ui/AppText";
import { Button } from "../../components/ui/Button";
import { scopedProjectKey, scopedThreadKey } from "../../lib/scopedEntities";
-import { useProjects, useNavigationThreadShells } from "../../state/entities";
+import { useProjects } from "../../state/entities";
+import { steadyNavigationThreadShellsAtom } from "../../state/threads";
import { useThreadSearch } from "../../state/queries";
import { useThreadListV2ShelfPreferences } from "./use-thread-list-v2-shelf-preferences";
import { useThreadListNow } from "./use-thread-list-now";
@@ -121,7 +122,7 @@ function ThreadNavigationSidebarPane(props: ThreadNavigationSidebarProps) {
const insets = useSafeAreaInsets();
const { fabClearance, fabSize } = useAndroidControlSizing();
const projects = useProjects();
- const threads = useNavigationThreadShells();
+ const threads = useAtomValue(steadyNavigationThreadShellsAtom);
const { environments: workspaceEnvironments, state: catalogState } = useWorkspaceState();
const { savedConnectionsById } = useSavedRemoteConnections();
const openSwipeableRef = useRef(null);
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts
index d810563f72660..86e7f3f7182ac 100644
--- a/apps/mobile/src/lib/threadActivity.test.ts
+++ b/apps/mobile/src/lib/threadActivity.test.ts
@@ -896,16 +896,20 @@ describe("buildThreadFeed", () => {
projected(runless ? { ...item, runId: null } : item, position),
),
);
- const foldRunId = messageFoldRunId(feed, "message-middle");
- expect(foldRunId, String(runless)).toBe(runless ? "runless:message-user" : runId);
const ids = (expanded: ReadonlySet) =>
deriveThreadFeedPresentation(feed, null, expanded).map((entry) => entry.id);
+ const foldRunId = messageFoldRunId(
+ feed,
+ "message-middle",
+ deriveThreadFeedPresentation(feed, null, new Set()),
+ );
+ expect(foldRunId, String(runless)).toBe(runless ? "runless:message-user" : runId);
expect(ids(new Set())).not.toContain("message-middle");
expect(ids(new Set([foldRunId!]))).toContain("message-middle");
}
- expect(messageFoldRunId(buildThreadFeed([projected(userMessage(), 0)]), "message-user")).toBe(
- null,
- );
+ expect(
+ messageFoldRunId(buildThreadFeed([projected(userMessage(), 0)]), "message-user", []),
+ ).toBe(null);
});
it("folds progress messages while keeping the final assistant answer visible", () => {
@@ -1010,6 +1014,66 @@ describe("buildThreadFeed", () => {
]);
});
+ it("splits a settled turn's work fold at a steer", () => {
+ const steer = {
+ ...userMessage("2026-06-20T00:00:04.000Z"),
+ id: TurnItemId.make("item-steer"),
+ messageId: MessageId.make("message-steer"),
+ inputIntent: "steer" as const,
+ };
+ const after = { ...command("2026-06-20T00:00:06.000Z"), id: TurnItemId.make("item-after") };
+ const progress = {
+ ...assistantMessage("2026-06-20T00:00:07.000Z"),
+ id: TurnItemId.make("item-progress"),
+ messageId: MessageId.make("message-progress"),
+ };
+ const feed = buildThreadFeed(
+ [
+ userMessage(),
+ command(),
+ steer,
+ after,
+ progress,
+ assistantMessage("2026-06-20T00:00:09.000Z"),
+ ].map((item, position) => projected(item, position)),
+ );
+
+ expect(
+ deriveThreadFeedPresentation(feed, null, new Set()).map((entry) =>
+ entry.type === "message" ? entry.id : entry.type,
+ ),
+ ).toEqual(["message-user", "run-fold", "message-steer", "run-fold", "message-assistant"]);
+ const foldRunId = messageFoldRunId(
+ feed,
+ "message-progress",
+ deriveThreadFeedPresentation(feed, null, new Set()),
+ );
+ expect(
+ deriveThreadFeedPresentation(feed, null, new Set([foldRunId!])).map((entry) =>
+ entry.type === "message" ? entry.id : entry.type,
+ ),
+ ).toEqual([
+ "message-user",
+ "run-fold",
+ "message-steer",
+ "run-fold",
+ "activity-group",
+ "message-progress",
+ "message-assistant",
+ ]);
+
+ // Hiding tools leaves no output before the steer, so nothing splits there.
+ const hideAll = (expanded: ReadonlySet) =>
+ deriveThreadFeedPresentation(feed, null, expanded, new Set(), null, false, undefined, {
+ toolCallVisibility: "hideAll",
+ revealedMessageId: null,
+ });
+ const hiddenToolsFoldRunId = messageFoldRunId(feed, "message-progress", hideAll(new Set()));
+ expect(hideAll(new Set([hiddenToolsFoldRunId!])).map((entry) => entry.id)).toContain(
+ "message-progress",
+ );
+ });
+
it("folds subagents while keeping created-thread and fork cards visible", () => {
const { providerThreadId: _providerThreadId, ...forkBase } = base(
"item-fork",
diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts
index 16f16b200c8d1..7591b0060985b 100644
--- a/apps/mobile/src/lib/threadActivity.ts
+++ b/apps/mobile/src/lib/threadActivity.ts
@@ -1058,25 +1058,51 @@ export function failedFeedRunIds(
/**
* The key a run fold uses for the message `entryId`: its run, or for an
* imported message with no run, the runless key of the user message before
- * it. Null for user messages, which never fold.
+ * it, or the segment after its run's last steer when `presented` shows that
+ * fold. Null for user messages, which never fold.
*/
export function messageFoldRunId(
feed: ReadonlyArray,
entryId: string,
+ presented: ReadonlyArray<{ readonly type: string; readonly runId?: RunId | null }>,
): RunId | null {
let runlessKey: RunId | null = null;
+ const lastSteerIdByRunId = new Map();
for (const entry of feed) {
if (entry.type !== "message") continue;
if (entry.message.role === "user") {
if (entry.id === entryId) return null;
+ if (isSteerMessage(entry.message) && entry.message.runId != null) {
+ lastSteerIdByRunId.set(entry.message.runId, entry.id);
+ }
runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null;
} else if (entry.id === entryId) {
- return entry.message.runId ?? runlessKey;
+ const runId = entry.message.runId ?? runlessKey;
+ const steerId = runId === null ? undefined : lastSteerIdByRunId.get(runId);
+ if (runId === null || steerId === undefined) return runId;
+ // Tool visibility can drop all output before the steer, leaving no split.
+ const steerKey = steerFoldRunId(runId, steerId);
+ return presented.some((row) => row.type === "run-fold" && row.runId === steerKey)
+ ? steerKey
+ : runId;
}
}
return null;
}
+function steerFoldRunId(runId: RunId, steerEntryId: string): RunId {
+ return RunId.make(`${runId}:steer:${steerEntryId}`);
+}
+
+function feedEntryFoldRunId(entry: ThreadFeedEntry, runlessKey: RunId | null): RunId | null {
+ if (entry.type === "message") {
+ return entry.message.role === "assistant" ? (entry.message.runId ?? runlessKey) : null;
+ }
+ return entry.type === "activity-group" || entry.type === "html-render" || entry.type === "mcp-app"
+ ? (entry.runId ?? runlessKey)
+ : null;
+}
+
function answersBeforeSteers(feed: ReadonlyArray): ReadonlySet {
const ids = new Set();
let previous: ThreadFeedEntry | undefined;
@@ -1121,26 +1147,35 @@ function deriveThreadFeedRunFolds(
}
const groupsByRunId = new Map<
RunId,
- { entries: ThreadFeedEntry[]; startBoundary: string | null }
+ {
+ entries: ThreadFeedEntry[];
+ startBoundary: string | null;
+ /** Each steer after the run has output starts a segment at this index into `entries`. */
+ steerSegments: Array<{ startIndex: number; steer: ThreadFeedEntry }>;
+ }
>();
let runlessKey: RunId | null = null;
let responseKey: RunId | null = null;
let pendingUserBoundary: string | null = null;
for (const [index, entry] of feed.entries()) {
if (entry.type === "message" && entry.message.role === "user") {
+ const steerGroup =
+ isSteerMessage(entry.message) && entry.message.runId != null
+ ? groupsByRunId.get(entry.message.runId)
+ : undefined;
+ if (steerGroup && steerGroup.entries.length > 0) {
+ // Back-to-back steers split once, after the last of them.
+ if (steerGroup.steerSegments.at(-1)?.startIndex === steerGroup.entries.length) {
+ steerGroup.steerSegments.pop();
+ }
+ steerGroup.steerSegments.push({ startIndex: steerGroup.entries.length, steer: entry });
+ }
pendingUserBoundary = entry.message.createdAt;
runlessKey = entry.message.runId == null ? RunId.make(`runless:${entry.id}`) : null;
responseKey = entry.message.runId ?? runlessKey;
continue;
}
- const ownRunId =
- entry.type === "message" && entry.message.role === "assistant"
- ? (entry.message.runId ?? runlessKey)
- : entry.type === "activity-group" ||
- entry.type === "html-render" ||
- entry.type === "mcp-app"
- ? (entry.runId ?? runlessKey)
- : null;
+ const ownRunId = feedEntryFoldRunId(entry, runlessKey);
if (!ownRunId) continue;
// Resumed subagents keep their original turn position and fold, leaving later run folds under their own prompts.
const runId =
@@ -1149,7 +1184,7 @@ function deriveThreadFeedRunFolds(
: ownRunId;
let group = groupsByRunId.get(runId);
if (!group) {
- group = { entries: [], startBoundary: pendingUserBoundary };
+ group = { entries: [], startBoundary: pendingUserBoundary, steerSegments: [] };
pendingUserBoundary = null;
groupsByRunId.set(runId, group);
}
@@ -1215,15 +1250,15 @@ function deriveThreadFeedRunFolds(
.map((entry) => entry.id),
);
const firstEntry = group.entries[0];
- const firstHiddenEntry = group.entries.find((entry) => hiddenEntryIds.has(entry.id));
const lastEntry = group.entries.at(-1);
- if (!firstHiddenEntry || !firstEntry || !lastEntry) continue;
- const hidesNonCompactionWork = group.entries.some(
- (entry) =>
- hiddenEntryIds.has(entry.id) &&
- !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
- );
- if (!hidesNonCompactionWork) continue;
+ if (!firstEntry || !lastEntry) continue;
+ const hidesNonCompactionWork = (entries: ReadonlyArray) =>
+ entries.some(
+ (entry) =>
+ hiddenEntryIds.has(entry.id) &&
+ !(entry.type === "activity-group" && isContextCompactionActivityGroup(entry)),
+ );
+ if (!hidesNonCompactionWork(group.entries)) continue;
const terminalEntry = terminalAssistantId
? group.entries.find((entry) => entry.id === terminalAssistantId)
: null;
@@ -1243,28 +1278,58 @@ function deriveThreadFeedRunFolds(
const duration = elapsedMs === null ? null : formatDuration(elapsedMs);
const interrupted =
latestRunMatches && (latestRun.status === "interrupted" || latestRun.status === "cancelled");
- const deferredWorkItemIds = group.entries.flatMap((entry) =>
- entry.type === "activity-group"
- ? entry.activities.flatMap((activity) =>
- activity.projectedItem.item.deferredWork
- ? [String(activity.projectedItem.sourceItemId)]
- : [],
- )
- : [],
- );
- foldsByAnchorId.set(firstHiddenEntry.id, {
- ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}),
- runId,
- createdAt: firstHiddenEntry.createdAt,
- hiddenEntryIds,
- label: interrupted
- ? duration
- ? `You stopped after ${duration}`
- : "You stopped this response"
- : duration
- ? `Worked for ${duration}`
- : "Worked",
- });
+ const label = interrupted
+ ? duration
+ ? `You stopped after ${duration}`
+ : "You stopped this response"
+ : duration
+ ? `Worked for ${duration}`
+ : "Worked";
+ // The top row keeps the whole turn's time. Work after a steer folds under
+ // its own row below that steer, keyed apart so each segment opens alone.
+ const segments = [
+ {
+ runId,
+ entries: group.entries.slice(0, group.steerSegments[0]?.startIndex),
+ label,
+ },
+ ...group.steerSegments.map(({ startIndex, steer }, index) => {
+ const entries = group.entries.slice(startIndex, group.steerSegments[index + 1]?.startIndex);
+ const segmentMs = computeElapsedMs(
+ steer.createdAt,
+ entries
+ .map((entry) => (entry.type === "message" ? entry.message.updatedAt : entry.createdAt))
+ .reduce(maxIsoTimestamp, null) ?? steer.createdAt,
+ );
+ return {
+ runId: steerFoldRunId(runId, steer.id),
+ entries,
+ label: segmentMs !== null ? `Continued for ${formatDuration(segmentMs)}` : "Continued",
+ };
+ }),
+ ];
+ for (const segment of segments) {
+ const firstHiddenEntry = segment.entries.find((entry) => hiddenEntryIds.has(entry.id));
+ if (!firstHiddenEntry || !hidesNonCompactionWork(segment.entries)) continue;
+ const deferredWorkItemIds = segment.entries.flatMap((entry) =>
+ entry.type === "activity-group"
+ ? entry.activities.flatMap((activity) =>
+ activity.projectedItem.item.deferredWork
+ ? [String(activity.projectedItem.sourceItemId)]
+ : [],
+ )
+ : [],
+ );
+ foldsByAnchorId.set(firstHiddenEntry.id, {
+ ...(deferredWorkItemIds.length > 0 ? { deferredWorkItemIds } : {}),
+ runId: segment.runId,
+ createdAt: firstHiddenEntry.createdAt,
+ hiddenEntryIds: new Set(
+ segment.entries.flatMap((entry) => (hiddenEntryIds.has(entry.id) ? [entry.id] : [])),
+ ),
+ label: segment.label,
+ });
+ }
}
const covered = new Set(
[...foldsByAnchorId.values()].flatMap((fold) => [...fold.hiddenEntryIds]),
diff --git a/apps/mobile/src/state/shell.ts b/apps/mobile/src/state/shell.ts
index deb0e2e59fd04..8f92c7c1a42c7 100644
--- a/apps/mobile/src/state/shell.ts
+++ b/apps/mobile/src/state/shell.ts
@@ -1,3 +1,4 @@
+import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections";
import {
createEnvironmentShellAtoms,
createEnvironmentShellSummaryAtom,
@@ -27,6 +28,25 @@ const shellHasError = (state: EnvironmentShellState) => Option.isSome(state.erro
// The empty placeholder stands until the environment has read its cached shell.
const shellCacheRead = (state: EnvironmentShellState) => state !== EMPTY_SHELL_STATE;
+const shellCacheReadAtom = Atom.family((environmentId: EnvironmentId) =>
+ Atom.make((get) => shellCacheRead(get(environmentShell.stateValueAtom(environmentId)))),
+);
+
+/**
+ * True once every enabled environment has read its cached shell. A list that paints before
+ * then gets the cached rows of one environment at a time.
+ */
+export const shellCachesReadAtom = Atom.make((get) => {
+ const catalog = get(environmentCatalog.catalogValueAtom);
+ if (!catalog.isReady) return false;
+ // Reads every environment, so each one loads its cache now and not after the one before it.
+ let allRead = true;
+ for (const environmentId of enabledEnvironmentIds(catalog)) {
+ if (!get(shellCacheReadAtom(environmentId))) allRead = false;
+ }
+ return allRead;
+}).pipe(Atom.withLabel("mobile-shell-caches-read"));
+
export function useEnvironmentShellReadiness(environmentId: EnvironmentId | null) {
const atom =
environmentId === null
diff --git a/apps/mobile/src/state/thread-order.test.ts b/apps/mobile/src/state/thread-order.test.ts
index 032744c75d641..d51370b4abc69 100644
--- a/apps/mobile/src/state/thread-order.test.ts
+++ b/apps/mobile/src/state/thread-order.test.ts
@@ -12,7 +12,7 @@ import {
pendingThreadOrderAtom,
} from "./thread-order";
import { environmentServerConfigsAtom } from "./server";
-import { environmentThreadShells } from "./threads";
+import { steadyNavigationThreadShellsAtom } from "./threads";
vi.mock("./atom-registry", async () => {
const { AtomRegistry } = await import("effect/reactivity");
@@ -21,7 +21,7 @@ vi.mock("./atom-registry", async () => {
vi.mock("./threads", async () => {
const { Atom } = await import("effect/reactivity");
return {
- environmentThreadShells: { navigationThreadShellsAtom: Atom.make([]).pipe(Atom.keepAlive) },
+ steadyNavigationThreadShellsAtom: Atom.make([]).pipe(Atom.keepAlive),
};
});
vi.mock("./server", async () => {
@@ -36,7 +36,7 @@ vi.mock("./use-thread-outbox", async () => {
type ServerConfigs = Atom.Type;
type ServerConfig = ServerConfigs extends ReadonlyMap ? Config : never;
const configsAtom = environmentServerConfigsAtom as Atom.Writable;
-const shellsAtom = environmentThreadShells.navigationThreadShellsAtom as Atom.Writable<
+const shellsAtom = steadyNavigationThreadShellsAtom as Atom.Writable<
readonly EnvironmentThreadShell[],
readonly EnvironmentThreadShell[]
>;
diff --git a/apps/mobile/src/state/thread-order.ts b/apps/mobile/src/state/thread-order.ts
index 41a4671a8f530..14e8f6505b5fc 100644
--- a/apps/mobile/src/state/thread-order.ts
+++ b/apps/mobile/src/state/thread-order.ts
@@ -12,7 +12,7 @@ import {
} from "../features/threads/threadListV2";
import { appAtomRegistry } from "./atom-registry";
import { environmentServerConfigsAtom } from "./server";
-import { environmentThreadShells } from "./threads";
+import { steadyNavigationThreadShellsAtom } from "./threads";
import { queuedThreadKeysAtom } from "./use-thread-outbox";
export const threadArrangementOpenAtom = Atom.make(false).pipe(Atom.keepAlive);
@@ -64,7 +64,7 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
const current = appAtomRegistry.get(pendingThreadOrderAtom);
if (current === null) return;
const configs = appAtomRegistry.get(environmentServerConfigsAtom);
- const threads = appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom);
+ const threads = appAtomRegistry.get(steadyNavigationThreadShellsAtom);
const nowMs = Date.now();
const ordered = getThreadListV2OrderedSection({
threads,
@@ -87,17 +87,12 @@ export function beginPendingThreadOrder(pending: PendingThreadOrder) {
teardownPendingOrder = teardown;
appAtomRegistry.set(pendingThreadOrderAtom, pending);
unsubscribers.push(
- appAtomRegistry.subscribe(environmentThreadShells.navigationThreadShellsAtom, refresh),
+ appAtomRegistry.subscribe(steadyNavigationThreadShellsAtom, refresh),
appAtomRegistry.subscribe(environmentServerConfigsAtom, refresh),
appAtomRegistry.subscribe(queuedThreadKeysAtom, refresh),
minuteTick.subscribe(refresh),
);
- armWake(
- nextSnoozeWakeAfter(
- appAtomRegistry.get(environmentThreadShells.navigationThreadShellsAtom),
- Date.now(),
- ),
- );
+ armWake(nextSnoozeWakeAfter(appAtomRegistry.get(steadyNavigationThreadShellsAtom), Date.now()));
return {
isPending: () => {
refresh();
diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts
index d6e784377cca6..bf2013aef5398 100644
--- a/apps/mobile/src/state/threads.ts
+++ b/apps/mobile/src/state/threads.ts
@@ -10,6 +10,7 @@ import {
createThreadEnvironmentAtoms,
createThreadFamilyAtoms,
} from "@t3tools/client-runtime/state/threads";
+import { createSteadyShellAtoms } from "@t3tools/client-runtime/state/shell";
import type { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { AsyncResult, Atom } from "effect/reactivity";
@@ -46,6 +47,23 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({
snapshotAtom: threadEnvironment.snapshotAtom,
hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
});
+const steadyShells = createSteadyShellAtoms({
+ catalogValueAtom: environmentCatalog.catalogValueAtom,
+ snapshotAtom: threadEnvironment.snapshotAtom,
+ shellStateAtom: environmentShell.stateValueAtom,
+ rowActionsAtom: threadEnvironment.rowActionsAtom,
+ connectionStateAtom: environmentCatalog.stateAtom,
+});
+/**
+ * The threads that lists arrange. Rows wait while their environment synchronizes, so a list
+ * changes once when environments connect, not once per environment.
+ */
+export const steadyShellsHoldingAtom = steadyShells.holdingAtom;
+export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtoms({
+ catalogValueAtom: environmentCatalog.catalogValueAtom,
+ snapshotAtom: steadyShells.snapshotAtom,
+ hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom,
+}).navigationThreadShellsAtom;
export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({
childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom,
pendingRequestsAtom: environmentThreadDetails.pendingRequestsAtom,
diff --git a/apps/server/integration/TransferBudgetReport.integration.ts b/apps/server/integration/TransferBudgetReport.integration.ts
index 0b3cdb78589a0..bcfa2f3896f20 100644
--- a/apps/server/integration/TransferBudgetReport.integration.ts
+++ b/apps/server/integration/TransferBudgetReport.integration.ts
@@ -38,6 +38,11 @@ const STALE_TODO_RECORD_KINDS = [
] as const;
type StaleTodoRecordCounts = Readonly>;
+/** One new socket, read from the subscribe call until the subscription caught up. */
+export interface SocketOpenMeasurement {
+ readonly totals: WebSocketTransferTotals;
+}
+
export interface TransferBudgetRun {
readonly provider: ProviderDriverKind;
readonly threadSnapshot: HttpTransferMeasurement;
@@ -49,15 +54,32 @@ export interface TransferBudgetRun {
readonly reconnectShell: WebSocketCatchUpMeasurement;
readonly measuredTurnSqlStatements: number;
readonly reconnectSqlStatements: number;
- /** The compact bounded snapshot web and mobile load when the long-turn thread opens. */
- readonly longTurnColdOpen: TimelineHttpMeasurement;
- readonly longTurnHistoryPage: TimelineHttpMeasurement;
+ /** A thread resumed from the cursor it held before one ordinary turn. */
+ readonly shortTurnResume: SocketOpenMeasurement;
+ /** The long-turn thread while its last turn runs: the bounded snapshot, then one older page. */
+ readonly longTurnRunningColdOpen: TimelineHttpMeasurement;
+ readonly longTurnRunningHistoryPage: TimelineHttpMeasurement;
/** The same reads as an older client that only sends `compactTurnItems`, to show the savings. */
- readonly longTurnColdOpenLegacy: TimelineHttpMeasurement;
- readonly longTurnHistoryPageLegacy: TimelineHttpMeasurement;
+ readonly longTurnRunningColdOpenLegacy: TimelineHttpMeasurement;
+ readonly longTurnRunningHistoryPageLegacy: TimelineHttpMeasurement;
+ /** The same thread once the turn finished, over HTTP (web) and over the socket alone (mobile). */
+ readonly longTurnColdOpen: TimelineHttpMeasurement;
+ readonly longTurnSocketColdOpen: SocketOpenMeasurement & { readonly rows: number };
+ /** The first page of the finished turn's deferred work, loaded when its group is expanded. */
+ readonly longTurnWorkPage: TimelineHttpMeasurement;
+ /** A thread resumed from the cursor of its own last event. */
+ readonly idleThreadResume: SocketOpenMeasurement;
/** The cold-connect shell snapshot after the settled-thread fleet is written. */
readonly fleetShell: TimelineHttpMeasurement;
readonly fleetShellLegacy: TimelineHttpMeasurement;
+ /** The shell subscription a cold connect opens from that snapshot's cursor. */
+ readonly fleetShellSubscribe: SocketOpenMeasurement;
+ /** A client that holds that snapshot's rows asks the HTTP route whether they still resume. */
+ readonly fleetShellResume: TimelineHttpMeasurement;
+ /** The same question from a cursor too old to replay: the route answers with the snapshot. */
+ readonly staleShellReload: TimelineHttpMeasurement;
+ /** A shell resumed over the socket from that old cursor, by a client that reloads over HTTP. */
+ readonly staleShellResume: SocketOpenMeasurement;
/**
* The compact bounded snapshot of the long thread whose finished runs left todo lists open,
* with the count of each record kind that rides along with its rows.
@@ -89,20 +111,57 @@ const TRANSFER_BUDGETS: Readonly> = {
claudeAgent: TRANSFER_BUDGET,
};
-// Decoded bytes, not wire bytes: phones parse and keep the decoded JSON. About 7% above the
-// observed 103 KB, so a cold open without body dedupe (117 KB), the ID table, or row budgets
-// (all 920 rows) fails. Kept apart from TRANSFER_BUDGET because the PR comment validates its keys.
-const LONG_TURN_BUDGET = {
+// Decoded bytes, not wire bytes: phones parse and keep the decoded JSON. About 15% above the
+// observed 95 KB history page, so a page without the ID table (130 KB) or row budgets fails.
+// Kept apart from TRANSFER_BUDGET because the PR comment validates its keys.
+const LONG_TURN_PAGE_BUDGET = {
decodedBytes: 110_000,
rows: 75,
};
+// About 7% above the observed 290 KB. The window holds 75 rows, but every message of a running
+// turn rides along with it: 196 KB here. Without body dedupe or the ID table it is 354 KB.
+const LONG_TURN_RUNNING_BUDGET = {
+ decodedBytes: 310_000,
+ rows: 75,
+};
+
+// About 7% above the observed 393 KB. A finished turn defers its 770 work rows and stays whole:
+// 151 rows of messages, checkpoints and subagents, on both transports.
+const LONG_TURN_FINISHED_BUDGET = {
+ decodedBytes: 420_000,
+ rows: 151,
+};
+
+// About 6% above the observed 193 KB: one older page of work, twice the cold-open row budget.
+const LONG_TURN_WORK_PAGE_BUDGET = {
+ decodedBytes: 205_000,
+ rows: 150,
+};
+
+const SOCKET_BUDGETS = {
+ // One ordinary turn replays in 11 KB. With its tool bodies it is over 900 KB.
+ shortTurnResume: { decodedBytes: 13_000, messages: 2 },
+ longTurnColdOpen: { decodedBytes: LONG_TURN_FINISHED_BUDGET.decodedBytes, messages: 2 },
+ // These three send no rows. A snapshot in their place is 393 KB for the thread, 42 KB for the shell.
+ idleThreadResume: { decodedBytes: 200, messages: 1 },
+ // A subscribe that does not name the snapshot's project identities gets the project again: 851 B.
+ fleetShellSubscribe: { decodedBytes: 200, messages: 1 },
+ staleShellResume: { decodedBytes: 400, messages: 2 },
+};
+
// About 30% above the observed 42 KB. Without the shell opt-ins it carries all 142 rows (217 KB).
const FLEET_SHELL_BUDGET = {
decodedBytes: 55_000,
rows: 27,
};
+// The answer is `{"resumable":true}`. A snapshot in its place is 42 KB.
+const FLEET_SHELL_RESUME_BUDGET = {
+ decodedBytes: 100,
+ rows: 0,
+};
+
// About 14% above the observed 75 KB. The window holds the working run only: 2 nodes, 2 subagents,
// 1 plan, 1 provider turn and the last finished turn's checkpoint. When finished runs ride along
// it holds 82 nodes, 82 subagents, 41 plans, 41 provider turns, 40 checkpoints and 740 KB.
@@ -211,31 +270,141 @@ function webSocketRows(
];
}
-function timelineRows(
- provider: ProviderDriverKind,
+interface ScenarioRow {
+ readonly phase: string;
+ readonly metric: string;
+ readonly unit: "bytes" | "count";
+ readonly observed: number;
+ /** Absent on figures that only inform: wire bytes, and what an older client receives. */
+ readonly maximum: number | undefined;
+}
+
+function httpRows(
phase: string,
measured: TimelineHttpMeasurement,
- budget: { readonly decodedBytes: number; readonly rows: number },
-): string[] {
+ budget?: { readonly decodedBytes: number; readonly rows: number },
+): ScenarioRow[] {
return [
- infoRow(provider, phase, "HTTP wire", measured.http.wireBytes),
- row(provider, phase, "HTTP decoded", measured.http.decodedBodyBytes, budget.decodedBytes),
- row(provider, phase, "rows", measured.rows, budget.rows, String),
+ {
+ phase,
+ metric: "HTTP wire",
+ unit: "bytes",
+ observed: measured.http.wireBytes,
+ maximum: undefined,
+ },
+ {
+ phase,
+ metric: "HTTP decoded",
+ unit: "bytes",
+ observed: measured.http.decodedBodyBytes,
+ maximum: budget?.decodedBytes,
+ },
+ { phase, metric: "rows", unit: "count", observed: measured.rows, maximum: budget?.rows },
];
}
-function legacyRows(
- provider: ProviderDriverKind,
+function socketRows(
phase: string,
- measured: TimelineHttpMeasurement,
-): string[] {
+ { totals }: SocketOpenMeasurement,
+ budget: { readonly decodedBytes: number; readonly messages: number },
+): ScenarioRow[] {
+ return [
+ {
+ phase,
+ metric: "WebSocket wire",
+ unit: "bytes",
+ observed: totals.wireBytes,
+ maximum: undefined,
+ },
+ {
+ phase,
+ metric: "WebSocket decoded",
+ unit: "bytes",
+ observed: totals.decodedBytes,
+ maximum: budget.decodedBytes,
+ },
+ {
+ phase,
+ metric: "WebSocket messages",
+ unit: "count",
+ observed: totals.messages,
+ maximum: budget.messages,
+ },
+ ];
+}
+
+/**
+ * Every scenario figure beyond the thread totals. The violations, the report table and the PR
+ * comment's scenario file all read this list, so a row added here reaches all three. The PR
+ * comment only accepts letters, digits, spaces, commas and hyphens in `phase` and `metric`.
+ */
+function scenarioRows(run: TransferBudgetRun): ScenarioRow[] {
return [
- infoRow(provider, `${phase}, older client`, "HTTP wire", measured.http.wireBytes),
- infoRow(provider, `${phase}, older client`, "HTTP decoded", measured.http.decodedBodyBytes),
- infoRow(provider, `${phase}, older client`, "rows", measured.rows, String),
+ ...socketRows("short turn resume", run.shortTurnResume, SOCKET_BUDGETS.shortTurnResume),
+ ...httpRows(
+ "long turn running, cold open",
+ run.longTurnRunningColdOpen,
+ LONG_TURN_RUNNING_BUDGET,
+ ),
+ ...httpRows("long turn running, cold open, older client", run.longTurnRunningColdOpenLegacy),
+ ...httpRows(
+ "long turn running, history page",
+ run.longTurnRunningHistoryPage,
+ LONG_TURN_PAGE_BUDGET,
+ ),
+ ...httpRows(
+ "long turn running, history page, older client",
+ run.longTurnRunningHistoryPageLegacy,
+ ),
+ ...httpRows("long turn finished, cold open", run.longTurnColdOpen, LONG_TURN_FINISHED_BUDGET),
+ ...socketRows(
+ "long turn finished, socket cold open",
+ run.longTurnSocketColdOpen,
+ SOCKET_BUDGETS.longTurnColdOpen,
+ ),
+ {
+ phase: "long turn finished, socket cold open",
+ metric: "rows",
+ unit: "count",
+ observed: run.longTurnSocketColdOpen.rows,
+ maximum: LONG_TURN_FINISHED_BUDGET.rows,
+ },
+ ...httpRows("long turn finished, work page", run.longTurnWorkPage, LONG_TURN_WORK_PAGE_BUDGET),
+ ...socketRows("idle thread resume", run.idleThreadResume, SOCKET_BUDGETS.idleThreadResume),
+ ...httpRows("fleet shell snapshot", run.fleetShell, FLEET_SHELL_BUDGET),
+ ...httpRows("fleet shell snapshot, older client", run.fleetShellLegacy),
+ ...socketRows(
+ "fleet shell subscribe",
+ run.fleetShellSubscribe,
+ SOCKET_BUDGETS.fleetShellSubscribe,
+ ),
+ ...httpRows("fleet shell resume check", run.fleetShellResume, FLEET_SHELL_RESUME_BUDGET),
+ ...httpRows("stale shell reload", run.staleShellReload, FLEET_SHELL_BUDGET),
+ ...socketRows("stale shell resume", run.staleShellResume, SOCKET_BUDGETS.staleShellResume),
+ ...httpRows("stale todo list cold open", run.staleTodoColdOpen, STALE_TODO_BUDGET),
+ ...STALE_TODO_RECORD_KINDS.map((kind): ScenarioRow => ({
+ phase: "stale todo list cold open",
+ metric: kind,
+ unit: "count",
+ observed: run.staleTodoColdOpen.records[kind],
+ maximum: STALE_TODO_BUDGET.records[kind],
+ })),
];
}
+/** The budgeted scenario figures, for the PR comment to compare with `main`. */
+export function formatTransferBudgetScenarios(runs: ReadonlyArray): string {
+ const providers = Object.fromEntries(
+ runs.map((run) => [
+ run.provider,
+ scenarioRows(run).flatMap(({ maximum, ...row }) =>
+ maximum === undefined ? [] : [{ ...row, ceiling: maximum }],
+ ),
+ ]),
+ );
+ return `${JSON.stringify({ schemaVersion: 1, providers }, null, 2)}\n`;
+}
+
export function transferBudgetViolations(runs: ReadonlyArray): string[] {
const violations: string[] = [];
for (const run of runs) {
@@ -262,37 +431,8 @@ export function transferBudgetViolations(runs: ReadonlyArray)
run.measuredTurnWebSocket.messages,
budget.measuredTurnWebSocketMessages,
],
- [
- "long-turn cold open decoded bytes",
- run.longTurnColdOpen.http.decodedBodyBytes,
- LONG_TURN_BUDGET.decodedBytes,
- ],
- ["long-turn cold open rows", run.longTurnColdOpen.rows, LONG_TURN_BUDGET.rows],
- [
- "long-turn history page decoded bytes",
- run.longTurnHistoryPage.http.decodedBodyBytes,
- LONG_TURN_BUDGET.decodedBytes,
- ],
- ["long-turn history page rows", run.longTurnHistoryPage.rows, LONG_TURN_BUDGET.rows],
- [
- "fleet shell snapshot decoded bytes",
- run.fleetShell.http.decodedBodyBytes,
- FLEET_SHELL_BUDGET.decodedBytes,
- ],
- ["fleet shell snapshot rows", run.fleetShell.rows, FLEET_SHELL_BUDGET.rows],
- [
- "stale todo list cold open decoded bytes",
- run.staleTodoColdOpen.http.decodedBodyBytes,
- STALE_TODO_BUDGET.decodedBytes,
- ],
- ["stale todo list cold open rows", run.staleTodoColdOpen.rows, STALE_TODO_BUDGET.rows],
- ...STALE_TODO_RECORD_KINDS.map(
- (kind) =>
- [
- `stale todo list cold open ${kind}`,
- run.staleTodoColdOpen.records[kind],
- STALE_TODO_BUDGET.records[kind],
- ] as const,
+ ...scenarioRows(run).flatMap(({ phase, metric, observed, maximum }) =>
+ maximum === undefined ? [] : [[`${phase} ${metric}`, observed, maximum] as const],
),
] as const;
for (const [metric, observed, maximum] of checks) {
@@ -311,8 +451,9 @@ export function formatTransferBudgetReport(runs: ReadonlyArray
- row(
- run.provider,
- "stale todo list cold open",
- kind,
- run.staleTodoColdOpen.records[kind],
- STALE_TODO_BUDGET.records[kind],
- String,
- ),
- ),
+ ...scenarioRows(run).map(({ phase, metric, unit, observed, maximum }) => {
+ const format = unit === "bytes" ? formatBytes : String;
+ return maximum === undefined
+ ? infoRow(run.provider, phase, metric, observed, format)
+ : row(run.provider, phase, metric, observed, maximum, format);
+ }),
);
}
diff --git a/apps/server/integration/TransferBudgetV2Fixture.integration.ts b/apps/server/integration/TransferBudgetV2Fixture.integration.ts
index 9a857120c512f..68cb2c4e841da 100644
--- a/apps/server/integration/TransferBudgetV2Fixture.integration.ts
+++ b/apps/server/integration/TransferBudgetV2Fixture.integration.ts
@@ -14,8 +14,10 @@ import {
RunId,
ThreadId,
TurnItemId,
+ type ApplicationProjectEvent,
type ProviderDriverKind,
type OrchestrationV2DomainEvent,
+ type RepositoryIdentity,
type OrchestrationV2TurnItem,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
@@ -217,10 +219,10 @@ export const LONG_TURN_THREAD_ID = ThreadId.make("transfer-budget-long-turn");
export const LONG_TURN_WORK_ROWS = 900;
/**
- * Three short user turns, then one agent turn far longer than a cold-open
- * window, with the item kinds a long agent run produces. One batch per turn.
- * Run, node, provider and item IDs follow the composite shapes the Claude
- * adapter stores, and every assistant message has its record, as real threads do.
+ * Three short user turns, then one agent turn far longer than a cold-open window, with the item
+ * kinds a long agent run produces. One batch per turn; the last batch only finishes the long turn.
+ * Run, node, provider and item IDs follow the composite shapes the Claude adapter stores, and
+ * every assistant message has its record, as real threads do.
*/
export function longTurnThreadBatches(
provider: ProviderDriverKind,
@@ -434,12 +436,14 @@ export function longTurnThreadBatches(
return events;
};
+ const longTurn = turn(3, LONG_TURN_WORK_ROWS);
return [
[threadCreated(provider, threadId)],
turn(0, 4),
turn(1, 4),
turn(2, 4),
- turn(3, LONG_TURN_WORK_ROWS),
+ longTurn.slice(0, -1),
+ longTurn.slice(-1),
];
}
@@ -835,6 +839,44 @@ export function staleTodoListThreadBatches(
];
}
+const FLEET_PROJECT_ID = ProjectId.make("transfer-project");
+export const FLEET_PROJECT_IDENTITY: RepositoryIdentity = {
+ canonicalKey: "github.com/t3/transfer-budget",
+ locator: {
+ source: "git-remote",
+ remoteName: "origin",
+ remoteUrl: "git@github.com:t3/transfer-budget.git",
+ },
+ owner: "t3",
+ name: "transfer-budget",
+};
+
+/**
+ * The project every fixture thread belongs to. The test resolves it to FLEET_PROJECT_IDENTITY,
+ * which a shell resume sends again unless the client names the identities it already holds.
+ */
+export const fleetProjectCreated: ApplicationProjectEvent = {
+ sequence: 0,
+ eventId: EventId.make("project-created:transfer-project"),
+ aggregateKind: "project",
+ aggregateId: FLEET_PROJECT_ID,
+ occurredAt: "2026-06-01T00:00:00.000Z",
+ commandId: null,
+ causationEventId: null,
+ correlationId: null,
+ metadata: {},
+ type: "project.created",
+ payload: {
+ projectId: FLEET_PROJECT_ID,
+ title: "Transfer budget",
+ workspaceRoot: "/tmp/transfer-budget",
+ defaultModelSelection: null,
+ scripts: [],
+ createdAt: "2026-06-01T00:00:00.000Z",
+ updatedAt: "2026-06-01T00:00:00.000Z",
+ },
+};
+
export const SHELL_SETTLED_THREADS = 100;
export const SHELL_IDLE_SUBAGENTS = 40;
diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts
index 313c583eecf7a..4aaac3b9e30e9 100644
--- a/apps/server/integration/transferBudgetV2.integration.test.ts
+++ b/apps/server/integration/transferBudgetV2.integration.test.ts
@@ -19,12 +19,19 @@ import {
OrchestrationV2ThreadBoundedSnapshot,
OrchestrationV2ThreadDetailSnapshot,
OrchestrationV2ThreadHistoryPage,
- OrchestrationV2ShellSnapshot,
+ OrchestrationV2ShellHttpSnapshot,
+ OrchestrationV2ShellResumable,
OrchestrationV2GetThreadProjectionError,
OrchestrationV2GetShellSnapshotError,
ProviderDriverKind,
+ type EnvironmentOrchestrationShellSnapshotQuery,
+ type EnvironmentOrchestrationThreadBoundedSnapshotQuery,
+ type EnvironmentOrchestrationThreadHistoryQuery,
+ type OrchestrationV2SubscribeShellInput,
+ type OrchestrationV2SubscribeThreadInput,
type OrchestrationV2ThreadStreamItem,
type OrchestrationV2ShellStreamItem,
+ type ThreadId,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import * as Config from "effect/Config";
@@ -63,11 +70,14 @@ import { makeSqlStatementCounter } from "./SqlStatementCounter.integration.ts";
import {
formatTransferBudgetReport,
formatTransferBudgetResult,
+ formatTransferBudgetScenarios,
transferBudgetViolations,
type TransferBudgetRun,
} from "./TransferBudgetReport.integration.ts";
import { TRANSFER_HISTORY_TURN_COUNT } from "./fixtures/transferBudget.ts";
import {
+ FLEET_PROJECT_IDENTITY,
+ fleetProjectCreated,
LONG_TURN_THREAD_ID,
longTurnThreadBatches,
SHELL_IDLE_SUBAGENTS,
@@ -83,11 +93,47 @@ import {
turnEvents,
} from "./TransferBudgetV2Fixture.integration.ts";
-// The opt-ins current web and mobile clients send; keep in sync with client-runtime's
-// boundedThreadSnapshotHttp.ts, threadHistoryHttp.ts, shellSnapshotHttp.ts, threads.ts and shell.ts.
-const CLIENT_BOUNDED_QUERY = "compactTurnItems=1&dedupeBodies=1&compactIds=1";
-const CLIENT_HISTORY_QUERY = "compactIds=1";
-const CLIENT_SHELL_QUERY = "omitIdleSubagents=1&omitOlderSettled=1";
+// The opt-ins current web and mobile clients send, as client-runtime's boundedThreadSnapshotHttp.ts,
+// threadHistoryHttp.ts, shellSnapshotHttp.ts, threads.ts and shell.ts send them. Each is `Required`,
+// so an opt-in added to a contract fails typecheck here until this test sends it. An omitted field
+// differs per request (a cursor, or what the client holds), so each scenario sends its own.
+const CLIENT_BOUNDED_OPT_INS = {
+ compactTurnItems: "1",
+ dedupeBodies: "1",
+ compactIds: "1",
+ deferWork: "1",
+} satisfies Required;
+const CLIENT_HISTORY_OPT_INS = { compactIds: "1", deferWork: "1" } satisfies Required<
+ Omit
+>;
+const CLIENT_SHELL_OPT_INS = {
+ omitIdleSubagents: "1",
+ omitOlderSettled: "1",
+} satisfies Required>;
+const CLIENT_THREAD_SUBSCRIPTION = {
+ requestCompletionMarker: true,
+ acceptBoundedSnapshot: true,
+ acceptDeferredWork: true,
+ acceptCompactTurnItems: true,
+ acceptCompactIds: true,
+ acceptDedupedBodies: true,
+} satisfies Required>;
+type ShellResumeField = "afterSequence" | "httpSnapshotFallback" | "knownProjectIdentities";
+const CLIENT_SHELL_SUBSCRIPTION = {
+ requestCompletionMarker: true,
+ omitIdleSubagents: true,
+ omitOlderSettled: true,
+} satisfies Required>;
+const query = (optIns: Readonly>) => new URLSearchParams(optIns).toString();
+const CLIENT_BOUNDED_QUERY = query(CLIENT_BOUNDED_OPT_INS);
+const CLIENT_HISTORY_QUERY = query(CLIENT_HISTORY_OPT_INS);
+const CLIENT_SHELL_QUERY = query(CLIENT_SHELL_OPT_INS);
+// A client that holds shell rows names their cursor in the same request.
+const clientShellResumeQuery = (resumeFrom: number) =>
+ query({
+ ...CLIENT_SHELL_OPT_INS,
+ resumeFrom: String(resumeFrom),
+ } satisfies Required);
const decodeThreadSnapshot = Schema.decodeUnknownEffect(
Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot)),
@@ -99,7 +145,10 @@ const decodeHistoryPage = Schema.decodeUnknownEffect(
Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadHistoryPage)),
);
const decodeShellSnapshot = Schema.decodeUnknownEffect(
- Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ShellSnapshot)),
+ Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ShellHttpSnapshot)),
+);
+const decodeShellResumable = Schema.decodeUnknownEffect(
+ Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ShellResumable)),
);
const layerPersistence = EventSink.layer.pipe(
@@ -139,7 +188,7 @@ const layerEnrichment = Layer.unwrap(
return Layer.mock(ProjectEnrichmentService.ProjectEnrichmentService)({
getAvailable: () =>
Effect.succeed({
- repositoryIdentity: null,
+ repositoryIdentity: FLEET_PROJECT_IDENTITY,
faviconPath: null,
repositoryIdentityResolved: true,
}),
@@ -224,30 +273,33 @@ const collectUntil = Effect.fn("transfer.collectUntil")(function* )
+ | ({ readonly shell: true } & Pick);
+function subscriptionStream(
+ client: MeasuredWsClient,
+ subscription: Subscription,
+): Stream.Stream {
+ if ("thread" in subscription) {
+ const { thread, ...resume } = subscription;
+ return client.client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({
+ ...CLIENT_THREAD_SUBSCRIPTION,
+ ...resume,
+ threadId: thread,
+ });
+ }
+ const { shell: _, ...resume } = subscription;
+ return client.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({
+ ...CLIENT_SHELL_SUBSCRIPTION,
+ ...resume,
+ });
+}
const subscribe = Effect.fn("transfer.subscribe")(function* (
client: MeasuredWsClient,
- kind: "thread" | "shell",
- afterSequence: number,
+ subscription: Subscription,
) {
const queue = yield* Queue.unbounded();
- const stream: Stream.Stream =
- kind === "thread"
- ? client.client[ORCHESTRATION_V2_WS_METHODS.subscribeThread]({
- threadId: THREAD_ID,
- afterSequence,
- requestCompletionMarker: true,
- acceptBoundedSnapshot: true,
- acceptCompactTurnItems: true,
- acceptCompactIds: true,
- acceptDedupedBodies: true,
- })
- : client.client[ORCHESTRATION_V2_WS_METHODS.subscribeShell]({
- afterSequence,
- requestCompletionMarker: true,
- omitIdleSubagents: true,
- omitOlderSettled: true,
- });
- yield* stream.pipe(
+ yield* subscriptionStream(client, subscription).pipe(
Stream.runForEach((item) => Queue.offer(queue, item)),
Scope.provide(client.scope),
Effect.forkIn(client.scope),
@@ -324,10 +376,11 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
const shell = yield* openMeasuredWsClient({ url, cookie: "" });
const second = yield* openMeasuredWsClient({ url, cookie: "" });
assert.include(thread.recorder.negotiatedExtensions(), "permessage-deflate");
- const tq = yield* subscribe(thread, "thread", sequence);
- const sq = yield* subscribe(shell, "shell", sequence);
- const ttq = yield* subscribe(second, "thread", sequence);
- const ssq = yield* subscribe(second, "shell", sequence);
+ const fromSnapshot = { afterSequence: sequence };
+ const tq = yield* subscribe(thread, { thread: THREAD_ID, ...fromSnapshot });
+ const sq = yield* subscribe(shell, { shell: true, ...fromSnapshot });
+ const ttq = yield* subscribe(second, { thread: THREAD_ID, ...fromSnapshot });
+ const ssq = yield* subscribe(second, { shell: true, ...fromSnapshot });
for (const queue of [tq, sq, ttq, ssq])
assert.equal(yield* synchronized(queue), "replay");
const threadBefore = thread.recorder.totals();
@@ -376,8 +429,8 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
const reconnectSqlStart = counter.count();
const resumedThread = yield* openMeasuredWsClient({ url, cookie: "" });
const resumedShell = yield* openMeasuredWsClient({ url, cookie: "" });
- const rq = yield* subscribe(resumedThread, "thread", sequence);
- const rsq = yield* subscribe(resumedShell, "shell", sequence);
+ const rq = yield* subscribe(resumedThread, { thread: THREAD_ID, ...fromSnapshot });
+ const rsq = yield* subscribe(resumedShell, { shell: true, ...fromSnapshot });
const threadMode = yield* synchronized(rq);
const shellMode = yield* synchronized(rsq);
const reconnectThread = { ...resumedThread.recorder.totals(), mode: threadMode };
@@ -385,7 +438,6 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
const reconnectSqlStatements = counter.count() - reconnectSqlStart;
assert.equal(threadMode, "snapshot");
- for (const events of longTurnThreadBatches(provider)) yield* sink.write({ events });
const get = (path: string) =>
measureHttpGet({
url: `${base}${path}`,
@@ -398,8 +450,9 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
Effect.gen(function* () {
const http = yield* get(`${longTurnPath}/bounded?${query}`);
const snapshot = yield* decodeBoundedSnapshot(decoded(http));
- const rows = snapshot.projection.visibleTurnItems.length;
- return { http, rows, cursor: snapshot.historyCursor };
+ const rows = snapshot.projection.visibleTurnItems;
+ const workAnchor = rows.find((row) => row.item.deferredWork !== undefined);
+ return { http, rows: rows.length, cursor: snapshot.historyCursor, workAnchor };
});
const readHistoryPage = (cursor: string, query: string) =>
Effect.gen(function* () {
@@ -413,18 +466,82 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
const readShell = (query: string) =>
Effect.gen(function* () {
const http = yield* get(`/api/orchestration/shell?${query}`);
- return { http, rows: (yield* decodeShellSnapshot(decoded(http))).threads.length };
+ const { threads, snapshotSequence, projectIdentities } = yield* decodeShellSnapshot(
+ decoded(http),
+ );
+ return { http, rows: threads.length, snapshotSequence, projectIdentities };
});
+ // A new socket, read until the subscription caught up or the server ended it.
+ const open = (subscription: Subscription) =>
+ Effect.gen(function* () {
+ const socket = yield* openMeasuredWsClient({ url, cookie: "" });
+ const items = yield* subscriptionStream(socket, subscription).pipe(
+ Stream.takeUntil((item) => item.kind === "synchronized"),
+ Stream.runCollect,
+ Scope.provide(socket.scope),
+ Effect.orDie,
+ );
+ const totals = socket.recorder.totals();
+ yield* socket.close;
+ return { kinds: items.map((item) => item.kind), items, totals };
+ });
+
+ // A phone that comes back after one ordinary turn replays it, without tool bodies.
+ const shortTurn = yield* sink.write({
+ events: turnEvents(provider, TRANSFER_HISTORY_TURN_COUNT + 1, false),
+ });
+ const shortTurnResume = yield* open({ thread: THREAD_ID, afterSequence: last.sequence });
+ assert.notInclude(shortTurnResume.kinds, "snapshot");
+ // The byte cap below also passes when the resume skips the turn.
+ assert.isTrue(
+ shortTurnResume.items.some(
+ (item) => "sequence" in item && item.sequence === shortTurn.at(-1)!.sequence,
+ ),
+ );
- const { cursor: _, ...longTurnColdOpenLegacy } =
- yield* readColdOpen("compactTurnItems=1");
- const { cursor, ...longTurnColdOpen } = yield* readColdOpen(CLIENT_BOUNDED_QUERY);
+ // A turn that is still running cannot defer its work, so it loads in row-budget windows.
+ const [finishLongTurn, ...longTurnHistory] = longTurnThreadBatches(provider).toReversed();
+ for (const events of longTurnHistory.toReversed()) yield* sink.write({ events });
+ const longTurnRunningColdOpenLegacy = yield* readColdOpen("compactTurnItems=1");
+ const longTurnRunningColdOpen = yield* readColdOpen(CLIENT_BOUNDED_QUERY);
+ const { cursor } = longTurnRunningColdOpen;
if (cursor === null) return yield* Effect.die("Expected older long-turn history");
- const longTurnHistoryPageLegacy = yield* readHistoryPage(cursor, "");
- const longTurnHistoryPage = yield* readHistoryPage(cursor, CLIENT_HISTORY_QUERY);
+ const longTurnRunningHistoryPageLegacy = yield* readHistoryPage(cursor, "");
+ const longTurnRunningHistoryPage = yield* readHistoryPage(cursor, CLIENT_HISTORY_QUERY);
+
+ // Once it finishes, its work stays on the server until a group is expanded.
+ yield* sink.write({ events: finishLongTurn! });
+ const longTurnColdOpen = yield* readColdOpen(CLIENT_BOUNDED_QUERY);
+ const { workAnchor } = longTurnColdOpen;
+ if (workAnchor?.item.deferredWork === undefined)
+ return yield* Effect.die("Expected the finished long turn to defer its work");
+ const longTurnWorkPage = yield* readHistoryPage(
+ workAnchor.item.deferredWork.cursor,
+ `view=work&throughEntryId=${encodeURIComponent(workAnchor.sourceItemId)}&compactIds=1`,
+ );
+ // Mobile opens a thread over the socket alone.
+ const socketOpen = yield* open({ thread: LONG_TURN_THREAD_ID });
+ const socketSnapshot = socketOpen.items.find(
+ (item) => item.kind === "snapshot" && "projection" in item,
+ );
+ if (socketSnapshot?.kind !== "snapshot" || !("projection" in socketSnapshot))
+ return yield* Effect.die("Expected a bounded socket snapshot");
+ const longTurnSocketColdOpen = {
+ ...socketOpen,
+ rows: socketSnapshot.projection.visibleTurnItems.length,
+ };
+ // The row cap below also passes when the socket ignores the deferral and sends a window.
+ assert.equal(longTurnSocketColdOpen.rows, longTurnColdOpen.rows);
+ const idleThreadResume = yield* open({
+ thread: LONG_TURN_THREAD_ID,
+ afterSequence: socketSnapshot.snapshotSequence,
+ });
+ assert.deepEqual(idleThreadResume.kinds, ["synchronized"]);
// The transfer thread plus the long-turn thread.
const earlierThreads = decodedShell.threads.length + 1;
+ // The fleet's project is in a repository. Earlier phases have no project, as on `main`.
+ yield* (yield* ProjectStore.ProjectStoreV2).apply(fleetProjectCreated);
yield* sink.write({ events: shellFleetEvents(provider) });
const fleetShellLegacy = yield* readShell("");
const fleetShell = yield* readShell(CLIENT_SHELL_QUERY);
@@ -432,6 +549,33 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
fleetShellLegacy.rows,
earlierThreads + SHELL_SETTLED_THREADS + SHELL_IDLE_SUBAGENTS,
);
+ const { projectIdentities } = fleetShell;
+ if (projectIdentities === undefined)
+ return yield* Effect.die("Expected the shell snapshot to name its project identities");
+ // A cold connect subscribes from the snapshot it just loaded and names its identities.
+ // Without them the resume sends the project again, in a marked snapshot.
+ const fleetShellSubscribe = yield* open({
+ shell: true,
+ afterSequence: fleetShell.snapshotSequence,
+ knownProjectIdentities: projectIdentities,
+ });
+ assert.notInclude(fleetShellSubscribe.kinds, "snapshot");
+ // A client that holds those rows asks the route whether they still resume, and keeps them.
+ const fleetShellResumeHttp = yield* get(
+ `/api/orchestration/shell?${clientShellResumeQuery(fleetShell.snapshotSequence)}`,
+ );
+ yield* decodeShellResumable(decoded(fleetShellResumeHttp));
+ const fleetShellResume = { http: fleetShellResumeHttp, rows: 0 };
+ // A cursor too old to replay gets the snapshot in the same answer.
+ const staleShellReload = yield* readShell(clientShellResumeQuery(sequence));
+ assert.equal(staleShellReload.rows, fleetShell.rows);
+ // When that request fails, the socket tells the client to reload, with no snapshot.
+ const staleShellResume = yield* open({
+ shell: true,
+ afterSequence: sequence,
+ httpSnapshotFallback: true,
+ });
+ assert.deepEqual(staleShellResume.kinds, ["snapshot-required"]);
for (const events of staleTodoListThreadBatches(provider)) yield* sink.write({ events });
const staleTodoHttp = yield* get(
@@ -472,12 +616,21 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
reconnectThread,
reconnectShell,
reconnectSqlStatements,
- longTurnColdOpenLegacy,
+ shortTurnResume,
+ longTurnRunningColdOpenLegacy,
+ longTurnRunningColdOpen,
+ longTurnRunningHistoryPageLegacy,
+ longTurnRunningHistoryPage,
longTurnColdOpen,
- longTurnHistoryPageLegacy,
- longTurnHistoryPage,
+ longTurnWorkPage,
+ longTurnSocketColdOpen,
+ idleThreadResume,
fleetShellLegacy,
fleetShell,
+ fleetShellSubscribe,
+ fleetShellResume,
+ staleShellReload,
+ staleShellResume,
staleTodoColdOpen,
} satisfies TransferBudgetRun;
}).pipe(
@@ -492,10 +645,14 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () =>
const outputPaths = yield* Config.all({
report: Config.String("T3CODE_TRANSFER_BUDGET_REPORT_PATH").pipe(Config.withDefault("")),
result: Config.String("T3CODE_TRANSFER_BUDGET_RESULT_PATH").pipe(Config.withDefault("")),
+ scenarios: Config.String("T3CODE_TRANSFER_BUDGET_SCENARIOS_PATH").pipe(
+ Config.withDefault(""),
+ ),
});
for (const [path, contents] of [
[outputPaths.report, report],
[outputPaths.result, formatTransferBudgetResult(runs)],
+ [outputPaths.scenarios, formatTransferBudgetScenarios(runs)],
])
if (path && contents) yield* fs.writeFileString(path, contents);
yield* Effect.log(report);
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 0bc1387ea7c1b..1f56d49c88b04 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -291,6 +291,8 @@ export const make = Effect.gen(function* () {
linkFence: true,
mcpApprovalCodes: true,
mcpHostedApproval: true,
+ shellThreadFamilies: true,
+ shellOlderSettled: true,
},
};
diff --git a/apps/server/src/httpResponseErrorGuard.test.ts b/apps/server/src/httpResponseErrorGuard.test.ts
index ed3c7e65c7974..7227e03dade0a 100644
--- a/apps/server/src/httpResponseErrorGuard.test.ts
+++ b/apps/server/src/httpResponseErrorGuard.test.ts
@@ -125,6 +125,83 @@ describe("guardHttpResponseWriteErrors", () => {
});
});
+describe("keepIdleConnections", () => {
+ it("closes a connection whose response finishes after the server stopped listening", async () => {
+ const server = HttpResponseErrorGuard.keepIdleConnections(NodeHttp.createServer());
+ const body = "x".repeat(1_000_000);
+ const closed = Promise.withResolvers();
+ server.on("request", (_request, response) => {
+ // The server shuts down while this request is in flight.
+ server.close(() => closed.resolve());
+ response.end(body);
+ });
+ const port = await listen(server);
+ const agent = new NodeHttp.Agent({ keepAlive: true });
+
+ const received = await new Promise((resolve, reject) => {
+ const request = NodeHttp.get({ host: "127.0.0.1", port, agent }, (response) => {
+ let bytes = 0;
+ response.on("data", (chunk: Buffer) => {
+ bytes += chunk.length;
+ });
+ response.on("end", () => resolve(bytes));
+ response.on("error", reject);
+ });
+ requests.push(request);
+ request.on("error", reject);
+ });
+
+ expect(received).toBe(body.length);
+ // Left alone, the kept-alive connection holds the server open for the keep-alive time.
+ await closed.promise;
+ agent.destroy();
+ });
+
+ it("keeps a connection until every response on it has finished", async () => {
+ const server = HttpResponseErrorGuard.keepIdleConnections(NodeHttp.createServer());
+ const closed = Promise.withResolvers();
+ // Larger than a socket buffer, so it still has output to send after `end`.
+ const thirdBody = "x".repeat(8_000_000);
+ const held: NodeHttp.ServerResponse[] = [];
+ server.on("request", (request, response) => {
+ if (request.url !== "/third") {
+ held.push(response);
+ return;
+ }
+ const [first, second] = held;
+ // All three pipelined requests are in flight when the server shuts down. The third
+ // response is ended before the first two, and the second ends after the first.
+ response.end(thirdBody);
+ server.close(() => closed.resolve());
+ first?.once("finish", () => setImmediate(() => second?.end("second-body")));
+ first?.end("first-body");
+ });
+ const port = await listen(server);
+
+ const received = await new Promise((resolve, reject) => {
+ let data = "";
+ const client = NodeNet.connect(port, "127.0.0.1", () => {
+ client.write(
+ ["/first", "/second", "/third"]
+ .map((path) => `GET ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n`)
+ .join(""),
+ );
+ });
+ sockets.push(client);
+ client.on("data", (chunk: Buffer) => {
+ data += chunk.toString();
+ });
+ client.on("end", () => resolve(data));
+ client.on("error", reject);
+ });
+
+ expect(received.slice(0, 1_000)).toContain("first-body");
+ expect(received.slice(0, 1_000)).toContain("second-body");
+ expect(received.endsWith(thirdBody)).toBe(true);
+ await closed.promise;
+ });
+});
+
describe("rejectRequestsUntilServing", () => {
it("rejects early HTTP and upgrades, then hands each off to its serving handler", async () => {
const writeErrors: unknown[] = [];
diff --git a/apps/server/src/httpResponseErrorGuard.ts b/apps/server/src/httpResponseErrorGuard.ts
index 0f215ba797f87..c75ccae660a55 100644
--- a/apps/server/src/httpResponseErrorGuard.ts
+++ b/apps/server/src/httpResponseErrorGuard.ts
@@ -20,6 +20,32 @@ export function guardHttpResponseWriteErrors(
return server;
}
+// cloudflared and Tailscale serve keep an idle connection to this server for 90
+// seconds. Node's 5 second default closes it first, so they can send a request
+// into a closed connection, and a slow client reconnects in the middle of a connect.
+const HTTP_KEEP_ALIVE_TIMEOUT_MS = 95_000;
+
+/** Install before `rejectRequestsUntilServing`, whose handoff starts at the next request listener. */
+export function keepIdleConnections(server: T): T {
+ server.keepAliveTimeout = HTTP_KEEP_ALIVE_TIMEOUT_MS;
+ // `close` drops only the connections idle at that moment. One that finishes
+ // its responses later would hold shutdown for the whole keep-alive time.
+ // `closeIdleConnections` cannot do this: it destroys a socket whose next
+ // pipelined response is ended but still has output to send.
+ const responsesInFlight = new WeakMap