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(); + server.on("request", (request, response) => { + const socket = request.socket; + responsesInFlight.set(socket, (responsesInFlight.get(socket) ?? 0) + 1); + response.once("close", () => { + const left = (responsesInFlight.get(socket) ?? 1) - 1; + responsesInFlight.set(socket, left); + // Pipelined requests share the socket, so the last response ends it. + if (left === 0 && !server.listening) socket.end(); + }); + }); + return server; +} + /** * NodeHttpServer listens before serve() attaches its handlers, so requests in * between would hang. Install this after the write-error guards so only the diff --git a/apps/server/src/mcp/toolkits/core.test.ts b/apps/server/src/mcp/toolkits/core.test.ts index 99937d68b80d3..9682a45f5e592 100644 --- a/apps/server/src/mcp/toolkits/core.test.ts +++ b/apps/server/src/mcp/toolkits/core.test.ts @@ -10,6 +10,7 @@ import { EnvironmentId, NodeId, OrchestratorMcpThreadReadResult, + ProjectId, ProviderDriverKind, ProviderInstanceId, RunId, @@ -59,6 +60,7 @@ import * as AnalyticsService from "../../telemetry/AnalyticsService.ts"; import { dispatchFailure } from "../threadAccess.ts"; import * as EnvironmentHandlers from "./environment/handlers.ts"; import * as AttachmentHandlers from "./attachment/handlers.ts"; +import { ThreadToolkit } from "./thread/tools.ts"; import * as PeerForwarding from "../../peer/PeerForwarding.ts"; import * as PeerLinkRequests from "../../peer/PeerLinkRequests.ts"; import * as PeerLinks from "../../peer/PeerLinks.ts"; @@ -76,6 +78,9 @@ import { htmlRenderFromToolItem } from "@t3tools/shared/toolOutput"; const decodeMcpAttachmentInput = Schema.decodeUnknownEffect(McpAttachmentInput); const decodeThreadReadResult = Schema.decodeUnknownEffect(OrchestratorMcpThreadReadResult); +const decodeThreadSearchResult = Schema.decodeUnknownEffect( + ThreadToolkit.tools.t3_thread_search.successSchema, +); const layerThreadToolkit = McpHttpServer.layerThreadToolkit.pipe( Layer.provide(Layer.mock(ThreadSearch.ThreadSearch)({})), @@ -589,6 +594,59 @@ it.effect("a client caller targets any thread within its ceiling and cannot act ), ); +it.effect("search names the calling thread, so an agent can tell its own match apart", () => + Effect.gen(function* () { + const server = yield* McpServer.McpServer; + const search = (invocation: McpInvocationContext.McpInvocationScope) => + server + .callTool({ name: "t3_thread_search", arguments: { query: "release notes" } }) + .pipe( + Effect.provideService(McpInvocationContext.McpInvocationContext, invocation), + Effect.provideService(McpSchema.McpServerClient, client), + ); + + const fromThread = yield* search(scope); + expect(fromThread.structuredContent).toMatchObject({ + currentThreadId: threadId, + matches: [{ threadId }, { threadId: "earlier-thread" }], + }); + + const fromClient = yield* search(clientScope("auto")); + expect(fromClient.structuredContent).toMatchObject({ currentThreadId: null }); + + // A linked environment on an older version answers without the field. + const fromOlderPeer = yield* decodeThreadSearchResult({ matches: [] }); + expect(fromOlderPeer).toEqual({ matches: [] }); + }).pipe( + Effect.provide( + McpHttpServer.layerThreadToolkit.pipe( + Layer.provideMerge(McpHttpServer.layerInProcessMcpServer), + Layer.provide(NodeCrypto.layer), + Layer.provide(McpToolAccessTestkit.liveThreadsLayer), + Layer.provide( + Layer.mock(ThreadSearch.ThreadSearch)({ + searchThreads: () => + Effect.succeed({ + matches: [threadId, ThreadId.make("earlier-thread")].map((id) => ({ + threadId: id, + projectId: ProjectId.make("project:mcp-test"), + title: "Release notes", + source: "title" as const, + snippet: "", + messageCreatedAt: null, + })), + }), + }), + ), + Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})), + Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})), + Layer.provide(Layer.mock(PeerLinkRequests.PeerLinkRequests)({})), + Layer.provide(Layer.mock(PeerLinks.PeerLinks)({})), + ), + ), + ), +); + it.effect("a read-only client reads threads and is refused every write before it runs", () => Effect.gen(function* () { const server = yield* McpServer.McpServer; diff --git a/apps/server/src/mcp/toolkits/thread/handlers.ts b/apps/server/src/mcp/toolkits/thread/handlers.ts index 32e45b5d0a1c0..62023dd986b55 100644 --- a/apps/server/src/mcp/toolkits/thread/handlers.ts +++ b/apps/server/src/mcp/toolkits/thread/handlers.ts @@ -132,6 +132,7 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, { .searchThreads({ ...input, projectId: input.projectId ?? caller?.projectId }) .pipe(Effect.mapError(unavailable)); return { + currentThreadId: scope.thread?.threadId ?? null, matches: matches.map((match) => ({ ...match, link: McpInvocationContext.threadLinkFor(scope, match.threadId, match.title), diff --git a/apps/server/src/mcp/toolkits/thread/tools.ts b/apps/server/src/mcp/toolkits/thread/tools.ts index c6670c4e953d3..750bf15afc019 100644 --- a/apps/server/src/mcp/toolkits/thread/tools.ts +++ b/apps/server/src/mcp/toolkits/thread/tools.ts @@ -199,6 +199,7 @@ const ThreadSearchTool = Tool.make("t3_thread_search", { projectId: Schema.optional(ProjectId), }), success: Schema.Struct({ + currentThreadId: Schema.optional(Schema.NullOr(ThreadId)), matches: Schema.Array( Schema.Struct({ threadId: OrchestrationThreadSearchMatch.fields.threadId, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index fb51465629018..9083cbba80d92 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -521,6 +521,10 @@ const isProviderAdapterProtocolError = Schema.is(ProviderAdapter.ProviderAdapter const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { readonly environment: (runtimeOrdinal: number) => Readonly>; readonly runtimeMode?: "full-access" | "approval-required"; + readonly wrapPrompt?: ( + prompt: AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"], + ) => AcpSessionRuntime.AcpSessionRuntime["Service"]["prompt"]; + readonly cancelled?: Deferred.Deferred; }) { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; const path = yield* Path.Path; @@ -540,7 +544,14 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { environment: input.environment, wrapRuntime: (runtime) => { natives.push(runtime); - return runtime; + return { + ...runtime, + prompt: input.wrapPrompt?.(runtime.prompt) ?? runtime.prompt, + cancel: + input.cancelled === undefined + ? runtime.cancel + : Deferred.succeed(input.cancelled, undefined).pipe(Effect.andThen(runtime.cancel)), + }; }, }), }, @@ -571,6 +582,7 @@ const makePromptInactivityHarness = Effect.fnUntraced(function* (input: { return { runtime, natives, + providerThread, startTurn, /** A turn still running makes the next start fail, without waiting on time. */ nextTurnRejected: (ordinal: number) => @@ -4097,6 +4109,90 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + it.effect("delivers a follow-up the agent rejects while it is still processing", () => + Effect.gen(function* () { + let promptCalls = 0; + const rejected = yield* Deferred.make(); + const harness = yield* makePromptInactivityHarness({ + environment: () => ({}), + // pi-agent-core based agents (oh-my-pi) end a turn but keep background work running. + wrapPrompt: (prompt) => (payload, options) => { + promptCalls += 1; + return promptCalls === 2 + ? Deferred.succeed(rejected, undefined).pipe( + Effect.andThen( + Effect.fail( + EffectAcpErrors.AcpRequestError.internalError( + "Agent is already processing. Use steer() or followUp() to queue messages, or wait for completion.", + ), + ), + ), + ) + : prompt(payload, options); + }, + }); + yield* harness.startTurn(1); + const [first] = yield* harness.terminals(1); + assert.equal(first?.status, "completed"); + + const followUp = yield* harness.terminals(1).pipe(Effect.forkScoped); + yield* harness.startTurn(2); + yield* Deferred.await(rejected); + yield* TestClock.adjust("1 minute"); + const [delivered] = yield* Fiber.join(followUp); + assert.equal(delivered?.status, "completed"); + assert.equal(promptCalls, 3); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + + it.effect("sends no more prompts once a follow-up waiting on a busy agent is stopped", () => + Effect.gen(function* () { + let promptCalls = 0; + const rejected = yield* Deferred.make(); + const cancelled = yield* Deferred.make(); + const harness = yield* makePromptInactivityHarness({ + environment: () => ({}), + cancelled, + wrapPrompt: (prompt) => (payload, options) => { + promptCalls += 1; + return promptCalls === 1 + ? prompt(payload, options) + : Deferred.succeed(rejected, undefined).pipe( + Effect.andThen( + Effect.fail( + EffectAcpErrors.AcpRequestError.internalError( + "Agent is already processing. Use steer() or followUp() to queue messages, or wait for completion.", + ), + ), + ), + ); + }, + }); + yield* harness.startTurn(1); + yield* harness.terminals(1); + + const stopped = yield* harness.terminals(1).pipe(Effect.forkScoped); + yield* harness.startTurn(2); + yield* Deferred.await(rejected); + const providerTurnId = (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({ + driver: ACP_TEST_DRIVER, + nativeTurnId: acpScopedNativeId( + ProviderInstanceId.make("acp-prompt-inactivity"), + "mock-session-1:turn:2", + ), + }); + const interrupt = yield* harness.runtime + .interruptTurn({ providerThread: harness.providerThread, providerTurnId }) + .pipe(Effect.forkScoped); + yield* Deferred.await(cancelled); + yield* TestClock.adjust("1 second"); + const [terminal] = yield* Fiber.join(stopped); + yield* Fiber.join(interrupt); + assert.equal(terminal?.status, "interrupted"); + assert.equal(promptCalls, 2); + }).pipe(Effect.provide(layerTest), Effect.scoped), + ); + it.effect("holds the inactivity timeout while the agent waits on an approval", () => Effect.gen(function* () { const harness = yield* makePromptInactivityHarness({ diff --git a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts index e17d6f084a931..635d63d91473a 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.test.ts @@ -23,6 +23,7 @@ import * as Stream from "effect/Stream"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import * as HttpClient from "effect/http/HttpClient"; @@ -471,6 +472,7 @@ describe("AcpRegistryAdapterV2", () => { const openWithStoredPicks = Effect.fn("openWithStoredPicks")(function* (input: { readonly setup: unknown; readonly pickFrames: ReadonlyArray; + readonly agentId?: string; readonly customModels?: ReadonlyArray; readonly storedModel?: string; readonly storedModePick?: string; @@ -478,6 +480,7 @@ describe("AcpRegistryAdapterV2", () => { readonly rejectedModel?: string; readonly storedOptions?: ReadonlyArray<{ readonly id: string; readonly value: string }>; readonly failsConfiguration?: boolean; + readonly liveConfiguration?: AcpRegistryLiveConfiguration; }) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; // Scope release gives the replay agent at most a second to exit, so the status @@ -524,7 +527,7 @@ describe("AcpRegistryAdapterV2", () => { selfInvocation: yield* resolveSelfInvocation(), instanceId, settings: yield* decodeAcpRegistryAdapterSettings({ - agentId: "fixture-agent", + agentId: input.agentId ?? "fixture-agent", authMethodId: "test", customModels: input.customModels ?? [], }), @@ -545,6 +548,8 @@ describe("AcpRegistryAdapterV2", () => { layerInjectedRuntimeCatalog, Layer.mock(AcpRegistryRuntimeCoordinator.AcpRegistryRuntimeCoordinator)({ withForegroundStartup: (_startupKey, effect) => effect, + getLiveConfiguration: () => + Effect.sync(() => Option.fromUndefinedOr(published ?? input.liveConfiguration)), publishLiveConfiguration: (_instanceId, configuration) => Effect.sync(() => { published = configuration; @@ -799,6 +804,85 @@ describe("AcpRegistryAdapterV2", () => { }).pipe(Effect.provide(layerTest), Effect.scoped), ); + // Copilot's session/new reports its built-in default, not the model it will run + // (github/copilot-cli#5363), so the selected model must be written even when it matches, + // and an unset effort gets the value the composer shows. + it.effect( + "writes the selected Copilot model and the shown effort when session/new reports defaults", + () => { + const copilotModel = (currentValue: string) => ({ + ...modelOption("model", currentValue), + options: ["claude-sonnet-5.5", "claude-haiku-4.5"].map((value) => ({ + value, + name: value, + })), + }); + const effort = (currentValue: string) => ({ + id: "reasoning_effort", + name: "Reasoning effort", + category: "thought_level", + type: "select", + currentValue, + options: ["medium", "xhigh"].map((value) => ({ value, name: value })), + }); + return openWithStoredPicks({ + agentId: "github-copilot-cli", + setup: { configOptions: [copilotModel("claude-sonnet-5.5"), effort("medium")] }, + storedModel: "claude-sonnet-5.5", + liveConfiguration: { + models: [], + currentModelId: null, + configOptions: [ + { + id: "reasoning_effort", + label: "Reasoning effort", + type: "select", + role: "reasoning", + currentValue: "xhigh", + options: [ + { id: "medium", label: "medium" }, + { id: "xhigh", label: "xhigh" }, + ], + }, + ], + }, + pickFrames: [ + // The new session's own update replaces the shared live configuration. + { + type: "emit_inbound", + frame: { + kind: "notification", + method: "session/update", + params: { + sessionId: "agent-session", + update: { + sessionUpdate: "config_option_update", + configOptions: [copilotModel("claude-sonnet-5.5"), effort("medium")], + }, + }, + }, + }, + outbound("session/set_config_option", { + sessionId: "agent-session", + configId: "model", + value: "claude-sonnet-5.5", + }), + answer("session/set_config_option", { + configOptions: [copilotModel("claude-sonnet-5.5"), effort("medium")], + }), + outbound("session/set_config_option", { + sessionId: "agent-session", + configId: "reasoning_effort", + value: "xhigh", + }), + answer("session/set_config_option", { + configOptions: [copilotModel("claude-sonnet-5.5"), effort("xhigh")], + }), + ], + }).pipe(Effect.provide(layerTest), Effect.scoped); + }, + ); + it.effect.each([ "config", "legacy", diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 1efbbfad09d81..acfbdad41ea8e 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -496,6 +496,21 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect("never sends a saved variant the catalog model does not list", () => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed([ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.execution.succeeded", { sessionID: SESSION }), + ]); + const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped); + yield* runtime.startTurn( + turnInput(thread, { ...bigPickle, options: [{ id: "variant", value: "medium" }] }), + ); + assert.equal((yield* Fiber.join(terminal))?.status, "completed"); + }).pipe(Effect.scoped), + ); + it.effect("renames the session before the first turn after the thread was renamed", () => Effect.gen(function* () { const { runtime, thread } = yield* resumed([ diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index c61f9bc175edc..e5ef81ad46b54 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -174,8 +174,13 @@ it.effect.each([ { order: "cleanup-first", restoreFiles: true }, { order: "rollback-first", restoreFiles: true }, { order: "cleanup-first", restoreFiles: false, unmanaged: true }, -])("locks rollback with %s", ({ order, restoreFiles, unmanaged = false }) => + { order: "cleanup-first", restoreFiles: true, leavesFolder: true }, + { order: "cleanup-first", restoreFiles: false, leavesFolder: true }, + { order: "cleanup-first", restoreFiles: true, leavesFolder: true, shared: true }, + { order: "cleanup-first", restoreFiles: true, leavesFolder: true, createFails: true }, +])("locks rollback with %s", (row) => Effect.gen(function* () { + const { order, restoreFiles, unmanaged, leavesFolder, shared, createFails } = row; const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; const workspaceRoot = yield* fileSystem.realPath( @@ -185,7 +190,7 @@ it.effect.each([ const worktreePath = unmanaged ? path.join(workspaceRoot, "elsewhere", "feature") : path.join(worktreesDir, "repo", "feature"); - yield* fileSystem.makeDirectory(worktreePath, { recursive: true }); + yield* fileSystem.makeDirectory(path.join(worktreePath, ".git"), { recursive: true }); const threadId = ThreadId.make("rollback-worktree"); const projectId = ProjectId.make("rollback-worktree-project"); const providerThreadId = ProviderThreadId.make("rollback-worktree-provider-thread"); @@ -246,14 +251,19 @@ it.effect.each([ path: worktreePath, }); calls.push("create"); - yield* fileSystem.makeDirectory(worktreePath).pipe(Effect.orDie); + if (createFails) return yield* Effect.die("the branch is gone"); + yield* fileSystem + .makeDirectory(path.join(worktreePath, ".git"), { recursive: true }) + .pipe(Effect.orDie); return {} as never; }), }), Layer.mock(CheckpointService.CheckpointServiceV2)({ restore: () => Effect.gen(function* () { - assert.isTrue(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie)); + assert.isTrue( + yield* fileSystem.exists(path.join(worktreePath, ".git")).pipe(Effect.orDie), + ); calls.push("files"); }), }), @@ -272,16 +282,31 @@ it.effect.each([ Effect.succeed({ schemaVersion: 1, snapshotSequence: 0, - threads: [], + threads: shared + ? [ + { + id: ThreadId.make("rollback-worktree-sharer"), + projectId, + worktreePath, + deletedAt: null, + lineage: {}, + }, + ] + : [], archivedThreads: [], - }), + } as never), + getCheckpointContext: () => Effect.succeed({ checkpointScopes: [] } as never), + getThreadProviderContext: () => Effect.succeed({ providerSessions: [] } as never), }), Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({ open: (input) => Effect.gen(function* () { assert.equal(input.runtimePolicy.cwd, worktreePath); if (!(yield* fileSystem.exists(worktreePath).pipe(Effect.orDie))) { - return yield* new ProviderWorkspaceMissingError({ threadId, cwd: worktreePath }); + return yield* new ProviderWorkspaceMissingError({ + threadId, + cwd: worktreePath, + }); } calls.push("session"); yield* Deferred.succeed(openEntered, undefined); @@ -306,6 +331,11 @@ it.effect.each([ cleanupEntered = true; if (order === "cleanup-first") yield* Deferred.await(release); yield* fileSystem.remove(worktreePath, { recursive: true, force: true }); + // A failed `git worktree remove` can leave the folder without its checkout. + if (leavesFolder) { + yield* fileSystem.makeDirectory(worktreePath); + yield* fileSystem.writeFileString(path.join(worktreePath, "unsaved.txt"), "keep"); + } calls.push("cleanup"); }), ); @@ -325,10 +355,24 @@ it.effect.each([ if (order === "rollback-first") assert.isFalse(cleanupEntered); yield* Deferred.succeed(release, undefined); if (cleanup !== undefined) yield* Fiber.join(cleanup); - if (unmanaged) { + if (unmanaged || shared) { const error = yield* Fiber.join(rollback).pipe(Effect.flip); assert.equal(error._tag, "CheckpointRollbackExecutionError"); assert.deepEqual(calls, ["cleanup"]); + if (shared) { + assert.equal(error.reason, "shared-workspace"); + assert.isTrue(yield* fileSystem.exists(path.join(worktreePath, "unsaved.txt"))); + } + return; + } + if (createFails) { + yield* Fiber.join(rollback).pipe(Effect.exit); + assert.deepEqual(calls, ["cleanup", "prune", "create"]); + assert.equal( + yield* fileSystem.readFileString(path.join(worktreePath, "unsaved.txt")), + "keep", + ); + assert.deepEqual(yield* fileSystem.readDirectory(path.dirname(worktreePath)), ["feature"]); return; } yield* Fiber.join(rollback); @@ -336,12 +380,16 @@ it.effect.each([ const rollbackCalls = restoreFiles ? ["session", "files", "projection"] : ["session", "projection"]; + const recreates = !leavesFolder || restoreFiles; assert.deepEqual( calls, order === "cleanup-first" - ? ["cleanup", "prune", "create", ...rollbackCalls] + ? ["cleanup", ...(recreates ? ["prune", "create"] : []), ...rollbackCalls] : [...rollbackCalls, "cleanup"], ); + if (!recreates) { + assert.isTrue(yield* fileSystem.exists(path.join(worktreePath, "unsaved.txt"))); + } }).pipe(Effect.provide(testLayer)); }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)), ); diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index 4d40641fa54db..16cbe8b101e28 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -10,6 +10,7 @@ import { import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; @@ -217,42 +218,87 @@ export const layer: Layer.Layer< }; }); - const { worktreePath, branch } = context.thread; - // Recreated only where the server would have made it, as turn start does. - if ( - worktreePath != null && - branch != null && - !(yield* fileSystem.exists(worktreePath)) && - (yield* isManagedWorktreePath(worktreePath)) - ) { - const project = yield* projects.get(context.thread.projectId); - if (Option.isSome(project)) { - yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }); - yield* gitWorkflow.createWorktree({ - cwd: project.value.workspaceRoot, - refName: branch, - path: worktreePath, - }); - } - } - - if ( - input.restoreFiles !== false && - !(yield* isCheckpointRestoreIsolated(context.thread, scope, { - fileSystem, - projections, - projects, - path, - })) - ) { - return yield* new CheckpointRollbackExecutionError({ + const restoreFiles = input.restoreFiles !== false; + const isolated = isCheckpointRestoreIsolated(context.thread, scope, { + fileSystem, + projections, + projects, + path, + }); + const sharedWorkspace = () => + new CheckpointRollbackExecutionError({ reason: "shared-workspace", threadId: input.threadId, providerThreadId: input.providerThreadId, checkpointId: input.checkpointId, }); + + const { worktreePath, branch } = context.thread; + // Recreated only where the server would have made it, as turn start does. + if (worktreePath != null && branch != null) { + // A failed removal can leave the folder without its checkout; only a file restore replaces it. + const leftover = + restoreFiles && + (yield* fileSystem.exists(worktreePath)) && + !(yield* fileSystem.exists(path.join(worktreePath, ".git"))); + if ( + (leftover || !(yield* fileSystem.exists(worktreePath))) && + (yield* isManagedWorktreePath(worktreePath)) + ) { + const project = yield* projects.get(context.thread.projectId); + if (Option.isSome(project)) { + const recreate = gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }).pipe( + Effect.andThen( + gitWorkflow.createWorktree({ + cwd: project.value.workspaceRoot, + refName: branch, + path: worktreePath, + }), + ), + ); + if (leftover) { + if (!(yield* isolated)) return yield* sharedWorkspace(); + // Set aside, not removed: a checkout that fails puts the folder and its files back. + yield* Effect.acquireUseRelease( + Effect.gen(function* () { + const aside = yield* fileSystem.makeTempDirectory({ + directory: path.dirname(worktreePath), + prefix: ".t3-replaced-", + }); + yield* fileSystem.rename(worktreePath, path.join(aside, "folder")); + return aside; + }), + () => recreate, + (aside, exit) => + (Exit.isSuccess(exit) + ? Effect.void + : fileSystem + .remove(worktreePath, { recursive: true, force: true }) + .pipe( + Effect.andThen( + fileSystem.rename(path.join(aside, "folder"), worktreePath), + ), + ) + ).pipe( + Effect.andThen(fileSystem.remove(aside, { recursive: true, force: true })), + Effect.catchCause((cause) => + Effect.logWarning("Edit from here left a worktree folder set aside", { + worktreePath, + setAside: path.join(aside, "folder"), + cause, + }), + ), + ), + ); + } else { + yield* recreate; + } + } + } } + if (restoreFiles && !(yield* isolated)) return yield* sharedWorkspace(); + const modelSelection = context.thread.modelSelection; const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ thread: context.thread, diff --git a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts index 117a7898a601f..f7773665aa9b0 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.control-reads.test.ts @@ -844,6 +844,21 @@ it.effect( (yield* Effect.exit(projections.getThreadRecords(threadId, ["contextTransfers"])))._tag, "Failure", ); + // A delegated task that ended and handed its result over. + yield* sql`INSERT INTO orchestration_v2_projection_subagents + (subagent_id, thread_id, run_id, parent_node_id, provider, provider_thread_id, + child_thread_id, origin, status, updated_at, payload_json, completion_delivery_state) + VALUES ('obsolete-task', ${threadId}, 'old-run', 'old-node', 'codex', 'obsolete-task-thread', + 'old-child', 'app_owned', 'completed', ${DateTime.formatIso(now)}, '{"obsolete":true}', + 'delivered')`; + yield* sql`INSERT INTO orchestration_v2_projection_nodes + (node_id, thread_id, run_id, root_node_id, kind, status, payload_json) + VALUES ('obsolete-task', ${threadId}, 'old-run', 'old-node', 'subagent', 'completed', + '{"obsolete":true}')`; + yield* sql`INSERT INTO orchestration_v2_projection_provider_threads + (provider_thread_id, thread_id, provider, status, updated_at, payload_json) + VALUES ('obsolete-task-thread', 'old-child', 'codex', 'idle', ${DateTime.formatIso(now)}, + '{"obsolete":true}')`; yield* orchestrator.dispatch({ type: "message.dispatch", commandId: CommandId.make("dispatch-with-old-history"), @@ -862,6 +877,12 @@ it.effect( // Deletion reads transfer history separately to find side chats. yield* sql`DELETE FROM orchestration_v2_projection_context_transfers WHERE target_thread_id = ${threadId}`; + // Archiving reads every task of the thread to stop the ones still running. + yield* sql`DELETE FROM orchestration_v2_projection_subagents + WHERE subagent_id = 'obsolete-task'`; + yield* sql`DELETE FROM orchestration_v2_projection_nodes WHERE node_id = 'obsolete-task'`; + yield* sql`DELETE FROM orchestration_v2_projection_provider_threads + WHERE provider_thread_id = 'obsolete-task-thread'`; yield* orchestrator.dispatch({ type: "thread.archive", commandId: CommandId.make("archive-with-old-history"), diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ac23af5324dae..c186c40f9e73a 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1528,7 +1528,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); // Runs in every command transaction; avoid reading thousands of finished leaf nodes. - const readCommandProjection = (threadId: ThreadId) => + const readCommandProjection = ( + threadId: ThreadId, + recent?: ProjectionRecordFilter["sinceLastCompaction"], + ) => projectionStore .getThreadRecords( threadId, @@ -1553,8 +1556,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // Commands here read only undelivered or active tasks; a dispatcher thread keeps // thousands of delivered ones, each carrying its full prompt. omitSettledSubagents: true, + // No command reads a settled task's node or its child's provider thread. + omitSettledSubagentRecords: true, // Commands act on pending forks and merge-backs only; consumed ones stay unread. contextTransferStatuses: ["pending"], + ...(recent === undefined ? {} : { sinceLastCompaction: recent }), }, ) .pipe( @@ -1643,9 +1649,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio Effect.fnUntraced(function* ( threadId: ThreadId, events: Ref.Ref>, + recent?: ProjectionRecordFilter["sinceLastCompaction"], ) { const pending = (yield* Ref.get(events)).filter((event) => event.threadId === threadId); - const stored = yield* Effect.option(readCommandProjection(threadId)); + const stored = yield* Effect.option(readCommandProjection(threadId, recent)); let projection: OrchestrationV2ThreadProjection; if (Option.isSome(stored)) { projection = stored.value; @@ -6305,7 +6312,28 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio events: Ref.Ref>, effects: Ref.Ref>, ) { - let projection = yield* getProjectionWithPendingEvents(command.threadId, events); + // A compacted thread reads every run and turn item, but attempts, nodes, messages and provider + // turns only for its recent runs and the runs this command names. An idle compaction reads + // in full: its busy check below looks for a delegated result's message under any old run. + let projection = yield* getProjectionWithPendingEvents( + command.threadId, + events, + command.idleCompaction === undefined + ? { + keepRunIds: [ + command.manualContinuationOfRunId, + command.restartContinuationOfRunId, + command.usageLimitContinuationOfRunId, + command.steerFollowUpOfRunId, + ...(command.dispatchMode.type === "steer_active" || + command.dispatchMode.type === "restart_active" + ? [command.dispatchMode.targetRunId] + : []), + ].flatMap((runId) => (runId === undefined ? [] : [runId])), + keepMessageId: command.messageId, + } + : undefined, + ); if (command.steerFollowUpOfRunId !== undefined) { const source = projection.runs.find((run) => run.id === command.steerFollowUpOfRunId); if ( @@ -6342,6 +6370,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }); return; } + const activeProviderInstanceId = projection.providerThreads.find( + (candidate) => candidate.id === projection.thread.activeProviderThreadId, + )?.providerInstanceId; + // Another provider is handed what ran since it last saw the thread, which can be older than + // the compaction, so a provider switch reads the whole history. + if ( + activeProviderInstanceId !== undefined && + activeProviderInstanceId !== + (command.modelSelection ?? projection.thread.modelSelection).instanceId + ) { + projection = yield* getProjectionWithPendingEvents(command.threadId, events); + } if (command.manualContinuationOfRunId !== undefined) { const source = projection.runs.find((run) => run.id === command.manualContinuationOfRunId); const limited = latestRootProviderFailure(source ?? null, projection.turnItems); @@ -6545,15 +6585,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection = applyToProjection(projection, event); } const userMessages = projection.messages.filter((message) => message.role === "user"); - const onlyMaintenanceHistory = - userMessages.length > 0 && userMessages.every(isNativeMaintenanceCommand); + // The recent runs of a compacted thread can hold only a `/compact` while an older prompt + // exists. Every prompt's turn item is loaded; without one, every user message is checked. + const onlyMaintenanceHistory = [ + ...userMessages, + ...projection.turnItems.flatMap((item) => (item.type === "user_message" ? [item] : [])), + ].every(isNativeMaintenanceCommand) + ? projectionStore + .getThreadRecords(command.threadId, ["messages"], { messageRoles: ["user"] }) + .pipe( + Effect.map(({ messages }) => [...messages, ...userMessages]), + Effect.map((all) => all.length > 0 && all.every(isNativeMaintenanceCommand)), + mapDispatchError(command), + ) + : Effect.succeed(false); if ( !isNativeMaintenanceCommand(command) && ((command.titleSeed !== undefined && (yield* projectionStore .getMessageCount(command.threadId) .pipe(mapDispatchError(command))) === 0) || - (command.createdBy === "user" && onlyMaintenanceHistory)) + (command.createdBy === "user" && (yield* onlyMaintenanceHistory))) ) { const now = yield* DateTime.now; const thread: OrchestrationV2AppThread = { diff --git a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts index e5482b2f99432..8563448071548 100644 --- a/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionRecovery.test.ts @@ -484,11 +484,12 @@ it.effect("selects unfinished recovery work without reading settled thread histo WHERE thread_id = ${queued} AND ordinal = 1 `; assert.deepEqual(yield* projections.getRecoveryThreadIds("queued-runs"), [queued]); - assert.deepEqual( - new Set(yield* projections.getRecoveryThreadIds("runtime")), - new Set([queued, archived, blocked, background, outboxOnly, requestOnly]), - ); for (const [kind, expected, index] of [ + [ + "runtime", + [queued, archived, blocked, background, outboxOnly, requestOnly], + "nodes_live_idx", + ], ["delegated-completions", [delivery], "runs_delegated_delivery_idx"], ["subagent-results", [], "threads_subagent_result_idx"], ] as const) { @@ -498,10 +499,12 @@ it.effect("selects unfinished recovery work without reading settled thread histo return Effect.succeed(statement); }; assert.deepEqual( - yield* projections - .getRecoveryThreadIds(kind) - .pipe(Effect.provideService(Statement.CurrentTransformer, observe)), - expected, + new Set( + yield* projections + .getRecoveryThreadIds(kind) + .pipe(Effect.provideService(Statement.CurrentTransformer, observe)), + ), + new Set(expected), ); const [query, params] = statements[0]!; const plan = yield* sql.unsafe<{ detail: string }>(`EXPLAIN QUERY PLAN ${query}`, params); @@ -1128,14 +1131,25 @@ it.effect("bounds runtime provider-thread reads by ownership and preserves recov ${ProviderThreadId.make("provider-thread:ownership:item")}, 1, 'assistant_message', 'waiting', '', '{}') `; const statements: Array["compile"]>> = []; + const nodeStatements: typeof statements = []; const observe: Statement.Transformer = (statement) => { const compiled = statement.compile(); if (compiled[0].includes("SELECT provider_thread.payload_json")) statements.push(compiled); + if (compiled[0].includes("SELECT node.payload_json")) nodeStatements.push(compiled); return Effect.succeed(statement); }; const projection = yield* projections .getRuntimeRecoveryProjection(threadId) .pipe(Effect.provideService(Statement.CurrentTransformer, observe)); + assert.equal(nodeStatements.length, 1); + const nodePlan = yield* sql.unsafe<{ detail: string }>( + `EXPLAIN QUERY PLAN ${nodeStatements[0]![0]}`, + nodeStatements[0]![1], + ); + assert.isTrue( + nodePlan.some((row) => /^SEARCH node USING INDEX .*nodes_live_idx/.test(row.detail)), + JSON.stringify(nodePlan), + ); assert.deepEqual( projection.providerThreads.map((row) => row.id), cases diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 856db5249885d..fa670c448c898 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -795,6 +795,441 @@ it.effect("idle compaction filters keep the latest run, live work and the newest }).pipe(Effect.provide(layerTest)), ); +// One thread holds every way a run can still matter after a compaction. A run is requested at +// its ordinal in minutes and ends 30 seconds later, unless the table says otherwise. +it.effect("a compacted thread reads every run, and run records only for its recent runs", () => + Effect.gen(function* () { + const store = yield* ProjectionStore.ProjectionStoreV2; + const threadId = yield* addRolledBackRecoveryCandidate("compacted"); + const created = yield* DateTime.now; + const at = (minutes: number) => DateTime.add(created, { minutes }); + const runId = (ordinal: number) => RunId.make(`run:compacted:${ordinal}`); + const rootNodeId = (ordinal: number) => NodeId.make(`node:compacted:${ordinal}`); + const attemptId = (ordinal: number) => RunAttemptId.make(`attempt:compacted:${ordinal}`); + const providerThreadId = ProviderThreadId.make("provider-thread:compacted"); + const messageId = (ordinal: number) => MessageId.make(`message:compacted:${ordinal}`); + const item = ( + ordinal: number, + itemOrdinal: number, + status: "completed" | "failed" | "running", + ) => ({ + threadId, + runId: runId(ordinal), + nodeId: rootNodeId(ordinal), + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: itemOrdinal, + status, + title: null, + startedAt: at(ordinal), + completedAt: status === "running" ? null : at(ordinal), + updatedAt: at(ordinal), + }); + const compaction = (ordinal: number, status: "completed" | "failed" | "running") => + store.apply({ + id: EventId.make(`event:compacted:compaction-${ordinal}`), + type: "turn-item.updated", + threadId, + runId: runId(ordinal), + nodeId: rootNodeId(ordinal), + driver, + occurredAt: at(ordinal), + payload: { + ...item(ordinal, ordinal * 10 + 1, status), + id: TurnItemId.make(`item:compacted:compaction-${ordinal}`), + type: "compaction", + driver, + }, + }); + for (const [ordinal, status, endedAt] of [ + [2, "queued", null], + [3, "completed"], + // A held queue ran this old run after the compactions. + [4, "completed", at(11.5)], + [5, "completed"], + [6, "completed"], + [7, "completed"], + [8, "completed"], + [9, "completed"], + [10, "completed"], + [11, "completed"], + [12, "completed"], + [13, "rolled_back"], + [14, "completed"], + [15, "running", null], + ] as const) { + const text = `Prompt ${ordinal}`; + const authored = { createdBy: "user", creationSource: "web" } as const; + const nodeId = rootNodeId(ordinal); + const ended = endedAt === undefined ? at(ordinal + 0.5) : endedAt; + yield* store.apply({ + id: EventId.make(`event:compacted:run-${ordinal}`), + type: "run.created", + threadId, + runId: runId(ordinal), + nodeId, + driver, + providerInstanceId, + occurredAt: at(ordinal), + payload: { + id: runId(ordinal), + threadId, + ordinal, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: messageId(ordinal), + rootNodeId: nodeId, + activeAttemptId: attemptId(ordinal), + status, + requestedAt: at(ordinal), + startedAt: status === "queued" ? null : at(ordinal), + completedAt: ended, + checkpointId: null, + contextHandoffId: null, + }, + }); + yield* store.apply({ + id: EventId.make(`event:compacted:attempt-${ordinal}`), + type: "run-attempt.created", + threadId, + runId: runId(ordinal), + nodeId, + driver, + occurredAt: at(ordinal), + payload: { + id: attemptId(ordinal), + runId: runId(ordinal), + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId, + providerTurnId: null, + reason: "initial", + status: ended === null ? "running" : "completed", + startedAt: at(ordinal), + completedAt: ended, + }, + }); + yield* store.apply({ + id: EventId.make(`event:compacted:node-${ordinal}`), + type: "node.updated", + threadId, + runId: runId(ordinal), + nodeId, + driver, + occurredAt: at(ordinal), + payload: { + id: nodeId, + threadId, + runId: runId(ordinal), + rootNodeId: nodeId, + parentNodeId: null, + kind: "root_turn", + status: ended === null ? "running" : "completed", + countsForRun: true, + providerThreadId, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: at(ordinal), + completedAt: ended, + }, + }); + yield* store.apply({ + id: EventId.make(`event:compacted:turn-${ordinal}`), + type: "provider-turn.updated", + threadId, + nodeId, + driver, + occurredAt: at(ordinal), + payload: { + id: ProviderTurnId.make(`turn:compacted:${ordinal}`), + providerThreadId, + nodeId, + runAttemptId: attemptId(ordinal), + nativeTurnRef: null, + ordinal, + status: ended === null ? "running" : "completed", + startedAt: at(ordinal), + completedAt: ended, + }, + }); + yield* store.apply({ + id: EventId.make(`event:compacted:message-${ordinal}`), + type: "message.updated", + threadId, + runId: runId(ordinal), + occurredAt: at(ordinal), + payload: { + ...authored, + id: messageId(ordinal), + threadId, + runId: runId(ordinal), + nodeId, + role: "user", + text, + attachments: [], + streaming: false, + createdAt: at(ordinal), + updatedAt: at(ordinal), + }, + }); + yield* store.apply({ + id: EventId.make(`event:compacted:prompt-${ordinal}`), + type: "turn-item.updated", + threadId, + runId: runId(ordinal), + nodeId, + driver, + occurredAt: at(ordinal), + payload: { + ...authored, + ...item(ordinal, ordinal * 10, status === "queued" ? "running" : "completed"), + ...(status === "queued" ? { status: "pending" as const } : {}), + id: TurnItemId.make(`item:compacted:prompt-${ordinal}`), + type: "user_message", + messageId: messageId(ordinal), + inputIntent: status === "queued" ? "queued_turn" : "turn_start", + text, + attachments: [], + }, + }); + } + // Each collection as the ordinals of the runs it was read for. Run 1 is the helper's. + const ordinals = (ids: ReadonlyArray) => + [...new Set(ids.map((id) => Number(id?.split(":").at(-1)) || 1))].toSorted((a, b) => a - b); + const read = (keepRunIds: ReadonlyArray = [], keepMessageId = messageId(0)) => + store + .getThreadRecords( + threadId, + ["runs", "attempts", "nodes", "providerTurns", "messages", "turnItems"], + { + messageRoles: ["user"], + omitSettledLeafNodes: true, + sinceLastCompaction: { keepRunIds, keepMessageId }, + }, + ) + .pipe( + Effect.map((records) => ({ + runs: records.runs.length, + attempts: ordinals(records.attempts.map((attempt) => attempt.runId)), + nodes: ordinals(records.nodes.map((node) => node.runId)), + providerTurns: ordinals(records.providerTurns.map((turn) => turn.runAttemptId)), + messages: ordinals(records.messages.map((message) => message.runId)), + turnItems: ordinals(records.turnItems.map((row) => row.runId)), + })), + ); + const all = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; + // Every run and every turn item is read, so a model switch is still measured from the last + // prompt. Run 1, the helper's, holds only a command item. + const expected = (recent: ReadonlyArray) => ({ + runs: 15, + attempts: recent, + nodes: recent, + providerTurns: recent, + messages: recent, + turnItems: [1, ...all], + }); + + // Nothing is compacted yet, so the whole history is current. + assert.deepEqual(yield* read(), expected(all)); + + // The window starts at the compaction's run. Queued run 2 and held run 4 are older but had + // not ended by then. + yield* compaction(7, "completed"); + assert.deepEqual(yield* read(), expected([2, 4, 7, 8, 9, 10, 11, 12, 13, 14, 15])); + + // The latest compaction wins. + yield* compaction(11, "completed"); + const latest = expected([2, 4, 11, 12, 13, 14, 15]); + assert.deepEqual(yield* read(), latest); + + // A compaction that was rolled back, failed or is still running does not move the window. + yield* compaction(13, "completed"); + yield* compaction(14, "failed"); + yield* compaction(15, "running"); + assert.deepEqual(yield* read(), latest); + + // A named run and the run that holds a re-sent message are read too. + assert.deepEqual( + yield* read([runId(3)], messageId(6)), + expected([2, 3, 4, 6, 11, 12, 13, 14, 15]), + ); + + // A command also skips the node and the provider thread of each settled task. Tasks ended on + // both sides of the compaction; one ran in the provider thread the thread's own runs use. + const addProviderThread = (id: ProviderThreadId, appThreadId: ThreadId) => + store.apply({ + id: EventId.make(`event:compacted:${id}`), + type: "provider-thread.updated", + threadId, + occurredAt: created, + payload: { + id, + appThreadId, + driver, + providerInstanceId, + providerSessionId: null, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + status: "idle", + firstRunOrdinal: null, + createdAt: created, + updatedAt: created, + }, + }); + yield* addProviderThread(providerThreadId, threadId); + for (const [name, ordinal, delivery] of [ + ["old-delivered", 5, "delivered"], + ["old-pending", 5, "pending"], + ["old-own-thread", 5, "delivered"], + ["recent-delivered", 12, "delivered"], + ["recent-pending", 12, "pending"], + ] as const) { + const id = NodeId.make(`node:compacted:task:${name}`); + const taskProviderThreadId = + name === "old-own-thread" + ? providerThreadId + : ProviderThreadId.make(`provider-thread:compacted:task:${name}`); + if (taskProviderThreadId !== providerThreadId) { + yield* addProviderThread( + taskProviderThreadId, + ThreadId.make(`thread:compacted:child:${name}`), + ); + } + const task = { + id, + threadId, + runId: runId(ordinal), + parentNodeId: rootNodeId(ordinal), + status: "completed", + startedAt: at(ordinal), + completedAt: at(ordinal), + } as const; + yield* store.apply({ + id: EventId.make(`event:compacted:task:${name}`), + type: "subagent.updated", + threadId, + runId: runId(ordinal), + nodeId: id, + driver, + providerInstanceId, + occurredAt: at(ordinal), + payload: { + ...task, + origin: "app_owned", + createdBy: "agent", + driver, + providerInstanceId, + providerThreadId: taskProviderThreadId, + childThreadId: null, + nativeTaskRef: null, + prompt: "Do the work", + title: name, + model: null, + completionDelivery: { state: delivery, observedByRunId: null }, + result: null, + updatedAt: at(ordinal), + }, + }); + yield* store.apply({ + id: EventId.make(`event:compacted:task-node:${name}`), + type: "node.updated", + threadId, + runId: runId(ordinal), + nodeId: id, + driver, + occurredAt: at(ordinal), + payload: { + ...task, + rootNodeId: rootNodeId(ordinal), + kind: "subagent", + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + }, + }); + } + const names = (ids: ReadonlyArray) => ids.map((id) => id.split(":").at(-1)).toSorted(); + const readWithTasks = (filter: ProjectionStore.ProjectionRecordFilter) => + store + .getThreadRecords( + threadId, + [ + "runs", + "attempts", + "nodes", + "providerThreads", + "providerTurns", + "messages", + "turnItems", + ], + { messageRoles: ["user"], omitSettledLeafNodes: true, ...filter }, + ) + .pipe( + Effect.map((records) => ({ + runs: names(records.runs.map((run) => run.id)), + turnItems: names(records.turnItems.map((row) => row.id)), + attempts: names(records.attempts.map((attempt) => attempt.id)), + rootNodes: names( + records.nodes.flatMap((node) => (node.kind === "root_turn" ? [node.id] : [])), + ), + taskNodes: names( + records.nodes.flatMap((node) => (node.kind === "subagent" ? [node.id] : [])), + ), + providerThreads: names(records.providerThreads.map((thread) => thread.id)), + providerTurns: names(records.providerTurns.map((turn) => turn.id)), + messages: names(records.messages.map((message) => message.id)), + })), + ); + const window = { + sinceLastCompaction: { keepRunIds: [runId(3)], keepMessageId: messageId(6) }, + }; + const windowed = yield* readWithTasks(window); + const unsettled = yield* readWithTasks({ omitSettledSubagentRecords: true }); + const both = yield* readWithTasks({ ...window, omitSettledSubagentRecords: true }); + // Each filter alone keeps records the other one drops. + assert.deepEqual(windowed.taskNodes, ["recent-delivered", "recent-pending"]); + assert.lengthOf(windowed.providerThreads, 5); + assert.deepEqual(unsettled.taskNodes, ["old-pending", "recent-pending"]); + assert.deepEqual(unsettled.providerThreads, ["compacted", "old-pending", "recent-pending"]); + assert.lengthOf(unsettled.rootNodes, all.length); + assert.lengthOf(unsettled.runs, 15); + // Together: every run, every turn item and the provider thread the runs use stay, and the + // windowed records are read for the recent and named runs, less each settled task's node. + const recentRuns = ["11", "12", "13", "14", "15", "2", "3", "4", "6"]; + assert.deepEqual(both, { + ...unsettled, + attempts: recentRuns, + rootNodes: recentRuns, + taskNodes: ["recent-pending"], + providerTurns: recentRuns, + messages: recentRuns, + }); + const keptUnsettled = new Map(Object.entries(unsettled)); + assert.deepEqual( + Object.fromEntries( + Object.entries(windowed).map(([key, kept]) => [ + key, + kept.filter((name) => keptUnsettled.get(key)?.includes(name)), + ]), + ), + both, + ); + }).pipe(Effect.provide(layerTest)), +); + it.effect("record reads filter notification sources without dropping matching message bodies", () => Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; @@ -1575,6 +2010,8 @@ const threadWorktreePathsIncludeArchivedOnRequest = Effect.gen(function* () { const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { const store = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const sharedSessionId = ProviderSessionId.make("session:settled-subagents:shared"); const now = yield* DateTime.now; const threadId = yield* addRolledBackRecoveryCandidate("settled-leaf-nodes"); const settledRun = (yield* store.getThreadProjection(threadId)).runs[0]!; @@ -1785,7 +2222,7 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { createdBy: "agent", driver, providerInstanceId, - providerThreadId: null, + providerThreadId: ProviderThreadId.make(`provider-thread:settled-subagents:${name}`), childThreadId, nativeTaskRef: null, prompt: "Do the work", @@ -1801,6 +2238,110 @@ const commandReadsSkipSettledLeafNodes = Effect.gen(function* () { updatedAt: now, }, }); + // Each task has a node in this thread and a provider thread in its child thread. + yield* store.apply({ + id: EventId.make(`event:settled-subagents:node:${name}`), + type: "node.updated", + threadId, + runId: run.id, + nodeId: id, + driver, + occurredAt: now, + payload: { + id, + threadId, + runId: run.id, + rootNodeId: run.rootNodeId!, + parentNodeId: run.rootNodeId, + kind: "subagent", + status, + countsForRun: false, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + runtimeRequestId: null, + checkpointScopeId: null, + startedAt: now, + completedAt: status === "running" ? null : now, + }, + }); + yield* store.apply({ + id: EventId.make(`event:settled-subagents:provider-thread:${name}`), + type: "provider-thread.updated", + threadId, + occurredAt: now, + payload: { + id: ProviderThreadId.make(`provider-thread:settled-subagents:${name}`), + appThreadId: ThreadId.make(`thread:settled-subagents:child:${name}`), + driver, + providerInstanceId, + // One settled task ran in a provider session this thread also uses. + providerSessionId: name === "acknowledged" ? sharedSessionId : null, + ownerNodeId: null, + nativeThreadRef: null, + nativeConversationHeadRef: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + status: "idle", + firstRunOrdinal: null, + createdAt: now, + updatedAt: now, + }, + }); + } + yield* sql`INSERT INTO orchestration_v2_projection_provider_session_bindings + (provider_session_id, thread_id) VALUES (${sharedSessionId}, ${threadId})`; + // A command drops the node and the provider thread of each task it drops. The provider thread + // in the shared session stays: detaching that session probes it for background work. + const kept = ["active-run-delivered", "claimed", "no-delivery", "pending-delivery", "running"]; + const commandTrace = traceSqlStatements(); + const commandRecords = yield* store + .getThreadRecords(threadId, ["nodes", "providerThreads"], { + omitSettledLeafNodes: true, + omitSettledSubagentRecords: true, + }) + .pipe(Effect.withTracer(commandTrace.tracer)); + assert.deepEqual( + commandRecords.nodes + .flatMap((node) => (node.kind === "subagent" ? [node.id.split(":").at(-1)] : [])) + .toSorted(), + // A subagent node that no task record names stays. + [...kept, "settled-subagent"], + ); + assert.deepEqual( + commandRecords.providerThreads.map((thread) => thread.id.split(":").at(-1)).toSorted(), + ["acknowledged", ...kept], + ); + assert.lengthOf( + (yield* store.getThreadRecords(threadId, ["providerThreads"])).providerThreads, + subagents.length, + ); + // Both reads stay inside their indexes: no scan of the thread's nodes or provider threads. + for (const [table, seeks] of [ + [ + "nodes", + [ + "SEARCH node USING INTEGER PRIMARY KEY", + "SEARCH settled USING COVERING INDEX", + "SEARCH settled_node USING COVERING INDEX", + "subagents_settled_idx (thread_id=?)", + ], + ], + [ + "provider_threads", + ["MULTI-INDEX OR", "provider_threads_session_idx (provider_session_id=?)"], + ], + ] as const) { + const query = commandTrace.statements.find((statement) => + statement.includes(`FROM orchestration_v2_projection_${table}`), + ); + assert.isDefined(query); + const plan = (yield* sql.unsafe<{ readonly detail: string }>(`EXPLAIN QUERY PLAN ${query}`)) + .map((row) => row.detail) + .join("\n"); + for (const seek of seeks) assert.include(plan, seek); + assert.notInclude(plan, `SCAN orchestration_v2_projection_${table}`); } const subagentNames = (records: { readonly subagents: ReadonlyArray<{ readonly title: string | null }>; @@ -3110,14 +3651,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { const threadId = ThreadId.make("thread:bounded-sql-history"); // The raw SQL edits below stand in for committed writes, which always append a thread event. let revision = 0; - const historyPage = (...args: Parameters) => + const committed = (read: Effect.Effect) => sql`INSERT INTO orchestration_events ( event_id, aggregate_kind, stream_id, stream_version, event_type, occurred_at, actor_kind, payload_json, metadata_json, application_event_version ) VALUES ( ${`event:bounded-sql-history:revision:${++revision}`}, 'thread', ${threadId}, ${revision}, 'turn-item.updated', ${nowIso}, 'user', '{}', '{}', 2 - )`.pipe(Effect.andThen(projectionStore.getThreadHistoryPage(...args))); + )`.pipe(Effect.andThen(read)); + const historyPage = (...args: Parameters) => + committed(projectionStore.getThreadHistoryPage(...args)); yield* projectionStore.apply({ id: EventId.make("event:bounded-sql-history:thread"), type: "thread.created", @@ -3509,6 +4052,134 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { WHERE thread_id = ${threadId} AND ordinal IN (500, 580) `; + // Older pages and timeline pages read the rows near the page, not the whole history. A + // full index that another read left cached gives the same page. + const pageStatements: Array]> = []; + const recordPageStatements = (read: Effect.Effect) => + committed( + read.pipe( + Effect.provideService(Statement.CurrentTransformer, (statement) => { + pageStatements.push(statement.compile()); + return Effect.succeed(statement); + }), + ), + ); + const olderCursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: TurnItemId.make("turn-item:bounded-sql-history:990"), + position: 989, + }); + const ordinalsFrom = (first: number, length: number) => + Array.from({ length }, (_, index) => first + index); + for (const workMode of [undefined, "deferred"] as const) { + const read = (throughEntryId?: string) => + projectionStore.getThreadHistoryPage( + threadId, + olderCursor, + throughEntryId, + false, + workMode, + ); + const page = yield* recordPageStatements(read()); + assert.deepEqual( + page.items.map((row) => row.item.ordinal), + ordinalsFrom(915, 75), + ); + assert.strictEqual(decodeThreadHistoryCursor(page.nextCursor!).p, 914); + // A jump to an entry reads the full index and leaves it cached. With work, it scans + // payloads for inline output only in its page's runs, not in a run after its cursor. + const scannedRuns: Array = []; + yield* read("turn-item:bounded-sql-history:950").pipe( + Effect.provideService(Statement.CurrentTransformer, (statement) => { + const [query, params] = statement.compile(); + if (query.includes("LIKE '%htmlRender%'")) scannedRuns.push(String(params[0])); + return Effect.succeed(statement); + }), + ); + assert.deepEqual( + [ + scannedRuns.length, + scannedRuns.some((runs) => runs.includes('"run:bounded-sql-history:950"')), + scannedRuns.some((runs) => runs.includes('"run:bounded-sql-history:995"')), + ], + workMode === undefined ? [0, false, false] : [1, true, false], + ); + assert.deepEqual(yield* read(), page); + } + for (const [view, ordinals] of [ + ["activity", ordinalsFrom(902, 20)], + ["messages", [1000]], + ] as const) { + const read = projectionStore.getTimelinePage(threadId, { + afterPosition: 900, + limit: 20, + view, + }); + const page = yield* recordPageStatements(read); + assert.deepEqual( + page.items.map((row) => [row.item.ordinal, row.position]), + ordinals.map((ordinal) => [ordinal, ordinal - 1]), + ); + assert.strictEqual(page.totalItems, 1000); + // An attachment lookup reads the full index and leaves it cached. + yield* projectionStore.getTimelinePage(threadId, { attachmentId: "absent", limit: 1 }); + assert.deepEqual(yield* read, page); + } + { + const pagePath = "file:/history-page-steps?vfs=memdb"; + using copy = new NodeSqlite.DatabaseSync(pagePath); + yield* sql`VACUUM INTO ${pagePath}`; + // Only statements that count positions may grow with the history, and those read an + // index alone. Every other statement costs the same when the rows below the page are gone. + const countsPositions = ([query]: readonly [string, ReadonlyArray]) => + /COUNT\(\*\)|OFFSET/.test(query); + for (const [query, params] of pageStatements.filter(countsPositions)) { + const plan = copy + .prepare(`EXPLAIN QUERY PLAN ${query}`) + .all(...(params as ReadonlyArray)) + .map((row) => String(row.detail)) + .filter((detail) => detail.includes("orchestration_v2_projection_turn_items")); + assert.isTrue( + plan.every((detail) => detail.includes("COVERING INDEX")), + `${query}\n${plan.join("\n")}`, + ); + } + const rowReads = pageStatements.filter((statement) => !countsPositions(statement)); + const rowReadSteps = () => + rowReads.reduce((steps, [query, params]) => { + const statement = copy.prepare(query); + statement.all(...(params as ReadonlyArray)); + return steps + statement.stat("vmStep"); + }, 0); + const fullSteps = rowReadSteps(); + assert.isAbove(fullSteps, 0); + copy.exec( + "DELETE FROM orchestration_v2_projection_turn_items WHERE ordinal BETWEEN 2 AND 400", + ); + assert.isAtMost(fullSteps, rowReadSteps() * 1.1); + } + // Rows that a rolled-back run hides below the page still shift every position above them. + const setOldRunStatus = (status: "rolled_back" | "completed") => sql` + UPDATE orchestration_v2_projection_runs + SET status = ${status}, payload_json = json_set(payload_json, '$.status', ${status}) + WHERE thread_id = ${threadId} AND ordinal BETWEEN 100 AND 109`; + yield* setOldRunStatus("rolled_back"); + const shiftedPage = yield* historyPage(threadId, olderCursor); + assert.strictEqual(decodeThreadHistoryCursor(shiftedPage.nextCursor!).p, 904); + const shiftedTimeline = yield* committed( + projectionStore.getTimelinePage(threadId, { + afterPosition: 900, + limit: 1, + view: "activity", + }), + ); + assert.deepEqual( + [shiftedTimeline.totalItems, shiftedTimeline.items[0]?.item.ordinal], + [990, 912], + ); + yield* setOldRunStatus("completed"); + const retainedRequestPlan = yield* sql<{ readonly detail: string }>` EXPLAIN QUERY PLAN WITH selected AS ( @@ -3664,23 +4335,115 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { window.projection.visibleTurnItems.find((row) => row.item.deferredWork)?.item.ordinal, 3, ); - const page = yield* historyPage( + const newestCursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: "turn-item:bounded-sql-history:1000", + position: 1000, + }); + const page = yield* historyPage(threadId, newestCursor, undefined, false, "deferred"); + assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); + // Tool payloads hold megabytes, so a page that reads the full index, as a jump to an + // entry does, looks for inline output only in its own runs. + const pageRead = traceSqlStatements(); + yield* historyPage( + threadId, + newestCursor, + "turn-item:bounded-sql-history:2", + false, + "deferred", + ).pipe(Effect.withTracer(pageRead.tracer)); + const payloadScans = pageRead.statements.filter((statement) => + statement.includes("LIKE '%htmlRender%'"), + ); + assert.lengthOf(payloadScans, 1); + assert.include(payloadScans[0], "item.run_id IS json_extract(wanted.value, '$.id')"); + } + // Until its run is scanned, a cursor on inline output is hidden inside a work group. + yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool', + payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', 't3-code.delegate_task') + WHERE thread_id = ${threadId} AND ordinal = 4`; + const sharedRunId = "run:bounded-sql-history:1"; + // A work page of rows that have no run leaves their inline output out too. + yield* sql`UPDATE orchestration_v2_projection_turn_items SET run_id = NULL + WHERE thread_id = ${threadId} AND ordinal BETWEEN 3 AND 6`; + const runlessWork = yield* historyPage( + threadId, + encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: "turn-item:bounded-sql-history:6", + position: 6, + inclusive: true, + }), + "turn-item:bounded-sql-history:3", + false, + "work", + ); + assert.deepEqual( + runlessWork.items.map((row) => row.item.ordinal), + [3, 5, 6], + ); + yield* sql`UPDATE orchestration_v2_projection_turn_items SET run_id = ${sharedRunId} + WHERE thread_id = ${threadId} AND ordinal BETWEEN 3 AND 6`; + // A stale position selects from the cursor row itself, or from more than a page after it + // once the later rows are another run's and cannot fold. + for (const [position, laterStatus, laterRun] of [ + [0, "completed", sharedRunId], + [999, "running", "run:bounded-sql-history:300"], + ] as const) { + yield* sql`UPDATE orchestration_v2_projection_turn_items SET status = ${laterStatus}, + run_id = ${laterRun}, + payload_json = json_set(payload_json, '$.status', ${laterStatus}, '$.runId', ${laterRun}) + WHERE thread_id = ${threadId} AND ordinal >= 300`; + const beforeInlineOutput = yield* historyPage( threadId, encodeThreadHistoryCursor({ snapshotSequence: 0, sourceThreadId: threadId, - sourceItemId: "turn-item:bounded-sql-history:1000", - position: 1000, + sourceItemId: "turn-item:bounded-sql-history:4", + position, }), undefined, false, "deferred", ); - assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); + assert.deepEqual( + beforeInlineOutput.items.map((row) => row.item.ordinal), + [1, 2, 3], + ); } + // A cursor whose row is gone falls back to its position. Inline output between the page + // and that position can belong to a run with no other row there. + yield* sql`UPDATE orchestration_v2_projection_turn_items + SET status = CASE WHEN ordinal <= 700 THEN 'running' ELSE 'completed' END, + run_id = CASE WHEN ordinal <= 700 THEN 'run:bounded-sql-history:300' ELSE ${sharedRunId} END, + payload_json = json_set(payload_json, + '$.status', CASE WHEN ordinal <= 700 THEN 'running' ELSE 'completed' END, + '$.runId', CASE WHEN ordinal <= 700 THEN 'run:bounded-sql-history:300' ELSE ${sharedRunId} END) + WHERE thread_id = ${threadId} AND ordinal >= 100`; + yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'dynamic_tool', + payload_json = json_set(payload_json, '$.type', 'dynamic_tool', '$.toolName', 't3-code.delegate_task') + WHERE thread_id = ${threadId} AND ordinal = 720`; + const beforeMissingCursor = yield* historyPage( + threadId, + encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: "turn-item:bounded-sql-history:gone", + position: 800, + }), + undefined, + false, + "deferred", + ); + assert.strictEqual(beforeMissingCursor.items.at(-1)?.item.ordinal, 720); + yield* sql`UPDATE orchestration_v2_projection_turn_items SET status = 'completed', + run_id = ${sharedRunId}, + payload_json = json_set(payload_json, '$.status', 'completed', '$.runId', ${sharedRunId}) + WHERE thread_id = ${threadId} AND ordinal >= 100`; yield* sql`UPDATE orchestration_v2_projection_turn_items SET type = 'command_execution', - payload_json = json_set(payload_json, '$.type', 'command_execution') WHERE thread_id = ${threadId} AND ordinal = 2`; - const sharedRunId = "run:bounded-sql-history:1"; + payload_json = json_set(payload_json, '$.type', 'command_execution') WHERE thread_id = ${threadId} AND ordinal IN (2, 4, 720)`; for (const [ordinal, status] of [ [0, "completed"], [1, "superseded"], @@ -4928,6 +5691,339 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { }), ); + it.effect("a page read from a window equals the page read from the full index", () => + Effect.gen(function* () { + const projectionStore = yield* ProjectionStore.ProjectionStoreV2; + const sql = yield* SqlClient.SqlClient; + const now = yield* DateTime.now; + const nowIso = DateTime.formatIso(now); + // Seeded, so every run builds the same threads. + let seed = 0x5eed; + const random = () => { + seed = (Math.imul(seed, 1_664_525) + 1_013_904_223) >>> 0; + return seed / 2 ** 32; + }; + const chance = (probability: number) => random() < probability; + const spans: Array = []; + const tracer = Tracer.make({ + span(options) { + spans.push(options.name); + return new Tracer.NativeSpan(options); + }, + }); + let windowReads = 0; + let foldedGroups = 0; + + for (let round = 0; round < 4; round += 1) { + const threadId = ThreadId.make(`thread:window-equivalence:${round}`); + const created = { + id: EventId.make(`event:window-equivalence:${round}`), + type: "thread.created", + threadId, + occurredAt: now, + payload: { + createdBy: "user", + creationSource: "web", + id: threadId, + projectId: ProjectId.make("project:window-equivalence"), + title: "Window equivalence", + providerInstanceId, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + activeProviderThreadId: null, + lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId }, + forkedFrom: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, + deletedAt: null, + }, + } satisfies Parameters[0]; + yield* projectionStore.apply(created); + // One run of each kind in a random order, then an active run. Every other thread has + // one user turn and then only wake turns. + // The last thread is a long run that a late notification wakes, then enough one-row + // runs that a page stops at the raw turn limit only if it counts that wake as a turn. + const kinds = + round === 3 + ? ["late wake", ...Array.from({ length: 148 }, () => "one row")] + : [ + "rolled back", + "cancelled queued turn", + "replaced attempt", + "stopped", + "stopped", + "folds work", + "folds work", + "short", + "short", + "short", + ] + .map((kind) => ({ kind, order: random() })) + .toSorted((left, right) => left.order - right.order) + .map(({ kind }) => kind); + const agentDriven = round === 1; + const runs: Array = []; + const attempts: Array = []; + const items: Array = []; + const tiedWithHidden: Array = []; + const repliesInStoppedRuns: Array = []; + let ordinal = 0; + for (const [index, kind] of [...kinds, "active"].entries()) { + const run = index + 1; + const runId = `run:window-equivalence:${round}:${run}`; + const nodeId = `node:window-equivalence:${round}:${run}`; + const status = + kind === "active" + ? "running" + : kind === "rolled back" + ? "rolled_back" + : kind === "cancelled queued turn" + ? "cancelled" + : kind === "short" && chance(0.5) + ? "interrupted" + : "completed"; + runs.push({ + id: runId, + threadId, + ordinal: run, + providerInstanceId, + modelSelection, + providerThreadId: null, + userMessageId: `message:window-equivalence:${round}:${run}`, + rootNodeId: nodeId, + activeAttemptId: null, + status, + requestedAt: nowIso, + startedAt: nowIso, + completedAt: nowIso, + checkpointId: null, + contextHandoffId: null, + }); + attempts.push({ + id: `attempt:window-equivalence:${round}:${run}`, + runId, + attemptOrdinal: 1, + rootNodeId: nodeId, + providerInstanceId, + providerThreadId: "provider-thread:window-equivalence", + providerTurnId: null, + reason: "initial", + status: kind === "replaced attempt" || chance(0.2) ? "superseded" : "completed", + startedAt: nowIso, + completedAt: nowIso, + }); + // The first row after a rolled-back run shares the ordinal of that run's last row. + let tie = kinds[index - 1] === "rolled back"; + if (tie) + tiedWithHidden.push( + TurnItemId.make(`turn-item:window-equivalence:${round}:${items.length}`), + ); + const add = (type: string, fields: Record = {}) => { + if (ordinal === 0 || !(tie || chance(0.04))) ordinal += 1; + tie = false; + items.push({ + id: `turn-item:window-equivalence:${round}:${items.length}`, + threadId, + runId, + nodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal, + status: "completed", + title: null, + startedAt: nowIso, + completedAt: nowIso, + updatedAt: nowIso, + type, + ...fields, + }); + }; + const userMessage = (inputIntent: string) => + add("user_message", { + createdBy: "user", + creationSource: "web", + messageId: `message:window-equivalence:${round}:${items.length}`, + inputIntent, + text: "Turn", + attachments: [], + }); + const notification = () => + add("notification", { + source: { kind: "system" }, + outcome: "completed", + summary: "Wake", + }); + const wakes = + kind === "one row" + ? run % 10 !== 0 + : kind !== "late wake" && (agentDriven ? run > 1 : chance(0.2)); + if (wakes) notification(); + else userMessage(kind === "cancelled queued turn" ? "queued_turn" : "turn_start"); + // A stopped run never folds, so it is long enough for page ends to fall inside it. + const work = + kind === "late wake" + ? 420 + Math.floor(random() * 40) + : kind === "stopped" + ? 320 + Math.floor(random() * 60) + : kind === "folds work" + ? 155 + Math.floor(random() * 60) + : kind === "one row" + ? 0 + : Math.floor(random() * 30); + for (let row = 0; row < work; row += 1) { + if (chance(0.5)) add("command_execution", { input: "echo", output: "ok", exitCode: 0 }); + else add("reasoning", { text: "", streaming: false }); + // A reply deep in a stopped run: a page that ends on it has enough work below it + // to fold, and only the stop request above it says that it does not. + const reply = kind === "stopped" && row === 200; + if (reply) + repliesInStoppedRuns.push(`turn-item:window-equivalence:${round}:${items.length}`); + if (reply || chance(0.02)) + add("assistant_message", { + messageId: `message:window-equivalence:${round}:${items.length}`, + text: "Reply", + streaming: false, + }); + if (chance(0.01)) notification(); + if (chance(0.004) && !agentDriven) userMessage("steer"); + } + if (kind === "late wake") notification(); + if (kind === "stopped") add("run_interrupt_request", { message: "Stop" }); + if (kind === "replaced attempt" || (kind === "stopped" && chance(0.5))) + add("run_interrupt_result", { message: "Stopped" }); + if (kind === "short" && chance(0.3)) + add("error", { + status: "failed", + failure: { class: "unknown", message: "Failed", code: null, retryable: false }, + }); + } + yield* sql` + INSERT INTO orchestration_v2_projection_runs ( + run_id, thread_id, ordinal, provider, provider_thread_id, status, + requested_at, completed_at, payload_json + ) + SELECT json_extract(value, '$.id'), ${threadId}, json_extract(value, '$.ordinal'), 'codex', + NULL, json_extract(value, '$.status'), ${nowIso}, ${nowIso}, value + FROM json_each(${encodeUnknownJsonString(runs)})`; + yield* sql` + INSERT INTO orchestration_v2_projection_run_attempts ( + attempt_id, thread_id, run_id, attempt_ordinal, root_node_id, provider, + provider_instance_id, provider_thread_id, provider_turn_id, status, payload_json + ) + SELECT json_extract(value, '$.id'), ${threadId}, json_extract(value, '$.runId'), 1, + json_extract(value, '$.rootNodeId'), ${providerInstanceId}, ${providerInstanceId}, + json_extract(value, '$.providerThreadId'), NULL, json_extract(value, '$.status'), value + FROM json_each(${encodeUnknownJsonString(attempts)})`; + yield* sql` + INSERT INTO orchestration_v2_projection_turn_items ( + turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id, + parent_item_id, ordinal, type, status, updated_at, payload_json + ) + SELECT json_extract(value, '$.id'), ${threadId}, json_extract(value, '$.runId'), + json_extract(value, '$.nodeId'), NULL, NULL, NULL, json_extract(value, '$.ordinal'), + json_extract(value, '$.type'), json_extract(value, '$.status'), ${nowIso}, value + FROM json_each(${encodeUnknownJsonString(items)})`; + + // Applying an event drops the thread's cached index, as each event of a run does, so + // each of these reads a window. + const requests: Array<{ + readonly read: Effect.Effect; + readonly page: unknown; + }> = []; + const windowed = (read: Effect.Effect) => + Effect.gen(function* () { + yield* projectionStore.apply(created); + spans.length = 0; + const page = yield* read.pipe(Effect.withTracer(tracer)); + if (spans.includes("ProjectionStore.readTimelineWindow")) windowReads += 1; + requests.push({ read, page }); + return page; + }); + const history = ( + cursor: string, + throughEntryId?: string, + conversationOnly?: boolean, + workMode?: "deferred" | "work", + ) => + projectionStore.getThreadHistoryPage( + threadId, + cursor, + throughEntryId, + conversationOnly, + workMode, + ); + const timeline = (options: ProjectionStore.ProjectionTimelinePageOptions) => + projectionStore.getTimelinePage(threadId, options); + + const { totalItems } = yield* windowed(timeline({ limit: 0 })); + const newest = (yield* windowed( + timeline({ view: "activity", afterPosition: totalItems - 2, limit: 1 }), + )).items[0]!; + const firstCursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId: newest.sourceItemId, + position: newest.position, + }); + const groups = new Map(); + for (const [conversationOnly, workMode] of [ + [false, "deferred"], + [false, undefined], + [true, undefined], + ] as const) { + for (let cursor: string | null = firstCursor; cursor !== null;) { + const page: OrchestrationV2ThreadHistoryPage = yield* windowed( + history(cursor, undefined, conversationOnly, workMode), + ); + for (const { item } of page.items) + if (item.deferredWork !== undefined) groups.set(item.id, item.deferredWork.cursor); + cursor = page.nextCursor; + } + } + for (const sourceItemId of repliesInStoppedRuns) { + const cursor = encodeThreadHistoryCursor({ + snapshotSequence: 0, + sourceThreadId: threadId, + sourceItemId, + position: 0, + }); + yield* windowed(history(cursor, undefined, false, "deferred")); + } + foldedGroups += groups.size; + for (const [anchorId, groupCursor] of groups) { + for (let cursor: string | null = groupCursor; cursor !== null;) + cursor = (yield* windowed(history(cursor, anchorId, false, "work"))).nextCursor; + } + for (const view of ["messages", "activity"] as const) { + for (const afterPosition of [-1, Math.floor(totalItems / 3), totalItems - 5]) + yield* windowed(timeline({ view, afterPosition, limit: 20 })); + } + for (const itemId of [newest.sourceItemId, ...tiedWithHidden]) + yield* windowed(timeline({ itemId, limit: 1 })); + + // An attachment lookup and a jump to an entry read the full index and leave it cached, + // so the same requests now come from it. + yield* timeline({ attachmentId: "absent", limit: 1 }); + yield* history(firstCursor, "absent", false, "deferred"); + spans.length = 0; + for (const { read, page } of requests) + assert.deepEqual(yield* read.pipe(Effect.withTracer(tracer)), page); + assert.notInclude(spans, "ProjectionStore.readTimelineWindow"); + } + assert.isAtLeast(foldedGroups, 2); + assert.isAbove(windowReads, 60); + }), + ); + it.effect("scopes actionable provider state to the requested bounded thread", () => Effect.gen(function* () { const projectionStore = yield* ProjectionStore.ProjectionStoreV2; @@ -8684,9 +9780,19 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { const boundedFork = yield* projectionStore .getThreadSnapshotWindow(targetThreadId, { rowLimit: 2 }) .pipe(Effect.withTracer(tracer)); - assert.lengthOf( - statements.filter((statement) => statement.includes("WITH RECURSIVE retained")), - 1, + const retained = statements.filter((statement) => + statement.includes("WITH RECURSIVE retained"), + ); + assert.lengthOf(retained, 1); + // The settled-leaf index also starts with thread_id, and through it this lookup fetches + // every node of the thread to check its status. + const retainedPlan = (yield* sql.unsafe<{ readonly detail: string }>( + `EXPLAIN QUERY PLAN ${retained[0]}`, + )).map((row) => row.detail); + assert.match( + retainedPlan.find((detail) => detail.startsWith("SEARCH live ")) ?? "", + /nodes_live_idx/, + JSON.stringify(retainedPlan), ); assert.lengthOf( statements.filter((statement) => statement.includes("SELECT node.payload_json")), diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 162b9c2cd0da9..02fadbc5f8a17 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -90,6 +90,7 @@ import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import * as SqlClient from "effect/sql/SqlClient"; import type * as Statement from "effect/sql/Statement"; @@ -103,12 +104,15 @@ import { openQuestionsAtFromCandidates, } from "./openQuestions.ts"; import { + isFoldableWorkItem, isThreadHistoryUserTurn, isConversationHistoryItem, THREAD_HISTORY_MAX_RAW_TURNS, missingInterruptRequests, DEFERRED_WORK_ITEM_TYPES, + decodeThreadHistoryCursor, deferWorkHistoryRows, + findCursorEndIndex, selectDeferredWorkPage, encodeThreadHistoryCursor, olderHistoryPagePolicy, @@ -117,6 +121,8 @@ import { THREAD_HISTORY_PAGE_POLICY, THREAD_HISTORY_INLINE_WORK_ITEM_LIMIT, THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT, + type SelectTimelinePageResult, + type ThreadHistoryPrefix, } from "./threadHistoryPaging.ts"; export class ProjectionStoreApplyEventError extends Schema.TaggedError()( @@ -377,6 +383,22 @@ export interface ProjectionRecordFilter { * run is active or `except` names them. */ readonly omitSettledSubagents?: true | { readonly except: ReadonlyArray }; + /** + * Also skips the provider thread of each subagent that `omitSettledSubagents: true` skips, and + * with `omitSettledLeafNodes` its node. A provider thread that shares a provider session with + * the thread stays. + */ + readonly omitSettledSubagentRecords?: boolean; + /** + * For a compacted thread: reads attempts, nodes, messages and provider turns only for runs from + * the latest completed compaction's run on, runs that had not ended when that run was + * requested, and the runs named here. Runs and turn items are not narrowed. + */ + readonly sinceLastCompaction?: { + readonly keepRunIds: ReadonlyArray; + /** Keeps the run that already holds this message, for a message that is sent again. */ + readonly keepMessageId: MessageId; + }; } // A fork inherits its source's history before it has messages of its own, @@ -441,6 +463,8 @@ export interface ActiveShellIndexEntry extends Pick< > { /** False only when no run, request, work item, or watch can make the shell live. */ readonly mayBeLive: boolean; + /** Whether it delegated a task to a linked environment, whose clients nest that task under it. */ + readonly hasRemoteTasks: boolean; } export interface OlderSettledThreadsQuery { @@ -1119,7 +1143,7 @@ type ShellItemCountRow = { const encodeTimelineSources = Schema.encodeEffect( Schema.fromJsonString( - Schema.Array(Schema.Struct({ threadId: Schema.String, id: Schema.String })), + Schema.Array(Schema.Struct({ threadId: Schema.String, id: Schema.NullOr(Schema.String) })), ), ); const encodeIdList = Schema.encodeSync(Schema.fromJsonString(Schema.Array(Schema.String))); @@ -2099,6 +2123,11 @@ export const layer: Layer.Layer = `(${DEFERRED_WORK_ITEM_TYPES.map((type) => `'${type}'`).join(", ")})`, ); + // Other node indexes also start with thread_id. Without this hint SQLite reads a thread's live + // nodes through one of them and fetches every node of the thread to check its status. The + // query must filter on the same status list as the index of migration 060. + const LIVE_NODES_INDEX = sql.literal("INDEXED BY orchestration_v2_projection_nodes_live_idx"); + // An ended task whose completion was acknowledged, delivered or disposed, outside an active run. const settledSubagent = (row: Statement.Fragment) => sql`( ${row}.status IN ('completed', 'failed', 'cancelled', 'interrupted') @@ -2110,6 +2139,16 @@ export const layer: Layer.Layer = ) )`; + // The settled index holds every column the check reads, so the settled tasks are dropped + // there and their rows, each with a full prompt, stay unread. + const unsettledSubagentRowids = (threadId: ThreadId) => sql` + SELECT candidate.rowid + FROM orchestration_v2_projection_subagents AS candidate + INDEXED BY orchestration_v2_projection_subagents_settled_idx + WHERE candidate.thread_id = ${threadId} + AND NOT ${settledSubagent(sql`candidate`)} + `; + // A todo list is never closed when its run ends, so a long thread holds an active one per // old run. Counting those as live work drags each run's nodes and subagents into every window. const todoListOfSettledRun = (row: Statement.Fragment) => sql`( @@ -3429,6 +3468,49 @@ export const layer: Layer.Layer = const threadColumn = (ids: ReadonlyArray | undefined, column = "thread_id") => sql.literal(ids === undefined ? column : `+${column}`); + /** The runs whose records a new message reads. Null when nothing was compacted. */ + const runIdsSinceLastCompaction = Effect.fn("ProjectionStore.runIdsSinceLastCompaction")( + function* ( + threadId: ThreadId, + keep: NonNullable, + ) { + // A held queue can run out of ordinal order, so a run that ended after the compaction's + // run was requested is recent too. Every run row is read anyway, so this scan reads no + // extra pages. + const recent = yield* sql<{ readonly run_id: RunId }>` + WITH compaction AS ( + SELECT run.ordinal, run.requested_at + FROM orchestration_v2_projection_turn_items AS item + INDEXED BY orchestration_v2_projection_turn_items_conversation_idx + INNER JOIN orchestration_v2_projection_runs AS run ON run.run_id = item.run_id + WHERE item.thread_id = ${threadId} + AND item.type = 'compaction' AND item.status = 'completed' + AND item.type NOT IN ${CONVERSATION_INDEX_EXCLUDED_TYPES} + AND run.status <> 'rolled_back' + ORDER BY item.ordinal DESC + LIMIT 1 + ) + SELECT run.run_id + FROM compaction + INNER JOIN orchestration_v2_projection_runs AS run ON run.thread_id = ${threadId} + WHERE run.ordinal >= compaction.ordinal + OR run.completed_at IS NULL + OR run.completed_at >= compaction.requested_at + OR run.status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + UNION + SELECT message.run_id + FROM compaction + INNER JOIN orchestration_v2_projection_messages AS message + ON message.message_id = ${keep.keepMessageId} + WHERE message.thread_id = ${threadId} AND message.run_id IS NOT NULL + `; + // The compaction's own run is always recent, so no rows means no compaction. + return recent.length === 0 + ? null + : encodeIdList([...recent.map((row) => row.run_id), ...keep.keepRunIds]); + }, + ); + const readCanonicalProjection = Effect.fn("ProjectionStore.readCanonicalProjection")( function* ( threadId: ThreadId, @@ -3446,6 +3528,19 @@ export const layer: Layer.Layer = if (!threadRow) { return yield* new ProjectionStoreThreadNotFoundError({ threadId }); } + const recentRunIds = + window === undefined && filter?.sinceLastCompaction !== undefined + ? yield* runIdsSinceLastCompaction(threadId, filter.sinceLastCompaction) + : null; + const inRecentRuns = (column: string) => + recentRunIds === null + ? sql`` + : sql`AND ${sql.literal(column)} IN (SELECT value FROM json_each(${recentRunIds}))`; + // Without the hint SQLite reads every row of the thread to find the recent runs' rows. + const recentRunIndex = (index: string) => + recentRunIds === null + ? sql`` + : sql`INDEXED BY ${sql.literal(`orchestration_v2_projection_${index}`)}`; type WindowPayloadRow = PayloadRow & { readonly work_last_id?: string | null; @@ -3550,6 +3645,7 @@ export const layer: Layer.Layer = SELECT value FROM json_each(${cohortJson("nodeId")}) UNION SELECT node_id FROM orchestration_v2_projection_nodes AS live + ${LIVE_NODES_INDEX} WHERE thread_id = ${threadId} AND status IN ('pending','starting','running','waiting') AND NOT ${todoListOfSettledRun(sql`live`)} UNION @@ -3723,6 +3819,7 @@ export const layer: Layer.Layer = SELECT payload_json FROM orchestration_v2_projection_run_attempts WHERE thread_id = ${threadId} + ${inRecentRuns("run_id")} ORDER BY run_id ASC, attempt_ordinal ASC ` : sql` @@ -3743,13 +3840,29 @@ export const layer: Layer.Layer = filter?.omitSettledLeafNodes === true ? // Seeks the kept nodes. One filter over the thread reads every settled leaf to // drop it. The first predicate must match migration 083's index expression. A - // node's run is always a run of its own thread. + // node's run is always a run of its own thread, and an active run is recent. sql`node.rowid IN ( SELECT rowid FROM orchestration_v2_projection_nodes + ${recentRunIndex("nodes_thread_run_idx")} WHERE thread_id = ${threadId} AND (kind IN ('tool_call', 'assistant_message', 'reasoning') AND status IN ('completed', 'interrupted', 'failed', 'cancelled', 'rolled_back') AND run_id IS NOT NULL) = 0 + ${inRecentRuns("run_id")} + ${ + filter.omitSettledSubagentRecords === true + ? // A subagent's node shares its id. Both indexes hold every column + // read here, so no settled subagent or node row is fetched. + sql`EXCEPT + SELECT settled_node.rowid + FROM orchestration_v2_projection_subagents AS settled + INDEXED BY orchestration_v2_projection_subagents_thread_idx + CROSS JOIN orchestration_v2_projection_nodes AS settled_node + ON settled_node.node_id = settled.subagent_id + WHERE settled.thread_id = ${threadId} + AND settled.rowid NOT IN (${unsettledSubagentRowids(threadId)})` + : sql`` + } UNION ALL SELECT rowid FROM orchestration_v2_projection_nodes WHERE thread_id = ${threadId} @@ -3761,7 +3874,8 @@ export const layer: Layer.Layer = AND kind IN ('tool_call', 'assistant_message', 'reasoning') AND status IN ('completed', 'interrupted', 'failed', 'cancelled', 'rolled_back') )` - : sql`${threadColumn(filter?.nodeIds, "node.thread_id")} = ${threadId}` + : sql`${threadColumn(filter?.nodeIds, "node.thread_id")} = ${threadId} + ${inRecentRuns("node.run_id")}` } ${filter?.nodeIds === undefined ? sql`` : sql`AND node.node_id IN (SELECT value FROM json_each(${encodeIdList(filter.nodeIds)}))`} ORDER BY COALESCE(node.started_at, ''), node.node_id ASC @@ -3792,15 +3906,7 @@ export const layer: Layer.Layer = ${filter?.subagentRunIds === undefined ? sql`` : sql`AND run_id IN (SELECT value FROM json_each(${encodeIdList(filter.subagentRunIds)}))`} ${ filter?.omitSettledSubagents === true - ? // The settled index holds every column this check reads, so the settled - // tasks are dropped there and their rows, each with a full prompt, stay unread. - sql`AND subagent.rowid IN ( - SELECT candidate.rowid - FROM orchestration_v2_projection_subagents AS candidate - INDEXED BY orchestration_v2_projection_subagents_settled_idx - WHERE candidate.thread_id = ${threadId} - AND NOT ${settledSubagent(sql`candidate`)} - )` + ? sql`AND subagent.rowid IN (${unsettledSubagentRowids(threadId)})` : filter?.omitSettledSubagents !== undefined ? sql`AND ( subagent_id IN (SELECT value FROM json_each(${encodeIdList(filter.omitSettledSubagents.except)})) @@ -3850,12 +3956,35 @@ export const layer: Layer.Layer = FROM orchestration_v2_projection_provider_threads WHERE (thread_id = ${threadId} OR owner_node_id IN (${nodesOwningProviderThreads(threadId)}) - OR provider_thread_id IN ( + OR ${ + filter?.omitSettledSubagentRecords === true + ? // A dispatcher thread holds thousands of settled tasks. Their provider + // threads belong to the child threads; only a session this thread also + // uses is probed for background work when the thread detaches it. + sql`provider_thread_id IN ( + SELECT provider_thread_id + FROM orchestration_v2_projection_subagents + WHERE rowid IN (${unsettledSubagentRowids(threadId)}) + AND provider_thread_id IS NOT NULL + ) + OR (provider_session_id IN ( + SELECT provider_session_id + FROM orchestration_v2_projection_provider_session_bindings + WHERE thread_id = ${threadId} + ) + AND EXISTS ( + SELECT 1 FROM orchestration_v2_projection_subagents AS owner + WHERE owner.provider_thread_id = + orchestration_v2_projection_provider_threads.provider_thread_id + AND owner.thread_id = ${threadId} + ))` + : sql`provider_thread_id IN ( SELECT provider_thread_id FROM orchestration_v2_projection_subagents WHERE thread_id = ${threadId} AND provider_thread_id IS NOT NULL - )) + )` + }) ${filter?.providerThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerThreadIds)}))`} ORDER BY COALESCE(first_run_ordinal, 0), provider_thread_id ASC ` @@ -3877,6 +4006,13 @@ export const layer: Layer.Layer = SELECT payload_json FROM orchestration_v2_projection_provider_turns WHERE thread_id = ${threadId} + ${ + recentRunIds === null + ? sql`` + : sql`AND run_attempt_id IN ( + SELECT attempt_id FROM orchestration_v2_projection_run_attempts + WHERE thread_id = ${threadId} ${inRecentRuns("run_id")})` + } ${filter?.providerTurnAttemptIds === undefined ? sql`` : sql`AND run_attempt_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerTurnAttemptIds)}))`} ${filter?.providerTurnThreadIds === undefined ? sql`` : sql`AND provider_thread_id IN (SELECT value FROM json_each(${encodeIdList(filter.providerTurnThreadIds)}))`} ${ @@ -3922,7 +4058,9 @@ export const layer: Layer.Layer = : window === undefined ? sql` SELECT payload_json FROM orchestration_v2_projection_messages - WHERE ${threadColumn(filter?.messageIds)} = ${threadId} + ${recentRunIndex("messages_run_idx")} + WHERE ${recentRunIds === null ? threadColumn(filter?.messageIds) : sql.literal("thread_id")} = ${threadId} + ${inRecentRuns("run_id")} ${filter?.messageIds === undefined ? sql`` : sql`AND message_id IN (SELECT value FROM json_each(${encodeIdList(filter.messageIds)}))`} ${filter?.messageRoles === undefined ? sql`` : sql`AND role IN (SELECT value FROM json_each(${encodeIdList(filter.messageRoles)}))`} ${filter?.monitorNotificationsOnly === true ? sql`AND json_extract(payload_json, '$.notification.source.kind') = 'monitor'` : sql``} @@ -4656,10 +4794,10 @@ export const layer: Layer.Layer = WHERE subagents.child_thread_id IS NOT NULL AND EXISTS ( SELECT 1 FROM orchestration_v2_projection_nodes AS node + ${LIVE_NODES_INDEX} WHERE node.thread_id = subagents.child_thread_id - -- Matches nodes_live_idx; +run_id keeps thread_run_idx from scanning settled nodes. AND node.status IN ('pending', 'starting', 'running', 'waiting') - AND +node.run_id IS NULL + AND node.run_id IS NULL AND node.kind = 'root_turn' ) UNION @@ -5060,6 +5198,7 @@ export const layer: Layer.Layer = `, nodes: sql` SELECT node.payload_json FROM orchestration_v2_projection_nodes AS node + ${LIVE_NODES_INDEX} WHERE node.thread_id = ${threadId} AND node.status IN ('pending', 'starting', 'running', 'waiting') AND ( @@ -6159,11 +6298,11 @@ export const layer: Layer.Layer = const readTimelineIndex: ( threadId: ThreadId, seen: ReadonlySet, - includePersistentOutput?: boolean, + includeAttempts?: boolean, ) => Effect.Effect = Effect.fn( "ProjectionStore.readTimelineIndex", )( - function* (threadId: ThreadId, seen: ReadonlySet, includePersistentOutput = false) { + function* (threadId: ThreadId, seen: ReadonlySet, includeAttempts = false) { const records = yield* getThreadRecords(threadId, ["runs", "attempts"]); const rows = yield* sql<{ turn_item_id: string; @@ -6176,21 +6315,17 @@ export const layer: Layer.Layer = message_id: string | null; status: OrchestrationV2TurnItem["status"]; ordinal: number; - persistent_output: number; attempt_id: string | null; attempt_status: string | null; }>`SELECT item.turn_item_id, item.run_id, item.node_id, item.parent_item_id, item.type, item.status, item.ordinal, - ${includePersistentOutput ? sql`attempt.attempt_id` : sql`NULL`} AS attempt_id, - ${includePersistentOutput ? sql`attempt.status` : sql`NULL`} AS attempt_status, - ${ - includePersistentOutput ? sql`CASE WHEN ${inlineWorkOutput} THEN 1 ELSE 0 END` : sql`0` - } AS persistent_output, + ${includeAttempts ? sql`attempt.attempt_id` : sql`NULL`} AS attempt_id, + ${includeAttempts ? sql`attempt.status` : sql`NULL`} AS attempt_status, CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.inputIntent') END AS input_intent, CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.createdBy') END AS created_by, CASE WHEN item.type IN ('user_message', 'assistant_message') THEN json_extract(item.payload_json, '$.messageId') END AS message_id FROM orchestration_v2_projection_turn_items AS item ${ - includePersistentOutput + includeAttempts ? sql`LEFT JOIN orchestration_v2_projection_nodes AS node ON node.node_id = item.node_id LEFT JOIN orchestration_v2_projection_run_attempts AS attempt ON attempt.attempt_id = ( SELECT attempt_id FROM orchestration_v2_projection_run_attempts @@ -6214,7 +6349,6 @@ export const layer: Layer.Layer = runStatus: row.run_id === null ? undefined : runStatuses.get(row.run_id), attemptId: row.attempt_id, attemptStatus: row.attempt_status, - persistentOutput: row.persistent_output === 1, ...(row.input_intent === null ? {} : { inputIntent: row.input_intent }), ...(row.created_by === null ? {} : { createdBy: row.created_by }), ...(row.message_id === null ? {} : { messageId: MessageId.make(row.message_id) }), @@ -6237,7 +6371,7 @@ export const layer: Layer.Layer = const source = yield* readTimelineIndex( fork.threadId, new Set([...seen, threadId]), - includePersistentOutput, + includeAttempts, ); const sourceRun = source.records.runs.find((run) => run.id === fork.runId); let inherited: Array = []; @@ -6308,14 +6442,14 @@ export const layer: Layer.Layer = Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })), ); const readSnapshotTimelineIndex = Effect.fn("ProjectionStore.readSnapshotTimelineIndex")( - function* (threadId: ThreadId, includePersistentOutput: boolean) { - const key = `${includePersistentOutput ? "work" : "plain"}:${threadId}`; + function* (threadId: ThreadId, includeAttempts: boolean) { + const key = `${includeAttempts ? "work" : "plain"}:${threadId}`; const cached = timelineIndexes.get(key); const index = cached !== undefined && (yield* latestThreadEventSequence(threadId, cached.index.threadIds)) === cached.sequence ? cached.index - : yield* readTimelineIndex(threadId, new Set(), includePersistentOutput); + : yield* readTimelineIndex(threadId, new Set(), includeAttempts); const sequence = index === cached?.index ? cached.sequence @@ -6333,6 +6467,459 @@ export const layer: Layer.Layer = readTimelineIndex(threadId, new Set()).pipe(Effect.map((index) => index.visible)), ); + /** + * Index columns of the thread's own turn items that `where` selects, in timeline order. The + * same columns as `readTimelineIndex`, which reads every row and stays as it is. + */ + const readTimelineWindow = Effect.fn("ProjectionStore.readTimelineWindow")(function* ( + threadId: ThreadId, + runs: ProjectionRecords<"runs">["runs"], + includePersistentOutput: boolean, + where: Statement.Fragment, + limit: Statement.Fragment = sql``, + ) { + const rows = yield* sql<{ + turn_item_id: string; + run_id: string | null; + node_id: string | null; + parent_item_id: string | null; + type: OrchestrationV2TurnItem["type"]; + input_intent: NonNullable | null; + created_by: "user" | "agent" | "system" | null; + message_id: string | null; + status: OrchestrationV2TurnItem["status"]; + ordinal: number; + persistent_output: number; + attempt_id: string | null; + attempt_status: string | null; + }>`SELECT item.turn_item_id, item.run_id, item.node_id, item.parent_item_id, item.type, item.status, item.ordinal, + ${includePersistentOutput ? sql`attempt.attempt_id` : sql`NULL`} AS attempt_id, + ${includePersistentOutput ? sql`attempt.status` : sql`NULL`} AS attempt_status, + ${ + includePersistentOutput ? sql`CASE WHEN ${inlineWorkOutput} THEN 1 ELSE 0 END` : sql`0` + } AS persistent_output, + CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.inputIntent') END AS input_intent, + CASE WHEN item.type = 'user_message' THEN json_extract(item.payload_json, '$.createdBy') END AS created_by, + CASE WHEN item.type IN ('user_message', 'assistant_message') THEN json_extract(item.payload_json, '$.messageId') END AS message_id + FROM orchestration_v2_projection_turn_items AS item + ${ + includePersistentOutput + ? sql`LEFT JOIN orchestration_v2_projection_nodes AS node ON node.node_id = item.node_id + LEFT JOIN orchestration_v2_projection_run_attempts AS attempt ON attempt.attempt_id = ( + SELECT attempt_id FROM orchestration_v2_projection_run_attempts + WHERE run_id = item.run_id AND root_node_id = COALESCE(node.root_node_id, item.node_id) + ORDER BY attempt_ordinal DESC LIMIT 1 + )` + : sql`` + } + WHERE item.thread_id = ${threadId} ${where} + ORDER BY item.ordinal ASC, item.turn_item_id ASC ${limit}`; + const runStatuses = new Map(runs.map((run) => [String(run.id), run.status])); + return rows.map((row): TimelineIndexItem => ({ + id: TurnItemId.make(row.turn_item_id), + threadId, + runId: row.run_id === null ? null : RunId.make(row.run_id), + nodeId: row.node_id === null ? null : NodeId.make(row.node_id), + parentItemId: row.parent_item_id === null ? null : TurnItemId.make(row.parent_item_id), + type: row.type, + status: row.status, + ordinal: row.ordinal, + runStatus: row.run_id === null ? undefined : runStatuses.get(row.run_id), + attemptId: row.attempt_id, + attemptStatus: row.attempt_status, + persistentOutput: row.persistent_output === 1, + ...(row.input_intent === null ? {} : { inputIntent: row.input_intent }), + ...(row.created_by === null ? {} : { createdBy: row.created_by }), + ...(row.message_id === null ? {} : { messageId: MessageId.make(row.message_id) }), + })); + }); + const localTimelineRow = (item: TimelineIndexItem): TimelineIndexRow => ({ + sourceThreadId: item.threadId, + sourceItemId: item.id, + visibility: "local", + item, + }); + + /** + * Reads parts of a thread's own timeline without indexing all of it. Null when callers read + * the full index instead: the thread shows fork ancestry, so its rows come from other threads, + * or a full index of this snapshot is cached already. + */ + const openLocalTimeline = Effect.fn("ProjectionStore.openLocalTimeline")(function* ( + threadId: ThreadId, + includePersistentOutput = false, + ) { + // A read that only the full index can answer left it cached, and it answers faster than + // a window. The key is the one `readSnapshotTimelineIndex` uses. + const cached = timelineIndexes.get( + `${includePersistentOutput ? "work" : "plain"}:${threadId}`, + ); + if ( + cached !== undefined && + (yield* latestThreadEventSequence(threadId, cached.index.threadIds)) === cached.sequence + ) + return null; + // Checked in SQL, so a fork loads no runs and no thread here before the full index does. + const ownRowsOnly = yield* sql` + SELECT 1 FROM orchestration_v2_projection_threads + WHERE thread_id = ${threadId} + AND NOT (json_extract(payload_json, '$.forkedFrom.type') IS 'run' + AND json_extract(payload_json, '$.lineage.sideChat') IS NOT 1)`; + if (ownRowsOnly.length === 0) return null; + const records = yield* getThreadRecords(threadId, ["runs", "attempts"]); + if (inheritedRunFork(records.thread) !== null) return null; + const superseded = records.attempts.filter((attempt) => attempt.status === "superseded"); + const stopRequests = + superseded.length === 0 + ? [] + : yield* sql<{ run_id: string | null }>` + SELECT DISTINCT run_id FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND type = 'run_interrupt_request'`; + const isVisible = createOrchestrationV2TurnItemVisibility({ + runs: records.runs, + attempts: records.attempts, + items: stopRequests.map((row) => ({ + type: "run_interrupt_request" as const, + runId: row.run_id === null ? null : RunId.make(row.run_id), + nodeId: null, + })), + }); + // Only these runs can hide rows: every row of a rolled-back run, the queued turn of a + // cancelled run, and the stop result of a replaced attempt. So the hidden rows are found + // without reading the thread. + const stoppedRuns = new Set(stopRequests.map((row) => row.run_id)); + const runsWithStatus = (status: "rolled_back" | "cancelled") => + records.runs.flatMap((run) => (run.status === status ? [String(run.id)] : [])); + const rolledBack = runsWithStatus("rolled_back"); + const cancelled = runsWithStatus("cancelled"); + const steered = [...new Set(superseded.map((attempt) => String(attempt.runId)))].filter( + (runId) => !stoppedRuns.has(runId) && !rolledBack.includes(runId), + ); + type HiddenCandidate = { + turn_item_id: string; + run_id: string; + node_id: string | null; + type: OrchestrationV2TurnItem["type"]; + ordinal: number; + input_intent: NonNullable | null; + }; + const candidateColumns = sql`item.turn_item_id, item.run_id, item.node_id, item.type, + item.ordinal, CASE WHEN item.type = 'user_message' + THEN json_extract(item.payload_json, '$.inputIntent') END AS input_intent`; + const [rolledBackRows, conversationRows] = yield* Effect.all([ + rolledBack.length === 0 + ? Effect.succeed([]) + : sql` + SELECT ${candidateColumns} + FROM json_each(${encodeIdList(rolledBack)}) AS wanted + CROSS JOIN orchestration_v2_projection_turn_items AS item + INDEXED BY orchestration_v2_projection_turn_items_thread_run_idx + ON item.thread_id = ${threadId} AND item.run_id = wanted.value`, + // The conversation index holds the type and run of these rows, so only the matches are + // fetched. Through the run index, every row of each cancelled run would be. + cancelled.length + steered.length === 0 + ? Effect.succeed([]) + : sql` + SELECT ${candidateColumns} + FROM orchestration_v2_projection_turn_items AS item + INDEXED BY orchestration_v2_projection_turn_items_conversation_idx + WHERE item.thread_id = ${threadId} + AND item.type NOT IN ${CONVERSATION_INDEX_EXCLUDED_TYPES} + AND ((item.type = 'user_message' + AND item.run_id IN (SELECT value FROM json_each(${encodeIdList(cancelled)}))) + OR (item.type = 'run_interrupt_result' + AND item.run_id IN (SELECT value FROM json_each(${encodeIdList(steered)}))))`, + ]); + const hidden = [...rolledBackRows, ...conversationRows].filter( + (row) => + !isVisible({ + type: row.type, + runId: RunId.make(row.run_id), + nodeId: row.node_id === null ? null : NodeId.make(row.node_id), + ...(row.input_intent === null ? {} : { inputIntent: row.input_intent }), + }), + ); + /** Counts the visible rows that sort before the given ordinal and item id. */ + const visibleBefore = Effect.fn("ProjectionStore.countVisibleTimelineRows")(function* ( + ordinal: number, + itemId = "", + ) { + const rows = yield* sql<{ count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND (ordinal, turn_item_id) < (${ordinal}, ${itemId})`; + const hiddenBefore = hidden.filter( + (row) => + row.ordinal < ordinal || + (row.ordinal === ordinal && + Buffer.compare(Buffer.from(row.turn_item_id), Buffer.from(itemId)) < 0), + ); + return (rows[0]?.count ?? 0) - hiddenBefore.length; + }); + return { + records, + isVisible, + hidden, + visibleBefore, + read: (where: Statement.Fragment, limit?: Statement.Fragment) => + readTimelineWindow(threadId, records.runs, includePersistentOutput, where, limit), + }; + }); + type LocalTimeline = NonNullable>>; + type IndexedTimelineRow = TimelineIndexRow & { + readonly position: number; + readonly canonicalPosition: number; + }; + + /** True when a visible user turn starts before the ordinal. Reads the nearest user messages. */ + const olderUserTurn = (local: LocalTimeline, ordinal: number) => + sql<{ + run_id: string | null; + node_id: string | null; + input_intent: NonNullable; + }>` + SELECT item.run_id, item.node_id, + json_extract(item.payload_json, '$.inputIntent') AS input_intent + FROM orchestration_v2_projection_turn_items AS item + INDEXED BY orchestration_v2_projection_turn_items_user_message_idx + WHERE item.thread_id = ${local.records.thread.id} AND item.type = 'user_message' + AND item.ordinal < ${ordinal} + AND json_extract(item.payload_json, '$.inputIntent') IN ('turn_start', 'queued_turn') + AND json_extract(item.payload_json, '$.createdBy') = 'user' + ORDER BY item.ordinal DESC, item.turn_item_id DESC + LIMIT ${local.hidden.length + 1}`.pipe( + Effect.map((rows) => + rows.some((row) => + local.isVisible({ + type: "user_message", + runId: row.run_id === null ? null : RunId.make(row.run_id), + nodeId: row.node_id === null ? null : NodeId.make(row.node_id), + inputIntent: row.input_intent, + }), + ), + ), + ); + + /** + * A notification starts a turn only as its run's first input. For each run whose first input + * in `rows` is a notification, this finds whether an input row sits before the ordinal. + */ + const runsStartedBefore = Effect.fn("ProjectionStore.runsStartedBefore")(function* ( + local: LocalTimeline, + ordinal: number, + rows: ReadonlyArray, + ) { + const seen = new Set(); + const unknown = new Set(); + for (const { item } of rows) { + if (item.runId === null) continue; + if (item.type !== "user_message" && item.type !== "notification") continue; + if (item.type === "notification" && !seen.has(item.runId)) unknown.add(item.runId); + seen.add(item.runId); + } + if (unknown.size === 0) return new Set(); + const counts = yield* sql<{ run_id: string; inputs: number }>` + SELECT wanted.value AS run_id, ( + SELECT COUNT(*) FROM orchestration_v2_projection_turn_items AS input + INDEXED BY orchestration_v2_projection_turn_items_conversation_idx + WHERE input.thread_id = ${local.records.thread.id} + AND input.ordinal >= ( + SELECT MIN(ordinal) FROM orchestration_v2_projection_turn_items + WHERE run_id = wanted.value + ) + AND input.ordinal < ${ordinal} + AND input.type NOT IN ${CONVERSATION_INDEX_EXCLUDED_TYPES} + AND input.type IN ('user_message', 'notification') + AND input.run_id = wanted.value + ) AS inputs + FROM json_each(${encodeIdList([...unknown])}) AS wanted`; + const isHiddenInput = (row: LocalTimeline["hidden"][number], runId: string) => + row.run_id === runId && + row.ordinal < ordinal && + (row.type === "user_message" || row.type === "notification"); + return new Set( + counts.flatMap((row) => + row.inputs > local.hidden.filter((hidden) => isHiddenInput(hidden, row.run_id)).length + ? [row.run_id] + : [], + ), + ); + }); + + /** + * Selects an older history page from the rows near its cursor. The window grows until the + * page ends inside rows whose inputs are all known, so `select` gives the page it gives on + * the full index. Null when the cursor names no visible row, which needs the full index. + */ + const selectHistoryPageInWindow = Effect.fn("ProjectionStore.selectHistoryPageInWindow")( + function* < + Selection extends { + readonly page: SelectTimelinePageResult; + readonly historyItems: ReadonlyArray; + }, + >( + local: LocalTimeline, + input: { + readonly cursor: string; + readonly throughEntryId: string | undefined; + readonly workMode: "deferred" | "work" | undefined; + }, + select: ( + indexed: ReadonlyArray, + prefix?: ThreadHistoryPrefix, + ) => Effect.Effect, + ) { + const threadId = local.records.thread.id; + const decoded = Result.try(() => decodeThreadHistoryCursor(input.cursor)); + if (Result.isFailure(decoded) || decoded.success.st !== threadId) return null; + const cursor = decoded.success; + // Looked up by key alone: with the thread in the query, SQLite scans the thread's index. + const ends = (yield* sql<{ turn_item_id: string; thread_id: string; ordinal: number }>` + SELECT turn_item_id, thread_id, ordinal FROM orchestration_v2_projection_turn_items + WHERE turn_item_id IN (${cursor.si}, ${input.throughEntryId ?? cursor.si})`).filter( + (row) => row.thread_id === threadId, + ); + const upper = ends.find((row) => row.turn_item_id === cursor.si)?.ordinal; + if (upper === undefined) return null; + /* Runs for each window this operation tries; the operation owns the span. */ + const indexFrom = Effect.fnUntraced(function* ( + items: ReadonlyArray, + from: number | null, + ) { + const base = from === null ? 0 : yield* local.visibleBefore(from); + return items.filter(local.isVisible).map((item, offset): IndexedTimelineRow => ({ + ...localTimelineRow(item), + position: base + offset, + canonicalPosition: base + offset, + })); + }); + const isCursorRow = (row: TimelineIndexRow) => row.sourceItemId === cursor.si; + // The ordinals come from the stop request index, so this does not walk the thread. + const interruptRequests = local + .read( + sql`AND item.type = 'run_interrupt_request' AND item.ordinal IN ( + SELECT ordinal FROM orchestration_v2_projection_turn_items + INDEXED BY orchestration_v2_projection_turn_items_stop_request_idx + WHERE thread_id = ${threadId} AND type = 'run_interrupt_request')`, + ) + .pipe(Effect.flatMap((items) => indexFrom(items, null))); + + if (input.workMode === "work") { + // A work group lies between its first row and the cursor, so that range is the read. + const lower = ends.find((row) => row.turn_item_id === input.throughEntryId)?.ordinal; + if (lower === undefined) return null; + const indexed = yield* indexFrom( + yield* local.read(sql`AND item.ordinal >= ${lower} AND item.ordinal <= ${upper}`), + lower, + ); + if (!indexed.some(isCursorRow)) return null; + if (!indexed.some((row) => row.sourceItemId === input.throughEntryId)) return null; + return { + indexed, + selection: yield* select(indexed), + olderUserTurn: olderUserTurn(local, lower), + interruptRequests, + }; + } + + const rowsBelow = (ordinal: number, count: number) => + sql<{ ordinal: number }>` + SELECT ordinal FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND ordinal < ${ordinal} + ORDER BY ordinal DESC LIMIT 1 OFFSET ${count - 1}`.pipe( + Effect.map((rows) => rows[0]?.ordinal ?? null), + ); + // `trusted` is the lowest ordinal the page may reach. `lower` can sit below it, because + // a run that folds work is read whole. + let step = THREAD_HISTORY_TURN_SNAPSHOT_ROW_LIMIT; + let trusted = yield* rowsBelow(upper, step); + let lower = trusted; + let higher = upper; + let items = yield* local.read( + lower === null + ? sql`AND item.ordinal <= ${upper}` + : sql`AND item.ordinal >= ${lower} AND item.ordinal <= ${upper}`, + ); + const wholeRuns = new Set(); + while (true) { + if (input.workMode === "deferred") { + // Folding needs every row of a run: its stop and error rows, and its group sizes. + const folding = new Set(); + for (const item of items) { + if (item.runId === null || wholeRuns.has(item.runId)) continue; + if (item.ordinal > upper || (trusted !== null && item.ordinal < trusted)) continue; + if (isFoldableWorkItem(item) && local.isVisible(item)) folding.add(item.runId); + } + if (folding.size > 0) { + const runs = encodeIdList([...folding]); + const [extent] = yield* sql<{ lower: number; higher: number }>` + SELECT MIN(run.lower) AS lower, MAX(run.higher) AS higher FROM ( + SELECT + (SELECT MIN(ordinal) FROM orchestration_v2_projection_turn_items + WHERE run_id = wanted.value) AS lower, + (SELECT MAX(ordinal) FROM orchestration_v2_projection_turn_items + WHERE run_id = wanted.value) AS higher + FROM json_each(${runs}) AS wanted + ) AS run`; + if (extent !== undefined && lower !== null && extent.lower < lower) { + const below = yield* local.read( + sql`AND item.ordinal >= ${extent.lower} AND item.ordinal < ${lower}`, + ); + items = below.concat(items); + lower = extent.lower; + } + if (extent !== undefined && extent.higher > higher) { + const newer = yield* local.read( + sql`AND item.ordinal > ${higher} AND item.ordinal <= ${extent.higher}`, + ); + items = items.concat(newer); + higher = extent.higher; + } + for (const runId of folding) wholeRuns.add(runId); + } + } + const indexed = yield* indexFrom(items, lower); + const end = indexed.findIndex(isCursorRow); + if (end < 0) return null; + const older = lower === null ? Effect.succeed(false) : olderUserTurn(local, lower); + const prefix: ThreadHistoryPrefix | undefined = + lower === null + ? undefined + : { + hasUserTurn: indexed + .slice(0, end) + .some((row) => isThreadHistoryUserTurn(row.item)) + ? false + : yield* older, + startedRuns: yield* runsStartedBefore(local, lower, indexed), + }; + const selection = yield* select(indexed, prefix); + // Without its row the cursor falls back to a position, which only the full index has. + if (!selection.historyItems.some(isCursorRow)) return null; + const oldest = selection.page.oldestScanned; + if ( + lower === null || + (trusted !== null && + oldest !== undefined && + oldest !== selection.historyItems[0] && + oldest.item.ordinal >= trusted) + ) { + return { indexed, selection, olderUserTurn: older, interruptRequests }; + } + step *= 2; + trusted = trusted === null ? null : yield* rowsBelow(trusted, step); + if (trusted === null || trusted < lower) { + const below = yield* local.read( + trusted === null + ? sql`AND item.ordinal < ${lower}` + : sql`AND item.ordinal >= ${trusted} AND item.ordinal < ${lower}`, + ); + items = below.concat(items); + lower = trusted; + } + } + }, + ); + const getThreadHistoryPage: ProjectionStoreV2Shape["getThreadHistoryPage"] = ( threadId, cursor, @@ -6343,8 +6930,15 @@ export const layer: Layer.Layer = sql .withTransaction( Effect.gen(function* () { - const index = yield* readSnapshotTimelineIndex(threadId, workMode !== undefined); - if (index.records.thread.deletedAt !== null) + const withWork = workMode !== undefined; + // A jump to a target entry selects from the whole index. + const local = + (workMode === "work") === (throughEntryId !== undefined) + ? yield* openLocalTimeline(threadId, withWork) + : null; + const full = + local === null ? yield* readSnapshotTimelineIndex(threadId, withWork) : null; + if ((local ?? full)?.records.thread.deletedAt !== null) return yield* new ProjectionStoreThreadNotFoundError({ threadId }); const revisions = yield* sql<{ sequence: number; @@ -6352,43 +6946,132 @@ export const layer: Layer.Layer = FROM orchestration_events WHERE application_event_version = 2 AND aggregate_kind = 'thread' AND stream_id = ${threadId}`; const snapshotSequence = revisions[0]?.sequence ?? 0; - const indexed = index.visible.map((row, position) => ({ - ...row, - position, - canonicalPosition: position, - })); - const historyItems = workMode === "deferred" ? deferWorkHistoryRows(indexed) : indexed; - const selection = yield* Effect.try({ - try: () => { - const policy = olderHistoryPagePolicy({ items: indexed, cursor, throughEntryId }); - const page = - workMode === "work" - ? selectDeferredWorkPage({ - items: indexed, - cursor, - throughEntryId, - snapshotSequence, - rowEncodedBytes: () => 0, - }) - : selectHistoryPageFromCursor({ - items: historyItems, - cursor, - snapshotSequence, - rowEncodedBytes: () => 0, - policy, - }); - return { policy, page }; - }, - catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), + const select = ( + indexed: ReadonlyArray, + prefix?: ThreadHistoryPrefix, + ) => + Effect.try({ + try: () => { + const historyItems = + workMode === "deferred" ? deferWorkHistoryRows(indexed) : indexed; + const policy = olderHistoryPagePolicy({ items: indexed, cursor, throughEntryId }); + const page = + workMode === "work" + ? selectDeferredWorkPage({ + items: indexed, + cursor, + throughEntryId, + snapshotSequence, + rowEncodedBytes: () => 0, + }) + : selectHistoryPageFromCursor({ + items: historyItems, + cursor, + snapshotSequence, + rowEncodedBytes: () => 0, + policy, + prefix, + }); + return { policy, page, historyItems }; + }, + catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), + }); + const window = + local === null + ? null + : yield* selectHistoryPageInWindow( + local, + { cursor, throughEntryId, workMode }, + select, + ); + const whole = Effect.gen(function* () { + const index = full ?? (yield* readSnapshotTimelineIndex(threadId, withWork)); + const indexed = index.visible.map((row, position): IndexedTimelineRow => ({ + ...row, + position, + canonicalPosition: position, + })); + let selection = yield* select(indexed); + // The full index does not say which rows hold inline output: finding it scans + // payloads, which costs a whole long thread several seconds. Scan only the runs + // the page spans, then select again with what they hold. + const scannedRuns = new Set(); + const persistentOutputs = new Set(); + // Rows hidden in a work group move the page, so the scan always reaches the + // cursor's own row, or the row its stale position falls back to. + const cursorPosition = + workMode === undefined + ? -1 + : Math.min( + findCursorEndIndex(indexed, decodeThreadHistoryCursor(cursor)), + indexed.length - 1, + ); + while (workMode !== undefined) { + const { page } = selection; + const span = [...page.items.slice(0, 1), ...page.items.slice(-1)].map( + (row) => row.canonicalPosition, + ); + if (cursorPosition >= 0) span.push(cursorPosition); + if (span.length === 0) break; + const runs = new Map( + // A work page holds rows of one run, which can be the rows that have no run. + (workMode === "work" + ? page.items.slice(0, 1) + : indexed.slice(Math.min(...span), Math.max(...span) + 1) + ).flatMap(({ sourceThreadId, item }) => + (workMode === "work" || + (item.runId !== null && + (item.runStatus === "completed" || item.attemptStatus === "superseded"))) && + !scannedRuns.has(`${sourceThreadId}:${item.runId}`) + ? [ + [ + `${sourceThreadId}:${item.runId}`, + { threadId: sourceThreadId, id: item.runId }, + ] as const, + ] + : [], + ), + ); + if (runs.size === 0) break; + for (const run of runs.keys()) scannedRuns.add(run); + const found = yield* sql<{ thread_id: string; turn_item_id: string }>` + SELECT item.thread_id, item.turn_item_id + FROM json_each(${yield* encodeTimelineSources([...runs.values()])}) AS wanted + CROSS JOIN orchestration_v2_projection_turn_items AS item + ON item.thread_id = json_extract(wanted.value, '$.threadId') + AND item.run_id IS json_extract(wanted.value, '$.id') + WHERE item.status = 'completed' AND ${inlineWorkOutput}`; + if (found.length === 0) break; + for (const row of found) + persistentOutputs.add(`${row.thread_id}:${row.turn_item_id}`); + selection = yield* select( + indexed.map((row) => + persistentOutputs.has(`${row.sourceThreadId}:${row.sourceItemId}`) + ? { ...row, item: { ...row.item, persistentOutput: true } } + : row, + ), + ); + } + return { + indexed, + selection, + olderUserTurn: Effect.succeed(false), + interruptRequests: Effect.succeed(indexed), + }; }); + const { indexed, selection, olderUserTurn, interruptRequests } = + window ?? (yield* whole); const { page } = selection; const policy = workMode === "work" ? THREAD_HISTORY_PAGE_POLICY : selection.policy; const end = (page.items.at(-1)?.canonicalPosition ?? -1) + 1; - const hasUserTurns = index.visible - .slice(0, end) - .some((row) => isThreadHistoryUserTurn(row.item)); + const hasUserTurns = + conversationOnly === true && + (indexed.some( + (row) => row.canonicalPosition < end && isThreadHistoryUserTurn(row.item), + ) || + (yield* olderUserTurn)); const materialize = Effect.fn("ProjectionStore.materializeHistoryRows")(function* ( - rows: ReadonlyArray<(typeof indexed)[number]>, + rows: ReadonlyArray, ) { if (rows.length === 0) return []; const sources = yield* encodeTimelineSources( @@ -6431,7 +7114,7 @@ export const layer: Layer.Layer = ); }); const items = yield* materialize( - conversationOnly && hasUserTurns + hasUserTurns ? page.items.filter((row) => isConversationHistoryItem(row.item)) : page.items, ); @@ -6439,7 +7122,14 @@ export const layer: Layer.Layer = const requests = workMode === "work" ? [] - : yield* materialize(missingInterruptRequests(indexed, bounded.items)); + : yield* materialize( + missingInterruptRequests( + bounded.items.some((row) => row.item.type === "run_interrupt_result") + ? yield* interruptRequests + : [], + bounded.items, + ), + ); const pageItems = [...requests, ...bounded.items].map((row, position) => ({ ...row, position, @@ -6456,39 +7146,118 @@ export const layer: Layer.Layer = ) .pipe(Effect.mapError(controlReadError(threadId))); + /** + * The rows `getTimelinePage` matches, cut after the first `limit + 1`, with their positions + * in the full visible index. Reads only the rows from the start position to the page end. + */ + const matchLocalTimelineRows = Effect.fn("ProjectionStore.matchLocalTimelineRows")(function* ( + local: LocalTimeline, + options: ProjectionTimelinePageOptions, + ) { + const threadId = local.records.thread.id; + const totals = yield* sql<{ count: number }>` + SELECT COUNT(*) AS count FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId}`; + const totalItems = (totals[0]?.count ?? 0) - local.hidden.length; + if (options.itemId !== undefined) { + const found = (yield* local.read(sql`AND item.turn_item_id = ${options.itemId}`)).filter( + local.isVisible, + ); + const matching = yield* Effect.forEach(found, (item) => + local + .visibleBefore(item.ordinal, item.id) + .pipe(Effect.map((position) => ({ ...localTimelineRow(item), position }))), + ); + return { matching, totalItems }; + } + const afterPosition = options.afterPosition ?? -1; + const firstPosition = Math.max(afterPosition + 1, 0); + // The row at this raw offset sorts at or before the first wanted row: hidden rows only + // push visible rows to later offsets. + const starts = yield* sql<{ ordinal: number }>` + SELECT ordinal FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} + ORDER BY ordinal ASC, turn_item_id ASC LIMIT 1 OFFSET ${firstPosition}`; + const start = starts[0]?.ordinal; + if (start === undefined) return { matching: [], totalItems }; + const base = yield* local.visibleBefore(start); + const hiddenAfter = local.hidden.filter((row) => row.ordinal >= start).length; + const messagesOnly = options.view !== "activity"; + const candidates = (yield* local.read( + messagesOnly + ? sql`AND item.ordinal >= ${start} + AND item.type IN ('user_message', 'assistant_message', 'proposed_plan')` + : sql`AND item.ordinal >= ${start}`, + sql`LIMIT ${firstPosition - base + Math.min(options.limit, totalItems) + 1 + hiddenAfter}`, + )).filter(local.isVisible); + const positions = new Map(); + const last = candidates.at(-1); + if (messagesOnly && last !== undefined) { + const hiddenIds = new Set(local.hidden.map((row) => row.turn_item_id)); + const span = yield* sql<{ turn_item_id: string }>` + SELECT turn_item_id FROM orchestration_v2_projection_turn_items + WHERE thread_id = ${threadId} AND ordinal >= ${start} AND ordinal <= ${last.ordinal} + ORDER BY ordinal ASC, turn_item_id ASC`; + for (const row of span) { + if (!hiddenIds.has(row.turn_item_id)) + positions.set(row.turn_item_id, base + positions.size); + } + } + const matching = candidates + .map((item, offset) => ({ + ...localTimelineRow(item), + position: messagesOnly ? (positions.get(item.id) ?? -1) : base + offset, + })) + .filter((row) => row.position > afterPosition); + return { matching, totalItems }; + }); + const getTimelinePage: ProjectionStoreV2Shape["getTimelinePage"] = (threadId, options) => sql .withTransaction( Effect.gen(function* () { - const index = yield* readSnapshotTimelineIndex(threadId, false); - const attachmentOwners = - options.attachmentId === undefined - ? undefined - : new Set( - (yield* sql<{ thread_id: string; turn_item_id: string }>` + const local = + options.attachmentId === undefined && + Number.isSafeInteger(options.limit) && + options.limit >= 0 && + Number.isSafeInteger(options.afterPosition ?? -1) + ? yield* openLocalTimeline(threadId) + : null; + const whole = Effect.gen(function* () { + const index = yield* readSnapshotTimelineIndex(threadId, false); + const attachmentOwners = + options.attachmentId === undefined + ? undefined + : new Set( + (yield* sql<{ thread_id: string; turn_item_id: string }>` SELECT item.thread_id, item.turn_item_id FROM orchestration_v2_projection_turn_items AS item, json_each(item.payload_json, '$.attachments') AS attachment WHERE item.thread_id IN ${sql.in([...new Set(index.visible.map((row) => row.sourceThreadId))])} AND item.type = 'user_message' AND json_extract(attachment.value, '$.id') = ${options.attachmentId}`).map( - (row) => `${row.thread_id}:${row.turn_item_id}`, - ), - ); - const matching = index.visible - .map((row, position) => ({ ...row, position })) - .filter((row) => - options.itemId === undefined - ? row.position > (options.afterPosition ?? -1) && - (options.view === "activity" || - ["user_message", "assistant_message", "proposed_plan"].includes( - row.item.type, - )) - : row.sourceItemId === options.itemId, - ) - .filter( - (row) => attachmentOwners?.has(`${row.sourceThreadId}:${row.sourceItemId}`) ?? true, - ); + (row) => `${row.thread_id}:${row.turn_item_id}`, + ), + ); + const matching = index.visible + .map((row, position) => ({ ...row, position })) + .filter((row) => + options.itemId === undefined + ? row.position > (options.afterPosition ?? -1) && + (options.view === "activity" || + ["user_message", "assistant_message", "proposed_plan"].includes( + row.item.type, + )) + : row.sourceItemId === options.itemId, + ) + .filter( + (row) => + attachmentOwners?.has(`${row.sourceThreadId}:${row.sourceItemId}`) ?? true, + ); + return { matching, totalItems: index.visible.length }; + }); + const { matching, totalItems } = + local === null ? yield* whole : yield* matchLocalTimelineRows(local, options); const page = matching.slice(0, options.limit); const sources = yield* encodeTimelineSources( page @@ -6538,11 +7307,7 @@ export const layer: Layer.Layer = }; }), ); - return { - items, - totalItems: index.visible.length, - hasMore: matching.length > page.length, - }; + return { items, totalItems, hasMore: matching.length > page.length }; }), ) .pipe( @@ -7762,6 +8527,7 @@ export const layer: Layer.Layer = readonly pinned_at: string | null; readonly snoozed_until: string | null; readonly may_be_live: number; + readonly has_remote_tasks: number; }>` SELECT t.thread_id, @@ -7807,7 +8573,15 @@ export const layer: Layer.Layer = SELECT 1 FROM json_each(t.payload_json, '$.pullRequests') link WHERE json_type(link.value, '$.watch') IS NOT NULL ) - ) AS may_be_live + ) AS may_be_live, + -- One list for the whole read, found through the child_thread_id index. A lookup per + -- thread would parse the payload of every subagent row. + t.thread_id IN ( + SELECT subagent.thread_id FROM orchestration_v2_projection_subagents subagent + WHERE subagent.origin = 'app_owned' + AND subagent.child_thread_id IS NULL + AND json_type(subagent.payload_json, '$.remoteChild') = 'object' + ) AS has_remote_tasks FROM orchestration_v2_projection_threads t WHERE t.deleted_at IS NULL AND json_extract(t.payload_json, '$.archivedAt') IS NULL @@ -7834,6 +8608,7 @@ export const layer: Layer.Layer = pinnedAt: row.pinned_at === null ? null : DateTime.makeUnsafe(row.pinned_at), snoozedUntil: row.snoozed_until === null ? null : DateTime.makeUnsafe(row.snoozed_until), mayBeLive: row.may_be_live === 1, + hasRemoteTasks: row.has_remote_tasks === 1, })); }, Effect.mapError(shellSnapshotReadError)); diff --git a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts index 4bb8c103f6df7..f8363bef98f9a 100644 --- a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts +++ b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts @@ -222,6 +222,10 @@ it.layer(layerTest)("a delegated task in a linked environment", (it) => { assert.deepEqual(item?.type === "subagent" ? item.remoteChild : undefined, remoteChild); // No thread was created here for the child. assert.equal(yield* orchestrator.getThreadShell(remoteChild.threadId), null); + const other = yield* seedLiveParent("records-no-task"); + const index = yield* (yield* ProjectionStore.ProjectionStoreV2).listActiveShellIndex(); + assert.isTrue(index.find((entry) => entry.id === parent.threadId)?.hasRemoteTasks); + assert.isFalse(index.find((entry) => entry.id === other.threadId)?.hasRemoteTasks); }), ); diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 0fa5251a7ef73..9a2b3c9a949f5 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -19,6 +19,8 @@ import { OrchestrationV2ThreadShell as ThreadShellSchema, } from "@t3tools/contracts"; import * as NodeSqliteClient from "@t3tools/shared/nodeSqliteClient"; +// @effect-diagnostics-next-line nodeBuiltinImport:off - a synchronous digest of a few project rows. +import * as NodeCrypto from "node:crypto"; import type * as Arr from "effect/Array"; import type * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; @@ -31,11 +33,113 @@ import * as Schema from "effect/Schema"; import type * as SqlClient from "effect/sql/SqlClient"; import * as Stream from "effect/Stream"; +import type * as OrchestrationEventStore from "../persistence/OrchestrationEventStore.ts"; import { bufferLatestLiveStream } from "./LiveStreamBudget.ts"; import type { ActiveShellIndexEntry } from "./ProjectionStore.ts"; type ShellDelta = Extract; +// Replaying each intervening event costs a shell refetch; past this gap a +// single O(active-threads) snapshot is cheaper and bounded. +const SHELL_RESUME_MAX_GAP = 1_000; +// Row counts do not bound large tool payloads; sum stored JSON bytes in SQL and snapshot above budget. +const SHELL_REPLAY_PAYLOAD_BUDGET_BYTES = 8 * 1024 * 1024; + +/** + * Whether the events after a shell cursor can be replayed. The socket resume and the HTTP + * snapshot's `resumeFrom` ask the same question, so a client the route tells to resume is not + * refused by the socket. + */ +export const canResumeShellFrom = Effect.fnUntraced(function* ( + events: Pick< + OrchestrationEventStore.OrchestrationEventStore["Service"], + "prunedThroughSequence" | "getReplayStats" + >, + afterSequence: number, + headSequence: number, +) { + // A cursor at the head missed nothing, even where pruning has passed the head. + if (afterSequence === headSequence) return true; + const replayGap = headSequence - afterSequence; + if (replayGap < 0 || replayGap > SHELL_RESUME_MAX_GAP) return false; + if (afterSequence < (yield* events.prunedThroughSequence)) return false; + const stats = yield* events.getReplayStats({ afterSequence, throughSequence: headSequence }); + if (stats.rawPayloadBytes > SHELL_REPLAY_PAYLOAD_BUDGET_BYTES) { + yield* Effect.logDebug("orchestration replay replaced by snapshot", { + afterSequence, + headSequence, + replayGap, + eventCount: stats.eventCount, + payloadBytes: stats.rawPayloadBytes, + payloadBudgetBytes: SHELL_REPLAY_PAYLOAD_BUDGET_BYTES, + }); + return false; + } + return true; +}); + +/** + * Answers a client that asks for the shell with the cursor of the rows it holds: `resumable` + * when the socket can replay from that cursor, so the client keeps its rows, else the snapshot. + */ +export const loadShellUnlessResumable = Effect.fnUntraced(function* (input: { + readonly events: Pick< + OrchestrationEventStore.OrchestrationEventStore["Service"], + "prunedThroughSequence" | "getReplayStats" | "latestApplicationSequence" + >; + readonly resumeFrom: number | undefined; + readonly loadSnapshot: Effect.Effect; +}) { + if ( + input.resumeFrom !== undefined && + (yield* canResumeShellFrom( + input.events, + input.resumeFrom, + yield* input.events.latestApplicationSequence, + )) + ) { + return { resumable: true as const }; + } + return yield* input.loadSnapshot; +}); + +/** + * Names the repository identities a list of project shells carries. A client sends back the one + * its HTTP snapshot had, and a resume that computes the same one skips its marked snapshot. + */ +export function projectIdentitiesDigest( + projects: ReadonlyArray>, +): string { + const hash = NodeCrypto.createHash("sha256"); + for (const project of projects) { + hash.update(JSON.stringify([project.id, project.repositoryIdentity ?? null])); + } + return hash.digest("base64url"); +} + +/** + * The resolved roots a resume sends. A client that names the current identities holds them + * already, but it keeps a cached identity over an absent one, so a root resolved to no identity + * still goes out. + */ +export function resumeIdentityRoots(input: { + readonly projects: ReadonlyArray< + Pick + >; + readonly resolvedRepositoryIdentityRoots: ReadonlyArray; + readonly knownProjectIdentities: string | undefined; +}): ReadonlyArray { + if (input.knownProjectIdentities !== projectIdentitiesDigest(input.projects)) { + return input.resolvedRepositoryIdentityRoots; + } + const withoutIdentity = new Set( + input.projects.flatMap((project) => + project.repositoryIdentity == null ? [project.workspaceRoot] : [], + ), + ); + return input.resolvedRepositoryIdentityRoots.filter((root) => withoutIdentity.has(root)); +} + /** Snapshots, synchronization, and enrichment markers must bypass full-state coalescing. */ export const bufferShellLiveStream = ( source: Stream.Stream, @@ -75,7 +179,7 @@ function buildActiveShellSnapshot(input: { type ShellTrimRow = Pick< OrchestrationV2ThreadShell, "id" | "projectId" | "lineage" | "settledOverride" | "settledAt" ->; +> & { readonly hasRemoteTasks?: boolean }; /** * What a subscriber's trims read across every active row. Computed from full shells or from the @@ -84,6 +188,8 @@ type ShellTrimRow = Pick< interface ShellTrimFacts { readonly subagentParentIds: ReadonlySet; readonly subagentThreadIds: Set; + /** Only the store's index knows these; shells alone leave it empty. */ + readonly remoteTaskParentIds: ReadonlySet; /** Undefined when no thread is settled, so none is older. */ readonly olderSettledBeforeMs: number | undefined; readonly olderSettledCounts: ReadonlyArray; @@ -94,8 +200,10 @@ const NEWEST_SETTLED_KEPT = 25; function shellTrimFacts(rows: ReadonlyArray): ShellTrimFacts { const subagentParentIds = new Set(); const subagentThreadIds = new Set(); + const remoteTaskParentIds = new Set(); const settledTimes: Array = []; for (const row of rows) { + if (row.hasRemoteTasks === true) remoteTaskParentIds.add(row.id); if (row.lineage.relationshipToParent === "subagent") { subagentThreadIds.add(row.id); if (row.lineage.parentThreadId) subagentParentIds.add(row.lineage.parentThreadId); @@ -121,6 +229,7 @@ function shellTrimFacts(rows: ReadonlyArray): ShellTrimFacts { return { subagentParentIds, subagentThreadIds, + remoteTaskParentIds, olderSettledBeforeMs, olderSettledCounts: Array.from(counts, ([projectId, count]) => ({ projectId, count })), }; @@ -140,13 +249,14 @@ function hiddenChildAncestorIds( function omitIdleSubagentShellsWith( threads: ReadonlyArray, - facts: Pick, + facts: Pick, ): ReadonlyArray { return threads.filter( (thread) => thread.lineage.relationshipToParent !== "subagent" || isLiveSubagentShell(thread) || - facts.subagentParentIds.has(thread.id), + facts.subagentParentIds.has(thread.id) || + facts.remoteTaskParentIds.has(thread.id), ); } @@ -156,7 +266,10 @@ function omitOlderSettledShellsWith( readonly snapshotSequence: number; readonly now: DateTime.Utc; }, - facts: Pick, + facts: Pick< + ShellTrimFacts, + "olderSettledBeforeMs" | "olderSettledCounts" | "remoteTaskParentIds" + >, ): { readonly threads: ReadonlyArray; readonly olderSettled: OrchestrationV2OlderSettledThreads; @@ -170,7 +283,8 @@ function omitOlderSettledShellsWith( thread.pinnedAt != null || (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) || isLiveSubagentShell(thread) || - ancestorIds.has(thread.id), + ancestorIds.has(thread.id) || + facts.remoteTaskParentIds.has(thread.id), ); return { threads, @@ -185,7 +299,8 @@ function omitOlderSettledShellsWith( /** * Idle subagent children have no sidebar row, so clients that opt in read them from their thread * family instead. A child stays while it is live or the parent of another child, so the request - * and working walks over shell rows never meet a gap in a nested chain. + * and working walks over shell rows never meet a gap in a nested chain. It also stays as the + * parent of a task in a linked environment, whose clients nest that task under it. */ export function omitIdleSubagentShells( threads: ReadonlyArray, @@ -214,8 +329,8 @@ export function activeShellRowsForSubscriber( /** * Opted-in snapshots keep the 25 newest settled top-level threads (and ties) and count the rest per * project in `olderSettled`; clients page them with `getOlderSettledThreads`. Older rows stay while - * pinned, snoozed, live, or above a kept subagent or side chat, so walks over shell rows still find - * them. + * pinned, snoozed, live, above a kept subagent or side chat, or the parent of a task in a linked + * environment, so walks over shell rows and other environments' tasks still find them. */ export function omitOlderSettledShells(input: { readonly threads: ReadonlyArray; @@ -261,7 +376,10 @@ function shellSubscriberThreadIds( const subagents = index.filter( (entry) => entry.lineage.relationshipToParent === "subagent" && - (!options.omitIdleSubagents || entry.mayBeLive || facts.subagentParentIds.has(entry.id)), + (!options.omitIdleSubagents || + entry.mayBeLive || + entry.hasRemoteTasks || + facts.subagentParentIds.has(entry.id)), ); const ancestorIds = hiddenChildAncestorIds([ ...subagents, @@ -280,6 +398,7 @@ function shellSubscriberThreadIds( entry.pinnedAt != null || entry.snoozedUntil != null || entry.mayBeLive || + entry.hasRemoteTasks || ancestorIds.has(entry.id) ? [entry.id] : [], diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 8d784a91f59cb..ad0c179d783fe 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -1635,6 +1635,8 @@ const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( "events" | "started" | "startFirstTurn" >, siblingFinishesFirst: boolean, + userRunBeforeWake = false, + intentNamesTarget = false, ) { const orchestrator = yield* Orchestrator.OrchestratorV2; const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; @@ -1736,6 +1738,24 @@ const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( })), }); yield* finishTurn(origin); + // The wake queues behind a user run that started after the origin run finished. + if (userRunBeforeWake) { + const userRunning = yield* watchTurnRunning(2); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("command:user-run"), + threadId, + messageId: MessageId.make("message:user-run"), + text: "unrelated question", + attachments: [], + modelSelection: runSelection, + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + yield* worker.drain(); + yield* Fiber.join(userRunning); + } const completeTask = (taskId: NodeId) => orchestrator.dispatch({ @@ -1769,19 +1789,55 @@ const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( createdBy: "agent", creationSource: "server", }); - const wakeRunning = yield* watchTurnRunning(2); + const wakeOrdinal = userRunBeforeWake ? 3 : 2; + const wakeRunning = yield* watchTurnRunning(wakeOrdinal); + if (userRunBeforeWake) yield* finishTurn(harness.started[1]!); yield* orchestrator.resumeQueuedRuns; yield* worker.drain(); yield* Fiber.join(wakeRunning); - const wake = harness.started[1]!; + const wake = harness.started[wakeOrdinal - 1]!; assert.equal(wake.message.messageId, firstDelivery.messageId); + if (userRunBeforeWake) { + // The wake's run holds a compaction, so the origin run's records are older than the window. + const compactedAt = yield* DateTime.now; + yield* sink.write({ + events: [ + { + id: EventId.make("event:wake-compaction"), + type: "turn-item.updated" as const, + threadId, + runId: wake.runId, + nodeId: wake.rootNodeId, + occurredAt: compactedAt, + payload: { + id: TurnItemId.make("item:wake-compaction"), + threadId, + runId: wake.runId, + nodeId: wake.rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 1_000, + status: "completed" as const, + title: null, + startedAt: compactedAt, + completedAt: compactedAt, + updatedAt: compactedAt, + type: "compaction" as const, + driver, + }, + }, + ], + }); + } if (siblingFinishesFirst) { yield* completeTask(siblingTaskId); } // The provider cannot steer natively, so the steer restarts the wake run. - const steeredRunning = yield* watchTurnRunning(3); + const steeredRunning = yield* watchTurnRunning(wakeOrdinal + 1); yield* orchestrator.dispatch({ type: "message.dispatch", commandId: CommandId.make("command:steer-wake"), @@ -1790,13 +1846,15 @@ const restartCompletionWake = Effect.fn("restartCompletionWake")(function* ( text: "also check the logs", attachments: [], modelSelection: runSelection, - dispatchMode: { type: "steer_active", targetRunId: wake.runId }, + ...(intentNamesTarget + ? { dispatchMode: { type: "start_immediately" as const }, deliveryIntent: "restart" as const } + : { dispatchMode: { type: "steer_active" as const, targetRunId: wake.runId } }), createdBy: "user", creationSource: "web", }); yield* worker.drain(); yield* Fiber.join(steeredRunning); - const steered = harness.started[2]!; + const steered = harness.started[wakeOrdinal]!; assert.equal(steered.runId, wake.runId); assert.equal( (yield* orchestrator.getThreadProjection(threadId)).attempts.find( @@ -1883,6 +1941,35 @@ it.effect("wakes the parent for a sibling result after a steer restarts the comp ), ); +it.effect.each([false, true])( + "settles a steered completion wake whose parent run is before the last compaction (restart by intent: %s)", + (intentNamesTarget) => + Effect.scoped( + Effect.gen(function* () { + const harness = yield* nextTurnSelectionHarness( + `steered-wake-after-compaction-${intentNamesTarget}`, + true, + false, + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const { threadId, steered, firstTaskId, finishTurn } = yield* restartCompletionWake( + harness, + false, + true, + intentNamesTarget, + ); + yield* finishTurn(steered); + const tasks = (yield* orchestrator.getThreadProjection(threadId)).subagents; + assert.equal( + tasks.find((task) => task.id === firstTaskId)?.completionDelivery?.state, + "delivered", + ); + }).pipe(Effect.provide(harness.layer)); + }), + ), +); + it.effect( "offers the next completion wake when a steer restarts a wake a sibling finished behind", () => diff --git a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts index 985815bd73eb4..3992d46e6bf9a 100644 --- a/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts +++ b/apps/server/src/orchestration-v2/UsageLimitRecoveryWorker.ts @@ -12,7 +12,7 @@ import * as ProjectionStore from "./ProjectionStore.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ThreadManagement from "./ThreadManagementService.ts"; -const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000; +export const MAX_OVERDUE_ARM_MS = 24 * 60 * 60 * 1000; export function limitRecoveryCommand( thread: ProjectionStore.ProjectionLimitRecoveryCandidate, diff --git a/apps/server/src/orchestration-v2/http.test.ts b/apps/server/src/orchestration-v2/http.test.ts index a32b4c63507d3..07385bf134d08 100644 --- a/apps/server/src/orchestration-v2/http.test.ts +++ b/apps/server/src/orchestration-v2/http.test.ts @@ -369,6 +369,8 @@ it.effect("leaves older settled threads out of the HTTP shell only when asked", }), ); return (await response.json()) as { + readonly snapshotSequence: number; + readonly projectIdentities?: string; readonly threads: ReadonlyArray<{ readonly id: string }>; readonly olderSettled?: { readonly counts: ReadonlyArray }; }; @@ -382,5 +384,13 @@ it.effect("leaves older settled threads out of the HTTP shell only when asked", [thread.id, ...Array.from({ length: 25 }, (_, index) => `settled-${index + 1}`)].toSorted(), ); expect(cut.olderSettled?.counts).toEqual([{ projectId: thread.projectId, count: 1 }]); + + // A client that holds rows the socket can replay from keeps them; any other cursor reloads. + expect(full.projectIdentities).toBeTypeOf("string"); + expect(yield* shell(`?resumeFrom=${full.snapshotSequence}`)).toEqual({ resumable: true }); + expect(yield* shell(`?resumeFrom=${full.snapshotSequence - 1}`)).toEqual({ resumable: true }); + for (const cursor of [full.snapshotSequence + 1, "x"]) { + expect((yield* shell(`?omitOlderSettled=1&resumeFrom=${cursor}`)).threads).toHaveLength(26); + } }), ); diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.ts index 3bba05f7db63a..b58ce1b143119 100644 --- a/apps/server/src/orchestration-v2/http.ts +++ b/apps/server/src/orchestration-v2/http.ts @@ -31,7 +31,11 @@ import { } from "./threadHistoryPaging.ts"; import * as ThreadManagementService from "./ThreadManagementService.ts"; import * as ProjectStore from "./ProjectStore.ts"; -import { loadSubscriberShellSnapshot } from "./ShellStream.ts"; +import { + loadShellUnlessResumable, + loadSubscriberShellSnapshot, + projectIdentitiesDigest, +} from "./ShellStream.ts"; import { boundedSnapshotResponseFields } from "./ThreadStream.ts"; import { projectThreadProjectionForWire } from "./WireProjection.ts"; @@ -94,10 +98,27 @@ export const layer = HttpApiBuilder.group( options, }); const projects = yield* enrichProjectShells(snapshot.projects); - return { ...snapshot, projects }; + return { ...snapshot, projects, projectIdentities: projectIdentitiesDigest(projects) }; }, ); + // A client that holds rows names their cursor; a small answer tells it to keep them. + const answerShellSnapshot = Effect.fn("http.orchestration.answerShellSnapshot")((query: { + readonly omitIdleSubagents?: string; + readonly omitOlderSettled?: string; + readonly resumeFrom?: string; + }) => { + const resumeFrom = query.resumeFrom === undefined ? Number.NaN : Number(query.resumeFrom); + return loadShellUnlessResumable({ + events: applicationEvents, + resumeFrom: Number.isSafeInteger(resumeFrom) && resumeFrom >= 0 ? resumeFrom : undefined, + loadSnapshot: loadShellSnapshot({ + omitIdleSubagents: query.omitIdleSubagents === "1", + omitOlderSettled: query.omitOlderSettled === "1", + }), + }); + }); + const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* ( threadId: Parameters[0], failureReason: @@ -166,10 +187,7 @@ export const layer = HttpApiBuilder.group( Effect.fn("environment.orchestration.shellSnapshot")(function* (args) { yield* annotateEnvironmentRequest(args.endpoint.name); yield* requireEnvironmentScope(AuthOrchestrationReadScope); - return yield* loadShellSnapshot({ - omitIdleSubagents: args.query.omitIdleSubagents === "1", - omitOlderSettled: args.query.omitOlderSettled === "1", - }).pipe( + return yield* answerShellSnapshot(args.query).pipe( traceLocalHandlerWork, Effect.catch((cause) => failEnvironmentInternal("orchestration_snapshot_failed", cause), diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts index 111cf0541358a..8d81cbfadda7b 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.test.ts @@ -396,6 +396,38 @@ describe("threadHistoryPaging", () => { expect([...older.items, ...first.items].map((row) => row.sourceItemId)).toEqual( items.map((row) => row.sourceItemId), ); + + // A caller that holds only the newest rows gets the same page when it says what it left + // out: a user turn, and run 3, whose late notification is then not a new turn. + const late = items.with(402, inRun(402, 3, notification("Late"))); + const cursor = encodeThreadHistoryCursor({ + snapshotSequence: 1, + sourceThreadId: THREAD, + sourceItemId: late.at(-1)!.sourceItemId, + position: late.length - 1, + }); + const prefix = { hasUserTurn: true, startedRuns: new Set(["run-3"]) }; + const whole = selectHistoryPageFromCursor({ items: late, cursor, snapshotSequence: 1, policy }); + expect(whole.items[0]?.sourceItemId).toBe(`item-${11 * 4 + 1}`); + expect( + selectHistoryPageFromCursor({ + items: late.slice(22), + cursor, + snapshotSequence: 1, + policy, + prefix, + }), + ).toEqual({ ...whole, oldestScanned: late[45] }); + // A part that ends above the page reports its first row, so the caller reads further back. + expect( + selectHistoryPageFromCursor({ + items: late.slice(60), + cursor, + snapshotSequence: 1, + policy, + prefix, + }).oldestScanned, + ).toBe(late[60]); }); it("pages agent-only child transcripts instead of dropping their earlier activity", () => { diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index 37b653c451fce..f088d389fdd50 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -72,10 +72,22 @@ type HistoryRow = Pick< readonly deferredWork?: OrchestrationV2TurnItem["deferredWork"]; }; }; +/** What a caller that passes only the newest part of a history knows about the rows it left out. */ +export type ThreadHistoryPrefix = { + readonly hasUserTurn: boolean; + /** Runs that have a user message or notification among the rows left out. */ + readonly startedRuns: ReadonlySet; +}; + export type SelectTimelinePageResult = { readonly items: ReadonlyArray; readonly nextCursor: string | null; readonly hasMoreHistory: boolean; + /** + * Set with `prefix`: the oldest row the selection read, which can be older than `items[0]`. + * The page is the same as on the full history only when a row lies before this one. + */ + readonly oldestScanned?: Row | undefined; }; export type BoundedProjectionResult = { @@ -200,6 +212,15 @@ function isDeferrableWorkItem(item: HistoryRow["item"]): boolean { ); } +/** A row that folds when its run is not blocked and its group is large enough. */ +export function isFoldableWorkItem(item: HistoryRow["item"]): boolean { + return ( + item.runId != null && + (item.runStatus === "completed" || item.attemptStatus === "superseded") && + isDeferrableWorkItem(item) + ); +} + export function deferWorkHistoryRows(items: ReadonlyArray): Row[] { const blocked = new Set( items.flatMap(({ item }) => @@ -217,12 +238,7 @@ export function deferWorkHistoryRows(items: ReadonlyArra const item = row.item; if (item.runId == null) continue; if (item.type === "user_message") segments.set(item.runId, (segments.get(item.runId) ?? 0) + 1); - if ( - (item.runStatus !== "completed" && item.attemptStatus !== "superseded") || - blocked.has(item.runId) || - !isDeferrableWorkItem(item) - ) - continue; + if (blocked.has(item.runId) || !isFoldableWorkItem(item)) continue; const key = `${row.sourceThreadId}:${item.runId}:${segments.get(item.runId) ?? 0}:${item.attemptId ?? ""}`; const group = groups.get(key) ?? []; group.push(row); @@ -287,8 +303,11 @@ export function selectDeferredWorkPage(input: { } /** Notifications can start wake turns when they are the run's first input; match ProjectionStore run_starts. */ -function threadHistoryTurnStarts(items: ReadonlyArray): ReadonlyArray { - const startedRuns = new Set(); +function threadHistoryTurnStarts( + items: ReadonlyArray, + earlierRuns?: ReadonlySet, +): ReadonlyArray { + const startedRuns = new Set(earlierRuns); return items.map((item) => { if (item.type !== "user_message" && item.type !== "notification") return false; const firstInput = item.runId != null && !startedRuns.has(item.runId); @@ -312,6 +331,7 @@ function selectOlderTimelinePage(input: { readonly snapshotSequence: number; readonly policy?: ThreadHistoryPagePolicy | undefined; readonly rowEncodedBytes?: ((row: Row) => number) | undefined; + readonly prefix?: ThreadHistoryPrefix | undefined; }): SelectTimelinePageResult { const policy = input.policy ?? THREAD_HISTORY_PAGE_POLICY; const rowCost = input.rowEncodedBytes ?? projectedRowEncodedBytes; @@ -325,10 +345,15 @@ function selectOlderTimelinePage(input: { let userTurns = 0; let rawTurns = 0; const candidates = input.items.slice(0, end); - const turnStarts = threadHistoryTurnStarts(candidates.map((row) => row.item)); - const turnLimit = candidates.some((row) => isThreadHistoryUserTurn(row.item)) - ? policy.maxUserTurns - : undefined; + const turnStarts = threadHistoryTurnStarts( + candidates.map((row) => row.item), + input.prefix?.startedRuns, + ); + const turnLimit = + input.prefix?.hasUserTurn === true || + candidates.some((row) => isThreadHistoryUserTurn(row.item)) + ? policy.maxUserTurns + : undefined; const maxItems = turnLimit === undefined ? policy.maxItems : (policy.maxTurnItems ?? policy.maxItems); for (let index = end - 1; index >= 0; index -= 1) { @@ -351,6 +376,7 @@ function selectOlderTimelinePage(input: { // Inside a turn longer than the window, no selected row starts a user turn. // Later pages and the snapshot query see only such rows and use `maxItems`, // so this page uses it too. + const oldestScanned = selected.at(-1); if (userTurns === 0) selected.splice(policy.maxItems); selected.reverse(); @@ -376,6 +402,7 @@ function selectOlderTimelinePage(input: { items: renumberPositions(selected), nextCursor, hasMoreHistory, + ...(input.prefix === undefined ? {} : { oldestScanned }), }; } @@ -394,7 +421,7 @@ export function selectRecentTimelineWindow(input: { }); } -function findCursorEndIndex( +export function findCursorEndIndex( items: ReadonlyArray, cursor: ThreadHistoryCursorPayload, ): number { @@ -458,6 +485,8 @@ export function selectHistoryPageFromCursor(input: { readonly policy?: ThreadHistoryPagePolicy | undefined; readonly rowEncodedBytes?: ((row: Row) => number) | undefined; readonly throughEntryId?: string | undefined; + /** Set when `items` holds only the newest part of the history. */ + readonly prefix?: ThreadHistoryPrefix | undefined; }): SelectTimelinePageResult { const decoded = decodeThreadHistoryCursor(input.cursor); return selectOlderTimelinePage({ @@ -466,6 +495,7 @@ export function selectHistoryPageFromCursor(input: { snapshotSequence: input.snapshotSequence, ...(input.rowEncodedBytes === undefined ? {} : { rowEncodedBytes: input.rowEncodedBytes }), policy: olderHistoryPagePolicy(input), + prefix: input.prefix, }); } diff --git a/apps/server/src/provider/AcpRegistryProbe.test.ts b/apps/server/src/provider/AcpRegistryProbe.test.ts index 77f2a1ae31d44..3b7b2b42f2b74 100644 --- a/apps/server/src/provider/AcpRegistryProbe.test.ts +++ b/apps/server/src/provider/AcpRegistryProbe.test.ts @@ -66,6 +66,22 @@ describe("ACP Registry probe", () => { { value: "gpt-5.4", name: "Duplicate" }, ], }, + { + id: "effort", + name: "Effort", + category: "thought_level", + type: "select", + currentValue: "high", + options: [{ value: "high", name: "High" }], + }, + { + id: "mode", + name: "Mode", + category: "mode", + type: "select", + currentValue: "ask", + options: [{ value: "ask", name: "Ask" }], + }, ], }, modelConfigId: "model", @@ -88,7 +104,24 @@ describe("ACP Registry probe", () => { ], models: [{ id: "gpt-5.4", name: "GPT-5.4", description: null }], currentModelId: "gpt-5.4", - configOptions: [], + configOptions: [ + { + id: "effort", + label: "Effort", + type: "select", + options: [{ id: "high", label: "High" }], + currentValue: "high", + role: "reasoning", + }, + { + id: "mode", + label: "Mode", + type: "select", + options: [{ id: "ask", label: "Ask" }], + currentValue: "ask", + }, + ], + modelOptionIds: ["effort"], sessionManagement: { canList: true, canLoad: true, diff --git a/apps/server/src/provider/AntigravityInstallation.test.ts b/apps/server/src/provider/AntigravityInstallation.test.ts index f8e6636f80673..f604f5e61edf9 100644 --- a/apps/server/src/provider/AntigravityInstallation.test.ts +++ b/apps/server/src/provider/AntigravityInstallation.test.ts @@ -17,12 +17,16 @@ import * as Schema from "effect/Schema"; import * as Scope from "effect/Scope"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; +import * as TestClock from "effect/testing/TestClock"; import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; +import { ACP_REGISTRY_URL } from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; + import * as AntigravityInstallation from "./AntigravityInstallation.ts"; import { type AntigravityReleaseAsset } from "./antigravityRelease.ts"; +import * as ModelManifest from "./ModelManifest.ts"; const serverContents = "antigravity runtime\n"; const harnessContents = "local harness\n"; @@ -126,6 +130,11 @@ interface HarnessOptions { readonly spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; readonly validate?: AntigravityInstallation.AntigravityInstallationOptions["validate"]; readonly useDefaultValidation?: boolean; + /** Served for the ACP Registry index. */ + readonly registry?: unknown; + /** Served by URL instead of the pinned archive. */ + readonly archives?: Readonly>; + readonly manifest?: Effect.Effect; readonly connectTimeout?: boolean; } @@ -186,11 +195,31 @@ const makeHarness = Effect.fn("test.makeAntigravityInstallation")(function* ( Effect.provideService(HostProcess.Platform, platform), Effect.provideService(HostProcess.Architecture, arch), Effect.provideService(HostProcess.Environment, { PATH: options.path ?? "" }), + Effect.provideService(ModelManifest.ModelManifest, { + current: options.manifest ?? Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + forceRefresh: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refreshOnDemand: Effect.succeed(ModelManifest.BUNDLED_MODEL_MANIFEST), + refreshInBackground: Effect.void, + }), Effect.provideService( HttpClient.HttpClient, HttpClient.make((request) => Effect.suspend(() => { requests.push(request.url); + if (request.url === ACP_REGISTRY_URL) { + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + options.registry === undefined + ? new Response(null, { status: 503 }) + : Response.json(options.registry), + ), + ); + } + const served = options.archives?.[request.url]; + if (served) + return Effect.succeed(HttpClientResponse.fromWeb(request, new Response(served))); if (options.connectTimeout) { return Effect.fail( new HttpClientError.HttpClientError({ @@ -254,6 +283,43 @@ const expectPreviousRelease = Effect.fn("test.expectPreviousAntigravityRelease") expect((yield* installation.state).installedVersion).toBe(previousVersion); }); +// A zip comment changes the archive's hash without changing its members. +const withZipComment = (archive: Buffer, comment: string) => { + const bytes = Buffer.concat([archive, Buffer.from(comment)]); + bytes.writeUInt16LE(Buffer.byteLength(comment), archive.byteLength - 2); + return bytes; +}; +const upstreamArchive = withZipComment(completeArchive, "upstream"); +const upstreamUrl = "https://dl.google.com/agy-extensions/releases/test/agy-acp-server-1.4.1.zip"; +const registryListing = (archive = upstreamUrl) => ({ + version: "1.0.0", + agents: [ + { id: "other-agent", version: "9.9.9", distribution: { npx: { package: "other" } } }, + { + id: "antigravity-acp", + version: "1.4.1", + distribution: { + binary: Object.fromEntries( + ["linux-x86_64", "windows-x86_64"].map((target) => [target, { archive, cmd: "./agy" }]), + ), + }, + }, + ], +}); +const withdrawnManifest: ModelManifest.ModelManifestData = { + ...ModelManifest.BUNDLED_MODEL_MANIFEST, + compatibility: [ + { + driver: "antigravity", + t3CodeRange: ">=0.0.42", + ranges: [{ range: ">=1.4.0", status: "broken" }], + }, + ], +}; +const pinnedAsset = Effect.fn("test.pinnedAntigravityAsset")(function* () { + return { ...(yield* releaseAsset()), version: "1.3.0" }; +}); + it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity installation", (it) => { it.effect("reports missing Node before downloading the standalone provider runtime", () => Effect.gen(function* () { @@ -764,7 +830,7 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst }); const { installation: windows } = yield* makeHarness({ baseDir, platform: "win32" }); - for (const name of ["agy.EXE", "agy.cmd"]) { + for (const name of ["agy.EXE", "agy.CMD"]) { const windowsDirectory = path.join(baseDir, `windows-${name}`); yield* fs.makeDirectory(windowsDirectory); yield* fs.writeFileString(path.join(windowsDirectory, name), "cli"); @@ -1018,4 +1084,167 @@ it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("Antigravity inst expect(requests).toEqual([]); }), ); + + it.effect("updates past the pinned release to the registry release and never downgrades", () => + Effect.gen(function* () { + const asset = yield* pinnedAsset(); + const h = yield* makeHarness({ + asset, + registry: registryListing(), + archives: { [upstreamUrl]: upstreamArchive }, + }); + yield* h.installation.checkForUpdate; + // A fresh install still gets the pinned release. + expect(yield* h.installation.state).toMatchObject({ version: "1.3.0" }); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.3.0", + version: "1.4.1", + totalBytes: null, + }); + + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.4.1", + version: "1.4.1", + }); + expect(h.validations.at(-1)?.version).toBe("1.4.1"); + expect(h.requests).toEqual([ACP_REGISTRY_URL, asset.url, upstreamUrl]); + const selected = yield* h.installation.resolve(); + expect(selected.version).toBe("1.4.1"); + expect(yield* h.fs.readFileString(selected.executablePath)).toBe(serverContents); + + // Without registry information the older pin is not offered as a reinstall. + const restarted = yield* makeHarness({ baseDir: h.baseDir, asset }); + expect(yield* restarted.installation.state).toMatchObject({ + installedVersion: "1.4.1", + version: "1.4.1", + }); + yield* restarted.installation.start; + expect(yield* terminalState(restarted.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.4.1", + }); + expect(restarted.requests).toEqual([]); + expect(restarted.validations.map((entry) => entry.version)).toEqual(["1.4.1"]); + }), + ); + + it.effect.each([ + { + name: "hosted outside Google's downloads", + registry: registryListing("https://example.com/agy.zip"), + }, + { + name: "from an oversized registry index", + registry: { ...registryListing(), padding: "x".repeat(1024 * 1024) }, + }, + { + name: "escaping Google's releases path", + registry: registryListing( + "https://dl.google.com/agy-extensions/releases/%2e%2e/%2e%2e/other.zip", + ), + }, + { + name: "withdrawn by the model manifest", + registry: registryListing(), + manifest: Effect.succeed(withdrawnManifest), + }, + ])("does not offer a registry release $name", ({ registry, manifest }) => + Effect.gen(function* () { + const h = yield* makeHarness({ + asset: yield* pinnedAsset(), + registry, + ...(manifest ? { manifest } : {}), + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + expect(yield* h.installation.state).toMatchObject({ + installedVersion: "1.3.0", + version: "1.3.0", + }); + }), + ); + + it.effect("does not retry a failed registry lookup within the hour", () => + Effect.gen(function* () { + const h = yield* makeHarness(); + yield* h.installation.checkForUpdate; + yield* h.installation.checkForUpdate; + expect(h.requests).toEqual([ACP_REGISTRY_URL]); + yield* TestClock.adjust("1 hour"); + yield* h.installation.checkForUpdate; + expect(h.requests).toEqual([ACP_REGISTRY_URL, ACP_REGISTRY_URL]); + }), + ); + + it.effect.each(["update", "reinstall"] as const)( + "rejects withdrawal during $0 validation", + (operation) => + Effect.gen(function* () { + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + let withdraw = operation === "update"; + const h = yield* makeHarness({ + asset: yield* pinnedAsset(), + registry: registryListing(), + archives: { [upstreamUrl]: upstreamArchive }, + manifest: Effect.sync(() => manifest), + validate: (_executable, version) => + Effect.sync(() => { + if (withdraw && version === "1.4.1") manifest = withdrawnManifest; + }), + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + if (operation === "reinstall") { + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("succeeded"); + withdraw = true; + } + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("failed"); + if (operation === "update") { + expect((yield* h.installation.resolve()).version).toBe("1.3.0"); + } else { + expect((yield* h.installation.state).version).toBe("1.3.0"); + yield* Effect.flip(h.installation.resolve()); + } + }), + ); + + it.effect("returns an install the manifest withdraws to the pinned release", () => + Effect.gen(function* () { + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + const h = yield* makeHarness({ + asset: yield* pinnedAsset(), + registry: registryListing(), + archives: { [upstreamUrl]: upstreamArchive }, + manifest: Effect.sync(() => manifest), + }); + yield* h.installation.checkForUpdate; + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ installedVersion: "1.4.1" }); + + manifest = withdrawnManifest; + expect((yield* Effect.flip(h.installation.resolve())).detail).toContain("no longer works"); + yield* h.installation.checkForUpdate; + expect(yield* h.installation.state).toMatchObject({ + installedVersion: "1.4.1", + version: "1.3.0", + }); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "1.3.0", + version: "1.3.0", + }); + expect((yield* h.installation.resolve()).version).toBe("1.3.0"); + }), + ); }); diff --git a/apps/server/src/provider/AntigravityInstallation.ts b/apps/server/src/provider/AntigravityInstallation.ts index 6f78dc15e842c..be6cba7c7afe4 100644 --- a/apps/server/src/provider/AntigravityInstallation.ts +++ b/apps/server/src/provider/AntigravityInstallation.ts @@ -22,13 +22,26 @@ import * as Scope from "effect/Scope"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; -import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { + FetchHttpClient, + HttpClient, + HttpClientError, + HttpClientRequest, + HttpClientResponse, +} from "effect/http"; import * as ChildProcess from "effect/process/ChildProcess"; import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner"; import * as NodeCrypto from "node:crypto"; import * as NodeFSP from "node:fs/promises"; import * as EffectAcpErrors from "effect-acp/errors"; +import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText"; +import { + ACP_REGISTRY_URL, + MAX_REGISTRY_BYTES, + resolveAcpRegistryPlatformTarget, +} from "@t3tools/provider-acp-registry/server/AcpRegistrySupport"; + import * as ServerConfig from "../config.ts"; import { openZipArchive } from "../zipArchive.ts"; import { makeAntigravityAcpRuntime } from "./acp/AntigravityAcpSupport.ts"; @@ -38,8 +51,13 @@ import { } from "./antigravityAuthSupport.ts"; import { resolveAntigravityReleaseAsset, + type AntigravityRelease, type AntigravityReleaseAsset, + type AntigravityUpstreamRelease, } from "./antigravityRelease.ts"; +import { selectManagedRelease } from "./managedRelease.ts"; +import * as ModelManifest from "./ModelManifest.ts"; +import { resolveProviderCompatibility } from "./providerCompatibility.ts"; const DRIVER = ProviderDriverKind.make("antigravity"); const DOWNLOAD_TIMEOUT = "45 minutes"; @@ -47,6 +65,29 @@ const VALIDATION_TIMEOUT = "90 seconds"; const FREE_SPACE_MARGIN = 256 * 1024 * 1024; const RECORD_MAX_BYTES = 8 * 1024; const RELEASE_RECORD = ".install-complete.json"; +const UPDATE_CHECK_INTERVAL_MS = 60 * 60_000; +const UPDATE_CHECK_TIMEOUT = "20 seconds"; +const UPSTREAM_AGENT_ID = "antigravity-acp"; +const UPSTREAM_DOWNLOAD_PREFIX = "https://dl.google.com/agy-extensions/releases/"; +// An upstream release has no pinned sizes. Current archives are about 340 MB +// and extract to about 1.1 GB. +const UPSTREAM_MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024; +const UPSTREAM_MAX_EXTRACTED_BYTES = 2 * 1024 * 1024 * 1024; + +const decodeRegistryIndex = Schema.decodeUnknownEffect( + Schema.fromJsonString(Schema.Struct({ agents: Schema.Array(Schema.Unknown) })), +); +const isUpstreamAgent = Schema.is(Schema.Struct({ id: Schema.Literal(UPSTREAM_AGENT_ID) })); +const decodeRegistryAgent = Schema.decodeUnknownEffect( + Schema.Struct({ + version: Schema.String, + distribution: Schema.Struct({ + binary: Schema.optionalKey( + Schema.Record(Schema.String, Schema.Struct({ archive: Schema.String })), + ), + }), + }), +); const LARGE_PAGE_KERNEL_MESSAGE = "Google's linux-arm64 Antigravity runtime needs a kernel with 4 KiB memory pages, and this kernel uses larger pages (as on Asahi Linux or Raspberry Pi 5). Use a remote environment or a custom Antigravity executable."; @@ -103,6 +144,11 @@ interface AntigravityInstallationService { ) => Effect.Effect; readonly state: Effect.Effect; readonly changes: Stream.Stream; + /** + * Looks up the newest release in the ACP Registry, at most hourly, and + * offers it through `state.version` when it is newer than the install. + */ + readonly checkForUpdate: Effect.Effect; readonly remove: ( protectedBinaryPaths?: ReadonlyArray, ) => Effect.Effect; @@ -162,6 +208,7 @@ function isRunning(state: ProviderInstallState) { export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.make")(function* ( options: AntigravityInstallationOptions, ) { + const manifestService = yield* ModelManifest.ModelManifest; const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const random = yield* SecureRandom.SecureRandom; @@ -185,20 +232,112 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const versionsDirectory = path.join(managedDirectory, "versions"); const activePath = path.join(managedDirectory, "active.json"); const gate = yield* Semaphore.make(1); + const updateCheckGate = yield* Semaphore.make(1); const leases = new Map(); let running: { readonly operationId: string; readonly fiber: Fiber.Fiber } | undefined; + let upstream: AntigravityUpstreamRelease | null = null; + let upstreamCheckedAt: number | null = null; + + // What `start` installs next. Clients compare `version` with + // `installedVersion` to offer an update. + const offer = (installedVersion: string | null) => { + const release = selectManagedRelease( + installedVersion, + releaseAsset, + upstream, + ); + return { + version: release?.version ?? installedVersion, + totalBytes: release && "archiveBytes" in release ? release.archiveBytes : null, + }; + }; + const state = yield* SubscriptionRef.make({ driver: DRIVER, operationId: null, phase: "idle", downloadedBytes: 0, - totalBytes: releaseAsset?.archiveBytes ?? null, - version: releaseAsset?.version ?? null, + ...offer(null), installedVersion: null, canRemove: false, message: null, }); + // The model manifest can withdraw a bad upstream release without a T3 Code release. + const isWithdrawn = Effect.fn("AntigravityInstallation.isWithdrawn")(function* (version: string) { + const manifest = yield* manifestService.current; + const status = ( + resolveProviderCompatibility(manifest.compatibility, DRIVER, version) ?? + resolveProviderCompatibility( + ModelManifest.BUNDLED_MODEL_MANIFEST.compatibility, + DRIVER, + version, + ) + )?.status; + return status === "broken" || status === "unsupported"; + }); + + // Forgets what the manifest withdrew after it was seen. A withdrawn install + // is not kept either, so the pin replaces it rather than a re-check. + const keptInstall = Effect.fn("AntigravityInstallation.keptInstall")(function* ( + installedVersion: string | null, + ) { + if (upstream && (yield* isWithdrawn(upstream.version))) upstream = null; + return installedVersion !== null && !(yield* isWithdrawn(installedVersion)) + ? installedVersion + : null; + }); + + const lookupUpstream = Effect.gen(function* () { + const target = resolveAcpRegistryPlatformTarget(platform, arch); + if (!target) return null; + const response = yield* http + .execute(HttpClientRequest.get(ACP_REGISTRY_URL)) + .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + const body = yield* collectUint8StreamText({ + stream: response.stream, + maxBytes: MAX_REGISTRY_BYTES + 1, + }); + if (body.truncated || body.bytes > MAX_REGISTRY_BYTES || body.invalidUtf8) return null; + const index = yield* decodeRegistryIndex(body.text); + const entry = index.agents.find(isUpstreamAgent); + if (!entry) return null; + const agent = yield* decodeRegistryAgent(entry); + // Checked after normalization so an encoded `..` cannot leave the releases path. + const archive = agent.distribution.binary?.[target]?.archive; + const url = archive === undefined ? undefined : URL.parse(archive)?.href; + if (!/^\d+\.\d+\.\d+$/u.test(agent.version) || !url?.startsWith(UPSTREAM_DOWNLOAD_PREFIX)) { + return null; + } + if (yield* isWithdrawn(agent.version)) return null; + return { version: agent.version, url } satisfies AntigravityUpstreamRelease; + }); + + // A check already in flight covers concurrent subscribers, including when it fails. + const checkForUpdate = updateCheckGate + .withPermitsIfAvailable(1)( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (upstreamCheckedAt === null || now - upstreamCheckedAt >= UPDATE_CHECK_INTERVAL_MS) { + // A failed lookup counts too, and keeps whatever release was offered before. + upstreamCheckedAt = now; + upstream = yield* lookupUpstream.pipe( + Effect.timeout(UPDATE_CHECK_TIMEOUT), + Effect.orElseSucceed(() => upstream), + ); + } + // A running install already published the release it is installing. + yield* SubscriptionRef.updateEffect(state, (current) => + isRunning(current) + ? Effect.succeed(current) + : keptInstall(current.installedVersion).pipe( + Effect.map((kept) => ({ ...current, ...offer(kept) })), + ), + ); + }), + ) + .pipe(Effect.ignore); + const readRecord = Effect.fn("AntigravityInstallation.readRecord")(function* ( filePath: string, schema: Schema.Codec, @@ -343,7 +482,15 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma } if (yield* fs.exists(activePath)) { const active = yield* readRecord(activePath, ActiveRelease); - return yield* completedRelease(active.releaseId); + const installed = yield* completedRelease(active.releaseId); + // Without this a withdrawn install keeps launching until its owner updates. + if (yield* isWithdrawn(installed.version)) { + return yield* installationError( + "resolve", + `Antigravity ${installed.version} no longer works with this T3 Code release. Update it in Antigravity setup.`, + ); + } + return installed; } for (const candidate of yield* commandCandidates(names.executable, processEnvironment)) { const selected = yield* fromExternal(candidate, "path"); @@ -472,7 +619,20 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); const install = Effect.fn("AntigravityInstallation.install")( - function* (asset: AntigravityReleaseAsset) { + function* (release: AntigravityRelease) { + // A pinned release is checked against its recorded hash and sizes. An + // upstream release is bounded instead and identified by what downloads. + const pin = "sha256" in release ? release : null; + const ensureEligible = Effect.fn("AntigravityInstallation.ensureEligible")(function* () { + if (!pin && (yield* isWithdrawn(release.version))) { + return yield* installationError( + "verify", + "This Antigravity release was withdrawn. Check for updates and try again.", + ); + } + }); + const executable = pin?.executable ?? { name: names.executable, bytes: null }; + const harness = pin?.harness ?? { name: names.harness, bytes: null }; yield* resolveNodeExecutable("Antigravity", environment).pipe( Effect.provideService(FileSystem.FileSystem, fs), Effect.provideService(Path.Path, path), @@ -497,27 +657,27 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma SubscriptionRef.update(state, (current) => ({ ...current, phase, message })); yield* fs.makeDirectory(versionsDirectory, { recursive: true }); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true })); - const destination = path.join(versionsDirectory, asset.sha256); const activate = Effect.fn("AntigravityInstallation.activate")( - function* () { + function* (releaseId: string) { const pointerDirectory = yield* fs.makeTempDirectoryScoped({ directory: managedDirectory, prefix: "active.json.", }); const pointerPath = path.join(pointerDirectory, "contents.tmp"); - yield* fs.writeFileString( - pointerPath, - yield* encodeActiveRelease({ releaseId: asset.sha256 }), - { flag: "wx", mode: 0o600 }, - ); + yield* fs.writeFileString(pointerPath, yield* encodeActiveRelease({ releaseId }), { + flag: "wx", + mode: 0o600, + }); + yield* ensureEligible(); yield* fs.rename(pointerPath, activePath); yield* SubscriptionRef.update( state, (current) => ({ ...current, + ...offer(release.version), phase: "succeeded", - installedVersion: asset.version, + installedVersion: release.version, message: null, }) satisfies ProviderInstallState, ); @@ -531,37 +691,52 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), Effect.uninterruptible, ); - - if (yield* fs.exists(destination)) { - const existing = yield* completedRelease(asset.sha256); - if (existing.version !== asset.version) { + const reuse = Effect.fn("AntigravityInstallation.reuse")(function* (releaseId: string) { + const existing = yield* completedRelease(releaseId); + if (existing.version !== release.version) { return yield* installationError( "verify", "The existing managed release has the wrong version. Remove it before reinstalling.", ); } yield* report("verifying", "Checking the installed runtime."); - yield* validate(existing, asset.version).pipe( + yield* ensureEligible(); + yield* validate(existing, release.version).pipe( Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT), ); - yield* activate(); - return; + yield* activate(releaseId); + }); + + if (pin && (yield* fs.exists(path.join(versionsDirectory, pin.sha256)))) { + return yield* reuse(pin.sha256); } - const available = yield* Effect.tryPromise({ - try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }), - catch: (cause) => installationError("download", "Could not check free disk space.", cause), - }).pipe(Effect.option); - const required = - asset.archiveBytes + asset.executable.bytes + asset.harness.bytes + FREE_SPACE_MARGIN; - if ( - Option.isSome(available) && - available.value.bavail * available.value.bsize < BigInt(required) + const ensureFreeSpace = Effect.fn("AntigravityInstallation.ensureFreeSpace")(function* ( + operation: string, + bytes: number, ) { - return yield* installationError( + const available = yield* Effect.tryPromise({ + try: () => NodeFSP.statfs(versionsDirectory, { bigint: true }), + catch: (cause) => installationError(operation, "Could not check free disk space.", cause), + }).pipe(Effect.option); + const required = bytes + FREE_SPACE_MARGIN; + if ( + Option.isSome(available) && + available.value.bavail * available.value.bsize < BigInt(required) + ) { + return yield* installationError( + operation, + `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`, + ); + } + }); + // An upstream release has no recorded sizes, so each member is checked + // against free space once the archive declares it. + if (pin) { + yield* ensureFreeSpace( "download", - `Antigravity needs at least ${Math.ceil(required / 1024 / 1024)} MiB of free space to install.`, + pin.archiveBytes + pin.executable.bytes + pin.harness.bytes, ); } const staging = yield* fs.makeTempDirectoryScoped({ @@ -571,40 +746,63 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const archivePath = path.join(staging, "download.zip"); const pairDirectory = path.join(staging, "runtime"); yield* fs.makeDirectory(pairDirectory); + const maxArchiveBytes = pin?.archiveBytes ?? UPSTREAM_MAX_ARCHIVE_BYTES; const hash = NodeCrypto.createHash("sha256"); let downloadedBytes = 0; let lastProgressAt = yield* Clock.currentTimeMillis; yield* Effect.gen(function* () { - const response = yield* http - .execute(HttpClientRequest.get(asset.url)) - .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); - // dl.google.com may gzip the zip: content-length is encoded, while byte/hash checks use decoded data. + const request = http.execute(HttpClientRequest.get(release.url)); + // Only its URL vouches for an upstream release, so a redirect is + // refused rather than followed somewhere that check never saw. + const response = yield* ( + pin + ? request + : request.pipe( + Effect.provideService(FetchHttpClient.RequestInit, { redirect: "error" }), + ) + ).pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + // dl.google.com gzips the zip when the client accepts it, so + // `content-length` is the encoded size. The decoded stream is still + // checked against the byte limit and, when pinned, the hash below. const contentLength = response.headers["content-length"]; const contentEncoding = response.headers["content-encoding"]?.trim().toLowerCase(); const identityBody = contentEncoding === undefined || contentEncoding === "identity"; - if ( - identityBody && - contentLength !== undefined && - Number(contentLength) !== asset.archiveBytes - ) { - return yield* installationError( - "download", - "The Antigravity download size did not match the pinned release.", - ); + if (identityBody && contentLength !== undefined) { + const declaredBytes = Number(contentLength); + if (pin && declaredBytes !== pin.archiveBytes) { + return yield* installationError( + "download", + "The Antigravity download size did not match the pinned release.", + ); + } + if (!pin && Number.isSafeInteger(declaredBytes) && declaredBytes > 0) { + if (declaredBytes > maxArchiveBytes) { + return yield* installationError( + "download", + "The Antigravity download is larger than T3 Code accepts.", + ); + } + yield* SubscriptionRef.update(state, (current) => ({ + ...current, + totalBytes: declaredBytes, + })); + } } yield* response.stream.pipe( Stream.tap((chunk) => Effect.gen(function* () { downloadedBytes += chunk.byteLength; - if (downloadedBytes > asset.archiveBytes) { + if (downloadedBytes > maxArchiveBytes) { return yield* installationError( "download", - "The Antigravity download exceeded the pinned release size.", + pin + ? "The Antigravity download exceeded the pinned release size." + : "The Antigravity download is larger than T3 Code accepts.", ); } hash.update(chunk); const now = yield* Clock.currentTimeMillis; - if (now - lastProgressAt >= 250 || downloadedBytes === asset.archiveBytes) { + if (now - lastProgressAt >= 250 || downloadedBytes === pin?.archiveBytes) { lastProgressAt = now; yield* SubscriptionRef.update(state, (current) => ({ ...current, @@ -627,14 +825,21 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma : cause, ), ); - if (downloadedBytes !== asset.archiveBytes || hash.digest("hex") !== asset.sha256) { + const releaseId = hash.digest("hex"); + if (pin && (downloadedBytes !== pin.archiveBytes || releaseId !== pin.sha256)) { return yield* installationError( "download", "The Antigravity download failed its size or SHA-256 check. Nothing was installed.", ); } + const destination = path.join(versionsDirectory, releaseId); + if (!pin && (yield* fs.exists(destination))) { + return yield* reuse(releaseId); + } yield* report("extracting", "Extracting the verified runtime."); + const extracted = new Map(); + let extractedTotal = 0; yield* Effect.gen(function* () { const archive = yield* openZipArchive(archivePath, (detail, cause) => installationError("extract", detail, cause), @@ -645,31 +850,33 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma "The archive must contain exactly the Antigravity executable and its harness.", ); } - const seen = new Set(); for (;;) { const entry = yield* archive.next; if (!entry) break; - const expected = [asset.executable, asset.harness].find( - (file) => file.name === entry.fileName, - ); + const expected = [executable, harness].find((file) => file.name === entry.fileName); + const expectedBytes = expected?.bytes ?? entry.uncompressedSize; const unixType = (entry.externalFileAttributes >>> 16) & 0o170000; if ( !expected || - seen.has(entry.fileName) || + extracted.has(entry.fileName) || entry.fileName.includes("/") || entry.fileName.includes("\\") || (unixType !== 0 && unixType !== 0o100000) || (entry.externalFileAttributes & 0x10) !== 0 || (entry.generalPurposeBitFlag & 1) !== 0 || ![0, 8].includes(entry.compressionMethod) || - entry.uncompressedSize !== expected.bytes + entry.uncompressedSize !== expectedBytes || + expectedBytes <= 0 || + extractedTotal + expectedBytes > UPSTREAM_MAX_EXTRACTED_BYTES ) { return yield* installationError( "extract", "The archive contains an unexpected, unsafe, or incorrectly sized member.", ); } - seen.add(entry.fileName); + if (!pin) yield* ensureFreeSpace("extract", expectedBytes); + extracted.set(entry.fileName, expectedBytes); + extractedTotal += expectedBytes; yield* Effect.gen(function* () { const readable = yield* archive.streamEntry(entry); let extractedBytes = 0; @@ -680,10 +887,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma Stream.tap((chunk) => Effect.gen(function* () { extractedBytes += chunk.byteLength; - if (extractedBytes > expected.bytes) { + if (extractedBytes > expectedBytes) { return yield* installationError( "extract", - "An archive member exceeded its pinned size.", + "An archive member exceeded its expected size.", ); } }), @@ -692,21 +899,23 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma fs.sink(path.join(pairDirectory, entry.fileName), { flag: "wx", mode: 0o700 }), ), ); - if (extractedBytes !== expected.bytes) { + if (extractedBytes !== expectedBytes) { return yield* installationError("extract", "An archive member was truncated."); } }).pipe(Effect.scoped); } - if (!seen.has(asset.executable.name) || !seen.has(asset.harness.name)) { - return yield* installationError( - "extract", - "The archive is missing the Antigravity executable or its harness.", - ); - } }).pipe(Effect.scoped); + const executableBytes = extracted.get(executable.name); + const harnessBytes = extracted.get(harness.name); + if (executableBytes === undefined || harnessBytes === undefined) { + return yield* installationError( + "extract", + "The archive is missing the Antigravity executable or its harness.", + ); + } yield* fs.remove(archivePath); - const executablePath = path.join(pairDirectory, asset.executable.name); - const harnessPath = path.join(pairDirectory, asset.harness.name); + const executablePath = path.join(pairDirectory, executable.name); + const harnessPath = path.join(pairDirectory, harness.name); if (platform !== "win32") { yield* fs.chmod(executablePath, 0o755); yield* fs.chmod(harnessPath, 0o755); @@ -734,24 +943,25 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma } } yield* report("verifying", "Checking the downloaded runtime."); + yield* ensureEligible(); yield* validate( { executablePath, harnessPath, source: "managed", - version: asset.version, + version: release.version, managedVersionDirectory: pairDirectory, }, - asset.version, + release.version, ).pipe(Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT)); const record: InstalledRelease = { - releaseId: asset.sha256, - version: asset.version, + releaseId, + version: release.version, executable: { - name: asset.executable.name, + name: executable.name, bytes: Number((yield* fs.stat(executablePath)).size), }, - harness: { name: asset.harness.name, bytes: Number((yield* fs.stat(harnessPath)).size) }, + harness: { name: harness.name, bytes: Number((yield* fs.stat(harnessPath)).size) }, }; yield* fs.writeFileString( path.join(pairDirectory, RELEASE_RECORD), @@ -760,10 +970,11 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ); yield* fs.rename(pairDirectory, destination).pipe( Effect.catch((cause) => - completedRelease(asset.sha256).pipe( + completedRelease(releaseId).pipe( Effect.flatMap((existing) => - existing.version === asset.version - ? validate(existing, asset.version).pipe( + existing.version === release.version + ? ensureEligible().pipe( + Effect.andThen(validate(existing, release.version)), Effect.scoped, Effect.timeout(VALIDATION_TIMEOUT), ) @@ -784,7 +995,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), ), ); - yield* activate(); + yield* activate(releaseId); }, Effect.scoped, Effect.mapError( @@ -795,12 +1006,56 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma ), ); + // Nothing newer is known, so "reinstall" re-checks the active runtime rather + // than replacing it with an older pinned release. + const reverify = Effect.fn("AntigravityInstallation.reverify")( + function* () { + const active = yield* readRecord(activePath, ActiveRelease); + const installed = yield* completedRelease(active.releaseId); + yield* validate(installed, installed.version).pipe( + Effect.scoped, + Effect.timeout(VALIDATION_TIMEOUT), + ); + const kept = yield* keptInstall(installed.version); + if (kept === null) { + yield* SubscriptionRef.update(state, (current) => ({ ...current, ...offer(kept) })); + return yield* installationError( + "verify", + "This Antigravity release was withdrawn. Check for updates and try again.", + ); + } + yield* SubscriptionRef.update( + state, + (current) => + ({ + ...current, + ...offer(kept), + phase: "succeeded", + installedVersion: installed.version, + message: null, + }) satisfies ProviderInstallState, + ); + }, + Effect.mapError( + wrapFailure( + "verify", + "The installed Antigravity runtime could not start. Remove it and reinstall.", + ), + ), + ); + const start = gate .withPermit( Effect.gen(function* () { const current = yield* SubscriptionRef.get(state); if (isRunning(current)) return current; - if (!releaseAsset) { + const installedVersion = yield* keptInstall(current.installedVersion); + const release = selectManagedRelease( + installedVersion, + releaseAsset, + upstream, + ); + if (!release && installedVersion === null) { return yield* installationError( "start", `Google does not publish an Antigravity runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`, @@ -810,16 +1065,17 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma const next: ProviderInstallState = { driver: DRIVER, operationId, - phase: "downloading", + phase: release ? "downloading" : "verifying", downloadedBytes: 0, - totalBytes: releaseAsset.archiveBytes, - version: releaseAsset.version, + ...offer(installedVersion), installedVersion: current.installedVersion, canRemove: current.canRemove, - message: "Downloading Google's official Antigravity runtime.", + message: release + ? "Downloading Google's official Antigravity runtime." + : "Checking the installed runtime.", }; yield* SubscriptionRef.set(state, next); - const work = install(releaseAsset).pipe( + const work = (release ? install(release) : reverify()).pipe( Effect.onExit((exit) => Exit.isFailure(exit) ? SubscriptionRef.update(state, (value) => { @@ -908,6 +1164,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma (current) => ({ ...current, + ...offer(null), operationId: null, phase: "idle", downloadedBytes: 0, @@ -933,8 +1190,10 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma if (!(yield* fs.exists(activePath))) return; const active = yield* readRecord(activePath, ActiveRelease); const installed = yield* completedRelease(active.releaseId); + const kept = yield* keptInstall(installed.version); yield* SubscriptionRef.update(state, (current) => ({ ...current, + ...offer(kept), installedVersion: installed.version, })); }).pipe( @@ -959,6 +1218,7 @@ export const makeAntigravityInstallation = Effect.fn("AntigravityInstallation.ma cancel, state: SubscriptionRef.get(state), changes: SubscriptionRef.changes(state), + checkForUpdate, remove, }); }); diff --git a/apps/server/src/provider/CodexInstallation.test.ts b/apps/server/src/provider/CodexInstallation.test.ts index 98861629c79f5..5536fe7a1704d 100644 --- a/apps/server/src/provider/CodexInstallation.test.ts +++ b/apps/server/src/provider/CodexInstallation.test.ts @@ -41,6 +41,8 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( platform?: NodeJS.Platform; spawner?: ChildProcessSpawner.ChildProcessSpawner["Service"]; runtimeRenameFailures?: number; + /** Served by URL instead of the pinned package. */ + responses?: Readonly Response>>; } = {}, ) { const fs = yield* FileSystem.FileSystem; @@ -110,6 +112,8 @@ const makeHarness = Effect.fn("test.makeCodexInstallation")(function* ( HttpClient.make((request) => Effect.sync(() => { downloads++; + const respond = input.responses?.[request.url]; + if (respond) return HttpClientResponse.fromWeb(request, respond()); return Object.defineProperty( HttpClientResponse.fromWeb( request, @@ -529,4 +533,214 @@ it.effect("keeps an activated runtime when a later update fails verification", ( }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); -// Stands in for Windows' bsdtar: CRLF listings, and extraction writes the Windows layout. +const upstreamVersion = "0.163.0"; +const upstreamArchive = Buffer.from( + "H4sIAAAAAAACA+3WzY7CIBQF4D5Kw1oqtNQmPoh7rKStP9BQdMaYefcBE43T9RQ1nm8B7Q1Jk94cYN3peW026juZDvOqsrzO3nj2yofnUK9KwZKUJREcByet/2TymabuPby29S3/NIz0EIbWDC5u/sXf/PO8EAL5j+G/ew1vuP/TXrp2bpunnf/5KP+syCvkP4bJmg5vlf96JxuVbQej4+efi2qUf17g/h/Hhezl2RzdStmhM5osUz5Lyen+RljGF0XGiK/6H9UoF4pS2rpdCCr7fq/oRtqvTocVSjt77k2nr6vud0vyg6ABAAAAAAAAAAAAAABE8gvVbjvaACgAAA==", + "base64", +); +const upstreamReleaseUrl = `https://github.com/openai/codex/releases/download/rust-v${upstreamVersion}`; +const upstreamResponses = (checksum: string) => ({ + "https://registry.npmjs.org/@openai/codex/latest": () => + Response.json({ version: upstreamVersion }), + [`${upstreamReleaseUrl}/codex-package_SHA256SUMS`]: () => + new Response( + `${"0".repeat(64)} codex-package-x86_64-apple-darwin.tar.gz\n${checksum} codex-package-aarch64-apple-darwin.tar.gz\n`, + ), + [`${upstreamReleaseUrl}/codex-package-aarch64-apple-darwin.tar.gz`]: () => + new Response(upstreamArchive), +}); + +it.effect("updates a managed install to OpenAI's newest release and never downgrades it", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + const h = yield* makeHarness({ responses: upstreamResponses(checksum) }); + yield* h.installation.checkForUpdate; + // A fresh install still gets the pinned release. + expect((yield* h.installation.state).version).toBe("0.156.1"); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: upstreamVersion, + }); + + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: upstreamVersion, + version: upstreamVersion, + }); + expect((yield* h.installation.resolve()).version).toBe(upstreamVersion); + + // Without upstream information the older pin is not offered as a reinstall. + const restarted = yield* makeHarness({ baseDir: h.baseDir }); + expect(yield* restarted.installation.state).toMatchObject({ + installedVersion: upstreamVersion, + version: upstreamVersion, + }); + yield* restarted.installation.start; + expect(yield* terminalState(restarted.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: upstreamVersion, + }); + expect(restarted.downloads()).toBe(0); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("keeps the managed install when an update fails its published checksum", () => + Effect.gen(function* () { + const h = yield* makeHarness({ responses: upstreamResponses("f".repeat(64)) }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "failed", + installedVersion: "0.156.1", + message: expect.stringContaining("SHA-256"), + }); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("does not install a cached update the manifest has since withdrawn", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + expect((yield* h.installation.state).version).toBe(upstreamVersion); + manifest = { + ...manifest, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + const downloads = h.downloads(); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: "0.156.1", + }); + expect(h.downloads()).toBe(downloads); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect("returns a managed install the manifest withdraws to the pinned release", () => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + }); + yield* h.installation.checkForUpdate; + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + installedVersion: upstreamVersion, + }); + + manifest = { + ...manifest, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + yield* h.installation.checkForUpdate; + expect(yield* h.installation.state).toMatchObject({ + installedVersion: upstreamVersion, + version: "0.156.1", + }); + yield* h.installation.start; + expect(yield* terminalState(h.installation)).toMatchObject({ + phase: "succeeded", + installedVersion: "0.156.1", + version: "0.156.1", + }); + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); + +it.effect.each(["update", "reinstall"] as const)( + "rejects withdrawal during $0 validation", + (operation) => + Effect.gen(function* () { + const digest = yield* Digest.Digest; + const checksum = Hex.encode( + yield* digest.digest(Digest.sha256, upstreamArchive).pipe(Effect.orDie), + ); + let manifest = ModelManifest.BUNDLED_MODEL_MANIFEST; + let withdraw = operation === "update"; + const h = yield* makeHarness({ + responses: upstreamResponses(checksum), + manifestCurrent: Effect.sync(() => manifest), + options: { + validate: (_executable, version) => + Effect.sync(() => { + if (withdraw && version === upstreamVersion) + manifest = { + ...ModelManifest.BUNDLED_MODEL_MANIFEST, + compatibility: [ + { + driver: "codex", + t3CodeRange: ">=0.0.42", + ranges: [ + { range: ">=0.160.0", status: "unsupported" }, + { range: ">=0.156.0 <0.160.0", status: "supported" }, + ], + }, + ], + }; + }), + }, + }); + yield* h.installation.start; + yield* terminalState(h.installation); + yield* h.installation.checkForUpdate; + if (operation === "reinstall") { + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("succeeded"); + withdraw = true; + } + yield* h.installation.start; + expect((yield* terminalState(h.installation)).phase).toBe("failed"); + if (operation === "update") { + expect((yield* h.installation.resolve()).version).toBe("0.156.1"); + } else { + expect((yield* h.installation.state).version).toBe("0.156.1"); + yield* Effect.flip(h.installation.resolve()); + } + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), +); diff --git a/apps/server/src/provider/CodexInstallation.ts b/apps/server/src/provider/CodexInstallation.ts index 8fdcfbebb328e..c1e489ec0e1eb 100644 --- a/apps/server/src/provider/CodexInstallation.ts +++ b/apps/server/src/provider/CodexInstallation.ts @@ -4,7 +4,7 @@ import { type ProviderInstallState, type ServerProviderCompatibilityAdvisory, } from "@t3tools/contracts"; -import { cliArchiveTarCommand } from "@t3tools/shared/cliRelease"; +import { cliArchiveTarCommand, parseChecksums } from "@t3tools/shared/cliRelease"; import { compareSemverVersions } from "@t3tools/shared/semver"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { resolveCommandPath, resolveSpawnCommand } from "@t3tools/shared/shell"; @@ -29,11 +29,18 @@ import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; import * as NodeCrypto from "node:crypto"; import * as ServerConfig from "../config.ts"; +import { selectManagedRelease } from "./managedRelease.ts"; import * as ModelManifest from "./ModelManifest.ts"; import { resolveProviderCompatibility } from "./providerCompatibility.ts"; const DRIVER = ProviderDriverKind.make("codex"); const STAGING_STALE_AFTER_MS = 24 * 60 * 60_000; +const UPDATE_CHECK_INTERVAL_MS = 60 * 60_000; +const UPDATE_CHECK_TIMEOUT = "20 seconds"; +const UPSTREAM_LATEST_URL = "https://registry.npmjs.org/@openai/codex/latest"; +const UPSTREAM_RELEASES_URL = "https://github.com/openai/codex/releases/download"; +// An upstream release has no recorded size; current packages are about 160 MB. +const UPSTREAM_MAX_ARCHIVE_BYTES = 1024 * 1024 * 1024; const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?$/u)); const ActiveRelease = Schema.Struct({ version: Version }); const InstalledRelease = Schema.Struct({ @@ -48,6 +55,7 @@ const PackageManifest = Schema.Struct({ entrypoint: Schema.String, }); const decodeVersion = Schema.decodeUnknownEffect(Version); +const decodeNpmLatest = Schema.decodeUnknownEffect(Schema.Struct({ version: Version })); const encodeRecord = Schema.encodeEffect(Schema.fromJsonString(InstalledRelease)); const encodeActive = Schema.encodeEffect(Schema.fromJsonString(ActiveRelease)); export interface CodexReleaseAsset { @@ -55,7 +63,8 @@ export interface CodexReleaseAsset { readonly target: string; readonly url: string; readonly sha256: string; - readonly archiveBytes: number; + /** Null for an upstream release, whose package checksum is published without a size. */ + readonly archiveBytes: number | null; } const RELEASES: Readonly> = { "darwin-arm64": { @@ -139,6 +148,11 @@ interface CodexInstallationService { ) => Effect.Effect; readonly state: Effect.Effect; readonly changes: Stream.Stream; + /** + * Looks up OpenAI's newest Codex release, at most hourly, and offers it + * through `state.version` when it is newer than the managed install. + */ + readonly checkForUpdate: Effect.Effect; readonly remove: ( protectedBinaryPaths?: ReadonlyArray, ) => Effect.Effect; @@ -186,15 +200,31 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const activePath = path.join(managedDirectory, "active.json"); const executableName = platform === "win32" ? "codex.exe" : "codex"; const gate = yield* Semaphore.make(1); + const updateCheckGate = yield* Semaphore.make(1); let leases = 0; let running: { readonly operationId: string; readonly fiber: Fiber.Fiber } | undefined; + let upstream: CodexReleaseAsset | null = null; + let upstreamCheckedAt: number | null = null; + + // A local Codex is used as is, so only a managed install is ever updated. + const managedVersion = (current: ProviderInstallState) => + current.source === "managed" ? current.installedVersion : null; + // What `start` installs next. Clients compare `version` with + // `installedVersion` to offer an update. + const offer = (installedVersion: string | null) => { + const release = selectManagedRelease(installedVersion, asset, upstream); + return { + version: release?.version ?? installedVersion, + totalBytes: release?.archiveBytes ?? null, + }; + }; + const state = yield* SubscriptionRef.make({ driver: DRIVER, operationId: null, phase: "idle", downloadedBytes: 0, - totalBytes: asset?.archiveBytes ?? null, - version: asset?.version ?? null, + ...offer(null), installedVersion: null, executablePath: null, canRemove: false, @@ -279,6 +309,70 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ) ); }); + const isSupported = (version: string) => + compatibility(version).pipe(Effect.map((advisory) => advisory?.status === "supported")); + // Forgets what the manifest withdrew after it was seen. Managed resolution + // refuses a withdrawn install, so the pin replaces it rather than a re-check. + const keptInstall = Effect.fn("CodexInstallation.keptInstall")(function* ( + installedVersion: string | null, + ) { + if (upstream && !(yield* isSupported(upstream.version))) upstream = null; + return installedVersion !== null && (yield* isSupported(installedVersion)) + ? installedVersion + : null; + }); + // npm names the latest stable release; its GitHub release lists the package + // checksums, so an upstream update stays SHA-256 verified. + const lookupUpstream = Effect.gen(function* () { + if (!asset) return null; + const latest = yield* http + .execute(HttpClientRequest.get(UPSTREAM_LATEST_URL)) + .pipe(Effect.flatMap(HttpClientResponse.filterStatusOk)); + const { version } = yield* latest.json.pipe(Effect.flatMap(decodeNpmLatest)); + // Managed resolution refuses anything else, so offering it would break sessions. + if (!(yield* isSupported(version))) return null; + const releaseUrl = `${UPSTREAM_RELEASES_URL}/rust-v${version}`; + const checksums = yield* http + .execute(HttpClientRequest.get(`${releaseUrl}/codex-package_SHA256SUMS`)) + .pipe( + Effect.flatMap(HttpClientResponse.filterStatusOk), + Effect.flatMap((response) => response.text), + ); + const fileName = `codex-package-${asset.target}.tar.gz`; + const sha256 = parseChecksums(checksums).get(fileName); + if (!sha256) return null; + return { + version, + target: asset.target, + url: `${releaseUrl}/${fileName}`, + sha256, + archiveBytes: null, + } satisfies CodexReleaseAsset; + }); + // A check already in flight covers concurrent subscribers, including when it fails. + const checkForUpdate = updateCheckGate + .withPermitsIfAvailable(1)( + Effect.gen(function* () { + const now = yield* Clock.currentTimeMillis; + if (upstreamCheckedAt === null || now - upstreamCheckedAt >= UPDATE_CHECK_INTERVAL_MS) { + // A failed lookup counts too, and keeps whatever release was offered before. + upstreamCheckedAt = now; + upstream = yield* lookupUpstream.pipe( + Effect.timeout(UPDATE_CHECK_TIMEOUT), + Effect.orElseSucceed(() => upstream), + ); + } + // A running install already published the release it is installing. + yield* SubscriptionRef.updateEffect(state, (current) => + isRunning(current) + ? Effect.succeed(current) + : keptInstall(managedVersion(current)).pipe( + Effect.map((kept) => ({ ...current, ...offer(kept) })), + ), + ); + }), + ) + .pipe(Effect.ignore); const resolveManaged = Effect.fn("CodexInstallation.resolveManaged")( function* () { const active = yield* readRecord(activePath, ActiveRelease); @@ -464,6 +558,14 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ); const install = Effect.fn("CodexInstallation.install")( function* (release: CodexReleaseAsset) { + const ensureEligible = Effect.fn("CodexInstallation.ensureEligible")(function* () { + if (release.version !== asset?.version && !(yield* isSupported(release.version))) { + return yield* installationError( + "verify", + "This Codex release was withdrawn. Check for updates and try again.", + ); + } + }); yield* decodeVersion(release.version); yield* fs.makeDirectory(managedDirectory, { recursive: true }); yield* SubscriptionRef.update(state, (current) => ({ ...current, canRemove: true })); @@ -480,12 +582,14 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function mode: 0o600, flag: "wx", }); + yield* ensureEligible(); yield* fs.rename(pointer, activePath); yield* SubscriptionRef.update( state, (current) => ({ ...current, + ...offer(release.version), phase: "succeeded", source: "managed", installedVersion: release.version, @@ -508,6 +612,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function "verify", "The existing managed Codex release differs from the official package. Remove it and reinstall.", ); + yield* ensureEligible(); yield* validate(existing, release.version).pipe( Effect.scoped, Effect.timeout("90 seconds"), @@ -523,6 +628,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const runtime = path.join(staging, "runtime"); yield* fs.makeDirectory(runtime); const hash = NodeCrypto.createHash("sha256"); + const maxArchiveBytes = release.archiveBytes ?? UPSTREAM_MAX_ARCHIVE_BYTES; let downloadedBytes = 0; let lastProgressAt = yield* Clock.currentTimeMillis; const response = yield* http @@ -532,7 +638,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function Stream.tap((chunk) => Effect.gen(function* () { downloadedBytes += chunk.byteLength; - if (downloadedBytes > release.archiveBytes) + if (downloadedBytes > maxArchiveBytes) return yield* installationError( "download", "The Codex download exceeded the expected release size.", @@ -556,7 +662,10 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ), }), ); - if (downloadedBytes !== release.archiveBytes || hash.digest("hex") !== release.sha256) + if ( + (release.archiveBytes !== null && downloadedBytes !== release.archiveBytes) || + hash.digest("hex") !== release.sha256 + ) return yield* installationError( "download", "The Codex download failed its size or SHA-256 check. Nothing was installed.", @@ -600,6 +709,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function }) satisfies ProviderInstallState, ); const executable = yield* fromDirectory(runtime, release.version, release.target); + yield* ensureEligible(); yield* validate(executable, release.version).pipe( Effect.scoped, Effect.timeout("90 seconds"), @@ -642,13 +752,54 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function ), ), ); + // Nothing newer is known, so "reinstall" re-checks the active runtime rather + // than replacing it with an older pinned release. + const reverify = Effect.fn("CodexInstallation.reverify")( + function* () { + const active = yield* readRecord(activePath, ActiveRelease); + const executable = yield* completedRelease(active.version); + yield* validate(executable, executable.version).pipe( + Effect.scoped, + Effect.timeout("90 seconds"), + ); + const kept = yield* keptInstall(executable.version); + if (kept === null) { + yield* SubscriptionRef.update(state, (current) => ({ ...current, ...offer(kept) })); + return yield* installationError( + "verify", + "This Codex release was withdrawn. Check for updates and try again.", + ); + } + yield* SubscriptionRef.update( + state, + (current) => + ({ + ...current, + ...offer(kept), + phase: "succeeded", + source: "managed", + installedVersion: executable.version, + executablePath: executable.executablePath, + message: null, + }) satisfies ProviderInstallState, + ); + }, + Effect.mapError( + wrapFailure( + "verify", + "The installed Codex runtime could not start. Remove it and reinstall.", + ), + ), + ); const start = gate .withPermit( Effect.gen(function* () { const current = yield* SubscriptionRef.get(state); if (isRunning(current)) return current; if (yield* reuseLocal()) return yield* SubscriptionRef.get(state); - if (!asset) { + const installedVersion = yield* keptInstall(managedVersion(current)); + const release = selectManagedRelease(installedVersion, asset, upstream); + if (!release && installedVersion === null) { return yield* installationError( "start", `OpenAI does not publish a Codex runtime for ${platform}-${arch}. Use a supported remote environment or a custom executable.`, @@ -658,14 +809,13 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function const next: ProviderInstallState = { ...current, operationId, - phase: "downloading", + phase: release ? "downloading" : "verifying", downloadedBytes: 0, - totalBytes: asset.archiveBytes, - version: asset.version, - message: "Downloading Codex.", + ...offer(installedVersion), + message: release ? "Downloading Codex." : "Checking Codex.", }; yield* SubscriptionRef.set(state, next); - const work = install(asset).pipe( + const work = (release ? install(release) : reverify()).pipe( Effect.onExit((exit) => Exit.isFailure(exit) ? SubscriptionRef.update(state, (value) => { @@ -745,6 +895,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function (current) => ({ ...current, + ...offer(null), operationId: null, phase: "idle", downloadedBytes: 0, @@ -796,11 +947,13 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function if (!(yield* fs.exists(activePath))) return; const active = yield* readRecord(activePath, ActiveRelease); const installed = yield* completedRelease(active.version); + const kept = yield* keptInstall(installed.version); yield* SubscriptionRef.update( state, (current) => ({ ...current, + ...offer(kept), installedVersion: installed.version, executablePath: installed.executablePath, source: "managed", @@ -832,6 +985,7 @@ export const makeCodexInstallation = Effect.fn("makeCodexInstallation")(function cancel, state: SubscriptionRef.get(state), changes: SubscriptionRef.changes(state), + checkForUpdate, remove, }); }); diff --git a/apps/server/src/provider/Drivers/claudeUsage.test.ts b/apps/server/src/provider/Drivers/claudeUsage.test.ts index 6f457f4f4cf2f..bc10ba5b7b29a 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.test.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; +import { parseRateTable, priceUsage } from "../../usage/usagePricing.ts"; import { claudeUsageFormat, parseClaudeLine } from "./claudeUsage.ts"; function claudeLine(overrides: { @@ -115,7 +116,8 @@ describe("Claude advisor iterations", () => { model: "claude-fable-5-1", input_tokens: 54204, cache_read_input_tokens: 0, - cache_creation_input_tokens: 0, + cache_creation_input_tokens: 500, + cache_creation: { ephemeral_5m_input_tokens: 200, ephemeral_1h_input_tokens: 300 }, output_tokens: 4229, }, { @@ -160,10 +162,11 @@ describe("Claude advisor iterations", () => { totals: { uncachedInputTokens: 54204, cachedInputTokens: 0, - cacheCreationTokens: 0, + cacheCreationTokens: 500, outputTokens: 4229, reasoningTokens: 0, }, + cacheCreation1hTokens: 300, dedupeKey: expect.any(String), }, ]; @@ -216,3 +219,44 @@ describe("Claude advisor iterations", () => { expect(parse(unusable).map((record) => record.model)).toEqual(["claude-opus-5-5"]); }); }); + +describe("Claude cache write pricing", () => { + it("prices one-hour cache writes at the one-hour rate and the rest at the five-minute rate", () => { + const model = "claude-opus-4-5-20251101"; + const rates = parseRateTable({ + [model]: { + litellm_provider: "anthropic", + input_cost_per_token: 5e-6, + output_cost_per_token: 25e-6, + cache_read_input_token_cost: 5e-7, + cache_creation_input_token_cost: 6.25e-6, + cache_creation_input_token_cost_above_1hr: 1e-5, + }, + }); + const [record] = parseClaudeLine( + JSON.stringify({ + type: "assistant", + timestamp: "2026-08-07T04:05:13.944Z", + sessionId: "s", + message: { + id: "msg_ttl", + model, + usage: { + input_tokens: 0, + cache_read_input_tokens: 0, + cache_creation_input_tokens: 1_000_000, + cache_creation: { + ephemeral_5m_input_tokens: 400_000, + ephemeral_1h_input_tokens: 600_000, + }, + output_tokens: 0, + }, + }, + }), + ); + + if (record === undefined) throw new Error("expected a usage record"); + // 0.4M x $6.25/M + 0.6M x $10/M + expect(priceUsage(rates, record).costUsd).toBeCloseTo(8.5, 9); + }); +}); diff --git a/apps/server/src/provider/Drivers/claudeUsage.ts b/apps/server/src/provider/Drivers/claudeUsage.ts index acb697d2941de..713b35884292b 100644 --- a/apps/server/src/provider/Drivers/claudeUsage.ts +++ b/apps/server/src/provider/Drivers/claudeUsage.ts @@ -30,6 +30,13 @@ export function parseClaudeLine(line: string): readonly UsageRecord[] { return parseClaudeRecord(parsed); } +function cacheCreation1h(usage: Record): { cacheCreation1hTokens?: number } { + const split = usage["cache_creation"]; + if (typeof split !== "object" || split === null) return {}; + const tokens = tokenCount((split as Record)["ephemeral_1h_input_tokens"]); + return tokens > 0 ? { cacheCreation1hTokens: tokens } : {}; +} + function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { if (typeof parsed !== "object" || parsed === null) return []; @@ -70,6 +77,7 @@ function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { // Anthropic folds thinking tokens into output and does not break them out. reasoningTokens: 0, }, + ...cacheCreation1h(usageRecord), reportedCostUsd: typeof cost === "number" && Number.isFinite(cost) ? cost : null, speed: usageRecord["speed"] === "fast" ? "fast" : "standard", dedupeKey, @@ -101,6 +109,7 @@ function parseClaudeRecord(parsed: unknown): readonly UsageRecord[] { outputTokens: tokenCount(advisor["output_tokens"]), reasoningTokens: 0, }, + ...cacheCreation1h(advisor), reportedCostUsd: null, speed: executor.speed, dedupeKey: dedupeKey === null ? null : `${dedupeKey}:advisor:${index}`, diff --git a/apps/server/src/provider/antigravityRelease.ts b/apps/server/src/provider/antigravityRelease.ts index 255a92761994a..ecec1aaa58799 100644 --- a/apps/server/src/provider/antigravityRelease.ts +++ b/apps/server/src/provider/antigravityRelease.ts @@ -17,6 +17,18 @@ export interface AntigravityReleaseAsset { }; } +/** + * A newer release Google lists in the ACP Registry. The registry publishes no + * hash or sizes, so the installer bounds the download, accepts only Google's + * download host, and relies on the runtime's own handshake to identify it. + */ +export interface AntigravityUpstreamRelease { + readonly version: string; + readonly url: string; +} + +export type AntigravityRelease = AntigravityReleaseAsset | AntigravityUpstreamRelease; + const releaseAssets = new Map([ [ "darwin-arm64", diff --git a/apps/server/src/provider/managedRelease.ts b/apps/server/src/provider/managedRelease.ts new file mode 100644 index 0000000000000..ca7c55e43b595 --- /dev/null +++ b/apps/server/src/provider/managedRelease.ts @@ -0,0 +1,29 @@ +import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver"; + +// Older pins recorded non-semver versions such as `agy_acp_server_1.1.1`; any +// other release is an update from those. +const isNewer = (candidate: string, current: string) => + parseSemver(candidate) && parseSemver(current) + ? compareSemverVersions(candidate, current) > 0 + : candidate !== current; + +/** + * Picks the release a managed installation's `start` downloads. A fresh install + * gets T3 Code's pinned release; an existing one moves to the newest known + * release above it. Null means nothing newer is known, so `start` re-checks the + * installed runtime instead of downgrading it. + */ +export function selectManagedRelease( + installedVersion: string | null, + pinned: Release | null, + upstream: Release | null, +): Release | null { + if (installedVersion === null) return pinned; + let selected: Release | null = null; + for (const candidate of [pinned, upstream]) { + if (candidate && isNewer(candidate.version, selected?.version ?? installedVersion)) { + selected = candidate; + } + } + return selected; +} diff --git a/apps/server/src/provider/providerInstallation.test.ts b/apps/server/src/provider/providerInstallation.test.ts index 8a3d3316ac320..d4c7467c62d0d 100644 --- a/apps/server/src/provider/providerInstallation.test.ts +++ b/apps/server/src/provider/providerInstallation.test.ts @@ -95,6 +95,7 @@ const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* }), state: Effect.succeed({ ...state, driver: ProviderDriverKind.make("codex") }), changes: Stream.succeed({ ...state, driver: ProviderDriverKind.make("codex") }), + checkForUpdate: Effect.void, remove: (paths) => Effect.sync(() => { protectedPaths = paths ?? []; @@ -103,6 +104,7 @@ const makeHarness = Effect.fn("providerInstallation.test.makeHarness")(function* }), Layer.mock(AntigravityInstallation.AntigravityInstallation)({ managedDirectory: "/unused-managed-runtime", + checkForUpdate: Effect.void, start: Effect.sync(() => { calls.push("start"); return { ...state, operationId: "install-1", phase: "downloading" as const }; diff --git a/apps/server/src/provider/providerInstallation.ts b/apps/server/src/provider/providerInstallation.ts index 7a628dfa5b318..e5e864517ba68 100644 --- a/apps/server/src/provider/providerInstallation.ts +++ b/apps/server/src/provider/providerInstallation.ts @@ -186,9 +186,21 @@ const make = Effect.fn("makeProviderInstallation")(function* () { .pipe(Effect.mapError(failure(input.instanceId))); }); + // Watching an installation is when its owner can act on an update, so the + // lookup runs then, in the background, unless update checks are off. const subscribe = (input: ProviderSetupInput) => Stream.unwrap( requireInstance(input.instanceId, "observe-install").pipe( + Effect.tap(({ installation }) => + settings.getSettings.pipe( + Effect.flatMap((current) => + current.enableProviderUpdateChecks + ? Effect.forkDetach(installation.checkForUpdate) + : Effect.void, + ), + Effect.ignore, + ), + ), Effect.map(({ installation }) => installation.changes), ), ); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 1e6172fc432c0..5a0cd335216c2 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -33,6 +33,7 @@ import { withUntracedRequests } from "./http.ts"; import * as ServerHttp from "./http.ts"; import { guardHttpResponseWriteErrors, + keepIdleConnections, rejectRequestsUntilServing, } from "./httpResponseErrorGuard.ts"; import { fixPath } from "./os-jank.ts"; @@ -361,7 +362,7 @@ const layerHttpServer = Layer.unwrap( return NodeHttpServer.layer( () => { const server = rejectRequestsUntilServing( - guardHttpResponseWriteErrors(NodeHttp.createServer()), + keepIdleConnections(guardHttpResponseWriteErrors(NodeHttp.createServer())), ); if (config.privateNetworkOnly) { server.on("connection", (socket) => { diff --git a/apps/server/src/storageCleanup.test.ts b/apps/server/src/storageCleanup.test.ts index b933895c4de1a..e7220718f15a4 100644 --- a/apps/server/src/storageCleanup.test.ts +++ b/apps/server/src/storageCleanup.test.ts @@ -205,6 +205,13 @@ describe("V2 storage cleanup eligibility", () => { resetIn: -1_000, idle: false, }, + { + name: "never armed because its reset is days overdue", + armed: false, + autoResumeSetting: true, + resetIn: -5 * DAY_MS, + idle: true, + }, { name: "not armed with recovery settings off", armed: false, diff --git a/apps/server/src/storageCleanup.ts b/apps/server/src/storageCleanup.ts index d044c2f7bdc40..673c121612c9a 100644 --- a/apps/server/src/storageCleanup.ts +++ b/apps/server/src/storageCleanup.ts @@ -42,6 +42,7 @@ import * as Orchestrator from "./orchestration-v2/Orchestrator.ts"; import * as ProjectionStore from "./orchestration-v2/ProjectionStore.ts"; import * as ProviderSessionManager from "./orchestration-v2/ProviderSessionManager.ts"; import { threadHasQueuedTurnStart } from "./orchestration-v2/ThreadSettlementService.ts"; +import { MAX_OVERDUE_ARM_MS } from "./orchestration-v2/UsageLimitRecoveryWorker.ts"; import { forkParked } from "./serverActivation.ts"; import * as Settings from "./serverSettings.ts"; import * as TerminalManager from "./terminal/Manager.ts"; @@ -182,10 +183,12 @@ function heldForLimitRecovery( // An auto-resume holds until its continuation replaces the failed run. return recovery.autoResume || (recovery.snooze === true && resetMs > now); // The recovery worker arms this failure on a later tick; hold it until then. - // Like the worker, skip a reset that had already passed when the run ended. + // Like the worker, skip a reset that had already passed when the run ended + // or that is too overdue to arm. if ( !Number.isFinite(resetMs) || - resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) + resetMs <= DateTime.toEpochMillis(thread.latestRunCompletedAt ?? thread.updatedAt) || + now - resetMs > MAX_OVERDUE_ARM_MS ) return false; return settings.autoResumeLimitedThreads || (settings.snoozeLimitedThreads && resetMs > now); diff --git a/apps/server/src/textGeneration/CodexTextGeneration.test.ts b/apps/server/src/textGeneration/CodexTextGeneration.test.ts index b67d3f0ac5830..389a6458677e7 100644 --- a/apps/server/src/textGeneration/CodexTextGeneration.test.ts +++ b/apps/server/src/textGeneration/CodexTextGeneration.test.ts @@ -1,5 +1,4 @@ import { - DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER, ProjectId, ProviderDriverKind, type ModelSelection, @@ -559,6 +558,11 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima model: "chat-model", options: [{ id: "effort", value: "high" }], }; + const threadDefault = { + instanceId: fallback, + model: "z-ai/glm-5.3-flash", + options: [{ id: "thinking", value: false }], + }; const calls: ModelSelection[] = []; const instances: ProviderInstance[] = [primary, fallback].map((instanceId) => { const driver = ProviderDriverKind.make(instanceId === primary ? "codex" : "claudeAgent"); @@ -627,8 +631,12 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima }), ServerSettings.layerTest({ providerInstances: { - [fallback]: { driver: ProviderDriverKind.make("claudeAgent"), config: {} }, + [fallback]: { + driver: ProviderDriverKind.make("claudeAgent"), + config: { customModels: [threadDefault.model] }, + }, }, + defaultModelSelection: threadDefault, ...(primaryState === "not installed, fallback disabled for project" ? { projectSettingsOverrides: { @@ -660,11 +668,7 @@ it.effect.each(PREFLIGHT_PRIMARY_STATES)("text generation preflight: %s", (prima primaryState === "not installed, fallback disabled for project" || primaryState === "signed out, fallback failed" ? selection - : { - instanceId: fallback, - model: - DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[ProviderDriverKind.make("claudeAgent")], - }, + : threadDefault, ]); }), ); diff --git a/apps/server/src/textGeneration/TextGeneration.ts b/apps/server/src/textGeneration/TextGeneration.ts index 3042c97191cbd..b89e264db8d57 100644 --- a/apps/server/src/textGeneration/TextGeneration.ts +++ b/apps/server/src/textGeneration/TextGeneration.ts @@ -9,10 +9,7 @@ import { } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { exhaustedUsageWindow } from "@t3tools/shared/usageLimits"; -import { - defaultTextGenerationModel, - fallbackTextGenerationModelSelection, -} from "@t3tools/shared/serverSettings"; +import { fallbackTextGenerationModelSelection } from "@t3tools/shared/serverSettings"; import * as ServerSettings from "../serverSettings.ts"; import type { ProviderTextGeneration } from "@t3tools/provider-core/server/textGeneration"; import { TextGenerationError } from "@t3tools/contracts"; @@ -125,21 +122,25 @@ export const make = Effect.gen(function* () { ), ); selection = - fallbackTextGenerationModelSelection(settings.providerInstances, (instanceId, driver) => { - const provider = snapshots.find((candidate) => candidate.instanceId === instanceId); - return ( - instanceId !== selection.instanceId && - provider?.enabled === true && - resolveProjectProviderInstanceEnabled(settings, projectId ?? null, instanceId) && - provider.installed && - provider.auth.status !== "unauthenticated" && - provider.status !== "error" && - isProviderAvailable(provider) && - isProviderTextGenerationCapable(provider) && - (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) && - !exhaustedUsageWindow(provider, now, defaultTextGenerationModel(driver)) - ); - }) ?? selection; + fallbackTextGenerationModelSelection( + settings.providerInstances, + (instanceId, driver, model) => { + const provider = snapshots.find((candidate) => candidate.instanceId === instanceId); + return ( + instanceId !== selection.instanceId && + provider?.enabled === true && + resolveProjectProviderInstanceEnabled(settings, projectId ?? null, instanceId) && + provider.installed && + provider.auth.status !== "unauthenticated" && + provider.status !== "error" && + isProviderAvailable(provider) && + isProviderTextGenerationCapable(provider) && + (operation !== "generateReviewGuide" || INVESTIGATING_DRIVERS.has(driver)) && + !exhaustedUsageWindow(provider, now, model) + ); + }, + { defaultModelSelection: settings.defaultModelSelection }, + ) ?? selection; } if (textGeneratorCannotRun && selection.instanceId === textGeneratorId) { return yield* new TextGenerationError({ diff --git a/apps/server/src/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index dc57d823f7484..4d119cdc081f3 100644 --- a/apps/server/src/usage/UsageService.test.ts +++ b/apps/server/src/usage/UsageService.test.ts @@ -2890,7 +2890,7 @@ describe("UsageService", () => { 60 + 20 * (version === 4 ? 1 : 2), ); yield* upgraded.awaitPersisted; - assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v12.json"); + assert.strictEqual(SCAN_CACHE_FILE_NAME, "usage-scan-cache-v13.json"); assert.deepStrictEqual( (yield* Effect.promise(() => NodeFSP.readdir(stateDir))) .filter((name) => name.startsWith("usage-scan-cache")) diff --git a/apps/server/src/usage/usageAggregation.test.ts b/apps/server/src/usage/usageAggregation.test.ts index 625f7a9d63eca..f99615085bd2a 100644 --- a/apps/server/src/usage/usageAggregation.test.ts +++ b/apps/server/src/usage/usageAggregation.test.ts @@ -12,11 +12,13 @@ const rates: RateTable = new Map([ outputCostPerToken: 5e-5, cacheReadCostPerToken: 1e-6, cacheCreationCostPerToken: 1.25e-5, + cacheCreation1hCostPerToken: 2e-5, fast: { inputCostPerToken: 2e-5, outputCostPerToken: 1e-4, cacheReadCostPerToken: 2e-6, cacheCreationCostPerToken: 2.5e-5, + cacheCreation1hCostPerToken: 4e-5, }, ultrafast: null, contextTiers: [], diff --git a/apps/server/src/usage/usageAggregation.ts b/apps/server/src/usage/usageAggregation.ts index 8d1d799859737..9ff9cb9369462 100644 --- a/apps/server/src/usage/usageAggregation.ts +++ b/apps/server/src/usage/usageAggregation.ts @@ -147,12 +147,18 @@ export function mergeUsageCopies(held: UsageRecord, copy: UsageRecord): UsageRec b.cacheCreationTokens <= a.cacheCreationTokens && b.outputTokens <= a.outputTokens && b.reasoningTokens <= a.reasoningTokens && + (copy.cacheCreation1hTokens ?? 0) <= (held.cacheCreation1hTokens ?? 0) && reportedCostUsd === held.reportedCostUsd ) { return held; } + const cacheCreation1hTokens = Math.max( + held.cacheCreation1hTokens ?? 0, + copy.cacheCreation1hTokens ?? 0, + ); return { ...held, + ...(cacheCreation1hTokens > 0 ? { cacheCreation1hTokens } : {}), totals: { uncachedInputTokens: Math.max(a.uncachedInputTokens, b.uncachedInputTokens), cachedInputTokens: Math.max(a.cachedInputTokens, b.cachedInputTokens), diff --git a/apps/server/src/usage/usagePricing.ts b/apps/server/src/usage/usagePricing.ts index 4a04116db2df9..21a1bd02bb178 100644 --- a/apps/server/src/usage/usagePricing.ts +++ b/apps/server/src/usage/usagePricing.ts @@ -12,6 +12,8 @@ export interface TokenRates { readonly outputCostPerToken: number; readonly cacheReadCostPerToken: number; readonly cacheCreationCostPerToken: number; + /** Cache writes with a 1-hour TTL; the 5-minute rate when unpublished. */ + readonly cacheCreation1hCostPerToken: number; } interface SpeedRates extends TokenRates { @@ -37,20 +39,24 @@ export function createOverrideRateTable( overrides: Readonly>, ): RateTable { return new Map( - Object.entries(overrides).map(([model, prices]) => [ - model.trim(), - { - inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000, - outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000, - cacheReadCostPerToken: - (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, - cacheCreationCostPerToken: - (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, - fast: null, - ultrafast: null, - contextTiers: [], - }, - ]), + Object.entries(overrides).map(([model, prices]) => { + const cacheCreationCostPerToken = + (prices.cacheWriteCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000; + return [ + model.trim(), + { + inputCostPerToken: prices.inputCostPerMillionTokens / 1_000_000, + outputCostPerToken: prices.outputCostPerMillionTokens / 1_000_000, + cacheReadCostPerToken: + (prices.cacheReadCostPerMillionTokens ?? prices.inputCostPerMillionTokens) / 1_000_000, + cacheCreationCostPerToken, + cacheCreation1hCostPerToken: cacheCreationCostPerToken, + fast: null, + ultrafast: null, + contextTiers: [], + }, + ]; + }), ); } @@ -60,7 +66,7 @@ function finiteNumber(value: unknown): number | null { return typeof value === "number" && Number.isFinite(value) ? value : null; } -// Missing cache rates fall back to input pricing; Anthropic normally discounts reads and charges extra for writes. +// Missing cache rates fall back to input pricing, and a missing 1-hour write rate to the 5-minute one. function readTokenRates( entry: LiteLlmEntry, suffix: string, @@ -70,18 +76,28 @@ function readTokenRates( const input = finiteNumber(entry[`input_cost_per_token${suffix}`]); const output = finiteNumber(entry[`output_cost_per_token${suffix}`]) ?? outputFallback ?? null; if (input === null || output === null) return null; - const cacheRate = (name: string, field: "cacheReadCostPerToken" | "cacheCreationCostPerToken") => + const cacheRate = ( + name: string, + field: "cacheReadCostPerToken" | "cacheCreationCostPerToken" | "cacheCreation1hCostPerToken", + fallback = input, + ) => finiteNumber(entry[`${name}${suffix}`]) ?? (standard !== undefined && standard.inputCostPerToken > 0 ? (standard[field] / standard.inputCostPerToken) * input - : input); + : fallback); + const cacheCreationCostPerToken = cacheRate( + "cache_creation_input_token_cost", + "cacheCreationCostPerToken", + ); return { inputCostPerToken: input, outputCostPerToken: output, cacheReadCostPerToken: cacheRate("cache_read_input_token_cost", "cacheReadCostPerToken"), - cacheCreationCostPerToken: cacheRate( - "cache_creation_input_token_cost", - "cacheCreationCostPerToken", + cacheCreationCostPerToken, + cacheCreation1hCostPerToken: cacheRate( + "cache_creation_input_token_cost_above_1hr", + "cacheCreation1hCostPerToken", + cacheCreationCostPerToken, ), }; } @@ -92,6 +108,7 @@ function scaleTokenRates(rates: TokenRates, multiple: number): TokenRates { outputCostPerToken: rates.outputCostPerToken * multiple, cacheReadCostPerToken: rates.cacheReadCostPerToken * multiple, cacheCreationCostPerToken: rates.cacheCreationCostPerToken * multiple, + cacheCreation1hCostPerToken: rates.cacheCreation1hCostPerToken * multiple, }; } @@ -192,7 +209,8 @@ function sameTokenRates(a: TokenRates | null, b: TokenRates | null): boolean { a.inputCostPerToken === b.inputCostPerToken && a.outputCostPerToken === b.outputCostPerToken && a.cacheReadCostPerToken === b.cacheReadCostPerToken && - a.cacheCreationCostPerToken === b.cacheCreationCostPerToken + a.cacheCreationCostPerToken === b.cacheCreationCostPerToken && + a.cacheCreation1hCostPerToken === b.cacheCreation1hCostPerToken ); } @@ -301,7 +319,7 @@ function resolveRate(table: RateTable, model: string): ModelRate | null { export type PricedRecord = Pick< UsageRecord, - "model" | "rateModel" | "totals" | "speed" | "reportedCostUsd" + "model" | "rateModel" | "totals" | "cacheCreation1hTokens" | "speed" | "reportedCostUsd" >; function recordRate(table: RateTable, record: PricedRecord): ModelRate | null { @@ -316,11 +334,15 @@ export interface PricedUsage { readonly speedPremiumUsd: number; } -function costByCategory(totals: UsageTokenTotals, rates: TokenRates): UsageCategoryCost { +function costByCategory(record: PricedRecord, rates: TokenRates): UsageCategoryCost { + const { totals } = record; + const oneHour = Math.min(record.cacheCreation1hTokens ?? 0, totals.cacheCreationTokens); return { input: totals.uncachedInputTokens * rates.inputCostPerToken, cacheRead: totals.cachedInputTokens * rates.cacheReadCostPerToken, - cacheWrite: totals.cacheCreationTokens * rates.cacheCreationCostPerToken, + cacheWrite: + (totals.cacheCreationTokens - oneHour) * rates.cacheCreationCostPerToken + + oneHour * rates.cacheCreation1hCostPerToken, output: totals.outputTokens * rates.outputCostPerToken, }; } @@ -352,13 +374,13 @@ export function priceUsage( return reported === null ? unsplit(0, "unpriced") : unsplit(reported, "providerReported"); } - const listCost = costByCategory(totals, ratesAt(rate, record.speed, totals)); + const listCost = costByCategory(record, ratesAt(rate, record.speed, totals)); const listCostUsd = sumCategories(listCost); if (reported !== null && listCostUsd <= 0) return unsplit(reported, "providerReported"); const premiumUsd = record.speed === "standard" ? 0 - : listCostUsd - sumCategories(costByCategory(totals, ratesAt(rate, "standard", totals))); + : listCostUsd - sumCategories(costByCategory(record, ratesAt(rate, "standard", totals))); const scale = reported === null ? 1 : reported / listCostUsd; return { costUsd: reported ?? listCostUsd, diff --git a/apps/server/src/usage/usageScanCache.test.ts b/apps/server/src/usage/usageScanCache.test.ts index 2866a295da8fe..a8fba4da62ae6 100644 --- a/apps/server/src/usage/usageScanCache.test.ts +++ b/apps/server/src/usage/usageScanCache.test.ts @@ -65,7 +65,15 @@ describe("scan cache round trip", () => { [ "/a.jsonl", 100, - [record(), record({ dedupeKey: "msg_2:", model: "claude-opus-5-5", speed: "fast" })], + [ + record(), + record({ + dedupeKey: "msg_2:", + model: "claude-opus-5-5", + speed: "fast", + cacheCreation1hTokens: 8, + }), + ], ], [ "/b.jsonl", @@ -244,11 +252,11 @@ describe("scan cache round trip", () => { }, ); - it("re-parses a Claude transcript cached before partial copies were merged", () => { + it("re-parses a Claude transcript cached before 1-hour cache writes were counted", () => { const original = cacheWith([["/claude.jsonl", 100, [record()]]]); - const v11 = { ...parse(makeScanCacheWriter()(original, {})), version: 11 }; + const v12 = { ...parse(makeScanCacheWriter()(original, {})), version: 12 }; - const restored = decodeScanCache(JSON.parse(JSON.stringify(v11)), TEST_FORMAT_MAP); + const restored = decodeScanCache(JSON.parse(JSON.stringify(v12)), TEST_FORMAT_MAP); expect(restored.get("/claude.jsonl")).toEqual({ ...original.get("/claude.jsonl"), size: -1, diff --git a/apps/server/src/usage/usageScanCache.ts b/apps/server/src/usage/usageScanCache.ts index 4cd959c75aa25..4f1137f3f7a1c 100644 --- a/apps/server/src/usage/usageScanCache.ts +++ b/apps/server/src/usage/usageScanCache.ts @@ -10,7 +10,7 @@ import { CLAUDE_SYNTHETIC_MODEL } from "../provider/Drivers/claudeUsage.ts"; import { mergeUsageCopies } from "./usageAggregation.ts"; import { GUARD_LENGTH, type TranscriptParsePosition } from "./usageTranscriptReader.ts"; -const USAGE_SCAN_CACHE_VERSION = 12 as const; +const USAGE_SCAN_CACHE_VERSION = 13 as const; const SPEED_COMPATIBLE_SINCE_VERSION = 4; /** @@ -18,8 +18,9 @@ const SPEED_COMPATIBLE_SINCE_VERSION = 4; * replace it, dropping saved usage for deleted transcripts. Separate files keep * the newer one; older files are removed once it is saved. */ -export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v12.json"; +export const SCAN_CACHE_FILE_NAME = "usage-scan-cache-v13.json"; export const LEGACY_SCAN_CACHE_FILE_NAMES = [ + "usage-scan-cache-v12.json", "usage-scan-cache-v11.json", "usage-scan-cache-v10.json", "usage-scan-cache-v9.json", @@ -59,7 +60,8 @@ type SerializedRecord = readonly [ reportedCostUsd: number | null, speed: number, rateModelIndex?: number | null, - unresolvedServiceTierTurnId?: string, + unresolvedServiceTierTurnId?: string | null, + cacheCreation1hTokens?: number, ]; interface SerializedFile { @@ -118,9 +120,11 @@ function serializeFile(entry: CachedFile, tables: InternTables): SerializedFile record.rateModel === undefined ? null : intern(tables.models, tables.modelIndex, record.rateModel), - ...(record.unresolvedServiceTierTurnId === undefined - ? ([] as const) - : ([record.unresolvedServiceTierTurnId] as const)), + ...(record.cacheCreation1hTokens !== undefined + ? ([record.unresolvedServiceTierTurnId ?? null, record.cacheCreation1hTokens] as const) + : record.unresolvedServiceTierTurnId !== undefined + ? ([record.unresolvedServiceTierTurnId] as const) + : ([] as const)), ]; return { s: entry.size, @@ -211,6 +215,7 @@ export function decodeScanCache( speedIndex, rateModelIndex, unresolvedServiceTierTurnId, + cacheCreation1h = 0, ] = row as SerializedRecord; const speed = typeof speedIndex === "number" ? SPEEDS[speedIndex] : undefined; @@ -220,8 +225,8 @@ export function decodeScanCache( typeof timestampMs !== "number" || !Number.isFinite(timestampMs) || model === undefined || - (unresolvedServiceTierTurnId !== undefined && - typeof unresolvedServiceTierTurnId !== "string") || + (unresolvedServiceTierTurnId != null && typeof unresolvedServiceTierTurnId !== "string") || + !Number.isFinite(cacheCreation1h) || (rateModelIndex != null && rateModel === undefined) || !Number.isFinite(uncached) || !Number.isFinite(cached) || @@ -250,9 +255,10 @@ export function decodeScanCache( outputTokens: output, reasoningTokens: reasoning, }, + ...(cacheCreation1h > 0 ? { cacheCreation1hTokens: cacheCreation1h } : {}), reportedCostUsd: typeof reportedCostUsd === "number" ? reportedCostUsd : null, speed, - ...(version >= 7 && unresolvedServiceTierTurnId !== undefined + ...(version >= 7 && unresolvedServiceTierTurnId != null ? { unresolvedServiceTierTurnId } : {}), dedupeKey: typeof dedupeKey === "string" ? dedupeKey : null, @@ -292,8 +298,9 @@ export function decodeScanCache( // Keep history for deleted rollouts, but re-parse incompatible reducer state. // v9 and v11 repair skipped Codex requests; clean v8+ entries stay served while unchanged. // v10 adds Claude advisor calls; before v12 a repeated Claude key kept its first, possibly partial, copy. + // v13 adds Claude 1-hour cache writes. const legacy = - (entry.p === "claude" && version < 12) || + (entry.p === "claude" && version < 13) || (format.state !== undefined && (version < 6 || (entry.p === "codex" && (version < 8 || (version < 11 && malformedRecords > 0))))); diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 25401ec98544c..542057e60c3ec 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -2184,6 +2184,31 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); + it.effect( + "switches a remote ref to its tracking branch when a tag shares the branch name", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", "HEAD:refs/heads/v1.2"]); + yield* git(cwd, ["fetch", "origin"]); + yield* git(cwd, ["branch", "--track", "v1.2", "origin/v1.2"]); + yield* git(cwd, ["tag", "v1.2"]); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + + const result = yield* (yield* GitVcsDriver.GitVcsDriver).switchRef({ + cwd, + refName: "origin/v1.2", + }); + + assert.equal(result.refName, "v1.2"); + assert.equal(yield* git(cwd, ["symbolic-ref", "HEAD"]), "refs/heads/v1.2"); + }), + ); + it.effect.each([ // Git cannot tell a missing revision from a missing file in these. { label: "an argument that may be a path", args: ["log", "-1", "missing"] }, @@ -6070,39 +6095,82 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("tracks a remote start point once another process releases the config lock", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - const { initialBranch } = yield* initRepoWithCommit(cwd); - const remote = yield* makeTmpDir("git-remote-"); - yield* git(remote, ["init", "--bare"]); - yield* git(cwd, ["remote", "add", "origin", remote]); - yield* git(cwd, ["push", "origin", initialBranch]); - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const lockPath = path.join(cwd, ".git", "config.lock"); - yield* fileSystem.writeFileString(lockPath, ""); - const { driver, failures } = yield* makeDriverReleasingLock( - (args) => args.some((arg) => arg.startsWith("--set-upstream-to")), - lockPath, - ); + it.effect.each(["createWorktree", "switchRef"] as const)( + "tracks a remote start point once another process releases the config lock: %s", + (operation) => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "origin", `${initialBranch}:refs/heads/feature/tracked`]); + yield* git(cwd, ["fetch", "origin"]); + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const lockPath = path.join(cwd, ".git", "config.lock"); + yield* fileSystem.writeFileString(lockPath, ""); + const { driver, failures } = yield* makeDriverReleasingLock( + (args) => args.some((arg) => arg.startsWith("--set-upstream-to")), + lockPath, + ); - // The upstream retry waits on the real clock; the lock is already gone by then. - yield* TestClock.withLive( - driver.createWorktree({ - cwd, - path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"), - refName: `origin/${initialBranch}`, - newRefName: "feature/tracked", - }), - ); + // The upstream retry waits on the real clock; the lock is already gone by then. + if (operation === "createWorktree") { + yield* TestClock.withLive( + driver.createWorktree({ + cwd, + path: path.join(yield* makeTmpDir("git-worktrees-"), "tracked"), + refName: "origin/feature/tracked", + newRefName: "feature/tracked", + }), + ); + } else { + const switched = yield* TestClock.withLive( + driver.switchRef({ cwd, refName: "origin/feature/tracked" }), + ); + assert.equal(switched.refName, "feature/tracked"); + } - assert.equal(yield* Ref.get(failures), 1); - assert.equal( - yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]), - `origin/${initialBranch}`, - ); - }), + assert.equal(yield* Ref.get(failures), 1); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature/tracked@{upstream}"]), + "origin/feature/tracked", + ); + }), + ); + + it.effect( + "leaves no untracked branch behind when the config stays locked during a switch", + () => + Effect.gen(function* () { + const cwd = yield* makeTmpDir(); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const remote = yield* makeTmpDir("git-remote-"); + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "upstream", remote]); + yield* git(cwd, ["push", "upstream", `${initialBranch}:refs/heads/feature`]); + yield* git(cwd, ["fetch", "upstream"]); + const fileSystem = yield* FileSystem.FileSystem; + const lockPath = (yield* Path.Path).join(cwd, ".git", "config.lock"); + yield* fileSystem.writeFileString(lockPath, ""); + const driver = yield* GitVcsDriver.GitVcsDriver; + + // The upstream retry waits on the real clock before giving up. + yield* TestClock.withLive(driver.switchRef({ cwd, refName: "upstream/feature" })).pipe( + Effect.flip, + ); + assert.equal(yield* git(cwd, ["branch", "--show-current"]), initialBranch); + assert.equal(yield* git(cwd, ["branch", "--list", "feature"]), ""); + + yield* fileSystem.remove(lockPath); + const switched = yield* driver.switchRef({ cwd, refName: "upstream/feature" }); + assert.equal(switched.refName, "feature"); + assert.equal( + yield* git(cwd, ["rev-parse", "--abbrev-ref", "feature@{upstream}"]), + "upstream/feature", + ); + }), ); it.effect("fetches a remote branch into a tracking branch past another process's lock", () => @@ -6341,28 +6409,42 @@ it.layer(layerTest)("GitVcsDriver core integration", (it) => { }), ); - it.effect("prepares selected files without staging and commits only those files", () => - Effect.gen(function* () { - const cwd = yield* makeTmpDir(); - yield* initRepoWithCommit(cwd); - const driver = yield* GitVcsDriver.GitVcsDriver; - - yield* writeTextFile(cwd, "a.txt", "a\n"); - yield* writeTextFile(cwd, "b.txt", "b\n"); - - const context = yield* driver.prepareCommitContext(cwd, ["a.txt"]); - assert.include(context?.stagedSummary ?? "", "a.txt"); - assert.notInclude(context?.stagedSummary ?? "", "b.txt"); - assert.equal(yield* git(cwd, ["diff", "--cached", "--name-only"]), ""); + it.effect.each(["root", "aliased-nested"] as const)( + "prepares selected files without staging and commits only those files from %s", + (location) => + Effect.gen(function* () { + const sandbox = yield* makeTmpDir(); + const path = yield* Path.Path; + const fileSystem = yield* FileSystem.FileSystem; + const repository = path.join(sandbox, "repo"); + const nested = path.join(repository, "sub", "dir"); + yield* fileSystem.makeDirectory(nested, { recursive: true }); + yield* initRepoWithCommit(repository); + const cwd = location === "aliased-nested" ? path.join(sandbox, "link") : repository; + if (location === "aliased-nested") NodeFS.symlinkSync(nested, cwd, "junction"); + const driver = yield* GitVcsDriver.GitVcsDriver; + const selected = "sub/dir/a.txt"; + yield* writeTextFile(repository, selected, "a\n"); + yield* writeTextFile(repository, "b.txt", "b\n"); - const commit = yield* driver.commit(cwd, "Add a", "", { stage: { filePaths: ["a.txt"] } }); - assert.match(commit.commitSha, /^[a-f0-9]{40}$/); - assert.equal(yield* git(cwd, ["log", "-1", "--pretty=%s"]), "Add a"); + const context = yield* driver.prepareCommitContext(cwd, [selected]); + assert.include(context?.stagedSummary ?? "", "a.txt"); + assert.notInclude(context?.stagedSummary ?? "", "b.txt"); + assert.equal(yield* git(repository, ["diff", "--cached", "--name-only"]), ""); - const status = yield* git(cwd, ["status", "--porcelain"]); - assert.include(status, "?? b.txt"); - assert.notInclude(status, "a.txt"); - }), + const commit = yield* driver.commit(cwd, "Add a", "", { + stage: { filePaths: [selected] }, + }); + assert.match(commit.commitSha, /^[a-f0-9]{40}$/); + assert.equal(yield* git(repository, ["log", "-1", "--pretty=%s"]), "Add a"); + assert.equal( + yield* git(repository, ["diff-tree", "--no-commit-id", "--name-only", "-r", "HEAD"]), + selected, + ); + const status = yield* git(repository, ["status", "--porcelain"]); + assert.include(status, "?? b.txt"); + assert.notInclude(status, "a.txt"); + }), ); it.effect("stops a selected-file commit when another process holds the index lock", () => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a8e4fb9265f3d..a0b99e6d6d7f5 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -2633,7 +2633,9 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* cwd, ["rev-parse", "--git-path", "index", "--git-path", "objects"], )).split("\n"); - const indexPath = path.resolve(cwd, indexValue.trim()); + // Git's relative paths use the physical cwd, even when the project uses a symlink. + const physicalCwd = yield* fileSystem.realPath(cwd); + const indexPath = path.resolve(physicalCwd, indexValue.trim()); const directory = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3code-commit-index-", }); @@ -2651,7 +2653,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const quoted = (entry: string) => entry.startsWith('"') ? entry : `"${entry.replace(/[\\"]/g, "\\$&")}"`; const alternates = [ - path.resolve(cwd, objectsValue.trim()), + path.resolve(physicalCwd, objectsValue.trim()), ...objectDirectories .split("\n") .flatMap((line) => @@ -5255,7 +5257,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ? yield* executeGit( "GitVcsDriver.switchRef.localTrackingBranch", input.cwd, - ["for-each-ref", "--format=%(refname:short)\t%(upstream:short)", "refs/heads"], + // `:short` prefixes a name a tag shares with `heads/`, so names are unambiguous here. + ["for-each-ref", "--format=%(refname:lstrip=2)\t%(upstream)", "refs/heads"], { timeoutMs: 5_000, allowNonZeroExit: true, @@ -5263,7 +5266,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ).pipe( Effect.map((result) => result.exitCode === 0 - ? parseTrackingBranchByUpstreamRef(result.stdout, input.refName) + ? parseTrackingBranchByUpstreamRef(result.stdout, `refs/remotes/${input.refName}`) : null, ), ) @@ -5305,15 +5308,29 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* // Created before the checkout so the shared-config lock is not held while files are written. // Not rolled back on failure: Git may already have switched HEAD to it (post-checkout hooks). if (newTrackingBranch) { - yield* executeGit( + const startRef = `refs/remotes/${input.refName}`; + yield* executeGitWithStableDiagnostics( "GitVcsDriver.switchRef.createTrackingBranch", input.cwd, - ["branch", "--track", "--", newTrackingBranch, input.refName], - { - timeoutMs: 10_000, - fallbackErrorDetail: "git branch create failed", - writesSharedConfig: true, - }, + ["branch", "--no-track", "--", newTrackingBranch, startRef], + { fallbackErrorDetail: "git branch create failed" }, + ); + // An untracked branch of this name would make every later switch to the remote detach. + yield* executeGitWithStableDiagnostics( + "GitVcsDriver.switchRef.trackRemote", + input.cwd, + ["branch", `--set-upstream-to=${startRef}`, "--", newTrackingBranch], + { writesSharedConfig: true }, + ).pipe( + retryWhileConfigLocked, + Effect.tapError(() => + executeGit( + "GitVcsDriver.switchRef.removeUntrackedBranch", + input.cwd, + ["update-ref", "-d", `refs/heads/${newTrackingBranch}`, startRef], + { allowNonZeroExit: true }, + ), + ), ); } diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 15f320a700837..610568078e31a 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off import * as NodeFSP from "node:fs/promises"; import * as NodeServices from "@effect/platform-node/NodeServices"; +import { FileFinder } from "@ff-labs/fff-node"; import { it, afterEach, describe, expect } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; @@ -12,7 +13,6 @@ import { vi } from "vite-plus/test"; import * as ServerConfig from "../config.ts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import * as VcsProcess from "../vcs/VcsProcess.ts"; -import { WorkspaceFinderOpener } from "./WorkspaceFinderThread.ts"; import * as WorkspaceEntries from "./WorkspaceEntries.ts"; import * as WorkspacePaths from "./WorkspacePaths.ts"; @@ -457,17 +457,31 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { }), ); - it.effect("matches square brackets in the query literally", () => + it.effect("matches glob metacharacters in the query literally", () => Effect.gen(function* () { const cwd = yield* makeTempDir({ prefix: "t3code-workspace-brackets-" }); yield* writeTextFile(cwd, "src/app/game/[id]/index.tsx"); + yield* writeTextFile(cwd, "src/foo{bar}.ts"); + yield* writeTextFile(cwd, "src/main.ts"); + yield* writeTextFile(cwd, "src/notes.md"); - for (const query of ["game/[i", "game/[id]"]) { - const result = yield* searchWorkspaceEntries({ cwd, query, limit: 10 }); - expect(result.entries.map((entry) => entry.path)).toContain( - "src/app/game/[id]/index.tsx", + const search = (query: string) => + searchWorkspaceEntries({ cwd, query, limit: 10 }).pipe( + Effect.map((result) => result.entries.map((entry) => entry.path)), ); + + for (const query of ["game/[i", "game/[id]"]) { + expect(yield* search(query)).toContain("src/app/game/[id]/index.tsx"); } + expect(yield* search("foo{bar}.ts")).toContain("src/foo{bar}.ts"); + expect((yield* search("*.{ts,tsx}")).toSorted()).toEqual([ + "src/app/game/[id]/index.tsx", + "src/foo{bar}.ts", + "src/main.ts", + ]); + expect((yield* search("*.{ts}")).toSorted()).toEqual(["src/foo{bar}.ts", "src/main.ts"]); + expect(yield* search("src/{main}.ts")).toEqual(["src/main.ts"]); + expect(yield* search("src/{foo{bar},notes}.md")).toEqual(["src/notes.md"]); }), ); @@ -793,42 +807,43 @@ it.layer(layerTest, { excludeTestServices: true })("WorkspaceEntries", (it) => { let scansOutlastWait = false; let finders = 0; let rescans = 0; - const openFinder = yield* WorkspaceFinderOpener; - const countingOpener: typeof openFinder = async (options) => { - const opened = await openFinder(options); - if (!opened.ok) return opened; - finders += 1; - const call: typeof opened.value.call = (method, ...args) => { - if (method === "scanFiles") rescans += 1; - if (method === "waitForIndexReady" && scansOutlastWait) { - return Promise.resolve({ ok: true, value: false } as never); - } - return opened.value.call(method, ...args); - }; - return { ok: true, value: { ...opened.value, call } }; - }; - const result = yield* Effect.gen(function* () { - const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; - const searchNeedle = workspaceEntries.searchContents({ - cwd, - query: "needle", - limit: 100, - caseSensitive: true, - wholeWord: false, - useRegex: false, - }); - yield* searchNeedle; - - scansOutlastWait = true; - yield* workspaceEntries.refresh(cwd); - return yield* searchNeedle; - }).pipe( - Effect.provide( - Layer.fresh(WorkspaceEntries.layer).pipe( - Layer.provide(Layer.succeed(WorkspaceFinderOpener, countingOpener)), - ), - ), - ); + const createFinder = FileFinder.create.bind(FileFinder); + vi.spyOn(FileFinder, "create").mockImplementation((options) => { + const created = createFinder(options); + if (created.ok) { + const finder = created.value; + finders += 1; + // The synchronous rescan waits on fff's picker lock on the event loop. + finder.scanFiles = () => { + throw new Error("refresh must not rescan on the JS thread"); + }; + const scanFilesAsync = finder.scanFilesAsync.bind(finder); + finder.scanFilesAsync = () => { + rescans += 1; + return scanFilesAsync(); + }; + const waitForIndexReady = finder.waitForIndexReady.bind(finder); + finder.waitForIndexReady = (timeoutMs) => + scansOutlastWait + ? Promise.resolve({ ok: true, value: false }) + : waitForIndexReady(timeoutMs); + } + return created; + }); + const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries; + const searchNeedle = workspaceEntries.searchContents({ + cwd, + query: "needle", + limit: 100, + caseSensitive: true, + wholeWord: false, + useRegex: false, + }); + yield* searchNeedle; + + scansOutlastWait = true; + yield* workspaceEntries.refresh(cwd); + const result = yield* searchNeedle; expect(result.matches.map((match) => match.path)).toEqual(["src/notes.ts"]); // The second search ran on the rescanned live finder, not a rebuild. diff --git a/apps/server/src/workspace/WorkspaceFinderThread.ts b/apps/server/src/workspace/WorkspaceFinderThread.ts deleted file mode 100644 index ec15b59661943..0000000000000 --- a/apps/server/src/workspace/WorkspaceFinderThread.ts +++ /dev/null @@ -1,116 +0,0 @@ -// @effect-diagnostics nodeBuiltinImport:off -- fff's native calls block their thread, so each finder owns a Node worker. -import * as NodeModule from "node:module"; -import * as NodeWorkerThreads from "node:worker_threads"; - -import type { FileFinder, InitOptions, Result } from "@ff-labs/fff-node"; -import * as Context from "effect/Context"; - -type FinderMethod = - | "destroy" - | "directorySearch" - | "fileSearch" - | "grep" - | "isScanning" - | "mixedSearch" - | "scanFiles" - | "waitForIndexReady"; - -export interface ThreadedFinder { - readonly call: ( - method: M, - ...args: Parameters - ) => Promise>>; - /** Stops the thread once any native call in flight returns; call `destroy` first. */ - readonly close: () => Promise; -} - -export type OpenFinder = (options: InitOptions) => Promise>; - -// An inline worker needs no extra build entry, so src, dist, the single executable and Electron all load it. -// Eval workers define a global `__dirname` of ".", which fff-node would use to look for its native library. -const FINDER_WORKER_SOURCE = ` -delete globalThis.__dirname; -delete globalThis.__filename; -const { parentPort, workerData } = require("node:worker_threads"); -const { FileFinder } = require(workerData.fffEntryPath); -const created = FileFinder.create(workerData.options); -parentPort.postMessage({ created: created.ok ? { ok: true } : created }); -if (created.ok) { - const finder = created.value; - parentPort.on("message", async ({ id, method, args }) => { - try { - parentPort.postMessage({ id, value: await finder[method](...args) }); - } catch (cause) { - parentPort.postMessage({ id, failed: true, cause }); - } - }); -} -`; - -// Node's watch mode posts its own `watch:require` messages on the same port, so every reply is tagged. -type WorkerMessage = - | { readonly created: Result } - | { readonly id: number; readonly value: unknown } - | { readonly id: number; readonly failed: true; readonly cause: unknown }; - -// fff-node's native library stays external; single-executables require disk packages instead of importing them. -const requireForFff = NodeModule.createRequire(import.meta.url); -const fffEntryPath = requireForFff.resolve("@ff-labs/fff-node"); -// ffi-rs crashes the process when the first thread that loaded it exits, so the main thread loads it first. -requireForFff(fffEntryPath); - -const openWorkerFinder: OpenFinder = (options) => - new Promise((resolve, reject) => { - const worker = new NodeWorkerThreads.Worker(FINDER_WORKER_SOURCE, { - eval: true, - workerData: { fffEntryPath, options }, - }); - worker.unref(); - const pending = new Map< - number, - { readonly resolve: (value: never) => void; readonly reject: (cause: unknown) => void } - >(); - let nextId = 0; - let failure: unknown; - const fail = (cause: unknown) => { - failure ??= cause; - reject(failure); - for (const request of pending.values()) request.reject(failure); - pending.clear(); - }; - worker.on("error", fail); - worker.on("exit", (code) => fail(new Error(`The fff worker exited with code ${code}.`))); - - const call: ThreadedFinder["call"] = (method, ...args) => - new Promise((resolveCall, rejectCall) => { - if (failure !== undefined) { - rejectCall(failure); - return; - } - const id = nextId++; - pending.set(id, { resolve: resolveCall, reject: rejectCall }); - worker.postMessage({ id, method, args }); - }); - - worker.on("message", (message: WorkerMessage) => { - if ("created" in message) { - resolve( - message.created.ok - ? { ok: true, value: { call, close: () => worker.terminate().then(() => undefined) } } - : message.created, - ); - return; - } - const request = pending.get(message.id); - if (!request) return; - pending.delete(message.id); - if ("failed" in message) request.reject(message.cause); - else request.resolve(message.value as never); - }); - }); - -/** Opens fff finders off the server's event loop, where a native call can block for as long as a file read. */ -export const WorkspaceFinderOpener = Context.Reference( - "t3/workspace/WorkspaceFinderThread/WorkspaceFinderOpener", - { defaultValue: () => openWorkerFinder }, -); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts index c667e4bf26bcf..2f9ac05bf9e3c 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.test.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.test.ts @@ -1,4 +1,10 @@ -import type { FileFinder, FileItem, GrepCursor, GrepOptions, GrepResult } from "@ff-labs/fff-node"; +import { + FileFinder, + type FileItem, + type GrepCursor, + type GrepOptions, + type GrepResult, +} from "@ff-labs/fff-node"; import * as NodeServices from "@effect/platform-node/NodeServices"; import { afterEach, expect, it } from "@effect/vitest"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -7,23 +13,12 @@ import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import { vi } from "vite-plus/test"; -import { WorkspaceFinderOpener } from "./WorkspaceFinderThread.ts"; import * as WorkspaceSearchIndex from "./WorkspaceSearchIndex.ts"; afterEach(() => { vi.restoreAllMocks(); }); -const withInProcessFinder = (finder: FileFinder) => - Effect.provideService(WorkspaceFinderOpener, async () => ({ - ok: true as const, - value: { - call: async (method, ...args) => - (finder[method] as (...input: typeof args) => never)(...args), - close: async () => undefined, - }, - })); - function fileItem(relativePath: string): FileItem { return { relativePath, @@ -58,10 +53,9 @@ it.effect("filters image searches before applying the result limit", () => waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), fileSearch, } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project").pipe( - withInProcessFinder(finder), - ); + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project"); const resultWithoutKind = yield* searchIndex.search("", 200, undefined, true); const resultWithDirectoryKind = yield* searchIndex.search("", 200, "directory", true); @@ -122,10 +116,9 @@ it.effect("continues whole-word searches after a filtered grep page", () => waitForIndexReady: vi.fn(async () => ({ ok: true as const, value: true })), grep, } as unknown as FileFinder; + vi.spyOn(FileFinder, "create").mockReturnValueOnce({ ok: true, value: finder }); - const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content").pipe( - withInProcessFinder(finder), - ); + const searchIndex = yield* WorkspaceSearchIndex.make("/workspace/project", "content"); const result = yield* searchIndex.searchContents({ query: "needle", limit: 1, diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 4cd7967196067..f276bfd9654ee 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -1,7 +1,10 @@ +import * as NodeModule from "node:module"; + import type { DirItem, DirSearchResult, FileItem, + FileFinder as FileFinderType, GrepCursor, MixedItem, MixedSearchResult, @@ -24,7 +27,9 @@ import type { } from "@t3tools/contracts"; import { isProjectFaviconPath } from "@t3tools/shared/projectFavicon"; -import { type ThreadedFinder, WorkspaceFinderOpener } from "./WorkspaceFinderThread.ts"; +// fff-node's native library stays external; single-executables require disk packages instead of importing them. +const requireForFff = NodeModule.createRequire(import.meta.url); +const { FileFinder } = requireForFff("@ff-labs/fff-node") as typeof import("@ff-labs/fff-node"); const WORKSPACE_INDEX_MAX_ENTRIES = 25_000; const WORKSPACE_INDEX_PAGE_SIZE = WORKSPACE_INDEX_MAX_ENTRIES + 2; @@ -283,10 +288,9 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* ( cwd: string, variant: WorkspaceSearchIndexVariant, ) { - const openFinder = yield* WorkspaceFinderOpener; - const result = yield* Effect.tryPromise({ + const result = yield* Effect.try({ try: () => - openFinder({ + FileFinder.create({ basePath: cwd, disableMmapCache: true, // Content indexing costs CPU/memory; path-only consumers use the lightweight index. @@ -309,11 +313,11 @@ const createFinder = Effect.fn("WorkspaceSearchIndex.createFinder")(function* ( const waitForIndexReady = Effect.fn("WorkspaceSearchIndex.waitForIndexReady")(function* ( cwd: string, - finder: ThreadedFinder, + finder: FileFinderType, onFailure: (input: { readonly reason: string; readonly cause?: unknown }) => E, ): Effect.fn.Return { const result = yield* Effect.tryPromise({ - try: () => finder.call("waitForIndexReady", WORKSPACE_INDEX_SCAN_TIMEOUT_MS), + try: () => finder.waitForIndexReady(WORKSPACE_INDEX_SCAN_TIMEOUT_MS), catch: (cause) => onFailure({ reason: "FileFinder.waitForIndexReady rejected unexpectedly.", @@ -336,8 +340,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( variant: WorkspaceSearchIndexVariant = "paths", ) { const finder = yield* Effect.acquireRelease(createFinder(cwd, variant), (finder) => - Effect.tryPromise({ - try: () => finder.call("destroy").finally(finder.close), + Effect.try({ + try: () => finder.destroy(), catch: (cause) => new WorkspaceSearchIndexDestroyFailed({ cwd, cause }), }).pipe(Effect.orDie), ); @@ -362,28 +366,15 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }), ); - const hasIncompleteInitialScan = () => - initialScanTimedOut - ? Effect.tryPromise({ - try: () => finder.call("isScanning"), - catch: (cause) => - new WorkspaceSearchIndexSearchFailed({ - cwd, - queryLength: 0, - pageSize: 0, - reason: "FileFinder.isScanning threw unexpectedly.", - cause, - }), - }) - : Effect.succeed(false); + const hasIncompleteInitialScan = () => initialScanTimedOut && finder.isScanning(); const runSearch = Effect.fn("WorkspaceSearchIndex.runSearch")(function* ( query: string, pageSize: number, operation: "directorySearch" | "fileSearch" | "grep" | "mixedSearch", - execute: () => Promise>, + execute: () => Result, ): Effect.fn.Return { - const result = yield* Effect.tryPromise({ + const result = yield* Effect.try({ try: execute, catch: (cause) => new WorkspaceSearchIndexSearchFailed({ @@ -408,12 +399,13 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn( "WorkspaceSearchIndex.refresh", )(function* () { + // scanFiles waits on fff's picker lock, which its watcher can hold for seconds. const result = yield* Effect.tryPromise({ - try: () => finder.call("scanFiles"), + try: () => finder.scanFilesAsync(), catch: (cause) => new WorkspaceSearchIndexRefreshFailed({ cwd, - reason: "FileFinder.scanFiles threw unexpectedly.", + reason: "FileFinder.scanFilesAsync rejected unexpectedly.", cause, }), }); @@ -439,9 +431,9 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( const list: WorkspaceSearchIndex["Service"]["list"] = Effect.fn("WorkspaceSearchIndex.list")( function* () { - const incompleteBeforeQuery = yield* hasIncompleteInitialScan(); + const incompleteBeforeQuery = hasIncompleteInitialScan(); const result = yield* runSearch("", WORKSPACE_INDEX_PAGE_SIZE, "mixedSearch", () => - finder.call("mixedSearch", "", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }), + finder.mixedSearch("", { pageSize: WORKSPACE_INDEX_PAGE_SIZE }), ); const mapped = mapMixedSearchResult(result, WORKSPACE_INDEX_MAX_ENTRIES); const sortedEntries = withDirectoryAncestors(mapped.entries).toSorted((left, right) => @@ -456,32 +448,43 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( }, ); - const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( - "WorkspaceSearchIndex.search", - )(function* (rawQuery, limit, kind, imageOnly) { - // fff parses any word containing "[" as a glob and has no escape for it; fuzzy - // matching is subsequence-based, so dropping "[" still matches "[id]" folders. - const query = rawQuery.replaceAll("[", ""); + const searchNames = Effect.fn("WorkspaceSearchIndex.searchNames")(function* ( + query: string, + limit: number, + kind: ProjectEntryKind | undefined, + imageOnly: boolean | undefined, + ) { const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1); - const incompleteBeforeQuery = yield* hasIncompleteInitialScan(); if (kind === "file" || imageOnly) { const result = yield* runSearch(query, pageSize, "fileSearch", () => - finder.call("fileSearch", query, { pageSize }), + finder.fileSearch(query, { pageSize }), ); - const mapped = mapFileSearchResult(result, limit, imageOnly); - return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; + return mapFileSearchResult(result, limit, imageOnly); } if (kind === "directory") { const result = yield* runSearch(query, pageSize, "directorySearch", () => - finder.call("directorySearch", query, { pageSize }), + finder.directorySearch(query, { pageSize }), ); - const mapped = mapDirectorySearchResult(result, limit); - return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; + return mapDirectorySearchResult(result, limit); } const result = yield* runSearch(query, pageSize, "mixedSearch", () => - finder.call("mixedSearch", query, { pageSize }), + finder.mixedSearch(query, { pageSize }), ); - const mapped = mapMixedSearchResult(result, limit); + return mapMixedSearchResult(result, limit); + }); + + const search: WorkspaceSearchIndex["Service"]["search"] = Effect.fn( + "WorkspaceSearchIndex.search", + )(function* (rawQuery, limit, kind, imageOnly) { + // fff parses any word containing "[" or "{" as a glob and has no escape for them; fuzzy + // matching is subsequence-based, so dropping them still matches "[id]" and "a{b}" paths. + // "{" is dropped only when the query finds nothing as a glob, so "*.{ts,tsx}" keeps working. + const query = rawQuery.replaceAll("[", ""); + const incompleteBeforeQuery = hasIncompleteInitialScan(); + let mapped = yield* searchNames(query, limit, kind, imageOnly); + if (mapped.entries.length === 0 && query.includes("{")) { + mapped = yield* searchNames(query.replaceAll("{", ""), limit, kind, imageOnly); + } return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; }); @@ -502,7 +505,7 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( do { const remainingTimeBudgetMs = Math.max(1, Math.ceil(deadline - performance.now())); const result = yield* runSearch(input.query, input.limit, "grep", () => - finder.call("grep", searchQuery, { + finder.grep(searchQuery, { mode: regexMode ? "regex" : "plain", smartCase: !input.caseSensitive && !regexMode, maxMatchesPerFile: Math.min(CONTENT_SEARCH_MAX_MATCHES_PER_FILE, rawPageSize), diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index 6a6a6f76e9c4f..5548607c46a3d 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -153,6 +153,7 @@ import * as EventSink from "./orchestration-v2/EventSink.ts"; import * as LegacyV1ThreadImporter from "./orchestration-v2/legacy/LegacyV1ThreadImporter.ts"; import * as ThreadCommandExecutor from "./orchestration-v2/ThreadCommandExecutor.ts"; import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator"; +import { projectIdentitiesDigest } from "./orchestration-v2/ShellStream.ts"; import * as OrchestrationEventStore from "./persistence/OrchestrationEventStore.ts"; import * as SqlitePersistence from "./persistence/Sqlite.ts"; import * as ExternalLauncher from "./process/externalLauncher.ts"; @@ -712,6 +713,8 @@ it.effect("shell snapshots omit idle children and older settled threads only on shell("live", "parent", "running"), ...Array.from({ length: 25 }, (_, index) => shell(`recent-${index}`, null, null, 1)), shell("old", null, null, 30), + shell("remote-parent", null, null, 40), + shell("remote-child-parent", "parent", null), ]; const firstSnapshot = (input: { readonly omitIdleSubagents?: boolean; @@ -728,6 +731,7 @@ it.effect("shell snapshots omit idle children and older settled threads only on pinnedAt: null, snoozedUntil: null, mayBeLive: thread.activityRunStatus !== null, + hasRemoteTasks: thread.id.startsWith("remote-"), })), ), readShellSnapshot: (options?: { readonly threadIds?: ReadonlyArray }) => @@ -771,15 +775,17 @@ it.effect("shell snapshots omit idle children and older settled threads only on const withoutChildren = yield* firstSnapshot({ omitIdleSubagents: true }); assert.deepEqual( withoutChildren?.threads.map((thread) => thread.id), - ["parent", "live", ...recent, "old"], + ["parent", "live", ...recent, "old", "remote-parent", "remote-child-parent"], ); + // A linked environment's clients nest its task under its parent, so that parent stays: an + // older settled thread or an idle subagent. const withoutOld = yield* firstSnapshot({ omitIdleSubagents: true, omitOlderSettled: true }); assert.deepEqual( withoutOld?.threads.map((thread) => thread.id), - ["parent", "live", ...recent], + ["parent", "live", ...recent, "remote-parent", "remote-child-parent"], ); assert.deepEqual(withoutOld?.olderSettled?.counts, [ - { projectId: ProjectId.make("project"), count: 1 }, + { projectId: ProjectId.make("project"), count: 2 }, ]); }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); @@ -1983,41 +1989,123 @@ it.effect.each(["thread", "shell"] as const)( }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); -// A thread idle since before the boundary missed nothing; resuming must not resend its body. -it.effect("thread resume at its own high-water below the pruned boundary skips the snapshot", () => - Effect.gen(function* () { - const sql = yield* SqlClient.SqlClient; - const now = "2026-10-13T00:00:00.000Z"; - const threadId = ThreadId.make("thread:idle"); - const [last] = yield* sql<{ sequence: number }>` - INSERT INTO orchestration_events ( - event_id, aggregate_kind, stream_id, stream_version, event_type, - occurred_at, actor_kind, payload_json, metadata_json, application_event_version - ) VALUES ( - 'idle:0', 'thread', ${threadId}, 0, 'provider-session.detached', - ${now}, 'server', ${JSON.stringify({ providerSessionId: "session:idle", detachedAt: now })}, - '{}', 2 - ) RETURNING sequence - `; - yield* sql` - INSERT INTO orchestration_v2_projection_metadata ( - projection_name, schema_version, last_sequence, updated_at - ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${last!.sequence + 10}, ${now}) - `; - const exit = yield* subscribeOrchestrationV2Thread({ - threadId, - afterSequence: last!.sequence, - }).pipe( - Effect.provideService(ThreadManagement.ThreadManagementService, { - ensureLegacyTranscript: () => Effect.void, - getThreadSnapshot: () => Effect.die("snapshot"), - streamStoredEventsFrom: () => Stream.empty, - } as unknown as ThreadManagement.ThreadManagementService["Service"]), - Effect.exit, - ); - // A snapshot load dies with "snapshot", so success means the resume replayed nothing. - assert.isTrue(Exit.isSuccess(exit)); - }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), +// A cursor at the high-water missed nothing, even below the boundary; resuming must not resend +// a snapshot. The shell cases are a client that just loaded the HTTP snapshot of a pruned +// database: it gets the marker, and the project identities only when it does not name them. +it.effect.each([ + { scope: "thread", knowsIdentities: false, isRepository: true, kinds: [] }, + { + scope: "shell", + knowsIdentities: false, + isRepository: true, + kinds: ["snapshot", "synchronized"], + }, + { scope: "shell", knowsIdentities: true, isRepository: true, kinds: ["synchronized"] }, + // The client keeps a cached identity over an absent one, so "resolved to none" still goes out. + { + scope: "shell", + knowsIdentities: true, + isRepository: false, + kinds: ["snapshot", "synchronized"], + }, +] as const)( + "$scope resume at its own high-water below the pruned boundary skips the snapshot (knows identities: $knowsIdentities, repository: $isRepository)", + ({ scope, knowsIdentities, isRepository, kinds }) => + Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + const now = "2026-10-13T00:00:00.000Z"; + const threadId = ThreadId.make("thread:idle"); + const [last] = yield* sql<{ sequence: number }>` + INSERT INTO orchestration_events ( + event_id, aggregate_kind, stream_id, stream_version, event_type, + occurred_at, actor_kind, payload_json, metadata_json, application_event_version + ) VALUES ( + 'idle:0', 'thread', ${threadId}, 0, 'provider-session.detached', + ${now}, 'server', ${JSON.stringify({ providerSessionId: "session:idle", detachedAt: now })}, + '{}', 2 + ) RETURNING sequence + `; + yield* sql` + INSERT INTO orchestration_v2_projection_metadata ( + projection_name, schema_version, last_sequence, updated_at + ) VALUES (${OrchestrationEventStore.EVENT_LOG_PRUNED_THROUGH}, 2, ${last!.sequence + 10}, ${now}) + `; + const identity = isRepository + ? ({ + canonicalKey: "github.com/t3/idle", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "git@github.com:t3/idle", + }, + } as const) + : null; + const project = { + id: ProjectId.make("project:idle"), + title: "Idle", + workspaceRoot: "/tmp/idle", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + } satisfies OrchestrationProjectShell; + const subscription = Effect.gen(function* () { + if (scope === "thread") { + return yield* subscribeOrchestrationV2Thread({ + threadId, + afterSequence: last!.sequence, + }).pipe(Effect.as([])); + } + const stream = yield* subscribeOrchestrationV2Shell({ + afterSequence: last!.sequence, + requestCompletionMarker: true, + ...(knowsIdentities + ? { + knownProjectIdentities: projectIdentitiesDigest([ + { ...project, repositoryIdentity: identity }, + ]), + } + : {}), + }); + return yield* stream.pipe( + Stream.takeUntil((item) => item.kind === "synchronized"), + Stream.map((item) => item.kind), + Stream.runCollect, + ); + }); + const exit = yield* subscription.pipe( + Effect.provideService(ThreadManagement.ThreadManagementService, { + ensureLegacyTranscript: () => Effect.void, + getThreadSnapshot: () => Effect.die("snapshot"), + listActiveShellIndex: () => Effect.die("snapshot"), + readShellSnapshot: () => Effect.die("snapshot"), + listActiveSubagentThreadIds: () => Effect.succeed([]), + streamStoredEventsFrom: () => Stream.empty, + } as unknown as ThreadManagement.ThreadManagementService["Service"]), + Effect.provideService(ProjectStore.ProjectStoreV2, { + listShells: () => Effect.succeed([project]), + } as unknown as ProjectStore.ProjectStoreV2["Service"]), + Effect.provideService( + ProjectService.ProjectService, + {} as ProjectService.ProjectService["Service"], + ), + Effect.provideService(ProjectEnrichment.ProjectEnrichmentService, { + subscribeChanges: PubSub.subscribe(yield* PubSub.unbounded()), + getAvailable: () => + Effect.succeed({ + repositoryIdentity: identity, + faviconPath: null, + repositoryIdentityResolved: true, + }), + } as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"]), + Effect.exit, + ); + // A snapshot load dies with "snapshot", so success means the resume replayed nothing. + assert.deepEqual( + Exit.isFailure(exit) ? Cause.squash(exit.cause) : Array.from(exit.value), + kinds, + ); + }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)), ); const acpDriver = ProviderDriverKind.make("acpRegistry"); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 66844ca35b49a..f69c66c59a964 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -136,6 +136,8 @@ import { shellStreamItemFromThreadShell, shellStreamItemsFromInitialSnapshot, loadSubscriberShellSnapshot, + canResumeShellFrom, + resumeIdentityRoots, shellStreamItemsFromResumeSnapshot, shouldPublishShellApplicationEvent, skipUnchangedThreadShells, @@ -726,12 +728,6 @@ const isOtherWsRpc = (rpc: ServerWsRpc): rpc is Exclude const serverWsRpcs = Array.from(ServerWsRpcGroup.requests.values()); const SplitWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isSplitWsRpc)); const OtherWsRpcGroup = RpcGroup.make(...serverWsRpcs.filter(isOtherWsRpc)); -// Replaying each intervening event costs a shell refetch; past this gap a -// single O(active-threads) snapshot is cheaper and bounded. -const SHELL_RESUME_MAX_GAP = 1_000; -// Row counts do not bound large tool payloads; sum stored JSON bytes in SQL and snapshot above budget. -const ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES = 8 * 1024 * 1024; - function toAuthAccessStreamEvent( change: PairingGrantStore.BootstrapCredentialChange | SessionStore.SessionCredentialChange, revision: number, @@ -868,36 +864,6 @@ function readClientOwners( ); } -const canReplayPersistedRange = Effect.fnUntraced(function* ( - afterSequence: number, - headSequence: number, - maxGap: number, -) { - const applicationEvents = yield* OrchestrationEventStore.OrchestrationEventStore; - - const replayGap = headSequence - afterSequence; - if (replayGap < 0 || replayGap > maxGap) { - return false; - } - if (afterSequence < (yield* applicationEvents.prunedThroughSequence)) return false; - const stats = yield* applicationEvents.getReplayStats({ - afterSequence, - throughSequence: headSequence, - }); - if (stats.rawPayloadBytes > ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES) { - yield* Effect.logDebug("orchestration replay replaced by snapshot", { - afterSequence, - headSequence, - replayGap, - eventCount: stats.eventCount, - payloadBytes: stats.rawPayloadBytes, - payloadBudgetBytes: ORCHESTRATION_REPLAY_PAYLOAD_BUDGET_BYTES, - }); - return false; - } - return true; -}); - const enrichProjectShells = Effect.fn("ws.orchestrationV2.enrichProjectShells")( (projects: ReadonlyArray) => Effect.flatMap(ProjectEnrichmentService.ProjectEnrichmentService, (projectEnrichment) => @@ -1162,6 +1128,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc function* (input: { readonly afterSequence?: number; readonly httpSnapshotFallback?: true; + readonly knownProjectIdentities?: string; readonly requestCompletionMarker?: boolean; readonly omitIdleSubagents?: boolean; readonly omitOlderSettled?: boolean; @@ -1387,7 +1354,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc }); }); const highWater = yield* applicationEvents.latestApplicationSequence; - if (!(yield* canReplayPersistedRange(input.afterSequence, highWater, SHELL_RESUME_MAX_GAP))) { + if (!(yield* canResumeShellFrom(applicationEvents, input.afterSequence, highWater))) { return yield* fromSnapshot; } @@ -1406,12 +1373,22 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc skipUnknownEventTypes: true, }) .pipe(Stream.filter(filterSubagentTranscript), Stream.runCollect); - if (input.afterSequence < (yield* applicationEvents.prunedThroughSequence)) { + if ( + input.afterSequence < highWater && + input.afterSequence < (yield* applicationEvents.prunedThroughSequence) + ) { return yield* fromSnapshot; } const replay = toShellStream(Stream.fromIterable(replayed)); return composeShellStreamWithEnrichment({ - initial: initialEnrichmentItems(loaded), + initial: initialEnrichmentItems({ + snapshot: loaded.snapshot, + resolvedRepositoryIdentityRoots: resumeIdentityRoots({ + projects: loaded.snapshot.projects, + resolvedRepositoryIdentityRoots: loaded.resolvedRepositoryIdentityRoots, + knownProjectIdentities: input.knownProjectIdentities, + }), + }), tail: Stream.concat(Stream.concat(replay, completionMarker), liveFrom(highWater)), enrichment: enrichmentRefreshes, }); diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index fa8e88e6b1a90..faa71137db049 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -14,6 +14,7 @@ import { startElectronBrowserHost } from "./browser/ElectronBrowserHost"; import { startBrowserProfileReporting } from "./browser/BrowserProfileReporter"; import { startPreviewTitleRecording } from "./browserHistoryStore"; import { retainThreadOverlaysForThread } from "./components/chat/threadOverlayRetention"; +import { resolveWindowTitleThreadStatus } from "./components/Sidebar.logic"; import { startBackgroundThreadAnnouncements } from "./components/BackgroundThreadAnnouncer"; import { startSshPasswordPromptQueue } from "./components/desktop/SshPasswordPromptDialog"; import { startHostFreezeToasts } from "./components/HostFreezeToastCoordinator"; @@ -133,7 +134,10 @@ function readOpenThreadRef(router: AppRouter): ScopedThreadRef | null { return resolveActiveThreadRouteRef(target, draft); } -/** Names the open thread and its project in the window title, or the app when none is open. */ +/** + * Names the open thread and its project in the window title, or the app when none is open. + * Screen readers read it on Alt+Tab, so it can lead with the thread and what it's doing. + */ function startDocumentTitle(router: AppRouter): void { const readOnGuestPage = () => router.state.matches.some((match) => match.routeId === "/guest"); let openThreadRef = readOpenThreadRef(router); @@ -163,6 +167,11 @@ function startDocumentTitle(router: AppRouter): void { }), projectTitle: project?.title ?? null, threadTitle: thread?.title ?? null, + ...(getClientSettings().screenReaderWindowTitle && { + screenReader: { + threadStatus: thread === null ? null : resolveWindowTitleThreadStatus(thread), + }, + }), desktop: isElectron, }); // Projects change whenever any project does; most changes leave the title alone. @@ -198,6 +207,7 @@ function startDocumentTitle(router: AppRouter): void { watchOpenThread(); appAtomRegistry.subscribe(primaryServerConfigAtom, write, { immediate: true }); appAtomRegistry.subscribe(environmentProjects.projectsAtom, write); + subscribeClientSettings(write); router.subscribe("onResolved", updateOpenThread); useComposerDraftStore.subscribe(updateOpenThread); } diff --git a/apps/web/src/branding.logic.ts b/apps/web/src/branding.logic.ts index 6490edbb4a05c..f53103d904ad0 100644 --- a/apps/web/src/branding.logic.ts +++ b/apps/web/src/branding.logic.ts @@ -60,14 +60,23 @@ export function resolveWindowTitle(input: { readonly appDisplayName: string; readonly projectTitle: string | null; readonly threadTitle: string | null; + /** The screen reader title: status, then thread, then project, since a screen reader reads from the start. */ + readonly screenReader?: { readonly threadStatus: string | null }; readonly desktop: boolean; }): string { const threadTitle = input.threadTitle?.trim() ?? ""; + const status = input.screenReader?.threadStatus; if (threadTitle === "") { - return input.appDisplayName; + return status ? `${status}: ${input.appDisplayName}` : input.appDisplayName; } const projectTitle = input.projectTitle?.trim() ?? ""; - const context = projectTitle === "" ? threadTitle : `${projectTitle} / ${threadTitle}`; - return input.desktop ? context : `${context} - ${input.appDisplayName}`; + const context = + projectTitle === "" + ? threadTitle + : input.screenReader + ? `${threadTitle} - ${projectTitle}` + : `${projectTitle} / ${threadTitle}`; + const title = status ? `${status}: ${context}` : context; + return input.desktop ? title : `${title} - ${input.appDisplayName}`; } diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 0e3f47b7f9ed8..d1d045ed41a35 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -16,6 +16,7 @@ import { resolveSidebarSweepKeys, resolveSidebarThreadStatus, resolveThreadStatusPill, + resolveWindowTitleThreadStatus, resolveWorkingStartedAt, searchSidebarThreads, shouldRecedeSidebarThread, @@ -310,6 +311,24 @@ describe("resolveSidebarThreadStatus", () => { }), ).toBe("waiting"); }); + + it("titles the window with live work and requests only", () => { + const cases = [ + [{ ...idle, hasPendingApprovals: true, runtime }, "Needs approval"], + [{ ...idle, hasPendingUserInput: true }, "Needs your input"], + [{ ...idle, runtime: { ...runtime, status: "preparing" as const } }, "Working"], + [{ ...idle, runtime }, "Working"], + [{ ...idle, runtime, pendingGuestMessageCount: 1 }, "Working"], + [{ ...idle, runtime, blockedOnThreadWait: true }, "Working"], + [{ ...idle, runtime: { ...runtime, status: "idle" as const } }, null], + [{ ...idle, runtime: { ...runtime, status: "failed" as const } }, null], + [{ ...idle, runtime: { ...runtime, status: "completed" as const } }, null], + [idle, null], + ] as const; + for (const [thread, title] of cases) { + expect(resolveWindowTitleThreadStatus(thread)).toBe(title); + } + }); }); describe("searchSidebarThreads", () => { diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 61b80349a5e96..9592d6000ed8e 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -44,6 +44,7 @@ import { import type { SidebarThreadSummary, Thread } from "../types"; import { normalizeSearchText } from "../lib/utils"; import { isLatestRunSettled } from "../session-logic"; +import { THREAD_STATUS_TEXT } from "@t3tools/client-runtime/state/thread-activity-announcement"; import { observeIntersection } from "../lib/observeIntersection"; import { deadlineAfter, deadlineStore, type ClockStore } from "@t3tools/client-runtime/clock"; import { useDeadlinePassed } from "../hooks/useDeadline"; @@ -999,6 +1000,25 @@ function resolveSidebarThreadRunStatus(thread: SidebarThreadStatusInput): Sideba return "ready"; } +/** What the window title says the open thread is doing, in the words its announcer uses. */ +export function resolveWindowTitleThreadStatus(thread: SidebarThreadStatusInput): string | null { + // A guest waiting doesn't hide that the agent is still working. + switch (resolveSidebarThreadStatus({ ...thread, pendingGuestMessageCount: 0 })) { + case "approval": + return THREAD_STATUS_TEXT.approval; + case "input": + return THREAD_STATUS_TEXT.input; + case "preparing": + case "working": + return THREAD_STATUS_TEXT.working; + case "waiting": + // Waiting on a child thread is still this turn, so it must not read as finished. + return thread.runtime?.status === "running" ? THREAD_STATUS_TEXT.working : null; + default: + return null; + } +} + /** * The dot on a closed boring-sidebar folder: the most urgent state among its * hidden threads. Waiting threads stay quiet, like their rows. diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index c33e311029bef..651d675092a7d 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -702,7 +702,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) uncommittedSnapShotIds, standaloneComposerImages, } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); - const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey); + const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( + (image) => !image.hidden, + ); const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); const openPrLink = useOpenPrLink(routeThreadRef); diff --git a/apps/web/src/components/chat/ComposerStashMenu.tsx b/apps/web/src/components/chat/ComposerStashMenu.tsx index a68bf9159b483..938c42d32c8c9 100644 --- a/apps/web/src/components/chat/ComposerStashMenu.tsx +++ b/apps/web/src/components/chat/ComposerStashMenu.tsx @@ -124,7 +124,11 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { }, []); return ( - + } aria-label="Close stash" @@ -141,7 +145,7 @@ export const ComposerStashMenu = memo(function ComposerStashMenu(props: { - + } aria-label="Stashed prompts"> {entries.length === 0 ? ( }> diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx index 3d9eeb2f1b3b9..49227eb76eadd 100644 --- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx @@ -228,9 +228,18 @@ describe("MessagesTimeline work rows", () => { const props = baseProps(); const html = injectHtmlRenderBootstrap(`
Earlier preview content
More rows
More rows
- `); + `); const src = URL.createObjectURL(new Blob([html], { type: "text/html" })); using _url = { [Symbol.dispose]: () => URL.revokeObjectURL(src) }; + // The frame loads on its own clock, and a toggle posted before its script runs is lost. + const listening = new Promise((resolve) => { + const onMessage = (event: MessageEvent) => { + if (event.data !== "listening") return; + window.removeEventListener("message", onMessage); + resolve(); + }; + window.addEventListener("message", onMessage); + }); function Preview() { const [height, setHeight] = useState(1437); return ( @@ -270,6 +279,7 @@ describe("MessagesTimeline work rows", () => { expect(viewport.scrollTop).toBeGreaterThan(0); expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2); }); + await listening; const top = frame.getBoundingClientRect().top; frame.focus(); frame.contentWindow!.postMessage("toggle", "*"); diff --git a/apps/web/src/components/chat/composerAttachmentFiles.ts b/apps/web/src/components/chat/composerAttachmentFiles.ts index 96575d393018e..f613b695ffd51 100644 --- a/apps/web/src/components/chat/composerAttachmentFiles.ts +++ b/apps/web/src/components/chat/composerAttachmentFiles.ts @@ -61,6 +61,28 @@ export function normalizeComposerImageFileMimeType(file: File): File { }); } +export function composerImageDedupKey( + image: Pick, +): string { + // Hydrated images get fresh lastModified values, so exclude it from dedupe. + return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`; +} + +// Compression changes an image's bytes, so a compressed image answers for the file it came from. +const composerImageSourceKeys = new WeakMap(); + +/** The draft store's image dedupe key, taken from the file as pasted rather than as compressed. */ +export function composerImageSourceKey(file: File): string { + return ( + composerImageSourceKeys.get(file) ?? + composerImageDedupKey({ mimeType: file.type, sizeBytes: file.size, name: file.name || "image" }) + ); +} + +export function rememberComposerImageSource(source: File, prepared: File): void { + if (prepared !== source) composerImageSourceKeys.set(prepared, composerImageSourceKey(source)); +} + function isDngFile(file: Pick): boolean { const mimeType = file.type.split(";", 1)[0]?.trim().toLowerCase(); return ( diff --git a/apps/web/src/components/chat/preparingComposerImages.ts b/apps/web/src/components/chat/preparingComposerImages.ts index 4ba7696a1789a..def7f023e8612 100644 --- a/apps/web/src/components/chat/preparingComposerImages.ts +++ b/apps/web/src/components/chat/preparingComposerImages.ts @@ -5,6 +5,8 @@ export interface PreparingComposerImage { readonly name: string; /** The uncompressed source, thumbnailed so the placeholder shows the image itself. */ readonly file: File; + /** Looks like an image the draft already has: it holds its slot but shows no tile. */ + readonly hidden: boolean; } const NO_PREPARING_IMAGES: ReadonlyArray = []; @@ -24,8 +26,14 @@ export function usePreparingComposerImages(targetKey: string) { ); } +export function getPreparingComposerImages( + targetKey: string, +): ReadonlyArray { + return usePreparingComposerImageStore.getState().byTargetKey[targetKey] ?? NO_PREPARING_IMAGES; +} + export function countPreparingComposerImages(targetKey: string): number { - return usePreparingComposerImageStore.getState().byTargetKey[targetKey]?.length ?? 0; + return getPreparingComposerImages(targetKey).length; } export function addPreparingComposerImages( diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx b/apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx new file mode 100644 index 0000000000000..cfacb19bc4101 --- /dev/null +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx @@ -0,0 +1,125 @@ +import { useEffect } from "react"; +import { ThreadId } from "@t3tools/contracts"; +import { expect, it, vi } from "vite-plus/test"; + +import { act, render } from "../../../test/render"; +import { + type ComposerImageAttachment, + DraftId, + useComposerDraftStore, +} from "../../composerDraftStore"; +import { getPreparingComposerImages } from "./preparingComposerImages"; +import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; + +const compression = vi.hoisted(() => ({ prepare: vi.fn() })); +vi.mock("../../lib/imageCompression", async (importOriginal) => ({ + ...(await importOriginal()), + prepareImageForAttachment: compression.prepare, +})); + +type IntakeInput = Parameters[0]; +type Intake = ReturnType; + +function Harness({ input, ready }: { input: IntakeInput; ready: (value: Intake) => void }) { + const intake = useComposerAttachmentIntake(input); + useEffect(() => ready(intake)); + return null; +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise((fulfill) => { + resolve = fulfill; + }); + return { promise, resolve }; +} + +// A clipboard image arrives as a new File named image.png on every paste. +const pastedImage = (fill = 0) => + new File([new Uint8Array(100).fill(fill)], "image.png", { type: "image/png" }); +// Compression shrinks an image, so the draft's copy no longer matches the pasted bytes; images +// with different pixels compress to different sizes. +const compress = async (source: File) => { + const [firstByte = 0] = new Uint8Array(await source.arrayBuffer()); + return { + ok: true as const, + file: new File([new Uint8Array(60 + firstByte)], "image.png", { type: "image/png" }), + recompressed: true as const, + }; +}; +const visiblePreparing = (targetKey: string) => + getPreparingComposerImages(targetKey).filter((image) => !image.hidden); + +it("prepares a repeated paste without a tile, and still keeps a different image", async () => { + const target = DraftId.make("intake-repeat-paste"); + const store = useComposerDraftStore.getState(); + using _draft = { [Symbol.dispose]: () => store.clearComposerContent(target) }; + const firstCompression = deferred(); + compression.prepare + .mockReset() + .mockImplementationOnce(async (file: File) => { + await firstCompression.promise; + return compress(file); + }) + .mockImplementation(compress); + const composerImagesRef = { current: [] as ComposerImageAttachment[] }; + const addImages = (images: ComposerImageAttachment[]) => { + const ids = store.addImages(target, images); + composerImagesRef.current = + useComposerDraftStore.getState().getComposerDraft(target)?.images ?? []; + return ids; + }; + const input = { + activeThreadId: ThreadId.make("thread"), + activePendingProgress: null, + activePendingIsResponding: false, + pendingUserInputs: [], + supportsQuestionAttachments: false, + isLiteralPendingAnswer: false, + projectSelectionRequired: false, + questionAttachmentTarget: null, + attachmentTargetKey: target, + fileStagingLimit: null, + promptRef: { current: "" }, + composerImagesRef, + composerFilesRef: { current: [] }, + composerEditorRef: { current: null }, + isRevertingCheckpointRef: { current: false }, + setThreadError: () => {}, + countReservedAttachments: () => + composerImagesRef.current.length + getPreparingComposerImages(target).length, + addComposerImage: (image) => addImages([image]), + addComposerImagesToDraft: addImages, + addComposerFilesToDraft: () => [], + removeComposerImageFromDraft: () => {}, + insertAttachmentReferences: () => false, + } satisfies IntakeInput; + let intake!: Intake; + await using _screen = await render( + { + intake = value; + }} + />, + ); + + const first = intake.addComposerAttachments([pastedImage()]); + const whileCompressing = intake.addComposerAttachments([pastedImage()]); + expect(visiblePreparing(target)).toHaveLength(1); + await act(async () => { + firstCompression.resolve(); + await Promise.all([first, whileCompressing]); + }); + + const afterCompression = intake.addComposerAttachments([pastedImage()]); + expect(visiblePreparing(target)).toHaveLength(0); + await act(() => afterCompression); + expect(composerImagesRef.current).toHaveLength(1); + + // Same name, type and size, different pixels: it compresses differently and is kept. + const different = intake.addComposerAttachments([pastedImage(7)]); + expect(visiblePreparing(target)).toHaveLength(0); + await act(() => different); + expect(composerImagesRef.current).toHaveLength(2); +}); diff --git a/apps/web/src/components/chat/useComposerAttachmentIntake.ts b/apps/web/src/components/chat/useComposerAttachmentIntake.ts index fe3a56a392203..a4e542b1cbe66 100644 --- a/apps/web/src/components/chat/useComposerAttachmentIntake.ts +++ b/apps/web/src/components/chat/useComposerAttachmentIntake.ts @@ -26,7 +26,9 @@ import { import { classifyComposerAttachmentFile, composerFileAttachmentMimeType, + composerImageSourceKey, normalizeComposerImageFileMimeType, + rememberComposerImageSource, } from "./composerAttachmentFiles"; import { fileAttachmentTooLargeMessage, @@ -48,6 +50,7 @@ import { toastManager } from "../ui/toast"; import { type RefObject, useRef } from "react"; import { addPreparingComposerImages, + getPreparingComposerImages, isPreparingComposerImage, removePreparingComposerImages, } from "./preparingComposerImages"; @@ -241,13 +244,21 @@ export function useComposerAttachmentIntake(input: { } if (acceptedImages.length === 0) return insertedAny; + // The store drops a repeated image only after compressing it, so a likely repeat prepares + // without a tile instead of flashing one. Only the store decides it is a duplicate. + const imageSourceKeys = new Set( + [...composerImagesRef.current, ...getPreparingComposerImages(attachmentTargetKey)].map( + (image) => composerImageSourceKey(image.file), + ), + ); // The draft image reuses its placeholder's id and thumbnail so the strip tile stays exactly // as it is when the compressed file replaces it. - const preparingImages = acceptedImages.map((file) => ({ - id: randomUUID(), - name: file.name || "image", - file, - })); + const preparingImages = acceptedImages.map((file) => { + const sourceKey = composerImageSourceKey(file); + const hidden = imageSourceKeys.has(sourceKey); + imageSourceKeys.add(sourceKey); + return { id: randomUUID(), name: file.name || "image", file, hidden }; + }); addPreparingComposerImages(attachmentTargetKey, preparingImages); if (questionAttachmentTarget) changeQuestionAttachmentPreparation(questionAttachmentTarget, acceptedImages.length); @@ -272,7 +283,8 @@ export function useComposerAttachmentIntake(input: { ); continue; } - inheritComposerImageThumbnail(file, result.file); + await inheritComposerImageThumbnail(file, result.file); + rememberComposerImageSource(file, result.file); compressed.push({ id, file: result.file }); } const questionDiscarded = diff --git a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx index 50b5ae47c449b..8e6c8fc42068a 100644 --- a/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx +++ b/apps/web/src/components/preview/ThreadPreviewMiniPlayer.tsx @@ -56,6 +56,7 @@ import { Atom } from "effect/reactivity"; import { deviceScreenKey, deviceStreamScreenAtom } from "../device/deviceStreamSession"; import type { PreviewStreamViewport } from "@t3tools/client-runtime/preview/server-browser-stream"; import { previewBridge } from "./previewBridge"; +import { PreviewUnreachable } from "./PreviewUnreachable"; import { showPreviewPopup } from "./showPreviewPopup"; import { clampPreviewMiniPlayerPosition, @@ -262,6 +263,7 @@ function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly snapshot.navStatus._tag === "Success" ? previewPdfAssetUrl(snapshot.navStatus.url, httpBaseUrl) : null; + const loadFailed = snapshot.navStatus._tag === "LoadFailed" ? snapshot.navStatus : null; const poppedOut = serverTab ? serverPictureInPicture : Boolean(desktopOverlay?.pictureInPicture); const canPopOut = serverTab ? poppedOut || (pdfUrl === null && supportsServerPictureInPicture()) @@ -335,14 +337,23 @@ function BrowserMiniPlayer({ threadRef, tabId, miniPlayer }: Props & { readonly <> - {!desktopOverlay?.hasWebContents ? ( + {loadFailed ? ( +
+ void previewBridge?.refresh(runtimeTabId)} + /> +
+ ) : !desktopOverlay?.hasWebContents ? (
Reconnecting preview…
diff --git a/apps/web/src/components/pullRequest/pullRequestListPreferences.ts b/apps/web/src/components/pullRequest/pullRequestListPreferences.ts index 649515eaf9a64..0c22c528226e4 100644 --- a/apps/web/src/components/pullRequest/pullRequestListPreferences.ts +++ b/apps/web/src/components/pullRequest/pullRequestListPreferences.ts @@ -29,8 +29,8 @@ export interface PullRequestListPreferences { readonly draft?: "only" | "hide"; readonly review?: NonNullable; readonly checks?: NonNullable; - readonly author?: string; - readonly labels?: ReadonlyArray; + readonly author?: string | undefined; + readonly labels?: ReadonlyArray | undefined; readonly sort?: PullRequestListSort; } diff --git a/apps/web/src/components/pullRequest/pullRequestsRouteSearch.test.ts b/apps/web/src/components/pullRequest/pullRequestsRouteSearch.test.ts index c2c9de1f94640..716a047655f2b 100644 --- a/apps/web/src/components/pullRequest/pullRequestsRouteSearch.test.ts +++ b/apps/web/src/components/pullRequest/pullRequestsRouteSearch.test.ts @@ -36,4 +36,9 @@ describe("pull requests route search", () => { expect(matchedSearch("/pull-requests?q=fix")?.q).toBe("fix"); expect(matchedSearch("/pull-requests?q=%224089%22")?.q).toBe("4089"); }); + + it("drops an author or labels the URL parser turned into a number", () => { + expect(matchedSearch("/pull-requests?author=4089")?.author).toBeUndefined(); + expect(matchedSearch("/pull-requests?labels=4089")?.labels).toBeUndefined(); + }); }); diff --git a/apps/web/src/components/pullRequest/useInlineActionConfirm.browser.test.tsx b/apps/web/src/components/pullRequest/useInlineActionConfirm.browser.test.tsx index c94403abde4d3..b96d2df0f3685 100644 --- a/apps/web/src/components/pullRequest/useInlineActionConfirm.browser.test.tsx +++ b/apps/web/src/components/pullRequest/useInlineActionConfirm.browser.test.tsx @@ -1,4 +1,4 @@ -import { render } from "../../../test/render"; +import { fakeTimers, render } from "../../../test/render"; import { expect, it, vi } from "vite-plus/test"; import { userEvent } from "vite-plus/test/browser"; @@ -22,6 +22,8 @@ function pressEscape(): KeyboardEvent { it("confirms on the second click and disarms on Escape", async () => { const onConfirm = vi.fn(); await using screen = await render(); + // An armed action disarms after 3s, and a slow runner can take longer between two clicks. + using _timers = fakeTimers(); const button = screen.getByRole("button"); await userEvent.click(button); @@ -99,6 +101,7 @@ it.each(["merge", "enable-auto-merge"] as const)( /> ); await using screen = await render(control("Checking stack membership…")); + using _timers = fakeTimers(); const button = screen.getByRole("button"); await userEvent.tab(); await expect.element(button).toHaveFocus(); diff --git a/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx b/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx index 2ef0d474ebb83..6b4d0a08a629f 100644 --- a/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx +++ b/apps/web/src/components/settings/AddEnvironmentDialog.browser.test.tsx @@ -88,7 +88,7 @@ describe("AddEnvironmentDialog", () => { await using _screen = await render(); await openDialogOnSsh(); - await userEvent.type(page.getByPlaceholder("Search hosts or type devbox"), "devbox"); + await userEvent.fill(page.getByPlaceholder("Search hosts or type devbox"), "devbox"); await userEvent.click( page.getByRole("dialog").getByRole("button", { name: "Add environment" }), ); @@ -103,12 +103,12 @@ describe("AddEnvironmentDialog", () => { await openDialogOnSsh(); await userEvent.click(remoteCard()); - await userEvent.type(page.getByPlaceholder("backend.example.com"), "devbox.example.com"); - await userEvent.type(page.getByPlaceholder("PAIRCODE"), "PAIRCODE"); + await userEvent.fill(page.getByPlaceholder("backend.example.com"), "devbox.example.com"); + await userEvent.fill(page.getByPlaceholder("PAIRCODE"), "PAIRCODE"); await userEvent.click(sshCard()); - await userEvent.type(page.getByPlaceholder("Search hosts or type devbox"), "devbox"); - await userEvent.type(page.getByPlaceholder("root"), "maria"); - await userEvent.type(page.getByPlaceholder("22"), "2222"); + await userEvent.fill(page.getByPlaceholder("Search hosts or type devbox"), "devbox"); + await userEvent.fill(page.getByPlaceholder("root"), "maria"); + await userEvent.fill(page.getByPlaceholder("22"), "2222"); await userEvent.keyboard("{Escape}"); await expectDefaultModeAfterReopen(); @@ -124,7 +124,7 @@ describe("AddEnvironmentDialog", () => { finishConnection = resolve; }); mocks.connectSshEnvironment.mockImplementationOnce(() => pending); - await userEvent.type(page.getByPlaceholder("Search hosts or type devbox"), "devbox"); + await userEvent.fill(page.getByPlaceholder("Search hosts or type devbox"), "devbox"); await userEvent.click( page.getByRole("dialog").getByRole("button", { name: "Add environment" }), ); diff --git a/apps/web/src/components/settings/CodexSetupSection.tsx b/apps/web/src/components/settings/CodexSetupSection.tsx index dea5f40dfea33..cbbe3d51a4ed5 100644 --- a/apps/web/src/components/settings/CodexSetupSection.tsx +++ b/apps/web/src/components/settings/CodexSetupSection.tsx @@ -983,6 +983,18 @@ function ManagedCodexSetup({ ) : authenticated ? ( <> + {updateAvailable ? ( + + ) : null}