From 1032135cf754dfa22ffd0e67266b320712e51e72 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 03:48:55 -0800 Subject: [PATCH 01/56] fix(server): Edit from here recreates a worktree folder that lost its checkout (#35194) --- .../CheckpointRollbackService.test.ts | 53 ++++++++++++--- .../CheckpointRollbackService.ts | 67 +++++++++++-------- 2 files changed, 82 insertions(+), 38 deletions(-) diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index c61f9bc175edc..dea2c0151d38f 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -174,7 +174,10 @@ 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 }, +])("locks rollback with %s", ({ order, restoreFiles, unmanaged, leavesFolder, shared }) => Effect.gen(function* () { const fileSystem = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -185,7 +188,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 +249,18 @@ it.effect.each([ path: worktreePath, }); calls.push("create"); - yield* fileSystem.makeDirectory(worktreePath).pipe(Effect.orDie); + 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 +279,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 +328,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 +352,14 @@ 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; } yield* Fiber.join(rollback); @@ -336,12 +367,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..a3604c278e3dd 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts @@ -217,42 +217,51 @@ 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)) { + if (leftover) { + if (!(yield* isolated)) return yield* sharedWorkspace(); + yield* fileSystem.remove(worktreePath, { recursive: true, force: true }); + } + yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }); + yield* gitWorkflow.createWorktree({ + cwd: project.value.workspaceRoot, + refName: branch, + path: worktreePath, + }); + } + } } + if (restoreFiles && !(yield* isolated)) return yield* sharedWorkspace(); + const modelSelection = context.thread.modelSelection; const resolvedRuntimePolicy = yield* runtimePolicy.resolve({ thread: context.thread, From d412871f27a52709c5978c3f9b0a0433242c50f6 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 03:50:24 -0800 Subject: [PATCH 02/56] fix(server): a task on a linked environment stays under its parent in trimmed shell snapshots (#34870) Fixes #30320. Co-authored-by: Theo Browne Co-Authored-By: Claude Fable 5.2 --- .../src/orchestration-v2/ProjectionStore.ts | 14 +++++++- .../RemoteDelegatedTask.test.ts | 4 +++ .../src/orchestration-v2/ShellStream.ts | 33 ++++++++++++++----- apps/server/src/ws.test.ts | 11 +++++-- 4 files changed, 49 insertions(+), 13 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index a4487831c450c..3f9eb59954c3f 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -436,6 +436,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 { @@ -7745,6 +7747,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, @@ -7790,7 +7793,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 @@ -7817,6 +7828,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..120d5c3690f00 100644 --- a/apps/server/src/orchestration-v2/ShellStream.ts +++ b/apps/server/src/orchestration-v2/ShellStream.ts @@ -75,7 +75,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 +84,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 +96,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 +125,7 @@ function shellTrimFacts(rows: ReadonlyArray): ShellTrimFacts { return { subagentParentIds, subagentThreadIds, + remoteTaskParentIds, olderSettledBeforeMs, olderSettledCounts: Array.from(counts, ([projectId, count]) => ({ projectId, count })), }; @@ -140,13 +145,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 +162,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 +179,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 +195,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 +225,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 +272,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 +294,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/ws.test.ts b/apps/server/src/ws.test.ts index 95e52602eaba1..c29b218adbfea 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -708,6 +708,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; @@ -724,6 +726,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 }) => @@ -767,15 +770,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)), ); From 64959eb9690aacd08e73848fcf9ad0357fca95e5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 04:03:56 -0800 Subject: [PATCH 03/56] fix(web): terminal Ctrl+Shift+C copies on non-Latin keyboard layouts (#35210) --- apps/web/src/terminal/ghostty/surface.test.ts | 17 +++++++++++++++++ apps/web/src/terminal/ghostty/surface.ts | 19 ++++++++++--------- 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/apps/web/src/terminal/ghostty/surface.test.ts b/apps/web/src/terminal/ghostty/surface.test.ts index 3cf4dee8d5d74..70087fd5d6bce 100644 --- a/apps/web/src/terminal/ghostty/surface.test.ts +++ b/apps/web/src/terminal/ghostty/surface.test.ts @@ -286,6 +286,21 @@ describe("GhosttyTerminalSurface visibility", () => { expect(surface.hasSelection()).toBe(false); }); + it("copies on Ctrl+Shift+C when a non-Latin layout reports another letter on KeyC", async () => { + vi.stubGlobal("navigator", { platform: "Linux x86_64" }); + const harness = createHarness(); + const surface = await harness.create({ beforeKey: () => true }); + Object.assign(surface.input, { select() {} }); + const execCommand = vi.fn(() => true); + Object.assign(document, { execCommand }); + surface.write("SELECTED_OUTPUT"); + surface.selectAll(); + // Russian layout: Cyrillic Es (U+0421) on the physical C key. + key(surface, "С", "KeyC", { ctrlKey: true, shiftKey: true }); + expect(execCommand).toHaveBeenCalledWith("copy"); + expect(harness.onData).not.toHaveBeenCalled(); + }); + it("skips middle-click selection paste when the desktop turned primary paste off", async () => { vi.stubGlobal("navigator", { platform: "Linux x86_64" }); const harness = createHarness(); @@ -918,6 +933,8 @@ describe("terminalLinkAtPositionWithRange", () => { describe("isTerminalCopyShortcut", () => { const event = (overrides: Partial[0]> = {}) => ({ + altKey: false, + code: "KeyC", ctrlKey: false, key: "c", metaKey: false, diff --git a/apps/web/src/terminal/ghostty/surface.ts b/apps/web/src/terminal/ghostty/surface.ts index 9de22fca7447c..c676ef1d7c6d4 100644 --- a/apps/web/src/terminal/ghostty/surface.ts +++ b/apps/web/src/terminal/ghostty/surface.ts @@ -1,3 +1,4 @@ +import { resolveEventKeys } from "@t3tools/shared/keybindingMatching"; import { isMacPlatform } from "../../lib/utils"; import { SELECTION_MULTI_CLICK_INTERVAL_MS } from "../../lib/selectionActions"; import { collectWrappedTerminalLinkLine, extractTerminalLinks } from "../../terminal-links"; @@ -313,14 +314,14 @@ export function terminalLinkAtPositionWithRange( } export function isTerminalCopyShortcut( - event: Pick, + event: Pick, platform = navigator.platform, ) { - const key = event.key.toLowerCase(); - if (key === "insert" && !isMacPlatform(platform)) { + const keys = resolveEventKeys(event); + if (keys.has("insert") && !isMacPlatform(platform)) { return event.ctrlKey && !event.shiftKey && !event.metaKey; } - if (key !== "c") return false; + if (!keys.has("c")) return false; return isMacPlatform(platform) ? event.metaKey : event.ctrlKey; } @@ -355,14 +356,14 @@ export function applyTerminalCopyEvent( } function isTerminalPasteShortcut( - event: Pick, + event: Pick, platform = navigator.platform, ) { - const key = event.key.toLowerCase(); - if (key === "insert" && !isMacPlatform(platform)) { + const keys = resolveEventKeys(event); + if (keys.has("insert") && !isMacPlatform(platform)) { return event.shiftKey && !event.ctrlKey && !event.metaKey; } - if (key !== "v") return false; + if (!keys.has("v")) return false; return isMacPlatform(platform) ? event.metaKey : event.ctrlKey && event.shiftKey; } @@ -1119,7 +1120,7 @@ export class GhosttyTerminalSurface { const mac = isMacPlatform(navigator.platform); const primaryModifier = mac ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey; const selectAllShortcut = - event.key.toLowerCase() === "a" && + resolveEventKeys(event).has("a") && primaryModifier && !event.altKey && (mac ? !event.shiftKey : event.shiftKey); From 5e2438ce94644653dfea926d31c35a87a09632e2 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 04:04:34 -0800 Subject: [PATCH 04/56] perf(server): sending to a thread with thousands of finished subagents reads about half as much (#35178) Refs #29468. Co-Authored-By: Claude Fable 5.2 --- .../Orchestrator.control-reads.test.ts | 21 ++++ .../src/orchestration-v2/Orchestrator.ts | 2 + .../orchestration-v2/ProjectionStore.test.ts | 108 +++++++++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 67 +++++++++-- 4 files changed, 186 insertions(+), 12 deletions(-) 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..076960f4dc1d5 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1553,6 +1553,8 @@ 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"], }, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 856db5249885d..bcd6732c23782 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -1575,6 +1575,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 +1787,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 +1803,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 }>; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 3f9eb59954c3f..2bf1e896b4973 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -372,6 +372,12 @@ 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; } // A fork inherits its source's history before it has messages of its own, @@ -2100,6 +2106,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`( @@ -3740,6 +3756,20 @@ export const layer: Layer.Layer = AND (kind IN ('tool_call', 'assistant_message', 'reasoning') AND status IN ('completed', 'interrupted', 'failed', 'cancelled', 'rolled_back') AND run_id IS NOT NULL) = 0 + ${ + 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} @@ -3782,15 +3812,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)})) @@ -3840,12 +3862,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 ` From 65c0195b46817a7b04e8765522f72ee08a7430f8 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 04:05:25 -0800 Subject: [PATCH 05/56] fix(mobile): the thread list no longer reshuffles once per environment on startup (#34596) Co-Authored-By: Claude Fable 5.2 --- apps/mobile/src/App.tsx | 27 +- .../src/features/home/HomeRouteScreen.tsx | 4 +- .../home/useThreadListActions.test.ts | 77 ++-- .../src/features/home/useThreadListActions.ts | 48 ++- .../threads/ThreadArrangementSheet.tsx | 6 +- .../threads/ThreadNavigationSidebar.tsx | 5 +- apps/mobile/src/state/shell.ts | 20 ++ apps/mobile/src/state/thread-order.test.ts | 6 +- apps/mobile/src/state/thread-order.ts | 13 +- apps/mobile/src/state/threads.ts | 18 + docs/internals/connection-runtime.md | 20 ++ packages/client-runtime/src/state/shell.ts | 1 + .../src/state/steadyShells.test.ts | 338 ++++++++++++++++++ .../client-runtime/src/state/steadyShells.ts | 217 +++++++++++ .../src/state/threadCommands.test.ts | 2 + .../src/state/threadCommands.ts | 31 +- .../src/state/threadInbox.test.ts | 20 ++ .../client-runtime/src/state/threadInbox.ts | 11 +- 18 files changed, 803 insertions(+), 61 deletions(-) create mode 100644 packages/client-runtime/src/state/steadyShells.test.ts create mode 100644 packages/client-runtime/src/state/steadyShells.ts 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/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/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/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/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/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/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.md index 698ddac7a73f9..5104a72e4dd07 100644 --- a/docs/internals/connection-runtime.md +++ b/docs/internals/connection-runtime.md @@ -75,6 +75,26 @@ connection nor overwrite newer live data during a reconnect. Loading and resuming snapshots belongs to the shared state services, so every view agrees on which data is current. +Each environment synchronizes at its own time, so a thread list that follows every +snapshot moves once per environment on each cold start and resume. Mobile lists read +[steady shells](../../packages/client-runtime/src/state/steadyShells.ts): an +environment's rows stay as shown until its connection's server snapshot arrives, +it is synchronized, or it disconnects, and environments that get there within two +seconds of each other show together. Only an environment that is connected or on +its first attempt, and still owes its snapshot, is waited for; a retry can take +minutes. A move in a list is refused while its rows wait, because its plan would +use order keys the server may have replaced. Every other row action looks up the +live row before it reads thread state, so an undo plan or a guard never uses a held +row. The hold stops only changes the user +did not cause: a command that moves or removes a row (settle, snooze, pin, archive, +delete, and their reverses) makes that environment's rows follow the live snapshot +until it is live. Point reads (a +thread's own shell, route checks) keep the live snapshot, where a row the server just +sent must not look missing. The decision reads the snapshot's own sequence: a second +atom derived from the same shell state can be one update behind the rows. The mobile +splash screen also waits, for a bounded time, until every enabled environment has +read its cached shell, so the first frame holds all cached rows. + Shell snapshots can leave rows out when the client asks. Servers that advertise `shellThreadFamilies` leave out idle subagent children: a child stays while it has a live or queued run, a pending request or background work, or a subagent diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 808fd9fdece56..7980800708285 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -719,3 +719,4 @@ export * from "./shellReducer.ts"; export * from "./shellPullRequests.ts"; export * as ShellSnapshotLoader from "./shellSnapshotHttp.ts"; export * from "./snapshots.ts"; +export * from "./steadyShells.ts"; diff --git a/packages/client-runtime/src/state/steadyShells.test.ts b/packages/client-runtime/src/state/steadyShells.test.ts new file mode 100644 index 0000000000000..d7af88d710db2 --- /dev/null +++ b/packages/client-runtime/src/state/steadyShells.test.ts @@ -0,0 +1,338 @@ +import { EnvironmentId, type OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test"; + +import { + AVAILABLE_CONNECTION_STATE, + PrimaryConnectionTarget, + type SupervisorConnectionState, +} from "../connection/model.ts"; +import type { EnvironmentCatalogState } from "./connections.ts"; +import { v2ShellSnapshot } from "./orchestrationV2TestFixtures.ts"; +import { EMPTY_SHELL_STATE, type EnvironmentShellState } from "./shell.ts"; +import { + createSteadyShellAtoms, + EMPTY_STEADY_SHELLS_STATE, + stepSteadyShells, + type SteadyShellInput, + type SteadyShellsState, +} from "./steadyShells.ts"; + +const A = EnvironmentId.make("a"); +const B = EnvironmentId.make("b"); +const WINDOW = 2_000; + +const snapshot = (snapshotSequence: number): OrchestrationV2ShellSnapshot => ({ + ...v2ShellSnapshot, + snapshotSequence, +}); +const shell = ( + environmentId: EnvironmentId, + value: OrchestrationV2ShellSnapshot | null, + phase: "connecting" | "disconnected" | "live", + generation = 0, + rowActions = 0, +): SteadyShellInput => ({ + environmentId, + snapshot: value, + serverSequence: value?.snapshotSequence ?? null, + status: phase === "live" ? "live" : phase === "connecting" ? "synchronizing" : "cached", + generation, + connecting: phase !== "disconnected", + rowActions, +}); +const shown = (state: SteadyShellsState, environmentId: EnvironmentId) => + state.shells.get(environmentId)?.shown; + +describe("stepSteadyShells", () => { + it("shows cached rows at once and holds server rows until the environment is synchronized", () => { + const cached = snapshot(7); + const withLinks = { ...cached }; + const fromServer = snapshot(9); + let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, cached, "connecting")], 0); + expect(shown(state, A)).toBe(cached); + + // The cached links fill in without new server data. + state = stepSteadyShells(state, [shell(A, withLinks, "connecting")], 10); + expect(shown(state, A)).toBe(withLinks); + + state = stepSteadyShells(state, [shell(A, fromServer, "connecting")], 20); + expect(shown(state, A)).toBe(withLinks); + + state = stepSteadyShells(state, [shell(A, fromServer, "live")], 30); + expect(shown(state, A)).toBe(fromServer); + expect(state.releaseAt).toBeNull(); + }); + + it("shows a connection's server snapshot when it arrives, and the events after it when live", () => { + const [cached, fromServer, withEvents] = [snapshot(7), snapshot(9), snapshot(10)]; + let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, cached, "connecting")], 0); + state = stepSteadyShells(state, [shell(A, fromServer, "connecting", 1)], 10); + expect(shown(state, A)).toBe(fromServer); + state = stepSteadyShells(state, [shell(A, withEvents, "connecting", 1)], 20); + expect(shown(state, A)).toBe(fromServer); + state = stepSteadyShells(state, [shell(A, withEvents, "live", 1)], 30); + expect(shown(state, A)).toBe(withEvents); + }); + + it("does not wait for an environment that already shows its server snapshot", () => { + const [cachedA, cachedB, serverA, serverB] = [ + snapshot(1), + snapshot(2), + snapshot(3), + snapshot(4), + ]; + let state = stepSteadyShells( + EMPTY_STEADY_SHELLS_STATE, + [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")], + 0, + ); + state = stepSteadyShells( + state, + [shell(A, cachedA, "connecting"), shell(B, serverB, "connecting", 1)], + 10, + ); + expect(shown(state, B)).toBe(cachedB); + state = stepSteadyShells( + state, + [shell(A, serverA, "connecting", 2), shell(B, serverB, "connecting", 1)], + 20, + ); + expect(shown(state, A)).toBe(serverA); + expect(shown(state, B)).toBe(serverB); + // B is not live yet, and A's next rows do not wait for it. + const liveA = snapshot(5); + state = stepSteadyShells( + state, + [shell(A, liveA, "live", 2), shell(B, serverB, "connecting", 1)], + 30, + ); + expect(shown(state, A)).toBe(liveA); + }); + + it("shows rows that wait when their environment disconnects", () => { + const [cachedA, cachedB, serverA] = [snapshot(7), snapshot(2), snapshot(9)]; + let state = stepSteadyShells( + EMPTY_STEADY_SHELLS_STATE, + [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")], + 0, + ); + state = stepSteadyShells( + state, + [shell(A, serverA, "connecting", 1), shell(B, cachedB, "connecting")], + 10, + ); + expect(shown(state, A)).toBe(cachedA); + const disconnected = [shell(A, serverA, "disconnected", 1), shell(B, cachedB, "connecting")]; + state = stepSteadyShells(state, disconnected, 20); + expect(shown(state, A)).toBe(cachedA); + expect(state.releaseAt).toBe(10 + WINDOW); + state = stepSteadyShells(state, disconnected, 10 + WINDOW); + expect(shown(state, A)).toBe(serverA); + }); + + it("holds replayed events after a reconnect until the environment is live again", () => { + const [first, replayed] = [snapshot(1), snapshot(4)]; + let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, first, "live", 1)], 0); + state = stepSteadyShells(state, [shell(A, replayed, "connecting", 1)], 10); + expect(shown(state, A)).toBe(first); + state = stepSteadyShells(state, [shell(A, replayed, "live", 1)], 20); + expect(shown(state, A)).toBe(replayed); + }); + + it("shows the cache of an environment that was first seen before its cache was read", () => { + const cached = snapshot(7); + let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, null, "connecting")], 0); + state = stepSteadyShells(state, [shell(A, cached, "connecting")], 10); + expect(shown(state, A)).toBe(cached); + state = stepSteadyShells(state, [shell(A, snapshot(9), "connecting")], 20); + expect(shown(state, A)).toBe(cached); + }); + + it("shows the rows of environments that synchronize within the window together", () => { + const [cachedA, cachedB, liveA, liveB] = [snapshot(1), snapshot(2), snapshot(3), snapshot(4)]; + let state = stepSteadyShells( + EMPTY_STEADY_SHELLS_STATE, + [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")], + 0, + ); + state = stepSteadyShells( + state, + [shell(A, liveA, "live"), shell(B, cachedB, "connecting")], + 500, + ); + expect(shown(state, A)).toBe(cachedA); + expect(state.releaseAt).toBe(500 + WINDOW); + + state = stepSteadyShells(state, [shell(A, liveA, "live"), shell(B, liveB, "live")], 900); + expect(shown(state, A)).toBe(liveA); + expect(shown(state, B)).toBe(liveB); + expect(state.releaseAt).toBeNull(); + }); + + it("stops waiting for a slow environment when the window ends, then shows it on its own", () => { + const [cachedA, cachedB, liveA, liveB] = [snapshot(1), snapshot(2), snapshot(3), snapshot(4)]; + let state = stepSteadyShells( + EMPTY_STEADY_SHELLS_STATE, + [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")], + 0, + ); + const waiting = [shell(A, liveA, "live"), shell(B, cachedB, "connecting")]; + state = stepSteadyShells(state, waiting, 500); + expect(stepSteadyShells(state, waiting, 500 + WINDOW - 1)).toBe(state); + + state = stepSteadyShells(state, waiting, 500 + WINDOW); + expect(shown(state, A)).toBe(liveA); + expect(shown(state, B)).toBe(cachedB); + + state = stepSteadyShells(state, [shell(A, liveA, "live"), shell(B, liveB, "live")], 9_000); + expect(shown(state, B)).toBe(liveB); + }); + + it("does not wait for an environment that already failed", () => { + const [cachedA, cachedB, liveA] = [snapshot(1), snapshot(2), snapshot(3)]; + let state = stepSteadyShells( + EMPTY_STEADY_SHELLS_STATE, + [shell(A, cachedA, "connecting"), shell(B, cachedB, "disconnected")], + 0, + ); + state = stepSteadyShells( + state, + [shell(A, liveA, "live"), shell(B, cachedB, "disconnected")], + 500, + ); + expect(shown(state, A)).toBe(liveA); + }); + + it("follows a synchronized environment, and holds its rows again while it reconnects", () => { + const [first, second, missed, caughtUp] = [snapshot(1), snapshot(2), snapshot(5), snapshot(6)]; + let state = stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, first, "live")], 0); + state = stepSteadyShells(state, [shell(A, second, "live")], 10); + expect(shown(state, A)).toBe(second); + + state = stepSteadyShells(state, [shell(A, second, "connecting")], 20); + state = stepSteadyShells(state, [shell(A, missed, "connecting")], 30); + expect(shown(state, A)).toBe(second); + + state = stepSteadyShells(state, [shell(A, caughtUp, "live")], 40); + expect(shown(state, A)).toBe(caughtUp); + }); + + it("follows an environment's live rows once the user moves or removes a row there", () => { + const [cachedA, cachedB, liveA, confirmedA] = [ + snapshot(1), + snapshot(2), + snapshot(3), + snapshot(4), + ]; + const [replayedB, archivedB, laterB] = [snapshot(5), snapshot(6), snapshot(7)]; + const settledA = { ...liveA }; + let state = stepSteadyShells( + EMPTY_STEADY_SHELLS_STATE, + [shell(A, cachedA, "connecting"), shell(B, cachedB, "connecting")], + 0, + ); + state = stepSteadyShells(state, [shell(A, liveA, "live"), shell(B, cachedB, "connecting")], 10); + expect(shown(state, A)).toBe(cachedA); + + // The user settles a thread of A: its rows show at once, and B's rows still wait. + const heldB = shell(B, replayedB, "connecting"); + state = stepSteadyShells(state, [shell(A, settledA, "live", 0, 1), heldB], 20); + expect(shown(state, A)).toBe(settledA); + expect(shown(state, B)).toBe(cachedB); + expect(state.releaseAt).toBeNull(); + state = stepSteadyShells(state, [shell(A, confirmedA, "live", 0, 1), heldB], 30); + expect(shown(state, A)).toBe(confirmedA); + + // B still synchronizes when the user archives a thread there. Its rows follow the + // replayed events until it is live, then wait again on the next reconnect. + const a = shell(A, confirmedA, "live", 0, 1); + state = stepSteadyShells(state, [a, shell(B, replayedB, "connecting", 0, 1)], 40); + expect(shown(state, B)).toBe(replayedB); + state = stepSteadyShells(state, [a, shell(B, archivedB, "connecting", 0, 1)], 50); + expect(shown(state, B)).toBe(archivedB); + state = stepSteadyShells(state, [a, shell(B, archivedB, "live", 0, 1)], 60); + state = stepSteadyShells(state, [a, shell(B, laterB, "connecting", 0, 1)], 70); + expect(shown(state, B)).toBe(archivedB); + }); + + it("drops an environment that left the list of enabled environments", () => { + const state = stepSteadyShells( + stepSteadyShells(EMPTY_STEADY_SHELLS_STATE, [shell(A, snapshot(1), "live")], 0), + [], + 10, + ); + expect(state.shells.size).toBe(0); + }); +}); + +describe("createSteadyShellAtoms", () => { + beforeEach(() => { + vi.useFakeTimers(); + vi.setSystemTime(10_000); + }); + afterEach(() => { + vi.clearAllTimers(); + vi.useRealTimers(); + }); + + it("shows held rows when the window ends without another change", () => { + const entry = (environmentId: EnvironmentId) => ({ + target: new PrimaryConnectionTarget({ + environmentId, + label: environmentId, + httpBaseUrl: "https://example.test", + wsBaseUrl: "wss://example.test", + }), + enabled: true, + profile: Option.none(), + }); + const catalog = Atom.make({ + isReady: true, + entries: new Map([ + [A, entry(A)], + [B, entry(B)], + ]), + }); + const [cachedA, liveA] = [snapshot(1), snapshot(3)]; + const snapshots = Atom.family((environmentId: EnvironmentId) => + Atom.make(environmentId === A ? cachedA : snapshot(2)), + ); + const rowActions = Atom.family((_: EnvironmentId) => Atom.make(0)); + const shellStates = Atom.family((_: EnvironmentId) => + Atom.make({ ...EMPTY_SHELL_STATE, status: "synchronizing" }), + ); + const connections = Atom.family((_: EnvironmentId) => + Atom.make( + AsyncResult.success({ + ...AVAILABLE_CONNECTION_STATE, + desired: true, + phase: "connecting", + attempt: 1, + }), + ), + ); + const steady = createSteadyShellAtoms({ + catalogValueAtom: catalog, + snapshotAtom: snapshots, + shellStateAtom: shellStates, + rowActionsAtom: rowActions, + connectionStateAtom: connections, + }); + const registry = AtomRegistry.make(); + const release = registry.mount(steady.snapshotAtom(A)); + + registry.set(snapshots(A), liveA); + registry.set(shellStates(A), { ...EMPTY_SHELL_STATE, status: "live", generation: 1 }); + registry.set( + connections(A), + AsyncResult.success({ ...AVAILABLE_CONNECTION_STATE, desired: true, phase: "connected" }), + ); + expect(registry.get(steady.snapshotAtom(A))).toBe(cachedA); + + vi.advanceTimersByTime(WINDOW); + expect(registry.get(steady.snapshotAtom(A))).toBe(liveA); + release(); + }); +}); diff --git a/packages/client-runtime/src/state/steadyShells.ts b/packages/client-runtime/src/state/steadyShells.ts new file mode 100644 index 0000000000000..9ecb534dd63b4 --- /dev/null +++ b/packages/client-runtime/src/state/steadyShells.ts @@ -0,0 +1,217 @@ +// @effect-diagnostics globalTimers:off - The release timer runs in web and native clients, outside an Effect runtime. +import type { EnvironmentId, OrchestrationV2ShellSnapshot } from "@t3tools/contracts"; +import { AsyncResult, Atom } from "effect/reactivity"; + +import { AVAILABLE_CONNECTION_STATE, type SupervisorConnectionState } from "../connection/model.ts"; +import { presentConnectionState } from "../connection/presentation.ts"; +import { type EnvironmentCatalogState, enabledEnvironmentIds } from "./connections.ts"; +import type { EnvironmentShellState, EnvironmentShellStatus } from "./shell.ts"; + +/** + * How long fresh rows wait for environments that are still connecting. Each environment + * gets its server data at its own time, and a list that follows each one moves once per + * environment; within this time they move together. + */ +const STEADY_SHELL_RELEASE_WINDOW_MS = 2_000; + +export interface SteadyShellInput { + readonly environmentId: EnvironmentId; + readonly snapshot: OrchestrationV2ShellSnapshot | null; + /** + * The snapshot's server sequence. It moves with new server data and with nothing else, and + * it comes from the snapshot itself: a second atom could be one update behind the rows. + */ + readonly serverSequence: number | null; + readonly status: EnvironmentShellStatus; + /** The shell state's generation: it grows with each server snapshot. */ + readonly generation: number; + /** The connection is up or on its first attempt, so fresh rows can come soon. */ + readonly connecting: boolean; + /** How many times the user moved or removed a row of this environment. */ + readonly rowActions: number; +} + +interface SteadyShell { + readonly shown: OrchestrationV2ShellSnapshot | null; + readonly shownSequence: number | null; + readonly shownGeneration: number; + /** The rows were shown while live, so each live change shows at once. */ + readonly following: boolean; + /** The rows hold a server snapshot of the connection that is synchronizing. */ + readonly caughtUp: boolean; + /** The `rowActions` count when the rows last showed while live. */ + readonly rowActions: number; +} + +export interface SteadyShellsState { + readonly shells: ReadonlyMap; + /** When held rows show at the latest; null while none wait. */ + readonly releaseAt: number | null; +} + +export const EMPTY_STEADY_SHELLS_STATE: SteadyShellsState = { shells: new Map(), releaseAt: null }; + +/** + * Decides which snapshot of each environment a thread list shows. New server rows wait for + * a complete state (a server snapshot, live, or disconnected), then show with every other + * environment that has one: at once when no other owes its rows, else when the window ends. + * Returns `previous` itself when nothing changes. + */ +export function stepSteadyShells( + previous: SteadyShellsState, + inputs: ReadonlyArray, + now: number, + windowMs = STEADY_SHELL_RELEASE_WINDOW_MS, +): SteadyShellsState { + const shells = new Map(); + const waiting: Array = []; + let othersOweRows = false; + const show = ( + input: SteadyShellInput, + caughtUp: boolean, + current: SteadyShell | undefined, + ): SteadyShell => ({ + shown: input.snapshot, + shownSequence: input.serverSequence, + shownGeneration: input.generation, + following: input.status === "live", + caughtUp, + rowActions: + input.status === "live" || current === undefined ? input.rowActions : current.rowActions, + }); + const keep = (input: SteadyShellInput, next: SteadyShell, current: SteadyShell | undefined) => { + othersOweRows ||= input.status === "synchronizing" && input.connecting && !next.caughtUp; + const same = + current !== undefined && + current.shown === next.shown && + current.shownSequence === next.shownSequence && + current.shownGeneration === next.shownGeneration && + current.following === next.following && + current.caughtUp === next.caughtUp && + current.rowActions === next.rowActions; + shells.set(input.environmentId, same ? current : next); + }; + for (const input of inputs) { + const current = previous.shells.get(input.environmentId); + const synchronizing = input.status === "synchronizing"; + if (current === undefined) { + keep(input, show(input, false, current), current); + continue; + } + const newSnapshot = input.generation > current.shownGeneration; + // Without new server data the change is local (cached links, rows loaded on demand), and + // an environment that shows nothing (its cache is not read yet) has nothing to hold back. + const local = + current.shown === null || (input.serverSequence === current.shownSequence && !newSnapshot); + // The hold stops changes the user did not cause. After the user moves or removes a row, + // the environment's rows follow the live data until it is live. + const userActed = input.rowActions !== current.rowActions; + if (local || userActed || (input.status === "live" && current.following)) { + const caughtUp = synchronizing && (current.caughtUp || newSnapshot); + keep(input, show(input, caughtUp, current), current); + } else if (!synchronizing || newSnapshot) { + waiting.push(input); + shells.set(input.environmentId, current); + } else { + // Events that a synchronizing environment replays are complete only when it is live. + keep(input, { ...current, following: false }, current); + } + } + + let releaseAt: number | null = null; + if (waiting.length > 0) { + releaseAt = previous.releaseAt ?? now + windowMs; + if (!othersOweRows || now >= releaseAt) { + releaseAt = null; + for (const input of waiting) { + const current = shells.get(input.environmentId); + shells.set(input.environmentId, show(input, input.status === "synchronizing", current)); + } + } + } + + const unchanged = + releaseAt === previous.releaseAt && + shells.size === previous.shells.size && + [...shells].every(([environmentId, shell]) => previous.shells.get(environmentId) === shell); + return unchanged ? previous : { shells, releaseAt }; +} + +/** + * Snapshots for lists that arrange threads across environments; see `stepSteadyShells`. + * Point reads (a thread's own shell, route checks) keep the live snapshot, where a row + * that the server just sent must not look missing. + */ +export function createSteadyShellAtoms(input: { + readonly catalogValueAtom: Atom.Atom; + readonly snapshotAtom: ( + environmentId: EnvironmentId, + ) => Atom.Atom; + readonly shellStateAtom: (environmentId: EnvironmentId) => Atom.Atom; + readonly rowActionsAtom: (environmentId: EnvironmentId) => Atom.Atom; + readonly connectionStateAtom: ( + environmentId: EnvironmentId, + ) => Atom.Atom>; +}) { + const now = () => { + // @effect-diagnostics-next-line globalDate:off - The release window is wall-clock time. + return Date.now(); + }; + // Outlives the atom's rebuilds, and its unmount while no list is on screen. + let state = EMPTY_STEADY_SHELLS_STATE; + const stateAtom = Atom.make((get) => { + const inputs: Array = []; + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + const snapshot = get(input.snapshotAtom(environmentId)); + const shell = get(input.shellStateAtom(environmentId)); + const connection = AsyncResult.getOrElse( + get(input.connectionStateAtom(environmentId)), + () => AVAILABLE_CONNECTION_STATE, + ); + // An enabled environment starts out connecting, before its supervisor reports. + const phase = + connection === AVAILABLE_CONNECTION_STATE + ? "connecting" + : presentConnectionState(connection).phase; + inputs.push({ + environmentId, + snapshot, + serverSequence: snapshot?.snapshotSequence ?? null, + status: shell.status, + generation: shell.generation, + // A retry after a failure can take minutes, so it is not waited for until it connects. + connecting: phase === "connecting" || phase === "connected", + rowActions: get(input.rowActionsAtom(environmentId)), + }); + } + state = stepSteadyShells(state, inputs, now()); + if (state.releaseAt !== null) { + const timer = setTimeout(() => get.refreshSelf(), Math.max(0, state.releaseAt - now())); + get.addFinalizer(() => clearTimeout(timer)); + } + return state; + }).pipe(Atom.withLabel("steady-shells")); + + const snapshotAtom = Atom.family((environmentId: EnvironmentId) => + Atom.make( + (get): OrchestrationV2ShellSnapshot | null => + get(stateAtom).shells.get(environmentId)?.shown ?? null, + ).pipe(Atom.withLabel(`steady-shell-snapshot:${environmentId}`)), + ); + + // Reads the live snapshots too, so it is current when a handler reads it once. + const holdingAtom = Atom.make((get) => { + const { shells } = get(stateAtom); + for (const environmentId of enabledEnvironmentIds(get(input.catalogValueAtom))) { + if (shells.get(environmentId)?.shown !== get(input.snapshotAtom(environmentId))) return true; + } + return false; + }).pipe(Atom.withLabel("steady-shells-holding")); + + return { + /** The snapshot a thread list shows for an environment. */ + snapshotAtom, + /** True while a list shows rows older than the server data the client holds. */ + holdingAtom, + }; +} diff --git a/packages/client-runtime/src/state/threadCommands.test.ts b/packages/client-runtime/src/state/threadCommands.test.ts index 9a723f0f6e05e..317ecab2bbb40 100644 --- a/packages/client-runtime/src/state/threadCommands.test.ts +++ b/packages/client-runtime/src/state/threadCommands.test.ts @@ -415,6 +415,8 @@ describe("remote thread lifecycle commands", () => { }); const request = yield* Queue.take(h.requests); expect(h.registry.get(h.commands.snapshotAtom(otherEnvironment))).toBe(SNAPSHOT); + expect(h.registry.get(h.commands.rowActionsAtom(ENVIRONMENT_ID))).toBe(1); + expect(h.registry.get(h.commands.rowActionsAtom(otherEnvironment))).toBe(0); const removed = { ...SNAPSHOT, snapshotSequence: 2, threads: [] }; h.registry.set(h.snapshotAtom(ENVIRONMENT_ID), removed); expect(h.registry.get(h.visibleAtom)?.threads).toEqual([]); diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts index 3761d0fa6e715..bb5f6b847fe52 100644 --- a/packages/client-runtime/src/state/threadCommands.ts +++ b/packages/client-runtime/src/state/threadCommands.ts @@ -13,6 +13,7 @@ import { createOptimisticThreadLifecycle } from "./threadLifecycle.ts"; import * as DateTime from "effect/DateTime"; import { + type AtomCommand, createAtomCommandScheduler, createEnvironmentCommand, createEnvironmentRpcCommand, @@ -119,7 +120,22 @@ export function createThreadEnvironmentAtoms( ); }); - const commands = { + // Counts the commands that move or remove a thread's row. A list that holds its rows while + // environments synchronize (`stepSteadyShells`) shows the user's own change at once. + const rowActionsAtom = Atom.family((_environmentId: EnvironmentId) => + Atom.make(0).pipe(Atom.keepAlive), + ); + const rowAction = ( + command: AtomCommand, + ): AtomCommand => ({ + label: command.label, + run: (registry, target) => { + registry.update(rowActionsAtom(target.environmentId), (count) => count + 1); + return command.run(registry, target); + }, + }); + + const sent = { create: createEnvironmentCommand(runtime, { label: "environment-data:commands:thread:create", execute: createThread, @@ -382,9 +398,22 @@ export function createThreadEnvironmentAtoms( concurrency, }), }; + const commands = { + ...sent, + delete: rowAction(sent.delete), + archive: rowAction(sent.archive), + unarchive: rowAction(sent.unarchive), + settle: rowAction(sent.settle), + unsettle: rowAction(sent.unsettle), + snooze: rowAction(sent.snooze), + unsnooze: rowAction(sent.unsnooze), + pin: rowAction(sent.pin), + unpin: rowAction(sent.unpin), + }; const optimistic = createOptimisticThreadLifecycle(snapshotAtom); return { ...commands, + rowActionsAtom, snapshotAtom: optimistic.snapshotAtom, pendingThreadIdsAtom: optimistic.pendingThreadIdsAtom, settle: optimistic.wrap(commands.settle, (thread, _input, now, accepted) => diff --git a/packages/client-runtime/src/state/threadInbox.test.ts b/packages/client-runtime/src/state/threadInbox.test.ts index 35c7fa8355e39..4e4a39d2c8a2d 100644 --- a/packages/client-runtime/src/state/threadInbox.test.ts +++ b/packages/client-runtime/src/state/threadInbox.test.ts @@ -79,6 +79,26 @@ describe("createInboxReturnTracker", () => { unsubscribe(); }); + it("moves a thread whose run ended long ago at once, as after a reconnect", () => { + const tracker = createInboxReturnTracker(); + const finished = { + ...thread("a", false), + latestRun: { + runId: RunId.make("ended-while-away"), + status: "completed" as const, + requestedAt: "1970-01-01T00:00:02.000Z", + startedAt: "1970-01-01T00:00:02.000Z", + completedAt: "1970-01-01T00:00:09.000Z", + assistantMessageId: null, + }, + }; + tracker.observe([thread("a", true)]); + vi.setSystemTime(200_000); + tracker.observe([finished]); + expect(tracker.isWorking(finished)).toBe(false); + expect(tracker.returnedAt(finished)).toBe(200_000); + }); + it("cancels a transient return on resume and grants a fresh grace after the next finish", () => { const tracker = createInboxReturnTracker(); tracker.observe([thread("a", false)]); diff --git a/packages/client-runtime/src/state/threadInbox.ts b/packages/client-runtime/src/state/threadInbox.ts index d3de3b0bc4c23..ac820acc9d1ea 100644 --- a/packages/client-runtime/src/state/threadInbox.ts +++ b/packages/client-runtime/src/state/threadInbox.ts @@ -133,6 +133,13 @@ type ThreadKeyInput = Pick; */ const WORKING_EXIT_GRACE_MS = 2_000; +/** + * A run that ended this long ago has no continuation about to start, so its thread gets no + * grace. A client sees this for work that ended while it was closed or disconnected; the + * margin is wide so a client clock that runs ahead of the server does not cancel the grace. + */ +const STALE_EXIT_MS = 60_000; + /** * Keep one at module scope so placement survives routes that unmount the list. Call * `observe` when the shells or the snapshot version change, or with null while the beta @@ -234,8 +241,10 @@ export function createInboxReturnTracker() { thread.settledOverride === "settled" || effectiveSnoozed(thread, { now: observedAt }); // Only shelf placement is held: execution state and attention requests stay authoritative. + const endedAt = toSortableTimestamp(thread.latestRun?.completedAt ?? undefined); + const endedLongAgo = endedAt !== null && endedAt <= at - STALE_EXIT_MS; const deadline = - !actual && previous?.working && !actionable && !moved && !excluded + !actual && previous?.working && !actionable && !moved && !excluded && !endedLongAgo ? (previous.deadline ?? at + WORKING_EXIT_GRACE_MS) : null; const working = actual || (deadline !== null && deadline > at); From bf8e5e61b6a2db6212b89afc21c3e6e80f44fdae Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 04:11:46 -0800 Subject: [PATCH 06/56] fix(web): a failed page in the floating browser preview shows the error instead of a blank panel (#35066) --- .../preview/ThreadPreviewMiniPlayer.tsx | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) 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…
From 1d218d1525bd051f61d0b2400508c8eff96fc811 Mon Sep 17 00:00:00 2001 From: shivam <91240327+shivamhwp@users.noreply.github.com> Date: Thu, 12 Nov 2026 17:45:59 +0530 Subject: [PATCH 07/56] feat(web): screen reader window title leads with the thread's status and name (#34697) Co-authored-by: Claude Opus 5.5 --- apps/web/src/appInit.tsx | 12 +++++- apps/web/src/branding.logic.ts | 15 ++++++-- apps/web/src/components/Sidebar.logic.test.ts | 19 ++++++++++ apps/web/src/components/Sidebar.logic.ts | 20 ++++++++++ .../components/settings/SettingsPanels.tsx | 38 +++++++++++++++++++ .../src/components/settings/settingsSearch.ts | 8 ++++ docs/user/activity-log.md | 7 ++++ .../src/state/threadActivityAnnouncement.ts | 3 +- packages/contracts/src/settings.ts | 2 + 9 files changed, 119 insertions(+), 5 deletions(-) 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 e84d307d0eec5..7f60c1d35215a 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -40,6 +40,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"; @@ -990,6 +991,25 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Si 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/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 95acb62765c98..82d6a35df6816 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -541,6 +541,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.screenReaderAnnouncements !== DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements ? ["Screen reader announcements"] : []), + ...(settings.screenReaderWindowTitle !== DEFAULT_UNIFIED_SETTINGS.screenReaderWindowTitle + ? ["Screen reader window title"] + : []), ...(settings.responseStreamingMode !== DEFAULT_UNIFIED_SETTINGS.responseStreamingMode ? ["Response streaming"] : []), @@ -658,6 +661,7 @@ export function useSettingsRestore(onRestored?: () => void) { followUpBehavior: DEFAULT_UNIFIED_SETTINGS.followUpBehavior, toolCallVisibility: DEFAULT_UNIFIED_SETTINGS.toolCallVisibility, screenReaderAnnouncements: DEFAULT_UNIFIED_SETTINGS.screenReaderAnnouncements, + screenReaderWindowTitle: DEFAULT_UNIFIED_SETTINGS.screenReaderWindowTitle, environmentIdentificationMode: DEFAULT_UNIFIED_SETTINGS.environmentIdentificationMode, glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity, panelAnimationDurationMs: DEFAULT_UNIFIED_SETTINGS.panelAnimationDurationMs, @@ -1289,7 +1293,11 @@ export function ChatSettingsPanel() { + + + + ); @@ -1403,6 +1411,36 @@ function ScreenReaderAnnouncementsRow() { ); } +function ScreenReaderWindowTitleRow() { + const settings = useScopedSettings(); + const updateSettings = useUpdateScopedSettings(); + return ( + + updateSettings({ + screenReaderWindowTitle: DEFAULT_UNIFIED_SETTINGS.screenReaderWindowTitle, + }) + } + /> + ) : null + } + control={ + updateSettings({ screenReaderWindowTitle: checked })} + aria-label="Screen reader window title" + /> + } + /> + ); +} + function DiffColorsSettingsRow() { const settings = useScopedSettings(); const updateSettings = useUpdateScopedSettings(); diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index 077b09b53771e..6a9ce0557ca5e 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -495,6 +495,14 @@ export const SETTINGS_SEARCH_ITEMS = [ "accessibility a11y screen reader nvda jaws voiceover orca narrator speech announce read aloud messages activity steps", ], }, + { + id: "screen-reader-window-title", + title: "Screen reader window title", + to: "/settings/chat", + searchTerms: [ + "accessibility a11y screen reader nvda jaws voiceover orca narrator window title tab title alt tab taskbar thread status order working approval", + ], + }, { id: "guest-links", title: "Guest links", diff --git a/docs/user/activity-log.md b/docs/user/activity-log.md index a2a9278b80890..93b198aa18f68 100644 --- a/docs/user/activity-log.md +++ b/docs/user/activity-log.md @@ -41,3 +41,10 @@ short. The reply that closes the turn is not read, so you can read it yourself w are spaced out, so a quick step can be skipped for a newer one. The agent's reasoning text is never read. The setting follows the agent's real activity, whatever **Tool calls in chat** hides, and applies to this browser or device only. + +To hear the open thread and what it's doing when you switch to T3 Code, turn on **Screen reader +window title** in the same section. The window title then starts with the thread's status +(**Working**, **Needs approval**, or **Needs your input**) and its name, then the project, so a +screen reader says them first. When the turn ends, only the status goes away. +Anyone who can see your taskbar, window switcher, or shared screen sees it too, and time trackers +that group by window title count each status separately. diff --git a/packages/client-runtime/src/state/threadActivityAnnouncement.ts b/packages/client-runtime/src/state/threadActivityAnnouncement.ts index 270f4c9896403..e002c57971b6b 100644 --- a/packages/client-runtime/src/state/threadActivityAnnouncement.ts +++ b/packages/client-runtime/src/state/threadActivityAnnouncement.ts @@ -5,6 +5,7 @@ export type ThreadActivityStatus = "working" | "approval" | "input" | "idle"; /** Background threads say these too, so a status sounds the same wherever it's heard. */ export const THREAD_STATUS_TEXT = { + working: "Working", approval: "Needs approval", input: "Needs your input", done: "Done", @@ -144,7 +145,7 @@ export function nextThreadAnnouncement( ? null : THREAD_STATUS_TEXT.input : turnStarted - ? "Working" + ? THREAD_STATUS_TEXT.working : null; return { memory: { ...memory, turnRunId: nextTurnRunId }, announcement }; } diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 00eeb1797870a..2844c8181324a 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -530,6 +530,7 @@ export const ClientSettingsSchema = Schema.Struct({ screenReaderAnnouncements: ScreenReaderAnnouncements.pipe( Schema.withDecodingDefault(Effect.succeed("status" as const)), ), + screenReaderWindowTitle: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), // Retired Labs toggle. Still read as the default for the Usage item in threadDetailsItems. threadDetailsUsageEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), // Sparse show/hide overrides for thread details card items. Missing ids use the client's @@ -2054,6 +2055,7 @@ export const ClientSettingsPatch = Schema.Struct({ boringSidebarMultilineRows: Schema.optionalKey(Schema.Boolean), toolCallVisibility: Schema.optionalKey(ToolCallVisibility), screenReaderAnnouncements: Schema.optionalKey(ScreenReaderAnnouncements), + screenReaderWindowTitle: Schema.optionalKey(Schema.Boolean), threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean), threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), From 476fc9be6691ab0d81e936f4cc674983cf3913be Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 04:18:49 -0800 Subject: [PATCH 08/56] test(server): wire budget measures what clients fetch today, and the PR comment shows every row (#35225) Co-authored-by: Claude Fable 5.2 --- .github/scripts/thread-transfer-report.cjs | 159 +++++++++- .../scripts/thread-transfer-report.test.cjs | 79 +++++ .github/workflows/ci.yml | 5 +- .../TransferBudgetReport.integration.ts | 273 ++++++++++++------ .../TransferBudgetV2Fixture.integration.ts | 12 +- .../transferBudgetV2.integration.test.ts | 214 +++++++++++--- docs/internals/performance-regressions.md | 26 +- packages/contracts/src/environmentHttp.ts | 6 +- packages/shared/src/testing/providerEnv.ts | 1 + 9 files changed, 623 insertions(+), 152 deletions(-) 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 6f75c92562d03..d27b2c6a85729 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/apps/server/integration/TransferBudgetReport.integration.ts b/apps/server/integration/TransferBudgetReport.integration.ts index 0b3cdb78589a0..005c15f8e1669 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,28 @@ 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 shell resumed from a cursor too old to replay, 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,14 +107,44 @@ 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 }, + 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, @@ -211,31 +259,139 @@ 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, + ), + ...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 +418,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 +438,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..a87788c7fdc75 100644 --- a/apps/server/integration/TransferBudgetV2Fixture.integration.ts +++ b/apps/server/integration/TransferBudgetV2Fixture.integration.ts @@ -217,10 +217,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 +434,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), ]; } diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.ts index 313c583eecf7a..16ee48d6de0e1 100644 --- a/apps/server/integration/transferBudgetV2.integration.test.ts +++ b/apps/server/integration/transferBudgetV2.integration.test.ts @@ -23,8 +23,14 @@ import { 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,6 +69,7 @@ import { makeSqlStatementCounter } from "./SqlStatementCounter.integration.ts"; import { formatTransferBudgetReport, formatTransferBudgetResult, + formatTransferBudgetScenarios, transferBudgetViolations, type TransferBudgetRun, } from "./TransferBudgetReport.integration.ts"; @@ -83,11 +90,41 @@ 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. +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>; +const CLIENT_SHELL_SUBSCRIPTION = { + requestCompletionMarker: true, + omitIdleSubagents: true, + omitOlderSettled: true, +} satisfies Required< + Omit +>; +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); const decodeThreadSnapshot = Schema.decodeUnknownEffect( Schema.fromJsonString(Schema.toCodecJson(OrchestrationV2ThreadDetailSnapshot)), @@ -224,30 +261,36 @@ const collectUntil = Effect.fn("transfer.collectUntil")(function* ) + | ({ readonly shell: true } & Pick< + OrchestrationV2SubscribeShellInput, + "afterSequence" | "httpSnapshotFallback" + >); +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 +367,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 +420,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 +429,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 +441,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,15 +457,75 @@ 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 } = yield* decodeShellSnapshot(decoded(http)); + return { http, rows: threads.length, snapshotSequence }; + }); + // 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 }; }); - const { cursor: _, ...longTurnColdOpenLegacy } = - yield* readColdOpen("compactTurnItems=1"); - const { cursor, ...longTurnColdOpen } = yield* readColdOpen(CLIENT_BOUNDED_QUERY); + // 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, + ), + ); + + // 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; @@ -432,6 +536,19 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => fleetShellLegacy.rows, earlierThreads + SHELL_SETTLED_THREADS + SHELL_IDLE_SUBAGENTS, ); + // A cold connect subscribes from the snapshot it just loaded. + const fleetShellSubscribe = yield* open({ + shell: true, + afterSequence: fleetShell.snapshotSequence, + }); + assert.notInclude(fleetShellSubscribe.kinds, "snapshot"); + // A cursor too old to replay is told to reload over HTTP, not sent a socket 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 +589,19 @@ 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, + staleShellResume, staleTodoColdOpen, } satisfies TransferBudgetRun; }).pipe( @@ -492,10 +616,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/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index a7d5be74fd175..95719e4901087 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -19,7 +19,8 @@ The v2 checks pin these invariants: large work groups until expansion. Messages and items outside those groups remain in normal history paging. Required control records and the at-least-one-row rule can exceed the byte target; it is not a hard cap. -- The bounded snapshot does not retain the full duplicate conversation-message table. +- The bounded snapshot does not retain the full duplicate conversation-message table. Messages of + a run that is still in progress are the exception: all of them accompany the window. - Older activity is fetched in bounded HTTP pages and merged without disturbing the live scroll window. - Clients with confirmed history paging opt into socket snapshot fallbacks that use the same @@ -68,13 +69,22 @@ These are neither compressed WebSocket captures nor measurements of server RSS, fixtures exclude unrelated settings calls and subscription events. Payload budgets belong in these tests so regressions fail locally. The transfer budget integration test (`apps/server/integration/transferBudgetV2.integration.test.ts`) sends the opt-ins current clients -send and caps the decoded bytes and rows of the bounded snapshot and one older page for a 900-row -agent turn, and of the cold-connect shell for a sidebar of settled threads and idle subagents. It -also caps the bytes and the node, subagent, plan, provider turn and checkpoint counts of the -bounded snapshot for a thread of 40 finished runs behind one working run, so finished runs cannot -ride along with a window. The working run has a ready context handoff, so its history cannot ride -along either. When clients gain an opt-in, add it to the test's client queries and give a fixture -the data it saves. +send. Its opt-in objects are typed `Required` against the contracts, so an opt-in added to a +contract fails typecheck until the test sends it; give a fixture the data the opt-in saves. The +test caps decoded bytes and rows for a 900-row agent turn in both states: while the turn runs (the +bounded snapshot and one older page) and after it finishes (the deferred cold open over HTTP and +over the socket alone, and the first page of its deferred work). It caps the socket bytes of three +resumes that must not send a snapshot: a thread after one ordinary turn, an idle thread, and a +shell cursor too old to replay. It caps the cold-connect shell for a sidebar of settled threads and +idle subagents, and the subscription a client opens from that snapshot. It also caps the bytes and +the node, subagent, plan, provider turn and checkpoint counts of the bounded snapshot for a thread +of 40 finished runs behind one working run, so finished runs cannot ride along with a window. The +working run has a ready context handoff, so its history cannot ride along either. + +CI prints every row in the job summary. The pull request comment compares the budgeted rows with +`main`, lists the rows that changed or failed, and names each ceiling a pull request raises. A row +added to `scenarioRows` in `TransferBudgetReport.integration.ts` reaches the pass/fail check, the +summary and the comment. The server config has its own budget in `apps/server/src/ws.test.ts`. A client that asks for catalog digests and status deltas gets the provider list of its first config in under 1 KiB, for a diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index 4bbae77fb922d..b9a2cacf6e7ce 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -682,19 +682,19 @@ const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({ threadId: ThreadId, }); -const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({ +export const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({ omitIdleSubagents: Schema.optionalKey(Schema.String), omitOlderSettled: Schema.optionalKey(Schema.String), }); -const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({ +export const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({ deferWork: Schema.optionalKey(Schema.String), compactTurnItems: Schema.optionalKey(Schema.String), dedupeBodies: Schema.optionalKey(Schema.String), compactIds: Schema.optionalKey(Schema.String), }); -const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({ +export const EnvironmentOrchestrationThreadHistoryQuery = Schema.Struct({ cursor: TrimmedNonEmptyString, throughEntryId: Schema.optional(TrimmedNonEmptyString), view: Schema.optional(Schema.Literals(["conversation", "activity", "work"])), diff --git a/packages/shared/src/testing/providerEnv.ts b/packages/shared/src/testing/providerEnv.ts index 21bf59e52b500..4961b70141b84 100644 --- a/packages/shared/src/testing/providerEnv.ts +++ b/packages/shared/src/testing/providerEnv.ts @@ -8,6 +8,7 @@ const KEPT_ENV = new Set([ // CI sets these so the transfer budget integration test writes its report for the job summary. "T3CODE_TRANSFER_BUDGET_REPORT_PATH", "T3CODE_TRANSFER_BUDGET_RESULT_PATH", + "T3CODE_TRANSFER_BUDGET_SCENARIOS_PATH", // Opt-in: points the HtmlRender tests at a headless browser, which they skip without. "T3CODE_TEST_HEADLESS_SHELL", ]); From 4947db07d319df031028338e71128b5e8ff45b1f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 04:35:41 -0800 Subject: [PATCH 09/56] fix(github): PR templates in a lowercase pull_request_template/ directory are found (#35212) --- .../src/server/gitHubChangeRequestTemplate.test.ts | 3 +++ .../src/server/gitHubChangeRequestTemplate.ts | 3 +++ 2 files changed, 6 insertions(+) diff --git a/packages/source-control-github/src/server/gitHubChangeRequestTemplate.test.ts b/packages/source-control-github/src/server/gitHubChangeRequestTemplate.test.ts index 29bf922020d0d..fdc27c2d3e4f3 100644 --- a/packages/source-control-github/src/server/gitHubChangeRequestTemplate.test.ts +++ b/packages/source-control-github/src/server/gitHubChangeRequestTemplate.test.ts @@ -16,6 +16,9 @@ const TEMPLATE_DIRECTORIES = [ ".github/PULL_REQUEST_TEMPLATE", "PULL_REQUEST_TEMPLATE", "docs/PULL_REQUEST_TEMPLATE", + ".github/pull_request_template", + "pull_request_template", + "docs/pull_request_template", ] as const; const layerPrTemplateDetectionTest = Layer.merge( diff --git a/packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts b/packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts index 9edbccdd504dc..1e24084b4e00f 100644 --- a/packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts +++ b/packages/source-control-github/src/server/gitHubChangeRequestTemplate.ts @@ -25,8 +25,11 @@ const TEMPLATE_PATHS = [ const TEMPLATE_DIRECTORIES = [ ".github/PULL_REQUEST_TEMPLATE", + ".github/pull_request_template", "PULL_REQUEST_TEMPLATE", + "pull_request_template", "docs/PULL_REQUEST_TEMPLATE", + "docs/pull_request_template", ] as const; type ExecuteGit = SourceControlHost.SourceControlHost["Service"]["git"]["execute"]; From 591188471a6d8df7dad63083670afb6c2fb4d100 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 04:55:00 -0800 Subject: [PATCH 10/56] perf(server): sending to a long compacted thread waits about 3x less on its history read (#35180) Replaces #34641. Refs #29468. Co-authored-by: Braulio Oliveira Co-authored-by: Theo Browne Co-Authored-By: Claude Fable 5.2 --- .../src/orchestration-v2/Orchestrator.ts | 62 ++- .../orchestration-v2/ProjectionStore.test.ts | 435 ++++++++++++++++++ .../src/orchestration-v2/ProjectionStore.ts | 85 +++- .../SteeringCompletion.integration.test.ts | 97 +++- 4 files changed, 665 insertions(+), 14 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 076960f4dc1d5..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, @@ -1557,6 +1560,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio omitSettledSubagentRecords: true, // Commands act on pending forks and merge-backs only; consumed ones stay unread. contextTransferStatuses: ["pending"], + ...(recent === undefined ? {} : { sinceLastCompaction: recent }), }, ) .pipe( @@ -1645,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; @@ -6307,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 ( @@ -6344,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); @@ -6547,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/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index bcd6732c23782..8ab27060636fe 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; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 2bf1e896b4973..6264b36dfbd7d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -378,6 +378,16 @@ export interface ProjectionRecordFilter { * 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, @@ -3435,6 +3445,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, @@ -3452,6 +3505,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; @@ -3729,6 +3795,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` @@ -3749,13 +3816,15 @@ 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 @@ -3781,7 +3850,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 @@ -3912,6 +3982,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)}))`} ${ @@ -3957,7 +4034,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``} 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", () => From e9e934bb3db7b13c8d09f103a59f317935e0bd72 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 05:16:09 -0800 Subject: [PATCH 11/56] fix(acp): new Copilot threads run the model the composer shows (#35199) --- .../Adapters/AcpRegistryAdapterV2.test.ts | 86 ++++++++++++++++++- .../src/server/adapter.ts | 24 ++++++ .../src/server/AcpSessionRuntime.ts | 17 +++- packages/provider-acp/src/server/adapter.ts | 40 +++++++-- 4 files changed, 154 insertions(+), 13 deletions(-) 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/packages/provider-acp-registry/src/server/adapter.ts b/packages/provider-acp-registry/src/server/adapter.ts index 06ca0971ed324..5efe4ac83e2dc 100644 --- a/packages/provider-acp-registry/src/server/adapter.ts +++ b/packages/provider-acp-registry/src/server/adapter.ts @@ -258,6 +258,8 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu normalizeSessionUpdate: copilotRouting.normalizeSessionUpdate, extractSubagentUpdate: extractCopilotSubagentUpdate, restartRuntimeAfterPromptError: isCopilotLostSessionError, + // session/new reports a built-in default, not the model Copilot runs (github/copilot-cli#5363). + alwaysSetModel: true, }), makeRuntime: options.makeRuntime ?? makeAcpRegistryRuntime(runtimeOptions, catalog), ...(runtimeCoordinator === undefined @@ -268,6 +270,28 @@ export const makeAcpRegistryAdapterV2 = Effect.fn("makeAcpRegistryAdapterV2")(fu options.instanceId, normalizeAcpRegistryCommands(commands), ), + // A new Copilot session starts at its own effort, not the one the composer shows. + ...(isCopilot + ? { + unsetOptionDefaults: runtimeCoordinator + .getLiveConfiguration(options.instanceId) + .pipe( + Effect.map( + Option.match({ + onNone: () => [], + onSome: ({ configOptions }) => + configOptions.flatMap((descriptor) => + descriptor.type === "select" && + descriptor.role === "reasoning" && + descriptor.currentValue !== undefined + ? [{ id: descriptor.id, value: descriptor.currentValue }] + : [], + ), + }), + ), + ), + } + : {}), onSessionConfigurationUpdate: (configOptions, modeState, modelState) => runtimeCoordinator.publishLiveConfiguration( options.instanceId, diff --git a/packages/provider-acp/src/server/AcpSessionRuntime.ts b/packages/provider-acp/src/server/AcpSessionRuntime.ts index 514ac91164153..9131e1eaf297c 100644 --- a/packages/provider-acp/src/server/AcpSessionRuntime.ts +++ b/packages/provider-acp/src/server/AcpSessionRuntime.ts @@ -1186,7 +1186,11 @@ export class AcpSessionRuntime extends Context.Service< readonly setConfigOption: ( configId: string, value: string | boolean, - options?: { readonly allowUnlistedValue?: boolean }, + options?: { + readonly allowUnlistedValue?: boolean; + /** Sends the write even when the cached value already matches it. */ + readonly resendCurrentValue?: boolean; + }, ) => Effect.Effect; readonly setModel: (model: string) => Effect.Effect; readonly request: ( @@ -2031,7 +2035,10 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( const setConfigOption = ( configId: string, value: string | boolean, - options?: { readonly allowUnlistedValue?: boolean }, + options?: { + readonly allowUnlistedValue?: boolean; + readonly resendCurrentValue?: boolean; + }, ): Effect.Effect => validateConfigOptionValue(configId, value, options?.allowUnlistedValue === true).pipe( Effect.andThen(getStartedState), @@ -2039,7 +2046,11 @@ export const make = Effect.fn("AcpSessionRuntime.make")(function* ( SubscriptionRef.get(configOptionsRef).pipe( Effect.flatMap((configOptions) => { const existing = findSessionConfigOption(configOptions, configId); - if (existing && configOptionCurrentValueMatches(existing, value)) { + if ( + existing && + options?.resendCurrentValue !== true && + configOptionCurrentValueMatches(existing, value) + ) { return Effect.succeed({ configOptions, } satisfies EffectAcpSchema.SetSessionConfigOptionResponse); diff --git a/packages/provider-acp/src/server/adapter.ts b/packages/provider-acp/src/server/adapter.ts index 6f818c442e0cd..8278dcc35fdfd 100644 --- a/packages/provider-acp/src/server/adapter.ts +++ b/packages/provider-acp/src/server/adapter.ts @@ -374,6 +374,10 @@ export interface AcpAdapterV2Flavor { ChildProcessSpawner.ChildProcessSpawner | SecureRandom.SecureRandom | Scope.Scope >; readonly customModels?: ReadonlyArray; + /** The agent may run another model than session/new reports, so the model is always written. */ + readonly alwaysSetModel?: boolean; + /** Values the client shows for options a new session's selection leaves unset. */ + readonly unsetOptionDefaults?: Effect.Effect>; readonly resolveModelId?: (selection: ModelSelection) => string | undefined; /** * The agent advertises its model option only after `session/new` returns @@ -7155,6 +7159,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( }, ); + // Read before the session exists: its own config updates replace what the client showed. + const unsetOptionDefaults = yield* flavor.unsetOptionDefaults ?? Effect.succeed([]); const initialStart = yield* Effect.result( startAcpRuntime(input.threadId, input.initialNativeThreadId), ); @@ -7253,6 +7259,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( startResult: AcpSessionRuntime.AcpSessionRuntimeStartResult, modelSelection: ModelSelection, runtimePolicy: ProviderAdapter.ProviderAdapterV2RuntimePolicy, + unsetOptionDefaults: NonNullable = [], ) { yield* Ref.set(activeSelection, null); yield* validateModelSelection(modelSelection); @@ -7288,7 +7295,9 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ) ) { yield* runtime - .setConfigOption(modelOption.id, requestedModel) + .setConfigOption(modelOption.id, requestedModel, { + resendCurrentValue: flavor.alwaysSetModel === true, + }) .pipe(Effect.mapError(rejectedModel)); appliedModel = requestedModel; } @@ -7343,13 +7352,21 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( : undefined; return granted !== undefined && !isRuntimeModeAbove(granted, ceiling); }; - const optionSelections = (modelSelection.options ?? []).flatMap((selection) => { - if (flavor.ownedModelOptionIds?.includes(selection.id) === true) return []; - if (!withinCeiling(selection)) return []; - return [ - selection.value === ACP_EMPTY_OPTION_VALUE ? { ...selection, value: "" } : selection, - ]; - }); + const explicitSelections = modelSelection.options ?? []; + const implicitSelections = unsetOptionDefaults.filter( + (implicit) => !explicitSelections.some((selection) => selection.id === implicit.id), + ); + const optionSelections = [...explicitSelections, ...implicitSelections].flatMap( + (selection) => { + if (flavor.ownedModelOptionIds?.includes(selection.id) === true) return []; + if (!withinCeiling(selection)) return []; + return [ + selection.value === ACP_EMPTY_OPTION_VALUE + ? { ...selection, value: "" } + : selection, + ]; + }, + ); const availableConfigIds = new Set(configOptions.map((option) => option.id)); const hasNativeConfigWithSyntheticModeId = availableConfigIds.has( ACP_SESSION_MODE_OPTION_ID, @@ -7501,7 +7518,12 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* ( ); }); - yield* configureSession(started, input.modelSelection, input.runtimePolicy); + yield* configureSession( + started, + input.modelSelection, + input.runtimePolicy, + started.sessionId !== input.initialNativeThreadId ? unsetOptionDefaults : [], + ); yield* Ref.set(activeSelection, input.modelSelection); yield* Ref.set(activeInteractionMode, input.runtimePolicy.interactionMode); const createdAt = yield* DateTime.now; From 156dcd8c7a9b6d664826926346efa8703d41f997 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 06:04:00 -0800 Subject: [PATCH 12/56] perf(server): long threads open 2 to 6x faster from a cold cache (#35286) Co-authored-by: Claude Fable 5.2 --- .../ProjectionRecovery.test.ts | 30 ++++++++++++++----- .../orchestration-v2/ProjectionStore.test.ts | 16 ++++++++-- .../src/orchestration-v2/ProjectionStore.ts | 11 +++++-- 3 files changed, 44 insertions(+), 13 deletions(-) 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 8ab27060636fe..ebafef4bc5621 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -9225,9 +9225,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 6264b36dfbd7d..101521c7e1064 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -2105,6 +2105,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') @@ -3622,6 +3627,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 @@ -4770,10 +4776,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 @@ -5174,6 +5180,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 ( From 3ffd38ef7f67439eaaf17d2ffc1a71ee7cf4f33f Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 06:05:11 -0800 Subject: [PATCH 13/56] ci(release): a repo variable pauses scheduled nightly releases (#35287) Co-authored-by: Claude Fable 5.2 --- .github/workflows/release.yml | 4 +++- docs/operations/release.md | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) 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/docs/operations/release.md b/docs/operations/release.md index be74b2ad2982e..bd7365d141357 100644 --- a/docs/operations/release.md +++ b/docs/operations/release.md @@ -414,6 +414,7 @@ One-time Vercel dashboard setup: - scheduled check every 30 minutes - manual `workflow_dispatch` with `channel=nightly` - Automatic nightlies require new commits and at least six hours since the last nightly was published, including manual nightlies. +- To pause automatic nightlies, run `gh variable set PAUSE_NIGHTLY -b true -R pingdotgg/t3code`. Scheduled runs then skip. Stable, preview, and manual nightly runs are unaffected. Resume with `gh variable delete PAUSE_NIGHTLY -R pingdotgg/t3code`. - Manual nightlies bypass the time and change checks. Nightly runs remain serialized. Scheduled runs wait for an active nightly to finish, then check the publication gap before building. - Runs the same desktop quality gates and artifact matrix as the tagged release flow. - Publishes a GitHub prerelease only: From 6807c3fb865d3f9fcc0679b2e283cfd6064a4ea7 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 06:18:13 -0800 Subject: [PATCH 14/56] fix(server): file search no longer crashes the server, and a failed Edit from here keeps your files (#35291) Co-authored-by: Claude Fable 5.2 --- .../CheckpointRollbackService.test.ts | 15 ++- .../CheckpointRollbackService.ts | 51 ++++++-- .../src/workspace/WorkspaceEntries.test.ts | 71 +++++------ .../src/workspace/WorkspaceFinderThread.ts | 116 ------------------ .../workspace/WorkspaceSearchIndex.test.ts | 29 ++--- .../src/workspace/WorkspaceSearchIndex.ts | 57 ++++----- 6 files changed, 127 insertions(+), 212 deletions(-) delete mode 100644 apps/server/src/workspace/WorkspaceFinderThread.ts diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts index dea2c0151d38f..e5ef81ad46b54 100644 --- a/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts +++ b/apps/server/src/orchestration-v2/CheckpointRollbackService.test.ts @@ -177,8 +177,10 @@ it.effect.each([ { order: "cleanup-first", restoreFiles: true, leavesFolder: true }, { order: "cleanup-first", restoreFiles: false, leavesFolder: true }, { order: "cleanup-first", restoreFiles: true, leavesFolder: true, shared: true }, -])("locks rollback with %s", ({ order, restoreFiles, unmanaged, leavesFolder, shared }) => + { 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( @@ -249,6 +251,7 @@ it.effect.each([ path: worktreePath, }); calls.push("create"); + if (createFails) return yield* Effect.die("the branch is gone"); yield* fileSystem .makeDirectory(path.join(worktreePath, ".git"), { recursive: true }) .pipe(Effect.orDie); @@ -362,6 +365,16 @@ it.effect.each([ } 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); if (laterCleanup !== undefined) yield* Fiber.join(laterCleanup); const rollbackCalls = restoreFiles diff --git a/apps/server/src/orchestration-v2/CheckpointRollbackService.ts b/apps/server/src/orchestration-v2/CheckpointRollbackService.ts index a3604c278e3dd..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"; @@ -246,16 +247,52 @@ export const layer: Layer.Layer< ) { 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(); - yield* fileSystem.remove(worktreePath, { recursive: true, force: true }); + // 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; } - yield* gitWorkflow.pruneWorktrees({ cwd: project.value.workspaceRoot }); - yield* gitWorkflow.createWorktree({ - cwd: project.value.workspaceRoot, - refName: branch, - path: worktreePath, - }); } } } diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 15f320a700837..62d6ab0a63b33 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"; @@ -793,42 +793,39 @@ 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; + const scanFiles = finder.scanFiles.bind(finder); + finder.scanFiles = () => { + rescans += 1; + return scanFiles(); + }; + 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..11a19e1839861 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,8 +399,8 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( const refresh: WorkspaceSearchIndex["Service"]["refresh"] = Effect.fn( "WorkspaceSearchIndex.refresh", )(function* () { - const result = yield* Effect.tryPromise({ - try: () => finder.call("scanFiles"), + const result = yield* Effect.try({ + try: () => finder.scanFiles(), catch: (cause) => new WorkspaceSearchIndexRefreshFailed({ cwd, @@ -439,9 +430,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) => @@ -463,23 +454,23 @@ export const make = Effect.fn("WorkspaceSearchIndex.make")(function* ( // matching is subsequence-based, so dropping "[" still matches "[id]" folders. const query = rawQuery.replaceAll("[", ""); const pageSize = imageOnly ? WORKSPACE_INDEX_PAGE_SIZE : Math.max(1, limit + 1); - const incompleteBeforeQuery = yield* hasIncompleteInitialScan(); + const incompleteBeforeQuery = 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 }; } 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 }; } const result = yield* runSearch(query, pageSize, "mixedSearch", () => - finder.call("mixedSearch", query, { pageSize }), + finder.mixedSearch(query, { pageSize }), ); const mapped = mapMixedSearchResult(result, limit); return { ...mapped, truncated: incompleteBeforeQuery || mapped.truncated }; @@ -502,7 +493,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), From 2482b03a01cf998a26cddbff65c5e5b0b0f39b38 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 06:31:02 -0800 Subject: [PATCH 15/56] perf(client): threads load while the socket connects, with fewer round trips (#35071) The prepare-time shell load follows the idea and structure of #27413. Co-authored-by: ahalekelly <7078138+ahalekelly@users.noreply.github.com> Co-Authored-By: Claude Fable 5.2 --- .../TransferBudgetReport.integration.ts | 19 +- .../TransferBudgetV2Fixture.integration.ts | 40 +++ .../transferBudgetV2.integration.test.ts | 61 +++- .../src/environment/ServerEnvironment.ts | 2 + .../server/src/httpResponseErrorGuard.test.ts | 77 +++++ apps/server/src/httpResponseErrorGuard.ts | 26 ++ .../src/orchestration-v2/ShellStream.ts | 104 ++++++ apps/server/src/orchestration-v2/http.test.ts | 10 + apps/server/src/orchestration-v2/http.ts | 30 +- apps/server/src/server.ts | 3 +- apps/server/src/ws.test.ts | 153 +++++++-- apps/server/src/ws.ts | 55 +--- docs/internals/connection-runtime.md | 10 + docs/internals/performance-regressions.md | 10 +- .../src/authorization/layer.test.ts | 100 +++++- .../src/authorization/service.ts | 112 ++++--- .../client-runtime/src/connection/driver.ts | 15 +- .../client-runtime/src/connection/model.ts | 4 +- .../src/connection/resolver.test.ts | 9 + .../client-runtime/src/connection/resolver.ts | 1 + .../src/connection/routes.test.ts | 31 ++ .../client-runtime/src/connection/routes.ts | 38 ++- .../src/state/environmentHttpAuth.test.ts | 6 +- .../src/state/shell-sync.test.ts | 306 +++++++++++++++++- packages/client-runtime/src/state/shell.ts | 292 +++++++++++++---- .../src/state/shellSnapshotHttp.ts | 68 ++-- packages/contracts/src/environment.ts | 6 + packages/contracts/src/environmentHttp.ts | 10 +- packages/contracts/src/orchestrationV2.ts | 21 ++ 29 files changed, 1363 insertions(+), 256 deletions(-) diff --git a/apps/server/integration/TransferBudgetReport.integration.ts b/apps/server/integration/TransferBudgetReport.integration.ts index 005c15f8e1669..bcfa2f3896f20 100644 --- a/apps/server/integration/TransferBudgetReport.integration.ts +++ b/apps/server/integration/TransferBudgetReport.integration.ts @@ -74,7 +74,11 @@ export interface TransferBudgetRun { readonly fleetShellLegacy: TimelineHttpMeasurement; /** The shell subscription a cold connect opens from that snapshot's cursor. */ readonly fleetShellSubscribe: SocketOpenMeasurement; - /** A shell resumed from a cursor too old to replay, by a client that reloads over HTTP. */ + /** 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, @@ -141,6 +145,7 @@ const SOCKET_BUDGETS = { 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 }, }; @@ -151,6 +156,12 @@ const FLEET_SHELL_BUDGET = { 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. @@ -367,6 +378,8 @@ function scenarioRows(run: TransferBudgetRun): ScenarioRow[] { 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 => ({ @@ -439,8 +452,8 @@ export function formatTransferBudgetReport(runs: ReadonlyArray; +} satisfies Required>; const CLIENT_THREAD_SUBSCRIPTION = { requestCompletionMarker: true, acceptBoundedSnapshot: true, @@ -114,17 +118,22 @@ const CLIENT_THREAD_SUBSCRIPTION = { acceptCompactIds: true, acceptDedupedBodies: true, } satisfies Required>; +type ShellResumeField = "afterSequence" | "httpSnapshotFallback" | "knownProjectIdentities"; const CLIENT_SHELL_SUBSCRIPTION = { requestCompletionMarker: true, omitIdleSubagents: true, omitOlderSettled: true, -} satisfies Required< - Omit ->; +} 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)), @@ -136,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( @@ -176,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, }), @@ -263,10 +275,7 @@ const collectUntil = Effect.fn("transfer.collectUntil")(function* ) - | ({ readonly shell: true } & Pick< - OrchestrationV2SubscribeShellInput, - "afterSequence" | "httpSnapshotFallback" - >); + | ({ readonly shell: true } & Pick); function subscriptionStream( client: MeasuredWsClient, subscription: Subscription, @@ -457,8 +466,10 @@ 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}`); - const { threads, snapshotSequence } = yield* decodeShellSnapshot(decoded(http)); - return { http, rows: threads.length, snapshotSequence }; + 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) => @@ -529,6 +540,8 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => // 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); @@ -536,13 +549,27 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => fleetShellLegacy.rows, earlierThreads + SHELL_SETTLED_THREADS + SHELL_IDLE_SUBAGENTS, ); - // A cold connect subscribes from the snapshot it just loaded. + 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 cursor too old to replay is told to reload over HTTP, not sent a socket 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, @@ -601,6 +628,8 @@ it.live("reports V2 thread HTTP and WebSocket transfer budgets", () => fleetShellLegacy, fleetShell, fleetShellSubscribe, + fleetShellResume, + staleShellReload, staleShellResume, staleTodoColdOpen, } satisfies TransferBudgetRun; 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/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.ts index 120d5c3690f00..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, 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/server.ts b/apps/server/src/server.ts index 8587e16d8e947..f92b3cbaaf636 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"; @@ -354,7 +355,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/ws.test.ts b/apps/server/src/ws.test.ts index c29b218adbfea..492b874cc451e 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -149,6 +149,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"; @@ -1980,41 +1981,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 f3aa5aa7f4263..4cfceb4ed8001 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, @@ -722,12 +724,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, @@ -864,36 +860,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) => @@ -1158,6 +1124,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; @@ -1383,7 +1350,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; } @@ -1402,12 +1369,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/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.md index 5104a72e4dd07..4ebad4c7056ef 100644 --- a/docs/internals/connection-runtime.md +++ b/docs/internals/connection-runtime.md @@ -75,6 +75,16 @@ connection nor overwrite newer live data during a reconnect. Loading and resuming snapshots belongs to the shared state services, so every view agrees on which data is current. +The shell snapshot loads over HTTP, which needs only the prepared connection, so +the [shell state](../../packages/client-runtime/src/state/shell.ts) can ask for +it before the socket and the config are ready. Two constraints follow. The live +config stays the authority: rows loaded early for a build or with omissions that +it does not confirm are replaced, never resumed. And an HTTP answer must never +land on rows the socket has moved on: the subscription waits for the answer, and +when held rows can resume, it ends the request 3 seconds after the socket is +ready. A proxy that drops `/api` without an answer then does not hold the +connect for the HTTP timeout. + Each environment synchronizes at its own time, so a thread list that follows every snapshot moves once per environment on each cold start and resume. Mobile lists read [steady shells](../../packages/client-runtime/src/state/steadyShells.ts): an diff --git a/docs/internals/performance-regressions.md b/docs/internals/performance-regressions.md index 95719e4901087..8dbf42fc45f72 100644 --- a/docs/internals/performance-regressions.md +++ b/docs/internals/performance-regressions.md @@ -54,7 +54,10 @@ The v2 checks pin these invariants: - The initial shell contains active navigation rows only. Archived rows use the dedicated archive query, and transcript message bodies stay in thread detail regardless of message size. - Shell resume sends deltas plus compact repository-enrichment metadata, not another full project - and thread snapshot. + and thread snapshot. A cursor at the head sequence always resumes, even below the pruned + boundary, so a client that just loaded the HTTP snapshot never downloads it again over the + socket. That client also names the snapshot's project identities, and a server whose + identities did not change since resends only the roots that resolved to no identity. - Auto, steer, and restart sends resolve delivery from authoritative state inside the server's per-thread dispatch lock. Model selection and identified-checkpoint rollback also dispatch without first fetching a full thread projection when the server advertises support. @@ -76,7 +79,10 @@ bounded snapshot and one older page) and after it finishes (the deferred cold op over the socket alone, and the first page of its deferred work). It caps the socket bytes of three resumes that must not send a snapshot: a thread after one ordinary turn, an idle thread, and a shell cursor too old to replay. It caps the cold-connect shell for a sidebar of settled threads and -idle subagents, and the subscription a client opens from that snapshot. It also caps the bytes and +idle subagents, and the subscription a client opens from that snapshot with its project identities. +It caps both answers of the HTTP shell route to a client that holds rows and names their cursor: the +few bytes that keep them, and the snapshot that replaces rows too old to replay. It also caps the +bytes and the node, subagent, plan, provider turn and checkpoint counts of the bounded snapshot for a thread of 40 finished runs behind one working run, so finished runs cannot ride along with a window. The working run has a ready context handoff, so its history cannot ride along either. diff --git a/packages/client-runtime/src/authorization/layer.test.ts b/packages/client-runtime/src/authorization/layer.test.ts index 8c7cd57502b8b..8db36ec6c399f 100644 --- a/packages/client-runtime/src/authorization/layer.test.ts +++ b/packages/client-runtime/src/authorization/layer.test.ts @@ -51,13 +51,16 @@ const BOOTSTRAP: RelayEnvironmentConnectResponse = { expiresAt: "2026-06-06T01:00:00.000Z", }; -type RecordedResponse = Response | ((init: RequestInit) => Response); +type RecordedResponse = Response | ((init: RequestInit) => Response | Promise); -function recordedFetch(responses: ReadonlyArray) { +function recordedFetch(responses: ReadonlyArray, descriptor?: object) { const calls: Array = []; let responseIndex = 0; const fetchFn = ((input, init) => { calls.push([input, init ?? {}]); + if (descriptor !== undefined && String(input).endsWith("/.well-known/t3/environment")) { + return Promise.resolve(Response.json(descriptor)); + } const response = responses[responseIndex++]; return response === undefined ? Promise.reject(new Error(`Unexpected fetch call to ${String(input)}`)) @@ -113,6 +116,8 @@ const persistedToken = ( const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* (input: { readonly initialToken?: TokenStore.RemoteDpopAccessToken; readonly responses: ReadonlyArray; + /** Answers every descriptor read, so one that runs beside a ticket does not shift `responses`. */ + readonly descriptor?: object; readonly bootstrap?: RelayEnvironmentConnectResponse; readonly beforeBootstrap?: Effect.Effect; readonly beforePut?: Effect.Effect; @@ -141,7 +146,7 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* ( readonly accessToken?: string; }> >([]); - const fetch = recordedFetch(input.responses); + const fetch = recordedFetch(input.responses, input.descriptor); const tokenStore = TokenStore.RemoteDpopAccessTokenStore.of({ get: (environmentId) => @@ -238,6 +243,9 @@ const makeHarness = Effect.fn("TestRemoteAuthorization.makeHarness")(function* ( }; }); +const requestsTo = (harness: Effect.Success>, path: string) => + harness.fetch.calls.filter(([url]) => String(url).endsWith(path)).length; + const prepareDirectBearer = Effect.fn("TestRemoteAuthorization.prepareDirectBearer")(function* ( harness: Effect.Success>, times: number, @@ -318,7 +326,7 @@ describe("RemoteEnvironmentAuthorization", () => { }), ); - it.effect("reuses a matching descriptor a check just read, once, while fresh, over HTTPS", () => + it.effect("reuses a matching descriptor a check just read, once, while fresh", () => Effect.gen(function* () { const descriptor = { ...DESCRIPTOR, @@ -327,10 +335,13 @@ describe("RemoteEnvironmentAuthorization", () => { const harness = yield* makeHarness({ responses: [ websocketTicket("reused"), - ...Array.from({ length: 5 }, () => [ + ...Array.from({ length: 4 }, () => [ Response.json(descriptor), websocketTicket("fresh"), ]).flat(), + websocketTicket("reused over plain HTTP"), + Response.json(descriptor), + websocketTicket("fresh"), ], }); @@ -346,7 +357,7 @@ describe("RemoteEnvironmentAuthorization", () => { }); const authorize = authorizeAt(ENDPOINT.httpBaseUrl); const remember = (value: Option.Option) => - remote.rememberCheckedDescriptor(ENDPOINT.httpBaseUrl, value); + remote.rememberCheckedDescriptor(ENDPOINT.httpBaseUrl, value, true); yield* remember(Option.some(descriptor)); yield* authorize; @@ -363,17 +374,31 @@ describe("RemoteEnvironmentAuthorization", () => { yield* remember(Option.some(descriptor)); yield* remember(Option.none()); yield* authorize; + // Plain HTTP is no reason to read again where the address keeps its host. + yield* remote.rememberCheckedDescriptor( + "http://127.0.0.1:3773", + Option.some(descriptor), + true, + ); + yield* authorizeAt("http://127.0.0.1:3773"); // After a network change, a plain LAN address can belong to another machine. - yield* remote.rememberCheckedDescriptor("http://192.168.1.2:3773", Option.some(descriptor)); + yield* remote.rememberCheckedDescriptor( + "http://192.168.1.2:3773", + Option.some(descriptor), + false, + ); yield* authorizeAt("http://192.168.1.2:3773"); }).pipe(Effect.provide(harness.layer)); expect(harness.fetch.calls.map(([url]) => new URL(String(url)).pathname)).toEqual([ "/api/auth/websocket-ticket/rpc", - ...Array.from({ length: 5 }, () => [ + ...Array.from({ length: 4 }, () => [ "/.well-known/t3/environment", "/api/auth/websocket-ticket/rpc", ]).flat(), + "/api/auth/websocket-ticket/rpc", + "/.well-known/t3/environment", + "/api/auth/websocket-ticket/rpc", ]); }), ); @@ -446,6 +471,44 @@ describe("RemoteEnvironmentAuthorization", () => { }), ); + it.effect("gives up on a silent loopback or LAN address sooner than on a remote one", () => + Effect.gen(function* () { + const silent = () => new Promise(() => {}); + const harness = yield* makeHarness({ responses: [silent, silent, silent] }); + + yield* Effect.gen(function* () { + const remote = yield* RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization; + const authorizeAt = (httpBaseUrl: string, connectionMethod: "direct" | "ssh" = "direct") => + remote + .authorizeBearer({ + expectedEnvironmentId: ENVIRONMENT_ID, + httpBaseUrl, + wsBaseUrl: httpBaseUrl.replace(/^http/, "ws"), + bearerToken: "bearer-token", + connectionMethod, + }) + .pipe(Effect.flip, Effect.forkChild); + const lan = yield* authorizeAt("http://192.168.1.2:3773"); + const tailnet = yield* authorizeAt("http://100.101.102.103:3773"); + // An SSH forward listens on loopback but reaches a remote host. + const forwarded = yield* authorizeAt("http://127.0.0.1:4010", "ssh"); + + yield* TestClock.adjust("3 seconds"); + expect(lan.pollUnsafe()).toBeDefined(); + expect(tailnet.pollUnsafe()).toBeUndefined(); + expect(forwarded.pollUnsafe()).toBeUndefined(); + expect(yield* Fiber.join(lan)).toMatchObject({ + _tag: "ConnectionTransientError", + reason: "timeout", + }); + + yield* TestClock.adjust("7 seconds"); + expect(tailnet.pollUnsafe()).toBeDefined(); + expect(forwarded.pollUnsafe()).toBeDefined(); + }).pipe(Effect.provide(harness.layer)); + }), + ); + it.effect("reuses a same-account persisted environment token without contacting the relay", () => Effect.gen(function* () { const cached = new TokenStore.RemoteDpopAccessToken({ @@ -459,6 +522,7 @@ describe("RemoteEnvironmentAuthorization", () => { }); const harness = yield* makeHarness({ initialToken: cached, + descriptor: DESCRIPTOR, responses: [websocketTicket("cached-ticket")], }); @@ -472,10 +536,12 @@ describe("RemoteEnvironmentAuthorization", () => { expect(authorized.socketUrl).toContain("wsTicket=cached-ticket"); expect(authorized.socketUrl).toContain("connectionMethod=relay"); expect(yield* Ref.get(harness.bootstrapCalls)).toBe(0); - expect(harness.fetch.calls).toHaveLength(1); - expect(String(harness.fetch.calls[0]?.[0])).toBe( + // The descriptor is read beside the ticket, so the connect needs no later read. + expect(authorized.descriptor).toMatchObject({ environmentId: ENVIRONMENT_ID }); + expect(harness.fetch.calls.map(([url]) => String(url)).toSorted()).toEqual([ + "https://environment.example.test/.well-known/t3/environment", "https://environment.example.test/api/auth/websocket-ticket/rpc", - ); + ]); }), ); @@ -576,6 +642,8 @@ describe("RemoteEnvironmentAuthorization", () => { }).pipe(Effect.provide(harness.layer)); expect(authorized.socketUrl).toContain("wsTicket=fresh-ticket"); + // The mint already read the descriptor. + expect(authorized.descriptor).toMatchObject({ environmentId: ENVIRONMENT_ID }); expect(yield* Ref.get(harness.bootstrapCalls)).toBe(1); expect((yield* Ref.get(harness.tokens)).get(ENVIRONMENT_ID)).toEqual( expect.objectContaining({ @@ -729,9 +797,9 @@ describe("RemoteEnvironmentAuthorization", () => { }); const harness = yield* makeHarness({ initialToken: cached, + descriptor: DESCRIPTOR, responses: [ authInvalid(), - Response.json(DESCRIPTOR), accessToken("replacement-access-token"), websocketTicket("replacement-ticket"), ], @@ -751,7 +819,8 @@ describe("RemoteEnvironmentAuthorization", () => { accessToken: "replacement-access-token", }), ); - expect(harness.fetch.calls).toHaveLength(4); + expect(requestsTo(harness, "/api/auth/websocket-ticket/rpc")).toBe(2); + expect(requestsTo(harness, "/oauth/token")).toBe(1); }), ); @@ -768,9 +837,9 @@ describe("RemoteEnvironmentAuthorization", () => { }); const harness = yield* makeHarness({ initialToken: cached, + descriptor: DESCRIPTOR, responses: [ new Response("endpoint unavailable", { status: 503 }), - Response.json(DESCRIPTOR), accessToken("replacement-access-token"), websocketTicket("replacement-ticket"), ], @@ -790,7 +859,8 @@ describe("RemoteEnvironmentAuthorization", () => { accessToken: "replacement-access-token", }), ); - expect(harness.fetch.calls).toHaveLength(4); + expect(requestsTo(harness, "/api/auth/websocket-ticket/rpc")).toBe(2); + expect(requestsTo(harness, "/oauth/token")).toBe(1); }), ); diff --git a/packages/client-runtime/src/authorization/service.ts b/packages/client-runtime/src/authorization/service.ts index c197c3a9b38d1..75b4921f0f85a 100644 --- a/packages/client-runtime/src/authorization/service.ts +++ b/packages/client-runtime/src/authorization/service.ts @@ -22,6 +22,7 @@ import { ConnectionTransientError, type ConnectionAttemptError, } from "../connection/model.ts"; +import { isNearbyAddress } from "../connection/routes.ts"; import { fetchRemoteEnvironmentDescriptor } from "../environment/descriptor.ts"; import { environmentEndpointUrl } from "../environment/endpoint.ts"; import * as ClientCapabilities from "../platform/capabilities.ts"; @@ -82,10 +83,14 @@ export class RemoteEnvironmentAuthorization extends Context.Service< readonly expectedEnvironmentId: EnvironmentId; readonly rejectedAccessToken?: string; }) => Effect.Effect; - /** Lets the next direct authorization of this address skip its own descriptor read. */ + /** + * Lets the next direct authorization of this address skip its own descriptor + * read. Kept only where the address reaches the same machine on every network. + */ readonly rememberCheckedDescriptor: ( httpBaseUrl: string, descriptor: Option.Option, + keepsItsHost: boolean, ) => Effect.Effect; /** * Renews a live socket's token before it expires, so the server moves the @@ -101,6 +106,14 @@ export class RemoteEnvironmentAuthorization extends Context.Service< const CACHED_ENDPOINT_SOCKET_TIMEOUT_MS = 3_000; const DPOP_AUTHORIZATION_TIMEOUT_MS = 30_000; const CHECKED_DESCRIPTOR_TTL_NANOS = 5_000_000_000n; +// A loopback or LAN host answers well inside this, so a dead one frees its attempt sooner. +const NEARBY_DESCRIPTOR_TIMEOUT_MS = 3_000; + +/** A token with the descriptor its mint read. A cached token has none. */ +interface IssuedDpopToken { + readonly token: TokenStore.RemoteDpopAccessToken; + readonly descriptor?: ExecutionEnvironmentDescriptor; +} function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemptError) { return error._tag === "ConnectionTransientError" || error._tag === "ConnectionBlockedError" @@ -111,10 +124,12 @@ function mapDpopSocketError(error: RemoteEnvironmentAuthError | ConnectionAttemp const fetchDescriptor = Effect.fn("clientRuntime.connection.remote.fetchDescriptor")(function* ( httpBaseUrl: string, connectionMethod: ClientConnectionMethod, + timeoutMs?: number, ) { - return yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe( - Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod)), - ); + return yield* fetchRemoteEnvironmentDescriptor({ + httpBaseUrl, + ...(timeoutMs === undefined ? {} : { timeoutMs }), + }).pipe(Effect.mapError((error) => mapRemoteEnvironmentError(error, connectionMethod))); }); export const make = Effect.gen(function* () { @@ -137,13 +152,13 @@ export const make = Effect.gen(function* () { readonly id: object; readonly identity: ClientCapabilities.CloudSessionIdentity; readonly thumbprint: string; - readonly token: Effect.Effect; + readonly issued: Effect.Effect; } >(); // A route or host check hands its descriptor to the connect it leads to, once, - // so the connect skips a round trip. Only over HTTPS: a plain LAN address can - // belong to another machine after a network change. + // so the connect skips a round trip. Only over HTTPS or loopback: any other + // plain http address can belong to another machine after a network change. const checkedDescriptors = new Map< string, { readonly descriptor: ExecutionEnvironmentDescriptor; readonly at: bigint } @@ -167,9 +182,14 @@ export const make = Effect.gen(function* () { checked.descriptor.environmentId === input.expectedEnvironmentId && (yield* Clock.monotonicTimeNanos) - checked.at <= CHECKED_DESCRIPTOR_TTL_NANOS ? checked.descriptor - : yield* fetchDescriptor(input.httpBaseUrl, input.connectionMethod).pipe( - Effect.provideService(HttpClient.HttpClient, httpClient), - ); + : yield* fetchDescriptor( + input.httpBaseUrl, + input.connectionMethod, + // An SSH forward listens on loopback but reaches a remote host. + input.connectionMethod === "direct" && isNearbyAddress(input.httpBaseUrl) + ? NEARBY_DESCRIPTOR_TIMEOUT_MS + : undefined, + ).pipe(Effect.provideService(HttpClient.HttpClient, httpClient)); if (descriptor.environmentId !== input.expectedEnvironmentId) { return yield* environmentMismatchError({ expected: input.expectedEnvironmentId, @@ -352,7 +372,7 @@ export const make = Effect.gen(function* () { Effect.withSpan("environment.authorization.accessToken.exchange"), ); const issuedAt = yield* Clock.currentTimeMillis; - return new TokenStore.RemoteDpopAccessToken({ + const token = new TokenStore.RemoteDpopAccessToken({ environmentId: descriptor.environmentId, accountId: identity.accountId, label: descriptor.label, @@ -361,6 +381,7 @@ export const make = Effect.gen(function* () { expiresAtEpochMs: issuedAt + access.expires_in * 1_000, dpopThumbprint: thumbprint, }); + return { token, descriptor } satisfies IssuedDpopToken; }, ); @@ -403,14 +424,17 @@ export const make = Effect.gen(function* () { accessToken: cached.value.accessToken, identity, }); - return { token: Effect.succeed(cached.value), fromCache: true }; + return { + issued: Effect.succeed({ token: cached.value }), + fromCache: true, + }; } if (input.rejectedAccessToken !== undefined) { yield* removeRejectedToken(input.expectedEnvironmentId, input.rejectedAccessToken); } const pending = pendingTokens.get(input.expectedEnvironmentId); if (pending?.identity === identity && pending.thumbprint === thumbprint) { - return { token: pending.token, fromCache: false }; + return { issued: pending.issued, fromCache: false }; } const id = {}; @@ -419,9 +443,10 @@ export const make = Effect.gen(function* () { thumbprint, identity, ).pipe( - Effect.flatMap((token) => + Effect.flatMap((issued) => tokenLock.withPermits(1)( Effect.gen(function* () { + const { token } = issued; yield* assertSession(identity); yield* tokenStore .put(token) @@ -438,7 +463,7 @@ export const make = Effect.gen(function* () { if (pendingTokens.get(input.expectedEnvironmentId)?.id === id) { pendingTokens.delete(input.expectedEnvironmentId); } - return token; + return issued; }), ), ), @@ -464,17 +489,17 @@ export const make = Effect.gen(function* () { // One caller's timeout must not cancel renewal for other HTTP requests. Effect.forkIn(serviceScope), ); - const token = Fiber.join(fiber); - pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, token }); - return { token, fromCache: false }; + const issued = Fiber.join(fiber); + pendingTokens.set(input.expectedEnvironmentId, { id, identity, thumbprint, issued }); + return { issued, fromCache: false }; }), ); yield* Effect.annotateCurrentSpan({ "connection.remote_token_cache": selected.fromCache ? "hit" : "miss", }); - const token = yield* selected.token; + const issued = yield* selected.issued; yield* assertSession(identity); - return { token, fromCache: selected.fromCache, identity }; + return { ...issued, fromCache: selected.fromCache, identity }; }); const httpAuthorization = ( @@ -495,7 +520,7 @@ export const make = Effect.gen(function* () { input: Parameters[0], ) { const endpoint = input.directEndpoint; - const descriptor = + const directDescriptor = endpoint === undefined ? undefined : yield* verifyDirectEndpoint({ @@ -503,21 +528,36 @@ export const make = Effect.gen(function* () { httpBaseUrl: endpoint.httpBaseUrl, connectionMethod: "direct", }); - const authorized = (token: TokenStore.RemoteDpopAccessToken, socketUrl: string) => ({ - ...httpAuthorization(token, endpoint?.httpBaseUrl), - socketUrl, - ...(descriptor === undefined ? {} : { descriptor }), + const authorized = ( + token: TokenStore.RemoteDpopAccessToken, + socketUrl: string, + descriptor: ExecutionEnvironmentDescriptor, + ) => ({ ...httpAuthorization(token, endpoint?.httpBaseUrl), socketUrl, descriptor }); + // A cached token comes without a descriptor. That read needs no ticket, so + // it runs beside the ticket request, and a failed ticket abandons it. + const openSocket = Effect.fnUntraced(function* (issued: IssuedDpopToken, timeoutMs?: number) { + const socket = createDpopSocketUrl(issued.token, timeoutMs, endpoint).pipe(Effect.result); + const known = directDescriptor ?? issued.descriptor; + if (known !== undefined) { + return Result.map(yield* socket, (socketUrl) => authorized(issued.token, socketUrl, known)); + } + const reading = yield* fetchDescriptor(issued.token.endpoint.httpBaseUrl, "relay").pipe( + Effect.provideService(HttpClient.HttpClient, httpClient), + Effect.forkChild, + ); + const opened = yield* socket; + if (Result.isFailure(opened)) { + yield* Fiber.interrupt(reading); + return Result.fail(opened.failure); + } + return Result.succeed(authorized(issued.token, opened.success, yield* Fiber.join(reading))); }); let selected = yield* getDpopToken(input); if (selected.fromCache) { - const cachedSocket = yield* createDpopSocketUrl( - selected.token, - CACHED_ENDPOINT_SOCKET_TIMEOUT_MS, - endpoint, - ).pipe(Effect.result); + const cachedSocket = yield* openSocket(selected, CACHED_ENDPOINT_SOCKET_TIMEOUT_MS); if (Result.isSuccess(cachedSocket)) { yield* assertSession(selected.identity); - return authorized(selected.token, cachedSocket.success); + return cachedSocket.success; } if (cachedSocket.failure._tag === "ConnectionBlockedError") { return yield* mapDpopSocketError(cachedSocket.failure); @@ -533,9 +573,7 @@ export const make = Effect.gen(function* () { rejectedAccessToken: selected.token.accessToken, }); } - const socket = yield* createDpopSocketUrl(selected.token, undefined, endpoint).pipe( - Effect.result, - ); + const socket = yield* openSocket(selected); if (Result.isFailure(socket)) { if (endpoint === undefined || socket.failure._tag === "ConnectionBlockedError") { yield* tokenLock.withPermits(1)( @@ -545,14 +583,14 @@ export const make = Effect.gen(function* () { return yield* mapDpopSocketError(socket.failure); } yield* assertSession(selected.identity); - return authorized(selected.token, socket.success); + return socket.success; }); return RemoteEnvironmentAuthorization.of({ authorizeBearer, // Untraced: it runs on every route and host check. - rememberCheckedDescriptor: Effect.fnUntraced(function* (httpBaseUrl, descriptor) { - if (Option.isNone(descriptor) || !httpBaseUrl.startsWith("https:")) { + rememberCheckedDescriptor: Effect.fnUntraced(function* (httpBaseUrl, descriptor, keepsItsHost) { + if (Option.isNone(descriptor) || !keepsItsHost) { checkedDescriptors.delete(httpBaseUrl); return; } diff --git a/packages/client-runtime/src/connection/driver.ts b/packages/client-runtime/src/connection/driver.ts index db253adea5333..512dba21e2d92 100644 --- a/packages/client-runtime/src/connection/driver.ts +++ b/packages/client-runtime/src/connection/driver.ts @@ -20,6 +20,7 @@ import { connectionRoutes, routeEntry, routeHttpBaseUrl, + routeKeepsItsHost, sendsTokenInClear, usableRoutes, } from "./routes.ts"; @@ -148,7 +149,7 @@ export const make = Effect.gen(function* () { // The descriptor is public, so this sends no credential to whatever // answers at a saved LAN address on a different network. - const checkDescriptor = (httpBaseUrl: string, environmentId: string) => + const checkDescriptor = (httpBaseUrl: string, environmentId: string, keepsItsHost: boolean) => fetchRemoteEnvironmentDescriptor({ httpBaseUrl, timeoutMs: ROUTE_CHECK_TIMEOUT_MS, @@ -156,7 +157,9 @@ export const make = Effect.gen(function* () { Effect.option, // The connect this check leads to skips its own read. Every answer, even a // failure, replaces what an older check remembered. - Effect.tap((descriptor) => remote.rememberCheckedDescriptor(httpBaseUrl, descriptor)), + Effect.tap((descriptor) => + remote.rememberCheckedDescriptor(httpBaseUrl, descriptor, keepsItsHost), + ), Effect.map((descriptor): RouteCheck => Option.exists(descriptor, (value) => value.environmentId === environmentId) ? "answered" @@ -170,7 +173,7 @@ export const make = Effect.gen(function* () { const checkRoute = (entry: ConnectionCatalogEntry, route: ConnectionRoute) => { const httpBaseUrl = routeHttpBaseUrl(route); if (httpBaseUrl === null) return Effect.succeed("unchecked"); - return checkDescriptor(httpBaseUrl, entry.target.environmentId).pipe( + return checkDescriptor(httpBaseUrl, entry.target.environmentId, routeKeepsItsHost(route)).pipe( Effect.withSpan("ConnectionDriver.checkRoute", { attributes: { "connection.target.kind": route.target._tag }, }), @@ -178,7 +181,11 @@ export const make = Effect.gen(function* () { }; const checkHost = (prepared: PreparedConnection) => - checkDescriptor(prepared.httpBaseUrl, prepared.environmentId).pipe( + checkDescriptor( + prepared.httpBaseUrl, + prepared.environmentId, + prepared.httpBaseUrl.startsWith("https:"), + ).pipe( Effect.withSpan("ConnectionDriver.checkHost", { attributes: { "connection.target.kind": prepared.target._tag }, }), diff --git a/packages/client-runtime/src/connection/model.ts b/packages/client-runtime/src/connection/model.ts index 73675d431aa7a..feeb0c25a6909 100644 --- a/packages/client-runtime/src/connection/model.ts +++ b/packages/client-runtime/src/connection/model.ts @@ -1,4 +1,4 @@ -import { EnvironmentId } from "@t3tools/contracts"; +import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts"; import { RelayEnvironmentEndpointFailure } from "@t3tools/contracts/relay"; import * as Schema from "effect/Schema"; @@ -154,6 +154,8 @@ export interface PreparedConnection { readonly socketUrl: string; readonly httpAuthorization: PreparedHttpAuthorization | null; readonly target: ConnectionTarget; + /** What the server said about itself while this connection was prepared. */ + readonly descriptor?: ExecutionEnvironmentDescriptor; } export type SupervisorConnectionPhase = diff --git a/packages/client-runtime/src/connection/resolver.test.ts b/packages/client-runtime/src/connection/resolver.test.ts index 62d43bbbe641a..df59003227e1b 100644 --- a/packages/client-runtime/src/connection/resolver.test.ts +++ b/packages/client-runtime/src/connection/resolver.test.ts @@ -206,6 +206,15 @@ describe("ConnectionResolver", () => { "ws://127.0.0.1:3777/ws?clientSurface=web&clientDeviceType=desktop&connectionMethod=direct&orchestrationProtocol=2&clientCapabilities=settingsSecretReferences", httpAuthorization: null, target, + // The shell reads the server's build and shell flags here before the socket opens. + descriptor: { + environmentId: ENVIRONMENT_ID, + label: "Compatible environment", + platform: { os: "linux", arch: "x64" }, + serverVersion: "0.0.0-test", + orchestrationProtocolVersion: ORCHESTRATION_PROTOCOL_VERSION, + capabilities: { repositoryIdentity: true }, + }, }); }), ); diff --git a/packages/client-runtime/src/connection/resolver.ts b/packages/client-runtime/src/connection/resolver.ts index d3b22143d327a..05235ef53603f 100644 --- a/packages/client-runtime/src/connection/resolver.ts +++ b/packages/client-runtime/src/connection/resolver.ts @@ -321,6 +321,7 @@ export const make = Effect.gen(function* () { } return { ...prepared, + descriptor, socketUrl: appendOrchestrationProtocol(prepared.socketUrl), }; }); diff --git a/packages/client-runtime/src/connection/routes.test.ts b/packages/client-runtime/src/connection/routes.test.ts index da9c631638cc4..e8dd244e043a6 100644 --- a/packages/client-runtime/src/connection/routes.test.ts +++ b/packages/client-runtime/src/connection/routes.test.ts @@ -16,9 +16,11 @@ import { credentialConnectionId, insertRoute, entryWithRoutes, + isNearbyAddress, mergeLearnedRoutes, pendingRouteOrder, removedWithRelay, + routeKeepsItsHost, routesAfterRemoving, sendsTokenInClear, upsertRoute, @@ -77,6 +79,35 @@ describe("connection routes", () => { expect(connectionRouteLabel(RELAY)).toBe("T3 Connect"); }); + it("knows which addresses reach the same machine on every network", () => { + const tailnetIp = direct("ts-ip", "http://100.101.102.103:3773/"); + const profile = Option.getOrThrow(tailnetIp.profile) as BearerConnectionProfile; + const marked = { + target: tailnetIp.target, + profile: Option.some(new BearerConnectionProfile({ ...profile, network: "tailscale" })), + }; + expect(routeKeepsItsHost(PUBLIC)).toBe(true); + expect(routeKeepsItsHost(direct("ts-tls", "https://desk.tail1234.ts.net/"))).toBe(true); + expect(routeKeepsItsHost(direct("lo", "http://127.0.0.1:3773/"))).toBe(true); + // With Tailscale down, a plain http tailnet address can reach another host: + // carrier networks use 100.64.0.0/10 too, and nothing proves who answers. + expect(routeKeepsItsHost(direct("ts", "http://desk.tail1234.ts.net:3773/"))).toBe(false); + expect(routeKeepsItsHost(marked)).toBe(false); + expect(routeKeepsItsHost(tailnetIp)).toBe(false); + expect(routeKeepsItsHost(LAN)).toBe(false); + expect(routeKeepsItsHost(direct("http", "http://desk.example.com/"))).toBe(false); + expect(routeKeepsItsHost(RELAY)).toBe(false); + }); + + it("treats only loopback and LAN addresses as nearby", () => { + expect(isNearbyAddress("http://127.0.0.1:3773/")).toBe(true); + expect(isNearbyAddress("http://192.168.1.10:3773/")).toBe(true); + expect(isNearbyAddress("http://100.101.102.103:3773/")).toBe(false); + expect(isNearbyAddress("https://desk.tail1234.ts.net/")).toBe(false); + expect(isNearbyAddress("https://desk.example.com/")).toBe(false); + expect(isNearbyAddress("not a url")).toBe(false); + }); + it("places a new route after faster kinds and ahead of T3 Connect", () => { expect(insertRoute([RELAY], LAN)).toEqual([LAN, RELAY]); expect(insertRoute([LAN, RELAY], TAILNET)).toEqual([LAN, TAILNET, RELAY]); diff --git a/packages/client-runtime/src/connection/routes.ts b/packages/client-runtime/src/connection/routes.ts index 9d83550a8c4a2..7a3b4a11e616c 100644 --- a/packages/client-runtime/src/connection/routes.ts +++ b/packages/client-runtime/src/connection/routes.ts @@ -81,6 +81,13 @@ function routeHostname(route: ConnectionRoute): string | null { } } +function directAddressKind(hostname: string, tailscale = false) { + if (isLocalLoopbackHost(hostname)) return "loopback"; + if (tailscale || isTailnetHost(hostname)) return "tailnet"; + if (isSharedAddressSpaceHost(hostname)) return "vpn"; + return isPrivateNetworkHost(hostname) ? "lan" : "public"; +} + export function connectionRouteKind(route: ConnectionRoute): ConnectionRouteKind { switch (route.target._tag) { case "RelayConnectionTarget": @@ -91,17 +98,36 @@ export function connectionRouteKind(route: ConnectionRoute): ConnectionRouteKind case "BearerConnectionTarget": { const hostname = routeHostname(route); if (hostname === null) return "public"; - if (isLocalLoopbackHost(hostname)) return "loopback"; const profile = Option.getOrNull(route.profile); - const tailscale = - profile?._tag === "BearerConnectionProfile" && profile.network === "tailscale"; - if (tailscale || isTailnetHost(hostname)) return "tailnet"; - if (isSharedAddressSpaceHost(hostname)) return "vpn"; - return isPrivateNetworkHost(hostname) ? "lan" : "public"; + return directAddressKind( + hostname, + profile?._tag === "BearerConnectionProfile" && profile.network === "tailscale", + ); } } } +/** + * Whether the route's address reaches the same machine on every network: TLS + * proves who answers, and loopback cannot move. Any other plain http address, + * a tailnet one too once Tailscale is down, can belong to another machine after + * a network change, so an answer from it is not kept. + */ +export function routeKeepsItsHost(route: ConnectionRoute): boolean { + if (routeHttpBaseUrl(route)?.startsWith("https:") === true) return true; + return connectionRouteKind(route) === "loopback"; +} + +/** A loopback or LAN host answers within a few seconds or is not there. */ +export function isNearbyAddress(httpBaseUrl: string): boolean { + try { + const kind = directAddressKind(new URL(httpBaseUrl).hostname); + return kind === "loopback" || kind === "lan"; + } catch { + return false; + } +} + const ROUTE_KIND_RANK: Record = { loopback: 0, lan: 1, diff --git a/packages/client-runtime/src/state/environmentHttpAuth.test.ts b/packages/client-runtime/src/state/environmentHttpAuth.test.ts index faac1a87ff6af..3839742694e81 100644 --- a/packages/client-runtime/src/state/environmentHttpAuth.test.ts +++ b/packages/client-runtime/src/state/environmentHttpAuth.test.ts @@ -223,7 +223,11 @@ const LOADERS: ReadonlyArray<{ expected: SHELL, load: (input: HttpInput) => fetchEnvironmentShellSnapshot(input).pipe( - Effect.map(({ loadPullRequests: _links, ...snapshot }) => snapshot), + Effect.map((answer) => { + if ("resumable" in answer) return answer; + const { loadPullRequests: _links, ...snapshot } = answer; + return snapshot; + }), ), }, { diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.ts index 062db03809cfc..2699c8846f7bc 100644 --- a/packages/client-runtime/src/state/shell-sync.test.ts +++ b/packages/client-runtime/src/state/shell-sync.test.ts @@ -1,5 +1,6 @@ import { EnvironmentId, + type ExecutionEnvironmentDescriptor, ORCHESTRATION_V2_WS_METHODS, type OrchestrationV2ShellSnapshot, type OrchestrationV2ShellStreamItem, @@ -1151,8 +1152,27 @@ describe("environment shell cold start", () => { }; const RECENT_ORIGIN = { ...CURRENT_ORIGIN, snapshotAt: NOW - HOUR }; + // A server that names its shell flags in the descriptor, and the matching live config. + const FAMILY_DESCRIPTOR = { + serverVersion: "1.0.0", + capabilities: { shellThreadFamilies: true, shellOlderSettled: true }, + } as ExecutionEnvironmentDescriptor; + const FAMILY_CONFIG = { + shellThreadFamilies: true, + shellOlderSettled: true, + environment: { serverVersion: "1.0.0" }, + }; + const FAMILY_FLAGS = { omitIdleSubagents: true, omitOlderSettled: true }; + const makeColdStart = Effect.fn("test.makeColdStartShell")(function* ( origin: Persistence.ShellCacheOrigin | undefined, + // Set for a connection that is prepared but has no session yet. + // Each held load waits for one `releaseLoads`. An "uninterruptible" hold stands for a load + // that applies its answer, which an interrupt has to wait for. + early?: { + readonly serverResumes: boolean; + readonly holdLoads?: boolean | "uninterruptible"; + }, ) { yield* TestClock.setTime(NOW); const subscriptions = yield* Queue.unbounded<{ @@ -1164,6 +1184,18 @@ describe("environment shell cold start", () => { readonly origin: Persistence.ShellCacheOrigin | undefined; }>(); const httpLoads = yield* Ref.make(0); + const loadOptions = yield* Queue.unbounded(); + const releases = yield* Queue.unbounded(); + const scope = yield* Effect.scope; + const holdLoad = + early?.holdLoads === "uninterruptible" + ? // Registered after the load's fiber, so the end of a failed test does not wait for it. + Scope.addFinalizer(scope, Queue.shutdown(releases)).pipe( + Effect.andThen(Effect.uninterruptible(Queue.take(releases))), + ) + : early?.holdLoads === true + ? Queue.take(releases) + : Effect.void; const client = { [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: unknown) => Stream.unwrap( @@ -1174,12 +1206,17 @@ describe("environment shell cold start", () => { }), ), } as unknown as WsRpcProtocolClient; - const activeSession = yield* SubscriptionRef.make(Option.some(session(client))); + const activeSession = yield* SubscriptionRef.make( + early === undefined ? Option.some(session(client)) : Option.none(), + ); + const prepared = yield* SubscriptionRef.make( + Option.some(early === undefined ? PREPARED : { ...PREPARED, descriptor: FAMILY_DESCRIPTOR }), + ); const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ target: TARGET, state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE), session: activeSession, - prepared: yield* SubscriptionRef.make(Option.some(PREPARED)), + prepared, connect: Effect.void, disconnect: Effect.void, retryNow: Effect.void, @@ -1205,10 +1242,20 @@ describe("environment shell cold start", () => { clear: () => Effect.void, }); const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({ - load: () => - Ref.updateAndGet(httpLoads, (count) => count + 1).pipe( + load: (_prepared, options = {}) => + Queue.offer(loadOptions, options).pipe( + Effect.andThen(holdLoad), + Effect.andThen(Ref.updateAndGet(httpLoads, (count) => count + 1)), Effect.map((count) => - Option.some({ ...v2ShellSnapshot, snapshotSequence: HTTP_SEQUENCE + count - 1 }), + Option.some( + early?.serverResumes === true && options.resumeFrom !== undefined + ? { resumable: true } + : { + ...v2ShellSnapshot, + snapshotSequence: HTTP_SEQUENCE + count - 1, + projectIdentities: `identities-${count}`, + }, + ), ), ), }); @@ -1217,11 +1264,45 @@ describe("environment shell cold start", () => { Effect.provideService(Persistence.EnvironmentCacheStore, cache), Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader), ); + const nextConnection = Effect.suspend(() => + SubscriptionRef.set( + prepared, + Option.some({ ...PREPARED, descriptor: { ...FAMILY_DESCRIPTOR } }), + ), + ); return { + shellState, subscriptions, saved, httpLoads, + loadOptions, + releaseLoads: Queue.offer(releases, undefined), + nextConnection, + // A connection attempt that ended, then the next one. + prepareAgain: SubscriptionRef.set(prepared, Option.none()).pipe( + Effect.andThen(nextConnection), + ), + // Resolves `configRead` when the subscription reads the config, just before it claims the load. + connect: (config: object, configRead?: Deferred.Deferred) => + SubscriptionRef.set( + activeSession, + Option.some({ + ...session(client), + initialConfig: (configRead === undefined + ? Effect.void + : Deferred.succeed(configRead, undefined) + ).pipe(Effect.as(config as never)), + }), + ), reconnect: SubscriptionRef.set(activeSession, Option.some(session(client))), + // The registry swaps a rotated bearer into the prepared connection of a live session. + rotateCredential: SubscriptionRef.update( + prepared, + Option.map((current) => ({ + ...current, + httpAuthorization: { _tag: "Bearer" as const, token: "rotated" }, + })), + ), liveAt: (sequence: number) => SubscriptionRef.changes(shellState).pipe( Stream.filter( @@ -1284,6 +1365,221 @@ describe("environment shell cold start", () => { }), ); + it.effect.each([ + { + label: "no rows to resume", + origin: undefined, + serverResumes: false, + config: FAMILY_CONFIG, + loads: [FAMILY_FLAGS], + subscribes: { afterSequence: HTTP_SEQUENCE, knownProjectIdentities: "identities-1" }, + }, + { + label: "rows the server can replay from", + origin: { ...RECENT_ORIGIN, ...FAMILY_FLAGS }, + serverResumes: true, + config: FAMILY_CONFIG, + loads: [{ ...FAMILY_FLAGS, resumeFrom: CACHED_SEQUENCE }], + subscribes: { afterSequence: CACHED_SEQUENCE, httpSnapshotFallback: true }, + }, + { + label: "rows the server cannot replay from", + origin: { ...RECENT_ORIGIN, ...FAMILY_FLAGS }, + serverResumes: false, + config: FAMILY_CONFIG, + loads: [{ ...FAMILY_FLAGS, resumeFrom: CACHED_SEQUENCE }], + subscribes: { afterSequence: HTTP_SEQUENCE, knownProjectIdentities: "identities-1" }, + }, + { + // The server answered that it can replay, then the rows passed their age limit. + label: "rows that expire before the socket is ready", + origin: { ...RECENT_ORIGIN, ...FAMILY_FLAGS, snapshotAt: NOW - 12 * HOUR + 1 }, + serverResumes: true, + config: FAMILY_CONFIG, + loads: [{ ...FAMILY_FLAGS, resumeFrom: CACHED_SEQUENCE }], + subscribes: {}, + expires: true, + }, + { + // The rows loaded with the descriptor's omissions are replaced, never kept. + label: "a live config with other omissions", + origin: undefined, + serverResumes: false, + config: { environment: { serverVersion: "1.0.0" } }, + loads: [FAMILY_FLAGS, { omitIdleSubagents: false, omitOlderSettled: false }], + subscribes: { afterSequence: HTTP_SEQUENCE + 1, knownProjectIdentities: "identities-2" }, + }, + ])( + "asks for the shell once the connection is prepared, with $label", + ({ origin, serverResumes, config, loads, subscribes, expires }) => + Effect.gen(function* () { + const h = yield* makeColdStart(origin, { serverResumes }); + expect(yield* Queue.take(h.loadOptions)).toEqual(loads[0]); + if (!serverResumes) { + // The rows are on screen before a socket exists, and are not live yet. + const early = yield* SubscriptionRef.changes(h.shellState).pipe( + Stream.filter((state) => + Option.exists( + state.snapshot, + (snapshot) => snapshot.snapshotSequence === HTTP_SEQUENCE, + ), + ), + Stream.runHead, + Effect.map(Option.getOrThrow), + ); + expect(early.status).not.toBe("live"); + expect(early.generation).toBeGreaterThan(0); + } + expect(yield* Queue.size(h.subscriptions)).toBe(0); + + if (expires) yield* TestClock.adjust("1 millis"); + yield* h.connect(config); + const first = yield* Queue.take(h.subscriptions); + expect(first.input).toMatchObject(subscribes); + for (const key of [ + "afterSequence", + "httpSnapshotFallback", + "knownProjectIdentities", + ] as const) { + if (!(key in subscribes)) expect(first.input).not.toHaveProperty(key); + } + expect(yield* Queue.clear(h.loadOptions)).toEqual(loads.slice(1)); + expect(yield* Ref.get(h.httpLoads)).toBe(loads.length); + // The socket sends the full snapshot these rows asked for; the rest needs a cursor. + if (!("afterSequence" in subscribes)) return; + + yield* Queue.offer(first.events, { kind: "synchronized" }); + yield* h.liveAt(subscribes.afterSequence); + if (loads.length > 1) { + yield* TestClock.adjust("500 millis"); + const saves = yield* Queue.takeAll(h.saved); + expect(saves.at(-1)).toMatchObject({ + snapshot: { snapshotSequence: subscribes.afterSequence }, + origin: { ...CURRENT_ORIGIN, snapshotAt: NOW }, + }); + } + + // A rotated credential keeps the session, so its events still apply and nothing reloads. + yield* h.rotateCredential; + yield* Queue.offer(first.events, { + kind: "thread.removed", + sequence: subscribes.afterSequence + 1, + location: "active", + threadId: ThreadId.make("no-such-thread"), + }); + yield* h.liveAt(subscribes.afterSequence + 1); + expect(yield* Ref.get(h.httpLoads)).toBe(loads.length); + }), + ); + + it.effect("a replaced session waits for the load its connection already started", () => + Effect.gen(function* () { + const h = yield* makeColdStart(undefined, { + serverResumes: false, + holdLoads: "uninterruptible", + }); + expect(yield* Queue.take(h.loadOptions)).toEqual(FAMILY_FLAGS); + const claimed = yield* Deferred.make(); + yield* h.connect(FAMILY_CONFIG, claimed); + yield* Deferred.await(claimed); + // Lets the first subscription run on from its config read to its wait for the load. + yield* TestClock.adjust("1 millis"); + // The first subscription waits for the load. A second request could answer first, and + // the older answer would then replace its rows under a cursor the socket has passed. + yield* h.connect(FAMILY_CONFIG); + yield* TestClock.adjust("1 millis"); + expect(yield* Queue.size(h.loadOptions)).toBe(0); + + // The connection changes twice while the first load ends. The next session reads the + // last connection before its load exists, so it replaces the load of the one between. + yield* h.nextConnection; + yield* TestClock.adjust("1 millis"); + yield* h.nextConnection; + yield* h.connect(FAMILY_CONFIG); + yield* TestClock.adjust("1 millis"); + yield* h.releaseLoads; + expect(yield* Queue.take(h.loadOptions)).toEqual(FAMILY_FLAGS); + yield* TestClock.adjust("1 millis"); + // That session is replaced while it waits for the load between to end. The load it then + // starts must stay the one load of the last connection. + yield* h.connect(FAMILY_CONFIG); + yield* TestClock.adjust("1 millis"); + yield* h.releaseLoads; + expect(yield* Queue.take(h.loadOptions)).toEqual(FAMILY_FLAGS); + yield* TestClock.adjust("1 millis"); + expect(yield* Queue.size(h.loadOptions)).toBe(0); + + yield* h.releaseLoads; + const subscribed = yield* Queue.take(h.subscriptions); + expect(subscribed.input).toMatchObject({ afterSequence: HTTP_SEQUENCE }); + expect(yield* Queue.size(h.loadOptions)).toBe(0); + expect(yield* Ref.get(h.httpLoads)).toBe(1); + }), + ); + + it.effect("resumes held rows on the socket when the HTTP answer does not come", () => + Effect.gen(function* () { + const h = yield* makeColdStart( + { ...RECENT_ORIGIN, ...FAMILY_FLAGS }, + { serverResumes: false, holdLoads: true }, + ); + yield* Queue.take(h.loadOptions); + const claimed = yield* Deferred.make(); + yield* h.connect(FAMILY_CONFIG, claimed); + yield* Deferred.await(claimed); + // Lets the subscription run on from its config read to its wait for the load. + yield* TestClock.adjust("1 millis"); + expect(yield* Queue.size(h.subscriptions)).toBe(0); + + yield* TestClock.adjust("3 seconds"); + const first = yield* Queue.take(h.subscriptions); + expect(first.input).toMatchObject({ + afterSequence: CACHED_SEQUENCE, + httpSnapshotFallback: true, + }); + yield* Queue.offer(first.events, { + kind: "thread.removed", + sequence: HTTP_SEQUENCE + 1, + location: "active", + threadId: ThreadId.make("no-such-thread"), + }); + yield* Queue.offer(first.events, { kind: "synchronized" }); + yield* h.liveAt(HTTP_SEQUENCE + 1); + + // The late answer is an older snapshot. It must not replace the rows the socket moved on. + yield* h.releaseLoads; + yield* TestClock.adjust("1 millis"); + expect(yield* Ref.get(h.httpLoads)).toBe(0); + expect(yield* SubscriptionRef.get(h.shellState)).toMatchObject({ + status: "live", + snapshot: Option.some({ snapshotSequence: HTTP_SEQUENCE + 1 }), + }); + }), + ); + + it.effect("drops the load of a connection that ended and waits for the next one", () => + Effect.gen(function* () { + const h = yield* makeColdStart(undefined, { serverResumes: false, holdLoads: true }); + yield* Queue.take(h.loadOptions); + yield* h.prepareAgain; + yield* Queue.take(h.loadOptions); + + // The socket is ready while the second load is in flight. + yield* h.connect(FAMILY_CONFIG); + yield* h.releaseLoads; + const first = yield* Queue.take(h.subscriptions); + expect(first.input).toMatchObject({ + afterSequence: HTTP_SEQUENCE, + knownProjectIdentities: "identities-1", + }); + // The first load ended with its connection and never answered. + expect(yield* Ref.get(h.httpLoads)).toBe(1); + + yield* Queue.offer(first.events, { kind: "synchronized" }); + yield* h.liveAt(HTTP_SEQUENCE); + }), + ); + it.effect("reloads over HTTP when the server answers a resume with snapshot-required", () => Effect.gen(function* () { const h = yield* makeColdStart(RECENT_ORIGIN); diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.ts index 7980800708285..86584c4a03faa 100644 --- a/packages/client-runtime/src/state/shell.ts +++ b/packages/client-runtime/src/state/shell.ts @@ -1,6 +1,7 @@ import { ORCHESTRATION_V2_WS_METHODS, type EnvironmentId, + type ExecutionEnvironmentDescriptor, type OrchestrationV2ShellSnapshot, type OrchestrationV2ShellStreamItem, type OrchestrationV2ThreadShell, @@ -11,6 +12,7 @@ import { import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Option from "effect/Option"; import * as Queue from "effect/Queue"; @@ -18,10 +20,11 @@ import * as Ref from "effect/Ref"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; import * as SubscriptionRef from "effect/SubscriptionRef"; +import * as SynchronizedRef from "effect/SynchronizedRef"; import { AsyncResult, Atom } from "effect/reactivity"; import * as EnvironmentRegistry from "../connection/registry.ts"; -import { connectionProjectionPhase } from "../connection/model.ts"; +import { connectionProjectionPhase, type PreparedConnection } from "../connection/model.ts"; import * as EnvironmentSupervisor from "../connection/supervisor.ts"; import * as ConnectionWakeups from "../connection/wakeups.ts"; import { safeErrorLogAttributes } from "../errors/safeLog.ts"; @@ -89,6 +92,11 @@ const SHELL_SYNCHRONIZATION_ERROR_MESSAGE = "Could not synchronize environment d */ const CACHE_RESUME_MAX_AGE_MILLIS = 12 * 60 * 60 * 1000; +// How long a ready socket waits for the early HTTP answer before it resumes held rows itself. +// The supervisor's quick probe allows a live host the same time. A proxy that drops `/api` +// without an answer would otherwise hold each connect for the full HTTP timeout. +const EARLY_LOAD_GRACE = "3 seconds"; + type ShellOriginIdentity = Omit; interface ShellSubscription { @@ -97,6 +105,42 @@ interface ShellSubscription { readonly identity: ShellOriginIdentity | null; } +function shellIdentity( + environment: Pick, + flags: { readonly shellThreadFamilies?: boolean; readonly shellOlderSettled?: boolean }, +): ShellOriginIdentity { + const omitIdleSubagents = flags.shellThreadFamilies === true; + return { + serverVersion: environment.serverVersion, + // Migrations rewrite projections without events, so a migrated server reloads. + databaseMigration: environment.databaseMigration ?? null, + omitIdleSubagents, + omitOlderSettled: flags.shellOlderSettled === true && omitIdleSubagents, + }; +} + +function sameConnection(left: PreparedConnection, right: PreparedConnection): boolean { + const keys = Object.keys({ ...left, ...right }) as Array; + return keys.every((key) => key === "httpAuthorization" || left[key] === right[key]); +} + +/** Null for a server whose descriptor does not name its shell flags; only its config does. */ +function descriptorShellIdentity( + descriptor: ExecutionEnvironmentDescriptor | undefined, +): ShellOriginIdentity | null { + if (descriptor?.capabilities.shellThreadFamilies === undefined) return null; + return shellIdentity(descriptor, descriptor.capabilities); +} + +function sameShellIdentity(left: ShellOriginIdentity, right: ShellOriginIdentity): boolean { + return ( + left.serverVersion === right.serverVersion && + left.databaseMigration === right.databaseMigration && + left.omitIdleSubagents === right.omitIdleSubagents && + left.omitOlderSettled === right.omitOlderSettled + ); +} + function canResumeFrom( origin: Persistence.ShellCacheOrigin | undefined, identity: ShellOriginIdentity | null, @@ -104,14 +148,21 @@ function canResumeFrom( ): boolean { if (origin === undefined || identity === null) return false; const age = now - origin.snapshotAt; - return ( - origin.serverVersion === identity.serverVersion && - origin.databaseMigration === identity.databaseMigration && - origin.omitIdleSubagents === identity.omitIdleSubagents && - origin.omitOlderSettled === identity.omitOlderSettled && - age >= 0 && - age < CACHE_RESUME_MAX_AGE_MILLIS - ); + return sameShellIdentity(origin, identity) && age >= 0 && age < CACHE_RESUME_MAX_AGE_MILLIS; +} + +type HttpShellOutcome = + | { readonly kind: "snapshot"; readonly projectIdentities: string | undefined } + /** The server can replay from the rows the client holds. */ + | { readonly kind: "resumable" } + | { readonly kind: "failed" }; + +interface EarlyShellLoad { + readonly prepared: PreparedConnection; + readonly identity: ShellOriginIdentity; + readonly fiber: Fiber.Fiber; + // One subscription uses a load; a later one on the same connection decides again. + readonly claimed: boolean; } interface LiveShell { @@ -249,17 +300,17 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") // time, so neither can overwrite what the other wrote in between. const snapshotWriteLock = yield* Semaphore.make(1); - const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* ( - entries: ReadonlyArray, + const applyLocked = Effect.fnUntraced(function* ( + items: ReadonlyArray, + /** What an authoritative snapshot among the items descends from. */ + identity: ShellOriginIdentity | null, + /** Set for an HTTP snapshot: the rows that still wait for their pull request links. */ pendingLinkIds?: ReadonlySet, ) { - // Read under the lock: items buffered across a session change must not land on the - // rows the next session loaded. - const subscription = yield* Ref.get(activeSubscription); - const items = entries.flatMap(([session, item]) => - session === subscription?.session ? [item] : [], - ); const initial = yield* SubscriptionRef.get(state); + // No socket has confirmed an HTTP snapshot, so it never makes the shell live. + const fromHttp = pendingLinkIds !== undefined; + const disconnected = initial.status === "empty" || initial.status === "cached"; let waiting = yield* Ref.get(awaitingCompletion); let next = initial; let receivedAuthoritativeSnapshot = false; @@ -330,7 +381,8 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") if (authoritative) receivedAuthoritativeSnapshot = true; next = { snapshot: Option.some(nextSnapshot), - status: waiting ? "synchronizing" : "live", + status: + fromHttp && disconnected ? "cached" : waiting || fromHttp ? "synchronizing" : "live", error: Option.none(), generation: authoritative ? ++lastShellGeneration : next.generation, removedAt: authoritative ? EMPTY_REMOVALS : next.removedAt, @@ -347,9 +399,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") yield* Queue.offer(reloadRequests, undefined); } else if (receivedAuthoritativeSnapshot) { nextOrigin = - subscription?.identity == null - ? undefined - : { ...subscription.identity, snapshotAt: yield* Clock.currentTimeMillis }; + identity === null ? undefined : { ...identity, snapshotAt: yield* Clock.currentTimeMillis }; yield* Ref.set(origin, nextOrigin); } if (next === initial) return; @@ -368,6 +418,18 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") if (next.snapshot !== initial.snapshot && Option.isSome(next.snapshot)) { yield* Queue.offer(persistence, next.snapshot.value); } + }); + + const applyItems = Effect.fn("EnvironmentShellState.applyItems")(function* ( + entries: ReadonlyArray, + ) { + // Read under the lock: items buffered across a session change must not land on the + // rows the next session loaded. + const subscription = yield* Ref.get(activeSubscription); + yield* applyLocked( + entries.flatMap(([session, item]) => (session === subscription?.session ? [item] : [])), + subscription?.identity ?? null, + ); }, snapshotWriteLock.withPermit); const stateScope = yield* Effect.scope; @@ -437,6 +499,120 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") yield* fillDeferredPullRequests(cached.value, cachedSnapshot.value); } + const applyHttpSnapshot = Effect.fnUntraced(function* ( + loaded: ShellSnapshotLoader.ShellHttpSnapshot, + identity: ShellOriginIdentity | null, + ) { + const { projectIdentities: _identities, ...deferred } = loaded; + yield* cancelActiveFill; + const previous = yield* SubscriptionRef.get(state); + const snapshot = reuseUnchangedThreadShells( + Option.getOrNull(previous.snapshot), + withoutDeferredPullRequests(deferred), + ); + const pendingLinkIds = new Set( + deferred.loadPullRequests === undefined ? [] : deferred.threads.map((thread) => thread.id), + ); + yield* snapshotWriteLock.withPermit( + applyLocked([{ kind: "snapshot", snapshot }], identity, pendingLinkIds), + ); + const current = yield* SubscriptionRef.get(state); + if (Option.isSome(current.snapshot)) { + yield* fillDeferredPullRequests(deferred, current.snapshot.value); + } + }, Effect.uninterruptible); + + /** + * One request to the HTTP shell route. Held rows that may resume are named, so the server + * answers that they still can, in a few bytes, or sends the snapshot that replaces them. + */ + const loadOverHttp = Effect.fn("EnvironmentShellState.loadOverHttp")(function* ( + prepared: PreparedConnection, + identity: ShellOriginIdentity | null, + ) { + const held = yield* SubscriptionRef.get(state); + const resumeFrom = + Option.isSome(held.snapshot) && + canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis) + ? held.snapshot.value.snapshotSequence + : undefined; + // HTTP and the socket must agree, or omitted children would return through the socket. + const answer = yield* snapshotLoader.load(prepared, { + omitIdleSubagents: identity?.omitIdleSubagents === true, + omitOlderSettled: identity?.omitOlderSettled === true, + ...(resumeFrom === undefined ? {} : { resumeFrom }), + }); + if (Option.isNone(answer)) return { kind: "failed" } satisfies HttpShellOutcome; + if ("resumable" in answer.value) return { kind: "resumable" } satisfies HttpShellOutcome; + yield* applyHttpSnapshot(answer.value, identity); + return { + kind: "snapshot", + projectIdentities: answer.value.projectIdentities, + } satisfies HttpShellOutcome; + }); + + // A server whose descriptor names its shell flags is asked for the shell as soon as the + // connection is prepared, while the socket opens and the config downloads. The subscription + // claims that load, and reloads when the live config disagrees with the descriptor. + const earlyLoad = yield* SynchronizedRef.make(null); + const useEarlyLoad = (prepared: PreparedConnection | null, claim: boolean) => + SynchronizedRef.modifyEffect( + earlyLoad, + Effect.fnUntraced(function* (current) { + // A rotated credential replaces the prepared connection of a session that stays up. + if (current !== null && prepared !== null && sameConnection(current.prepared, prepared)) { + const next = { ...current, prepared, claimed: current.claimed || claim }; + // A claimed load that still runs is handed out again. A second request could + // answer first, and this one would then replace its rows under a passed cursor. + const done = current.fiber.pollUnsafe() !== undefined; + return [current.claimed && done ? null : current, next] as const; + } + if (current !== null) yield* Fiber.interrupt(current.fiber); + const identity = descriptorShellIdentity(prepared?.descriptor); + if (prepared === null || identity === null) return [null, null] as const; + // Items a closed session still has in flight must not land on the rows this loads. + yield* Ref.set(activeSubscription, null); + const fiber = yield* loadOverHttp(prepared, identity).pipe(Effect.forkIn(stateScope)); + const next: EarlyShellLoad = { prepared, identity, fiber, claimed: claim }; + return [next, next] as const; + }), + ).pipe( + // Covers the store too. A cancel that lands during the wait above would otherwise take + // effect before the store, and the load just started would run on with no record. + Effect.uninterruptible, + ); + /** + * The subscription waits for the early load, so its answer is applied before the socket + * moves the rows on. Held rows that can resume wait a limited time only: after that the + * load is ended, so a late answer applies nothing, and the socket resumes them. + */ + const awaitEarlyLoad = Effect.fnUntraced(function* ( + early: EarlyShellLoad, + identity: ShellOriginIdentity | null, + ) { + const resumable = + Option.isSome((yield* SubscriptionRef.get(state)).snapshot) && + canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis); + if (!resumable) return yield* Fiber.await(early.fiber); + const answered = yield* Fiber.await(early.fiber).pipe(Effect.timeoutOption(EARLY_LOAD_GRACE)); + if (Option.isSome(answered)) return answered.value; + // Returns after an answer that is being applied has finished, so the cursor below is read + // from rows that no longer change under it. + yield* Fiber.interrupt(early.fiber); + return yield* Fiber.await(early.fiber); + }); + + yield* SubscriptionRef.changes(supervisor.prepared).pipe( + // Reads the connection of this moment: a change handled late must not start a load for a + // connection that ended, which would also drop the items of the session that replaced it. + Stream.runForEach(() => + SubscriptionRef.get(supervisor.prepared).pipe( + Effect.flatMap((prepared) => useEarlyLoad(Option.getOrNull(prepared), false)), + ), + ), + Effect.forkScoped, + ); + const resubscriptions = Stream.merge( Stream.fromQueue(reloadRequests), Option.match(wakeups, { @@ -452,37 +628,41 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") ORCHESTRATION_V2_WS_METHODS.subscribeShell, Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) { const identity = yield* session.initialConfig.pipe( - Effect.map((config): ShellOriginIdentity => { - const omitIdleSubagents = config.shellThreadFamilies === true; - return { - serverVersion: config.environment.serverVersion, - // Migrations rewrite projections without events, so a migrated server reloads. - databaseMigration: config.environment.databaseMigration ?? null, - omitIdleSubagents, - omitOlderSettled: config.shellOlderSettled === true && omitIdleSubagents, - }; - }), + Effect.map((config) => shellIdentity(config.environment, config)), Effect.orElseSucceed(() => null), ); const { omitIdleSubagents, omitOlderSettled } = identity ?? { omitIdleSubagents: false, omitOlderSettled: false, }; + const early = yield* useEarlyLoad( + Option.getOrNull(yield* SubscriptionRef.get(supervisor.prepared)), + true, + ); + const earlyExit = early === null ? null : yield* awaitEarlyLoad(early, identity); + // Rows the descriptor's flags or build loaded are not kept when the live config differs: + // their origin then cannot resume, so the load below replaces them. + let loaded = + early !== null && + earlyExit !== null && + Exit.isSuccess(earlyExit) && + identity !== null && + sameShellIdentity(early.identity, identity) + ? earlyExit.value + : null; yield* Ref.set(activeSubscription, { session, identity }); yield* Ref.set(awaitingCompletion, true); yield* setSynchronizing; // Rows from a recent server snapshot with the same omissions and server build resume // from their cursor, in memory or from the cache. Anything else reloads the HTTP - // snapshot so a valid cursor cannot preserve stale or incomplete data. - let current = yield* SubscriptionRef.get(state); - let canResume = - Option.isSome(current.snapshot) && + // snapshot so a valid cursor cannot preserve stale or incomplete data. A `resumable` + // answer is checked again too: the rows can pass their age limit while the socket opens. + const resumingHeldRows = + loaded?.kind !== "snapshot" && + Option.isSome((yield* SubscriptionRef.get(state)).snapshot) && canResumeFrom(yield* Ref.get(origin), identity, yield* Clock.currentTimeMillis); - // Only rows the client already held may be refused; a cursor from the snapshot just - // loaded falls back to the socket snapshot, so a refusal cannot loop. - const resumingHeldRows = canResume; - if (!canResume) { + if (!resumingHeldRows && loaded === null) { const prepared = yield* SubscriptionRef.get(supervisor.prepared).pipe( Effect.flatMap( Option.match({ @@ -497,42 +677,26 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make") }), ), ); - // HTTP and the socket must agree, or omitted children would return through the socket. - const httpSnapshot = yield* snapshotLoader.load(prepared, { - omitIdleSubagents, - omitOlderSettled, - }); - if (Option.isSome(httpSnapshot)) { - yield* cancelActiveFill; - const previous = yield* SubscriptionRef.get(state); - const snapshot = reuseUnchangedThreadShells( - Option.getOrNull(previous.snapshot), - withoutDeferredPullRequests(httpSnapshot.value), - ); - const pendingLinkIds = new Set( - httpSnapshot.value.loadPullRequests === undefined - ? [] - : httpSnapshot.value.threads.map((thread) => thread.id), - ); - yield* applyItems([[session, { kind: "snapshot", snapshot }]], pendingLinkIds); - canResume = true; - current = yield* SubscriptionRef.get(state); - if (Option.isSome(current.snapshot)) { - yield* fillDeferredPullRequests(httpSnapshot.value, current.snapshot.value); - } - } + loaded = yield* loadOverHttp(prepared, identity); } + const current = yield* SubscriptionRef.get(state); const omission = { ...(omitIdleSubagents ? { omitIdleSubagents: true as const } : {}), ...(omitOlderSettled ? { omitOlderSettled: true as const } : {}), }; - if (!canResume || Option.isNone(current.snapshot)) { + if (Option.isNone(current.snapshot) || !(resumingHeldRows || loaded?.kind === "snapshot")) { return { ...omission, requestCompletionMarker: true as const }; } return { afterSequence: current.snapshot.value.snapshotSequence, + // Only rows the client already held may be refused; a cursor from the snapshot just + // loaded falls back to the socket snapshot, so a refusal cannot loop. ...(resumingHeldRows ? { httpSnapshotFallback: true as const } : {}), + // No stream item has touched the snapshot just loaded, so its identities still hold. + ...(loaded?.kind === "snapshot" && loaded.projectIdentities !== undefined + ? { knownProjectIdentities: loaded.projectIdentities } + : {}), ...omission, requestCompletionMarker: true as const, }; diff --git a/packages/client-runtime/src/state/shellSnapshotHttp.ts b/packages/client-runtime/src/state/shellSnapshotHttp.ts index 9ff944ad6b2fe..e98846a0e3c73 100644 --- a/packages/client-runtime/src/state/shellSnapshotHttp.ts +++ b/packages/client-runtime/src/state/shellSnapshotHttp.ts @@ -1,9 +1,10 @@ -import { EnvironmentHttpCommonError } from "@t3tools/contracts"; +import { EnvironmentHttpCommonError, OrchestrationV2ShellResumable } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Predicate from "effect/Predicate"; import * as Schema from "effect/Schema"; import { HttpClient, HttpClientError, type HttpClientResponse } from "effect/http"; @@ -19,6 +20,20 @@ import { type DeferredShellSnapshot, } from "./shellPullRequests.ts"; +export interface ShellSnapshotOptions { + readonly omitIdleSubagents?: boolean; + readonly omitOlderSettled?: boolean; + /** The cursor of held rows loaded with these omissions; the server may answer `resumable`. */ + readonly resumeFrom?: number; +} + +/** `projectIdentities` names the repository identities the snapshot carried. */ +export interface ShellHttpSnapshot extends DeferredShellSnapshot { + readonly projectIdentities?: string; +} + +export type ShellHttpAnswer = ShellHttpSnapshot | OrchestrationV2ShellResumable; + // On timeout the socket asks the same server for the same full snapshot, so a // short deadline only throws the first build away. The socket fallback is for // setups where /api fails but /ws works, such as a proxy that blocks /api. @@ -26,20 +41,21 @@ const DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS = 20_000; export const fetchEnvironmentShellSnapshot = Effect.fn( "clientRuntime.state.fetchEnvironmentShellSnapshot", -)(function* (input: { - readonly prepared: PreparedConnection; - readonly signer: Option.Option; - readonly remoteAuthorization?: Option.Option< - RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"] - >; - readonly timeoutMs?: number; - readonly omitIdleSubagents?: boolean; - readonly omitOlderSettled?: boolean; -}) { +)(function* ( + input: { + readonly prepared: PreparedConnection; + readonly signer: Option.Option; + readonly remoteAuthorization?: Option.Option< + RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"] + >; + readonly timeoutMs?: number; + } & ShellSnapshotOptions, +) { const endpoint = { query: { ...(input.omitIdleSubagents === true ? { omitIdleSubagents: "1" } : {}), ...(input.omitOlderSettled === true ? { omitOlderSettled: "1" } : {}), + ...(input.resumeFrom === undefined ? {} : { resumeFrom: String(input.resumeFrom) }), }, }; return yield* executeAuthenticatedEnvironmentHttpRequest({ @@ -63,14 +79,29 @@ const decodeEnvironmentHttpCommonError = Schema.decodeUnknownEffect( Schema.toCodecJson(EnvironmentHttpCommonError), ); +const isShellResumable = Schema.is(OrchestrationV2ShellResumable); + const decodeShellSnapshotResponse = ( response: HttpClientResponse.HttpClientResponse, ): Effect.Effect< - DeferredShellSnapshot, + ShellHttpAnswer, HttpClientError.HttpClientError | Schema.SchemaError | EnvironmentHttpCommonError > => { if (response.status === 200) { - return response.json.pipe(Effect.flatMap(decodeShellSnapshotDeferringPullRequests)); + return response.json.pipe( + Effect.flatMap((json): Effect.Effect => { + if (isShellResumable(json)) return Effect.succeed(json); + const projectIdentities = + Predicate.isObject(json) && typeof json.projectIdentities === "string" + ? json.projectIdentities + : undefined; + return decodeShellSnapshotDeferringPullRequests(json).pipe( + Effect.map((snapshot) => + projectIdentities === undefined ? snapshot : { ...snapshot, projectIdentities }, + ), + ); + }), + ); } const statusError = new HttpClientError.HttpClientError({ reason: new HttpClientError.StatusCodeError({ request: response.request, response }), @@ -89,8 +120,8 @@ export class ShellSnapshotLoader extends Context.Service< { readonly load: ( prepared: PreparedConnection, - options?: { readonly omitIdleSubagents?: boolean; readonly omitOlderSettled?: boolean }, - ) => Effect.Effect>; + options?: ShellSnapshotOptions, + ) => Effect.Effect>; } >()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {} @@ -110,17 +141,16 @@ export const layer: Layer.Layer), + Effect.map(Option.some), Effect.provideService(HttpClient.HttpClient, httpClient), Effect.catchCause((cause) => Effect.logWarning( "Could not load the environment shell snapshot over HTTP; using the socket snapshot instead.", ).pipe( Effect.annotateLogs({ cause: Cause.pretty(cause) }), - Effect.as(Option.none()), + Effect.as(Option.none()), ), ), ); diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 5e9cca70752b6..45a8e7119b1e3 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -184,6 +184,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ /** Server can transcribe 16 kHz mono PCM audio on the environment machine. */ voiceTranscription: Schema.optionalKey(Schema.Boolean), cloudVoiceTranscription: Schema.optionalKey(Schema.Boolean), + /** + * The server config's flags of the same names. A server that names them here lets a client + * load the shell snapshot before the socket opens, and answers its `resumeFrom`. + */ + shellThreadFamilies: Schema.optionalKey(Schema.Boolean), + shellOlderSettled: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.ts index b9a2cacf6e7ce..a9c635486db7d 100644 --- a/packages/contracts/src/environmentHttp.ts +++ b/packages/contracts/src/environmentHttp.ts @@ -67,7 +67,8 @@ import { } from "./speech.ts"; import { SecretReference } from "./secretReference.ts"; import { - OrchestrationV2ShellSnapshot, + OrchestrationV2ShellHttpSnapshot, + OrchestrationV2ShellResumable, OrchestrationV2ThreadBoundedSnapshot, OrchestrationV2ThreadDetailSnapshot, OrchestrationV2ThreadHistoryPage, @@ -685,6 +686,11 @@ const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({ export const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({ omitIdleSubagents: Schema.optionalKey(Schema.String), omitOlderSettled: Schema.optionalKey(Schema.String), + /** + * The cursor of rows the client holds, loaded with the same omissions. The server answers + * `resumable` instead of a snapshot when the socket can replay from it. + */ + resumeFrom: Schema.optionalKey(Schema.String), }); export const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({ @@ -714,7 +720,7 @@ class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration") HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", { headers: OrchestrationProtocolHeaders, query: EnvironmentOrchestrationShellSnapshotQuery, - success: OrchestrationV2ShellSnapshot, + success: [OrchestrationV2ShellHttpSnapshot, OrchestrationV2ShellResumable], error: EnvironmentOrchestrationSnapshotErrors, }).middleware(EnvironmentAuthenticatedAuth), ) diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 7232eb2eb2b53..1fb918956933f 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2292,6 +2292,22 @@ export const OrchestrationV2ShellSnapshot = Schema.Struct({ }); export type OrchestrationV2ShellSnapshot = typeof OrchestrationV2ShellSnapshot.Type; +/** The HTTP shell snapshot. `projectIdentities` names its repository identities; see `knownProjectIdentities`. */ +export const OrchestrationV2ShellHttpSnapshot = Schema.Struct({ + ...OrchestrationV2ShellSnapshot.fields, + projectIdentities: Schema.optionalKey(Schema.String), +}); +export type OrchestrationV2ShellHttpSnapshot = typeof OrchestrationV2ShellHttpSnapshot.Type; + +/** + * The HTTP shell route's answer to `resumeFrom` when the socket can replay from that cursor: + * the client keeps its rows and subscribes from the cursor. + */ +export const OrchestrationV2ShellResumable = Schema.Struct({ + resumable: Schema.Literal(true), +}); +export type OrchestrationV2ShellResumable = typeof OrchestrationV2ShellResumable.Type; + export const OrchestrationV2ShellStreamItem = Schema.Union([ Schema.Struct({ kind: Schema.Literal("synchronized"), @@ -3792,6 +3808,11 @@ export const OrchestrationV2SubscribeShellInput = Schema.Struct({ * a socket snapshot, which clients without transport compression download over gzip HTTP. */ httpSnapshotFallback: Schema.optionalKey(Schema.Literal(true)), + /** + * The `projectIdentities` of the HTTP snapshot whose cursor is `afterSequence`, when the client + * changed nothing since. A resume that still has the same identities does not resend them. + */ + knownProjectIdentities: Schema.optionalKey(Schema.String), requestCompletionMarker: Schema.optionalKey(Schema.Boolean), /** * Snapshots leave out idle subagent children; read them with `getThreadFamily`. Send only to From 4fd40e1a16e3800418b8f6a32932b68179098c8d Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 07:13:55 -0800 Subject: [PATCH 16/56] perf(server): Load earlier turns takes about half the time on a running long thread (#35224) Co-Authored-By: Claude Fable 5.2 --- .../orchestration-v2/ProjectionStore.test.ts | 95 ++++++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 114 +++++++++++++----- .../orchestration-v2/threadHistoryPaging.ts | 2 +- 3 files changed, 177 insertions(+), 34 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index ebafef4bc5621..3f48cbf247fc7 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -4205,6 +4205,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { window.projection.visibleTurnItems.find((row) => row.item.deferredWork)?.item.ordinal, 3, ); + const pageRead = traceSqlStatements(); const page = yield* historyPage( threadId, encodeThreadHistoryCursor({ @@ -4216,12 +4217,100 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { undefined, false, "deferred", - ); + ).pipe(Effect.withTracer(pageRead.tracer)); assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); + // Tool payloads hold megabytes, so a page looks for inline output only in its own runs. + 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')"); } - 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`; + // 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:4", + position, + }), + undefined, + false, + "deferred", + ); + 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 IN (2, 4, 720)`; for (const [ordinal, status] of [ [0, "completed"], [1, "superseded"], diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 101521c7e1064..4ccb6bbf85ad8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -103,7 +103,9 @@ import { THREAD_HISTORY_MAX_RAW_TURNS, missingInterruptRequests, DEFERRED_WORK_ITEM_TYPES, + decodeThreadHistoryCursor, deferWorkHistoryRows, + findCursorEndIndex, selectDeferredWorkPage, encodeThreadHistoryCursor, olderHistoryPagePolicy, @@ -1131,7 +1133,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))); @@ -6280,11 +6282,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; @@ -6297,21 +6299,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 @@ -6335,7 +6333,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) }), @@ -6358,7 +6355,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 = []; @@ -6429,14 +6426,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 @@ -6478,32 +6475,89 @@ export const layer: Layer.Layer = 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 = + const { olderPolicy, cursorPosition } = yield* Effect.try({ + try: () => ({ + olderPolicy: olderHistoryPagePolicy({ items: indexed, cursor, throughEntryId }), + // The cursor's own row, or the row its stale position falls back to. + cursorPosition: Math.min( + findCursorEndIndex(indexed, decodeThreadHistoryCursor(cursor)), + indexed.length - 1, + ), + }), + catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), + }); + const selectPage = (rows: typeof indexed) => + Effect.try({ + try: () => workMode === "work" ? selectDeferredWorkPage({ - items: indexed, + items: rows, cursor, throughEntryId, snapshotSequence, rowEncodedBytes: () => 0, }) : selectHistoryPageFromCursor({ - items: historyItems, + items: workMode === "deferred" ? deferWorkHistoryRows(rows) : rows, cursor, snapshotSequence, rowEncodedBytes: () => 0, - policy, - }); - return { policy, page }; - }, - catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), - }); - const { page } = selection; - const policy = workMode === "work" ? THREAD_HISTORY_PAGE_POLICY : selection.policy; + policy: olderPolicy, + }), + catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), + }); + let page = yield* selectPage(indexed); + // Inline output is found by scanning 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(); + while (workMode !== undefined) { + // Rows hidden in a work group move the page, so the scan always reaches the cursor. + 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}`); + page = yield* selectPage( + indexed.map((row) => + persistentOutputs.has(`${row.sourceThreadId}:${row.sourceItemId}`) + ? { ...row, item: { ...row.item, persistentOutput: true } } + : row, + ), + ); + } + const policy = workMode === "work" ? THREAD_HISTORY_PAGE_POLICY : olderPolicy; const end = (page.items.at(-1)?.canonicalPosition ?? -1) + 1; const hasUserTurns = index.visible .slice(0, end) diff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.ts index 37b653c451fce..b79038a77a803 100644 --- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts +++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts @@ -394,7 +394,7 @@ export function selectRecentTimelineWindow(input: { }); } -function findCursorEndIndex( +export function findCursorEndIndex( items: ReadonlyArray, cursor: ThreadHistoryCursorPayload, ): number { From fd8e386f7f259070899553e55c99a2a49a378480 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 08:27:43 -0800 Subject: [PATCH 17/56] fix(mobile): the thread list shows server changes after a tab round trip (#35325) Co-Authored-By: Claude Fable 5.2 --- apps/mobile/src/Stack.tsx | 6 +- .../home/home-route-visibility.test.tsx | 62 ++++++++++++++++++- .../features/home/home-route-visibility.ts | 16 ++++- 3 files changed, 75 insertions(+), 9 deletions(-) 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/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(); From 2b4a9c744ec669cbbd31c083819d11d5d3358785 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 08:38:27 -0800 Subject: [PATCH 18/56] test(web): inline confirm tests no longer race the 3s disarm timer (#35361) Co-authored-by: Claude Fable 5.2 --- .../pullRequest/useInlineActionConfirm.browser.test.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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(); From 69dd4d08ea5a977a1cfb77abd5e92b99b7ea7a82 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 08:38:51 -0800 Subject: [PATCH 19/56] test(web): Add Environment dialog test fills fields instead of typing each key (#35360) Co-authored-by: Claude Fable 5.2 --- .../settings/AddEnvironmentDialog.browser.test.tsx | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) 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" }), ); From 4e48d9e6a5aba8d0184ac2c953598086ed034c29 Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 08:39:08 -0800 Subject: [PATCH 20/56] test(web): HTML preview accordion test waits for the frame's script before it toggles (#35359) Co-authored-by: Claude Fable 5.2 --- .../chat/MessagesTimeline.browser.test.tsx | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) 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", "*"); From 7c22095fcc7ad6b9324da9730960c38c5af53e90 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 08:51:48 -0800 Subject: [PATCH 21/56] fix(client-runtime): a stalled sign-in token or dead route no longer holds a reconnect for 40 seconds (#34623) Co-authored-by: Claude Fable 5.2 --- .../client-runtime/src/connection/driver.ts | 14 +++--- .../src/connection/supervisor.test.ts | 30 +++++++++++++ .../src/relay/managedRelayState.test.ts | 37 ++++++++++++++++ .../src/relay/managedRelayState.ts | 44 +++++++++++++------ 4 files changed, 105 insertions(+), 20 deletions(-) diff --git a/packages/client-runtime/src/connection/driver.ts b/packages/client-runtime/src/connection/driver.ts index 512dba21e2d92..416ca526db7a7 100644 --- a/packages/client-runtime/src/connection/driver.ts +++ b/packages/client-runtime/src/connection/driver.ts @@ -116,16 +116,16 @@ export const connectOverRoutes = Effect.fn("ConnectionDriver.connectOverRoutes") // An incompatible server is the same server on every route. if (result.failure.reason === "unsupported") return yield* result.failure; } - // A slow route that answered after the head start goes before one that is - // still dead, which can hold an attempt open far longer than its probe. const late = yield* Effect.forEach(silent, ({ index }) => Fiber.join(checks[index]!), { concurrency: "unbounded", }); - const retry = [ - ...silent.filter((_, position) => late[position] !== "silent"), - ...silent.filter((_, position) => late[position] === "silent"), - ]; - for (const { route } of retry) { + const answeredLate = silent.filter((_, position) => late[position] !== "silent"); + const stillSilent = silent.filter((_, position) => late[position] === "silent"); + for (const { route } of [...answeredLate, ...stillSilent]) { + // A route still silent after its whole check can hold the attempt open far + // longer than the check did. Once another route failed in a way that + // retries, the retry reaches it sooner than waiting here would. + if (transient !== undefined && stillSilent.some((entry) => entry.route === route)) break; const result = yield* attempt(route); if (result._tag === "Success") return result.success; if (result.failure.reason === "unsupported") return yield* result.failure; diff --git a/packages/client-runtime/src/connection/supervisor.test.ts b/packages/client-runtime/src/connection/supervisor.test.ts index 163075a6efa7f..8d23348fead94 100644 --- a/packages/client-runtime/src/connection/supervisor.test.ts +++ b/packages/client-runtime/src/connection/supervisor.test.ts @@ -1871,6 +1871,36 @@ describe("EnvironmentSupervisor routes", () => { }).pipe(Effect.provide(TestClock.layer())), ); + it.effect("retries instead of waiting on a LAN route that stayed silent after relay failed", () => + Effect.gen(function* () { + const checkingLan = yield* Deferred.make(); + const attempted: string[] = []; + const harness = yield* makeHarness({ + checkRoute: (route) => + route.target._tag === "BearerConnectionTarget" + ? Deferred.succeed(checkingLan, undefined).pipe( + Effect.andThen(Effect.sleep("2500 millis")), + Effect.as("silent" as const), + ) + : Effect.succeed("unchecked"), + prepare: (_attempt, target) => { + attempted.push(target._tag); + return target._tag === "RelayConnectionTarget" + ? Effect.fail(transient("Relay socket closed.")) + : Effect.never; + }, + }); + const supervisor = yield* EnvironmentSupervisor.make(LAN_THEN_RELAY_ENTRY, { + initiallyDesired: true, + }).pipe(Effect.provide(harness.dependencies)); + + yield* Deferred.await(checkingLan); + yield* TestClock.adjust("2500 millis"); + yield* awaitState(supervisor.state, (state) => state.phase === "backoff"); + expect(attempted).toEqual(["RelayConnectionTarget"]); + }).pipe(Effect.provide(TestClock.layer())), + ); + it.effect("skips a silent LAN route and connects over T3 Connect", () => Effect.gen(function* () { const harness = yield* makeHarness({ diff --git a/packages/client-runtime/src/relay/managedRelayState.test.ts b/packages/client-runtime/src/relay/managedRelayState.test.ts index 6b91a2213bbe7..41d7327ac14e4 100644 --- a/packages/client-runtime/src/relay/managedRelayState.test.ts +++ b/packages/client-runtime/src/relay/managedRelayState.test.ts @@ -8,6 +8,7 @@ import * as Effect from "effect/Effect"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Logger from "effect/Logger"; +import * as TestClock from "effect/testing/TestClock"; import { Atom, AtomRegistry } from "effect/reactivity"; import { afterEach, vi } from "vite-plus/test"; @@ -191,6 +192,42 @@ describe("createManagedRelayQueryManager", () => { }), ); + it.effect("replaces a Clerk token read that has not answered after 4 seconds", () => + Effect.gen(function* () { + const token = clerkToken(4_102_444_800); + const readClerkToken = vi + .fn<() => Promise>() + .mockReturnValueOnce(new Promise(() => {})) + .mockResolvedValue(token); + const session = createManagedRelaySession({ accountId: "account-1", readClerkToken }); + + const readsFiber = yield* Effect.all([session.readClerkToken(), session.readClerkToken()], { + concurrency: "unbounded", + }).pipe(Effect.forkChild); + yield* TestClock.adjust("3999 millis"); + expect(readClerkToken).toHaveBeenCalledTimes(1); + + yield* TestClock.adjust("1 millis"); + expect(yield* Fiber.join(readsFiber)).toEqual([token, token]); + expect(readClerkToken).toHaveBeenCalledTimes(2); + }), + ); + + it.effect("fails a Clerk token read that never answers after three tries", () => + Effect.gen(function* () { + const readClerkToken = vi.fn(() => new Promise(() => {})); + const session = createManagedRelaySession({ accountId: "account-1", readClerkToken }); + + const readFiber = yield* session.readClerkToken().pipe(Effect.flip, Effect.forkChild); + yield* TestClock.adjust("12 seconds"); + + expect((yield* Fiber.join(readFiber)).message).toBe( + "Timed out obtaining the T3 Connect session token.", + ); + expect(readClerkToken).toHaveBeenCalledTimes(3); + }), + ); + it.effect("updates the token provider without replacing a same-account session", () => Effect.gen(function* () { const firstRead = vi.fn(() => Promise.resolve(null)); diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.ts index 5a4b9a62a547a..90e635f4e328a 100644 --- a/packages/client-runtime/src/relay/managedRelayState.ts +++ b/packages/client-runtime/src/relay/managedRelayState.ts @@ -3,6 +3,7 @@ import { decodeRelayJwt } from "@t3tools/shared/relayJwt"; import * as Cause from "effect/Cause"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; import * as Stream from "effect/Stream"; import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; @@ -14,6 +15,11 @@ import { relayProtectedErrorMessage } from "./errorPresentation.ts"; const DEFAULT_STALE_TIME_MS = 15_000; const DEFAULT_IDLE_TTL_MS = 5 * 60_000; const CLERK_TOKEN_EXPIRY_SKEW_MS = 5_000; +// Clerk retries a failed token request itself, but waits 3 s before the first +// retry and longer before each next one. A fresh request usually answers at +// once, so a slow read is replaced instead of waited out. +const CLERK_TOKEN_READ_TIMEOUT_MS = 4_000; +const CLERK_TOKEN_READ_ATTEMPTS = 3; const isManagedRelayRequestFailedError = Schema.is(ManagedRelay.ManagedRelayRequestFailedError); export interface ManagedRelaySession { @@ -66,7 +72,10 @@ const managedRelaySessionControls = new WeakMap | null = null; + let pendingToken: { + readonly operation: Promise; + readonly startedAtMillis: number; + } | null = null; let readClerkToken = input.readClerkToken; let tokenProviderGeneration = 0; @@ -74,8 +83,10 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana if (cachedToken && cachedToken.expiresAtMillis > nowMillis + CLERK_TOKEN_EXPIRY_SKEW_MS) { return cachedToken.token; } - if (pendingToken) { - return await pendingToken; + // A read that outlived its timeout is left running, since it still fills + // the cache, but later readers start a fresh one instead of joining it. + if (pendingToken && nowMillis - pendingToken.startedAtMillis < CLERK_TOKEN_READ_TIMEOUT_MS) { + return await pendingToken.operation; } const operationGeneration = tokenProviderGeneration; @@ -99,11 +110,12 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana : null; return token; }); - pendingToken = operation; + const pending = { operation, startedAtMillis: nowMillis }; + pendingToken = pending; try { return await operation; } finally { - if (pendingToken === operation) { + if (pendingToken === pending) { pendingToken = null; } } @@ -112,14 +124,20 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Mana const session: ManagedRelaySession = { accountId: input.accountId, readClerkToken: Effect.fn("clientRuntime.managedRelaySession.readClerkToken")(function* () { - const nowMillis = yield* Clock.currentTimeMillis; - return yield* Effect.tryPromise({ - try: () => readCachedClerkToken(nowMillis), - catch: (cause) => - new ManagedRelaySessionError({ - message: "Could not obtain the T3 Connect session token.", - cause, - }), + for (let attempt = 0; attempt < CLERK_TOKEN_READ_ATTEMPTS; attempt += 1) { + const nowMillis = yield* Clock.currentTimeMillis; + const token = yield* Effect.tryPromise({ + try: () => readCachedClerkToken(nowMillis), + catch: (cause) => + new ManagedRelaySessionError({ + message: "Could not obtain the T3 Connect session token.", + cause, + }), + }).pipe(Effect.timeoutOption(CLERK_TOKEN_READ_TIMEOUT_MS)); + if (Option.isSome(token)) return token.value; + } + return yield* new ManagedRelaySessionError({ + message: "Timed out obtaining the T3 Connect session token.", }); }), }; From 34c5faa3c38bbbcc5914862e35c80a9969efd38d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 08:52:59 -0800 Subject: [PATCH 22/56] fix(desktop): release-note entities named like Object.prototype keys stay literal (#35366) --- apps/desktop/src/updates/releaseNotes.test.ts | 12 +++++++++--- apps/desktop/src/updates/releaseNotes.ts | 18 +++++++++--------- 2 files changed, 18 insertions(+), 12 deletions(-) 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); From 371963ce0b4cfe8bac3911efd57ae3af90750b41 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 08:58:29 -0800 Subject: [PATCH 23/56] fix(desktop): startup log prune keeps files that rotation never names (#35378) --- .../src/app/DesktopObservability.test.ts | 21 +++++++++++++++++++ apps/desktop/src/app/DesktopObservability.ts | 6 ++++-- 2 files changed, 25 insertions(+), 2 deletions(-) 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); } }); From f99b2835ef0d18559a59dd954e9f564fcb43e7d3 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:02:52 -0800 Subject: [PATCH 24/56] fix(provider-core): a timed-out status probe stops a CLI that ignores SIGTERM (#35379) --- .../src/server/snapshotProbe.test.ts | 18 ++++++++++++++++++ .../provider-core/src/server/snapshotProbe.ts | 16 +++++++++++++++- 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/packages/provider-core/src/server/snapshotProbe.test.ts b/packages/provider-core/src/server/snapshotProbe.test.ts index 58d52e1002c6e..26b66751516c5 100644 --- a/packages/provider-core/src/server/snapshotProbe.test.ts +++ b/packages/provider-core/src/server/snapshotProbe.test.ts @@ -1,8 +1,10 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; import { describe, expect, it } from "@effect/vitest"; import type { ModelCapabilities } from "@t3tools/contracts"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { createModelCapabilities } from "@t3tools/shared/model"; import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; import * as Sink from "effect/Sink"; import * as Stream from "effect/Stream"; import * as ChildProcess from "effect/process/ChildProcess"; @@ -158,3 +160,19 @@ describe("ProviderCommandNotFoundError", () => { }); }); }); + +describe("spawnAndCollect", () => { + // regression: #35262 - without forceKillAfter a timed-out probe whose CLI ignores + // SIGTERM waits for it to exit, so the caller's timeout never returns. + it.live.skipIf(HostProcess.Platform.defaultValue() === "win32")( + "lets a timed-out probe return when the CLI ignores SIGTERM", + () => + Effect.gen(function* () { + const result = yield* spawnAndCollect( + "sh", + ChildProcess.make("sh", ["-c", 'trap "" TERM; sleep 30']), + ).pipe(Effect.timeoutOption("200 millis")); + expect(Option.isNone(result)).toBe(true); + }).pipe(Effect.provide(NodeServices.layer)), + ); +}); diff --git a/packages/provider-core/src/server/snapshotProbe.ts b/packages/provider-core/src/server/snapshotProbe.ts index 8718231cd9679..a30b69ac98661 100644 --- a/packages/provider-core/src/server/snapshotProbe.ts +++ b/packages/provider-core/src/server/snapshotProbe.ts @@ -112,12 +112,26 @@ export function providerProbeEnvironment(environment: NodeJS.ProcessEnv): NodeJS return { ...environment, MISE_OFFLINE: "1" }; } +// A timed-out probe interrupts the child with SIGTERM and then waits for it to exit, +// so a CLI that ignores SIGTERM would hold the caller's timeout open without this. +const PROBE_FORCE_KILL_AFTER = "1 second"; + +function withProbeForceKill(command: ChildProcess.Command): ChildProcess.Command { + if (!ChildProcess.isStandardCommand(command) || command.options.forceKillAfter !== undefined) { + return command; + } + return ChildProcess.make(command.command, command.args, { + ...command.options, + forceKillAfter: PROBE_FORCE_KILL_AFTER, + }); +} + export const spawnAndCollect = Effect.fn("snapshotProbe.spawnAndCollect")(function* ( binaryPath: string, command: ChildProcess.Command, ) { const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; - const child = yield* spawner.spawn(command); + const child = yield* spawner.spawn(withProbeForceKill(command)); const [stdout, stderr, exitCode] = yield* Effect.all( [ collectStreamAsString(child.stdout), From 49b858b807faf994569bd435c942abee478adcaf Mon Sep 17 00:00:00 2001 From: kirat02 <142911687+Kirat0201@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:34:21 +0530 Subject: [PATCH 25/56] fix(git): selected-file commits work through symlinked subdirectories (#35278) Co-authored-by: Julius Marminge --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 54 ++++++++++++-------- apps/server/src/vcs/GitVcsDriverCore.ts | 6 ++- 2 files changed, 38 insertions(+), 22 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 25401ec98544c..6dec0cf0207b8 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -6341,28 +6341,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..5eae512995d3e 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) => From 833a15b6c1921dc3ee7a94f5a9fe8db13a6e93ed Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:10:40 -0800 Subject: [PATCH 26/56] fix(opencode): a project opened mid-scan lists its OpenCode skills (#35384) --- .../src/server/driver.test.ts | 67 +++++++++++++++++++ .../provider-opencode/src/server/driver.ts | 2 + .../provider-opencode/src/server/status.ts | 6 +- 3 files changed, 73 insertions(+), 2 deletions(-) diff --git a/packages/provider-opencode/src/server/driver.test.ts b/packages/provider-opencode/src/server/driver.test.ts index 6d74dc8dd2542..ffb91b6a31994 100644 --- a/packages/provider-opencode/src/server/driver.test.ts +++ b/packages/provider-opencode/src/server/driver.test.ts @@ -537,6 +537,73 @@ it.layer(layer)("OpenCodeDriver runtime selection", (it) => { }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), ); + it.effect("caches a cold OpenCode 2 directory's skills only after its scan ends", () => + Effect.gen(function* () { + // OpenCode 2.2.7: touching a location lists it as loaded with built-in commands and skills + // at once, while provider.list waits for the scan that adds the project's skills. + const scanEnded = yield* Deferred.make(); + const builtinSkills = JSON.stringify({ + location: { directory: "/work" }, + data: ( + JSON.parse(OPENCODE_2_WORKSPACE_RESPONSES["/api/skill"].body).data as Array<{ + id: string; + }> + ).filter((skill) => skill.id !== "plum"), + }); + const http = HttpClient.make((request) => { + const path = new URL(request.url).pathname; + const json = (body: string) => + Effect.succeed(HttpClientResponse.fromWeb(request, Response.json(JSON.parse(body)))); + const afterScan = (body: string) => + Deferred.await(scanEnded).pipe(Effect.andThen(json(body))); + switch (path) { + case "/api/info": + return json( + JSON.stringify({ + ...JSON.parse(OPENCODE_2_RESPONSES["/api/info"].body), + version: "2.2.7", + }), + ); + case "/api/event": + return Effect.succeed( + HttpClientResponse.fromWeb( + request, + new Response(new ReadableStream(), { + headers: { "content-type": "text/event-stream" }, + }), + ), + ); + case "/api/debug/location": + return json('[{"directory":"/work"}]'); + case "/api/provider": + case "/api/model": + return afterScan('{"location":{"directory":"/work"},"data":[]}'); + case "/api/command": + return json(OPENCODE_2_WORKSPACE_RESPONSES["/api/command"].body); + case "/api/skill": + return Deferred.isDone(scanEnded).pipe( + Effect.flatMap((done) => + json(done ? OPENCODE_2_WORKSPACE_RESPONSES["/api/skill"].body : builtinSkills), + ), + ); + default: + return Effect.die(`Unexpected request: ${path}`); + } + }); + const instance = yield* create({ serverUrl: "http://127.0.0.1:4096" }, http); + + const snapshot = yield* instance.snapshotForCwd!("/work").pipe(Effect.forkChild); + yield* TestClock.adjust("1 second"); + yield* Deferred.succeed(scanEnded, undefined); + yield* TestClock.adjust("30 seconds"); + const { skills } = yield* Fiber.join(snapshot); + assert.include( + skills.map((skill) => skill.name), + "plum", + ); + }).pipe(Effect.scoped, Effect.provide(TestClock.layer())), + ); + it.effect.each(["probe", "error", "empty"] as const)( "recovers discovery without a manual refresh after %s", (initialCatalog) => diff --git a/packages/provider-opencode/src/server/driver.ts b/packages/provider-opencode/src/server/driver.ts index 2686de885b3f0..a0d2f7905e4a5 100644 --- a/packages/provider-opencode/src/server/driver.ts +++ b/packages/provider-opencode/src/server/driver.ts @@ -438,6 +438,8 @@ export const OpenCodeDriver: ProviderDriver< Effect.timeout("2 seconds"), Effect.orElseSucceed(() => true), ), + // OpenCode answers provider.list for a location only once its skill scan has ended. + client.provider.list({ location }).pipe(Effect.timeout("10 seconds"), Effect.ignore), ); }).pipe(Effect.scoped), ); diff --git a/packages/provider-opencode/src/server/status.ts b/packages/provider-opencode/src/server/status.ts index 459904c27eb0e..0f24b1e22f479 100644 --- a/packages/provider-opencode/src/server/status.ts +++ b/packages/provider-opencode/src/server/status.ts @@ -578,16 +578,18 @@ export interface OpenCode2Workspace { /** * Reading a location the server has not loaded boots its scan, and only reads after the scan's * `command.updated` plus `skill.updated` are complete; `scanned` must listen before `read`. A - * loaded location listing no commands is still scanning. OpenCode exposes no readiness signal, - * so one another caller booted moments earlier can still read partial. + * loaded location listing no commands is still scanning. A location another caller booted + * moments earlier lists as loaded with only built-ins, so `settled` waits out its scan first. */ export const loadOpenCode2Workspace = Effect.fn("OpencodeProviderStatus.loadOpenCode2Workspace")( function* ( read: Effect.Effect, scanned: Effect.Effect, loaded: Effect.Effect, + settled: Effect.Effect = Effect.void, ) { const wasLoaded = yield* loaded; + yield* settled; const first = yield* read; if (wasLoaded && first.commands.length > 0) return first; yield* scanned.pipe(Effect.timeoutOption("10 seconds")); From a5bd0ba5265fdfbfadc9149a54300b5048f853cb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:11:02 -0800 Subject: [PATCH 27/56] fix(ssh): SSH setup on a host without gzip says gzip is missing (#35389) --- packages/ssh/src/tunnel.test.ts | 59 +++++++++++++++++++++++++++++++++ packages/ssh/src/tunnel.ts | 8 ++++- 2 files changed, 66 insertions(+), 1 deletion(-) diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 6fd9e71510e88..03f8ebe2a62e1 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -230,6 +230,65 @@ describe("ssh tunnel scripts", () => { }, ); + it("names gzip when a host with tar but no gzip cannot unpack the release archive", () => { + const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-ssh-runner-")); + try { + const bin = NodePath.join(root, "bin"); + const release = NodePath.join(root, "release"); + const archive = `t3-${ARCHIVE.archiveVersion}-linux-x64.tar.gz`; + NodeFS.mkdirSync(bin); + NodeFS.mkdirSync(NodePath.join(root, "home")); + NodeFS.mkdirSync(NodePath.join(release, "t3"), { recursive: true }); + NodeFS.writeFileSync(NodePath.join(release, "t3", "t3"), "#!/bin/sh\necho ok\n", { + mode: 0o755, + }); + NodeChildProcess.execFileSync("tar", ["-czf", archive, "t3"], { cwd: release }); + NodeChildProcess.execFileSync("sh", ["-c", `sha256sum ${archive} > SHA256SUMS`], { + cwd: release, + }); + for (const tool of [ + "sh", + "mkdir", + "mktemp", + "cat", + "rm", + "grep", + "cut", + "sha256sum", + "tar", + "mv", + ]) { + NodeFS.symlinkSync( + NodeChildProcess.execFileSync("sh", ["-c", `command -v ${tool}`], { + encoding: "utf8", + }).trim(), + NodePath.join(bin, tool), + ); + } + NodeFS.writeFileSync( + NodePath.join(bin, "uname"), + '#!/bin/sh\ncase "$1" in -s) echo Linux ;; -m) echo x86_64 ;; esac\n', + { mode: 0o755 }, + ); + NodeFS.writeFileSync( + NodePath.join(bin, "curl"), + `#!/bin/sh\nfor last; do :; done\nfor a; do case "$a" in http*) src="${release}/\${a##*/}" ;; esac; done\nexec cat "$src" > "$last"\n`, + { mode: 0o755 }, + ); + const runner = NodePath.join(root, "run-t3.sh"); + NodeFS.writeFileSync(runner, SshTunnel.buildRemoteT3RunnerScript(ARCHIVE)); + const result = NodeChildProcess.spawnSync(NodePath.join(bin, "sh"), [runner, "--version"], { + encoding: "utf8", + env: { HOME: NodePath.join(root, "home"), PATH: bin }, + }); + assert.notEqual(result.status, 0); + assert.match(result.stderr, /(missing|needs) gzip/); + assert.notInclude(result.stderr, "Cannot exec"); + } finally { + NodeFS.rmSync(root, { recursive: true, force: true }); + } + }); + it.effect("accepts launch JSON after remote shell startup noise", () => { const target = { alias: "devbox", diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index f981a86ec0a39..5d4ac857b17b7 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -526,7 +526,13 @@ if ! t3_runtime_ready; then if [ -z "$T3_EXPECTED" ] || [ "$T3_ACTUAL" != "$T3_EXPECTED" ]; then printf 'Checksum mismatch for %s.\\n' "$T3_ARCHIVE" >&2; exit 1 fi - tar -xzf "$T3_STAGING/$T3_ARCHIVE" -C "$T3_STAGING" --strip-components=1 + if ! T3_TAR_ERROR="$(tar -xzf "$T3_STAGING/$T3_ARCHIVE" -C "$T3_STAGING" --strip-components=1 2>&1)"; then + # Some tars (BusyBox) gunzip internally, so gzip is only blamed once extraction fails. + if command -v gzip >/dev/null 2>&1; then printf '%s\\n' "$T3_TAR_ERROR" >&2 + else printf 'Remote host needs gzip to unpack %s. Install gzip on it and try again.\\n' "$T3_ARCHIVE" >&2 + fi + exit 1 + fi rm -f "$T3_STAGING/$T3_ARCHIVE" "$T3_STAGING/SHA256SUMS" # Prove the binary runs here (libc, arch) before marking it ready, or every # later launch would exec a broken install instead of retrying. From f03db4fbef59c42113e37c32897bf4d25d31cb2b Mon Sep 17 00:00:00 2001 From: kirat02 <142911687+Kirat0201@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:41:19 +0530 Subject: [PATCH 28/56] fix(pi): blank extension dialog titles no longer fail the turn (#35271) Co-authored-by: Julius Marminge --- .../provider-pi/src/server/adapter.test.ts | 126 ++++++++++-------- packages/provider-pi/src/server/adapter.ts | 5 +- 2 files changed, 70 insertions(+), 61 deletions(-) diff --git a/packages/provider-pi/src/server/adapter.test.ts b/packages/provider-pi/src/server/adapter.test.ts index 65f3cc6c4344d..5d0c9db05db08 100644 --- a/packages/provider-pi/src/server/adapter.test.ts +++ b/packages/provider-pi/src/server/adapter.test.ts @@ -4115,32 +4115,35 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); - it.effect("keeps an input dialog's title as the header above its placeholder", () => - Effect.gen(function* () { - const fake = yield* makeFakePi; - const { runtime, takeEvent } = yield* openRuntime(fake); - yield* runtime.ensureThread({ - threadId: THREAD_ID, - modelSelection: modelSelection("default"), - runtimePolicy, - }); - yield* fake.emit({ - type: "extension_ui_request", - id: "ui-input-placeholder", - method: "input", - title: "Name", - placeholder: "Your name", - }); - const event = yield* takeEvent( - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", - ); - if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { - return assert.fail("expected a user input request"); - } - assert.equal(event.turnItem.questions[0]?.header, "Name"); - assert.equal(event.turnItem.questions[0]?.question, "Your name"); - }).pipe(Effect.scoped, Effect.provide(layerTest)), + it.effect.each(["Name", " "])( + "keeps input placeholder text answerable with title '%s'", + (title) => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-input-placeholder", + method: "input", + title, + placeholder: "Your name", + }); + const event = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ); + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { + return assert.fail("expected a user input request"); + } + const question = decodeUserInputQuestions(event.turnItem.questions)[0]!; + assert.equal(question.header, title.trim() ? title : "Question"); + assert.equal(question.question, "Your name"); + }).pipe(Effect.scoped, Effect.provide(layerTest)), ); it.effect("emits a valid empty select option and returns its original value", () => @@ -4186,39 +4189,44 @@ describe("PiAdapterV2", () => { }).pipe(Effect.scoped, Effect.provide(layerTest)), ); - it.effect("asks an input dialog's title when its placeholder is blank", () => - Effect.gen(function* () { - const fake = yield* makeFakePi; - const { runtime, takeEvent } = yield* openRuntime(fake); - yield* runtime.ensureThread({ - threadId: THREAD_ID, - modelSelection: modelSelection("default"), - runtimePolicy, - }); - const title = "Which database?\n1. Postgres\n2. Type something.\nType your answer:"; - yield* fake.emit({ - type: "extension_ui_request", - id: "ui-input", - method: "input", - title, - placeholder: "", - }); - const event = yield* takeEvent( - (event) => - event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", - ); - if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { - return assert.fail("expected a user input request"); - } - assert.equal(decodeUserInputQuestions(event.turnItem.questions)[0]?.header, "Question"); - assert.equal(decodeUserInputQuestions(event.turnItem.questions)[0]?.question, title); - yield* runtime.respondToRuntimeRequest({ - requestId: event.turnItem.requestId, - answers: { "ui-input": "SQLite" }, - }); - const response = yield* fake.takeRequest("extension_ui_response"); - assert.equal(response["value"], "SQLite"); - }).pipe(Effect.scoped, Effect.provide(layerTest)), + it.effect.each(["Which database?\n1. Postgres\n2. Type something.\nType your answer:", " "])( + "asks an input dialog's title when its placeholder is blank, with title '%s'", + (title) => + Effect.gen(function* () { + const fake = yield* makeFakePi; + const { runtime, takeEvent } = yield* openRuntime(fake); + const providerThread = yield* runtime.ensureThread({ + threadId: THREAD_ID, + modelSelection: modelSelection("default"), + runtimePolicy, + }); + yield* startTurn(runtime, providerThread); + yield* fake.takeRequest("prompt"); + yield* fake.emit({ + type: "extension_ui_request", + id: "ui-input", + method: "input", + title, + placeholder: "", + }); + const event = yield* takeEvent( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "user_input_request", + ); + if (event.type !== "turn_item.updated" || event.turnItem.type !== "user_input_request") { + return assert.fail("expected a user input request"); + } + const question = decodeUserInputQuestions(event.turnItem.questions)[0]!; + assert.equal(question.header, "Question"); + assert.equal(question.question, title.trim() ? title : "Question"); + yield* runtime.respondToRuntimeRequest({ + requestId: event.turnItem.requestId, + answers: { "ui-input": "SQLite" }, + }); + const response = yield* fake.takeRequest("extension_ui_response"); + assert.equal(response["value"], "SQLite"); + assert.isUndefined(response["cancelled"]); + }).pipe(Effect.scoped, Effect.provide(layerTest)), ); it.effect("keeps the complete editor prefill editable and returns exact edited text", () => diff --git a/packages/provider-pi/src/server/adapter.ts b/packages/provider-pi/src/server/adapter.ts index c237095e5e16a..65f2a778dd329 100644 --- a/packages/provider-pi/src/server/adapter.ts +++ b/packages/provider-pi/src/server/adapter.ts @@ -3682,10 +3682,11 @@ function piQuestion( const detail = [recordString(event, "message"), recordString(event, "placeholder")].find( (text) => text !== undefined && text.trim().length > 0, ); + const questionTitle = title.trim() ? title : "Question"; return { id: questionId, - header: detail === undefined ? "Question" : title, - question: detail ?? title, + header: detail === undefined ? "Question" : questionTitle, + question: detail ?? questionTitle, ...(method === "editor" ? { initialAnswer: recordString(event, "prefill") ?? "" } : {}), options, }; From c5f5efdbd2ce025fd5f10fae01d6b97c44e42f3e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:19:26 -0800 Subject: [PATCH 29/56] fix(server): text-generation fallback keeps the thread default's custom model (#35391) --- .../CodexTextGeneration.test.ts | 18 +++++---- .../src/textGeneration/TextGeneration.ts | 39 ++++++++++--------- packages/shared/src/serverSettings.test.ts | 19 +++++++++ packages/shared/src/serverSettings.ts | 32 ++++++++------- 4 files changed, 69 insertions(+), 39 deletions(-) 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/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts index 354260ea3cfb9..347e6c746648d 100644 --- a/packages/shared/src/serverSettings.test.ts +++ b/packages/shared/src/serverSettings.test.ts @@ -38,6 +38,25 @@ describe("fallbackTextGenerationModelSelection", () => { expect( fallbackTextGenerationModelSelection({}, (instanceId) => instanceId === "opencode"), ).toEqual({ instanceId: "opencode", model: "opencode/big-pickle" }); + const threadDefault = { + instanceId: ProviderInstanceId.make("opencode"), + model: "opencode-go/glm-5.3", + }; + const providerInstances = { + [threadDefault.instanceId]: { + driver: ProviderDriverKind.make("opencode"), + config: { customModels: [threadDefault.model] }, + }, + }; + // An exhausted Go quota leaves the custom model unusable but Big Pickle still works. + expect( + fallbackTextGenerationModelSelection( + providerInstances, + (instanceId, _driver, model) => + instanceId === "opencode" && !model.startsWith("opencode-go/"), + { defaultModelSelection: threadDefault }, + ), + ).toEqual({ instanceId: "opencode", model: "opencode/big-pickle" }); }); it("replaces and clears the fallback without carrying model options", () => { diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 24c418decfa29..24b8d8e39979a 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -73,9 +73,21 @@ const TEXT_GENERATION_FALLBACK_DRIVERS = [ /** Configured instances come after every default instance, so they only win when no default qualifies. */ export function fallbackTextGenerationModelSelection( providerInstances: ServerSettings["providerInstances"], - isEnabled: (instanceId: ProviderInstanceId, driver: ProviderDriverKind) => boolean, + isEnabled: (instanceId: ProviderInstanceId, driver: ProviderDriverKind, model: string) => boolean, options?: { readonly defaultModelSelection?: ModelSelection | null }, ): ModelSelection | null { + const threadDefault = options?.defaultModelSelection; + // The thread default's custom model wins on its instance; the driver default still serves when that model is unusable. + const selectionsFor = (instanceId: ProviderInstanceId, driver: ProviderDriverKind) => { + const config = providerInstances[instanceId]?.config as { customModels?: unknown } | undefined; + const driverDefault = { instanceId, model: defaultTextGenerationModel(driver) }; + return threadDefault?.instanceId === instanceId && + readCustomModelEntries(config?.customModels).some( + (entry) => entry.slug === threadDefault.model, + ) + ? [threadDefault, driverDefault] + : [driverDefault]; + }; const candidates = [ ...TEXT_GENERATION_FALLBACK_DRIVERS.map( (driver) => [defaultInstanceIdForDriver(driver), driver] as const, @@ -86,21 +98,15 @@ export function fallbackTextGenerationModelSelection( : [], ), ]; - const match = candidates.find(([instanceId, driver]) => isEnabled(instanceId, driver)); - if (match === undefined) return null; - const [instanceId, driver] = match; - const threadDefault = options?.defaultModelSelection; - const config = providerInstances[instanceId]?.config as { customModels?: unknown } | undefined; - if ( - threadDefault?.instanceId === instanceId && - readCustomModelEntries(config?.customModels).some((entry) => entry.slug === threadDefault.model) - ) { - return threadDefault; + for (const [instanceId, driver] of candidates) { + for (const selection of selectionsFor(instanceId, driver)) { + if (isEnabled(instanceId, driver, selection.model)) return selection; + } } - return { instanceId, model: defaultTextGenerationModel(driver) }; + return null; } -export function defaultTextGenerationModel(driver: ProviderDriverKind): string { +function defaultTextGenerationModel(driver: ProviderDriverKind): string { return ( DEFAULT_TEXT_GENERATION_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? From e96c96eafe2353734e41d5eba473056b2da85480 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:19:41 -0800 Subject: [PATCH 30/56] fix(server): storage cleanup stops holding usage-limited threads too overdue to auto-resume (#35397) --- .../src/orchestration-v2/UsageLimitRecoveryWorker.ts | 2 +- apps/server/src/storageCleanup.test.ts | 7 +++++++ apps/server/src/storageCleanup.ts | 7 +++++-- 3 files changed, 13 insertions(+), 3 deletions(-) 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/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); From 167d41c09449d2e7554d663bae78646a4ff300fb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:19:54 -0800 Subject: [PATCH 31/56] fix(web): a numeric author or labels in the URL no longer crashes Pull Requests (#35376) --- .../pullRequest/pullRequestListPreferences.ts | 4 ++-- .../pullRequest/pullRequestsRouteSearch.test.ts | 5 +++++ apps/web/src/routes/_chat.pull-requests.tsx | 15 ++++++++------- 3 files changed, 15 insertions(+), 9 deletions(-) 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/routes/_chat.pull-requests.tsx b/apps/web/src/routes/_chat.pull-requests.tsx index 95b72f57992e9..8090e3a1459b1 100644 --- a/apps/web/src/routes/_chat.pull-requests.tsx +++ b/apps/web/src/routes/_chat.pull-requests.tsx @@ -8,7 +8,7 @@ import { PullRequestsPage } from "../components/pullRequest/PullRequestsPage"; const MAX_SEARCH_LABEL_CANDIDATES = 100; -function pullRequestSearchLabels(raw: unknown): Partial> { +function pullRequestSearchLabels(raw: unknown): PullRequestsSearch["labels"] { const values = (Array.isArray(raw) ? raw : typeof raw === "string" ? [raw] : []).slice( 0, MAX_SEARCH_LABEL_CANDIDATES, @@ -24,7 +24,7 @@ function pullRequestSearchLabels(raw: unknown): Partial Date: Thu, 12 Nov 2026 22:51:15 +0530 Subject: [PATCH 32/56] fix(web): bare URLs end at Chinese and Japanese punctuation (#35267) Co-authored-by: Julius Marminge --- packages/shared/src/markdownPipeline.test.ts | 173 +++++++++++++++- packages/shared/src/markdownPipeline.ts | 205 ++++++++++++++++++- 2 files changed, 375 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/markdownPipeline.test.ts b/packages/shared/src/markdownPipeline.test.ts index 06ac60958e801..2319fa4475987 100644 --- a/packages/shared/src/markdownPipeline.test.ts +++ b/packages/shared/src/markdownPipeline.test.ts @@ -3,7 +3,7 @@ import { type PluggableList, unified } from "unified"; import rehypeRaw from "rehype-raw"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; -import type { Root, RootContent } from "mdast"; +import type { Link, Root, RootContent } from "mdast"; import { CHAT_MARKDOWN_REHYPE_PLUGINS, CHAT_MARKDOWN_REMARK_PLUGINS, @@ -15,7 +15,7 @@ import { it.each([ ["default", CHAT_MARKDOWN_REMARK_PLUGINS], ["with breaks", CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS], -] as const)("preserves trailing underscores and tildes in bare URLs (%s)", (_, plugins) => { +] as const)("preserves bare URL boundaries (%s)", (_, plugins) => { const processor = unified().use(remarkParse).use(plugins); const shape = (node: Root | RootContent): string => { if (node.type === "text") return node.value; @@ -90,6 +90,55 @@ it.each([ ["https\\://x.com/dimasike_", link("https://x.com/dimasike_")], ["https://x.com/a\\_", link("https://x.com/a\\_")], ["https://x.com/a_", `${link("https://x.com/a_")};`], + [ + "可以看了:**http://localhost:18780**(已重启)。", + `可以看了:**${link("http://localhost:18780")}**(已重启)。`, + ], + ["打开 http://localhost:18780,然后刷新", `打开 ${link("http://localhost:18780")},然后刷新`], + ["URL:https://example.com/a。下一句", `URL:${link("https://example.com/a")}。下一句`], + ["(预览:http://localhost:18780)", `(预览:${link("http://localhost:18780")})`], + [ + "能打开 http://localhost:3000?见 http://localhost:3001;「www.example.com」", + `能打开 ${link("http://localhost:3000")}?见 ${link("http://localhost:3001")};「${link("www.example.com")}」`, + ], + [ + "__http://localhost:18780__,*http://localhost:3000*,~~http://localhost:3001~~。", + `**${link("http://localhost:18780")}**,*${link("http://localhost:3000")}*,~~${link("http://localhost:3001")}~~。`, + ], + [ + "foo**http://localhost:18780**(bar)***http://localhost:3000***。", + `foo**${link("http://localhost:18780")}**(bar)***${link("http://localhost:3000")}***。`, + ], + [ + "http://a.com。http://b.com,www.c.com、person@example.com。", + `${link("http://a.com")}。${link("http://b.com")},${link("www.c.com")}、[person@example.com](mailto:person@example.com)。`, + ], + [ + "**http://localhost:18780**(重启)。 https://example.com/a。结束", + `**${link("http://localhost:18780")}**(重启)。 ${link("https://example.com/a")}。结束`, + ], + ["# **http://localhost:3000**,刷新", `**${link("http://localhost:3000")}**,刷新`], + [ + "| a |\n| - |\n| **http://localhost:3000**,刷新 |", + `a**${link("http://localhost:3000")}**,刷新`, + ], + ["www.example.com/preview。下一句", `${link("www.example.com/preview")}。下一句`], + ["https://example.com/a_。下一句", `${link("https://example.com/a_")}。下一句`], + ["https://example.com/a.,下一句", `${link("https://example.com/a")}.,下一句`], + [ + "https://example.com/search?q=hello,world", + `${link("https://example.com/search?q=hello")},world`, + ], + ["https://example.com/日本語,続き", link("https://example.com/日本語,続き")], + [ + "https://zh.wikipedia.org/wiki/北京(城市)", + link("https://zh.wikipedia.org/wiki/北京(城市)"), + ], + ["https://example.com/a%EF%BC%8Cb", link("https://example.com/a%EF%BC%8Cb")], + ["", link("https://example.com/日本語,続き")], + ["[記事](https://example.com/a,b)", "[記事](https://example.com/a,b)"], + ["[http://example.com/a,b](http://example.com/a,b)", link("http://example.com/a,b")], + ["`https://example.com/a。次`", "`https://example.com/a。次`"], [ "https://x.com/a_ https://x.com/b_", `${link("https://x.com/a_")} ${link("https://x.com/b_")}`, @@ -120,6 +169,126 @@ it.each([ } }); +it("ends bare URLs at CJK punctuation with source positions", () => { + const processor = unified().use(remarkParse).use(CHAT_MARKDOWN_REMARK_PLUGINS); + const parse = (markdown: string) => processor.runSync(processor.parse(markdown), markdown); + const at = (line: number, column: number, offset: number) => ({ line, column, offset }); + const url = "http://localhost:18780"; + expect(parse(`第一行\n可以看了:**${url}**(已重启)。`)).toMatchObject({ + children: [ + { + children: [ + { type: "text", value: "第一行\n可以看了:", position: { end: at(2, 6, 9) } }, + { + type: "strong", + position: { start: at(2, 6, 9), end: at(2, 32, 35) }, + children: [ + { + type: "link", + url, + position: { start: at(2, 8, 11), end: at(2, 30, 33) }, + children: [{ type: "text", value: url, position: { end: at(2, 30, 33) } }], + }, + ], + }, + { + type: "text", + value: "(已重启)。", + position: { start: at(2, 32, 35), end: at(2, 38, 41) }, + }, + ], + }, + ], + }); + // Markup the URL swallowed comes back once the URL ends. + expect(parse(`打开 ${url},然后运行\`pnpm dev\``)).toMatchObject({ + children: [ + { + children: [ + { type: "text", value: "打开 " }, + { type: "link", url }, + { type: "text", value: ",然后运行" }, + { type: "inlineCode", value: "pnpm dev" }, + ], + }, + ], + }); + // Every URL in one paragraph ends at its mark, with positions on its own line. + const lines = Array.from({ length: 300 }, (_, index) => `接口:http://localhost:${index},`); + const [paragraph] = (parse(lines.join("\n")) as Root).children; + const links = + paragraph?.type === "paragraph" + ? paragraph.children.filter((node): node is Link => node.type === "link") + : []; + expect(links.map((node) => node.url)).toEqual( + lines.map((_, index) => `http://localhost:${index}`), + ); + const lastLine = lines.slice(0, -1).join("\n").length + 1; + expect(links.at(-1)).toMatchObject({ + position: { start: at(300, 4, lastLine + 3), end: at(300, 24, lastLine + 23) }, + }); + // Only a table unescapes `\|` in code, so that cell keeps its parse and the URL is cut. + const descendants = (node: Root | RootContent): RootContent[] => + "children" in node + ? (node.children as RootContent[]).flatMap((child) => [child, ...descendants(child)]) + : []; + const cell = descendants(parse("| a |\n| - |\n| http://example.com, `a\\|b` |") as Root); + expect(cell.flatMap((node) => (node.type === "link" ? [node.url] : []))).toEqual([ + "http://example.com", + ]); + expect(cell.flatMap((node) => (node.type === "inlineCode" ? [node.value] : []))).toEqual(["a|b"]); + // A task item's checkbox is not part of its paragraph's text. + const task = descendants(parse("- [x] http://example.com,刷新") as Root); + expect(task.flatMap((node) => (node.type === "text" ? [node.value] : []))).toEqual([ + "http://example.com", + ",刷新", + ]); + // A list item's indentation stays out of a code span that crosses lines. + const code = descendants(parse("- `echo\n hello` http://example.com,结束") as Root); + expect(code.flatMap((node) => (node.type === "link" ? [node.url] : []))).toEqual([ + "http://example.com", + ]); + expect(code.flatMap((node) => (node.type === "inlineCode" ? [node.value] : []))).toEqual([ + "echo\nhello", + ]); + // A list item's continuation line parses the same on its own. + expect(parse(`- 第一行\n **${url}**(已重启)`)).toMatchObject({ + children: [ + { + children: [ + { + children: [ + { + children: [ + { type: "text", value: "第一行\n" }, + { type: "strong", children: [{ type: "link", url }] }, + { type: "text", value: "(已重启)" }, + ], + }, + ], + }, + ], + }, + ], + }); + // A quote's continuation line does not, so the URL ends and the asterisks stay as text. + expect(parse(`> 第一行\n> **${url}**(已重启)`)).toMatchObject({ + children: [ + { + children: [ + { + children: [ + { type: "text", value: "第一行\n**" }, + { type: "link", url, position: { end: at(2, 27, 32) } }, + { type: "text", value: "**(已重启)", position: { start: at(2, 27, 32) } }, + ], + }, + ], + }, + ], + }); +}); + const insightRule = "─".repeat(20); const insightFence = (body: string, wrap = "") => [`${wrap}★ Insight ${insightRule}${wrap}`, body, `${wrap}${insightRule}${wrap}`].join("\n"); diff --git a/packages/shared/src/markdownPipeline.ts b/packages/shared/src/markdownPipeline.ts index 9ad3299809f09..e8042ee6d4696 100644 --- a/packages/shared/src/markdownPipeline.ts +++ b/packages/shared/src/markdownPipeline.ts @@ -1,5 +1,14 @@ import { isLocalEditorFileUrl, LOCAL_FILE_LINK_SCHEMES } from "@t3tools/contracts"; -import type { Paragraph, PhrasingContent, Root, RootContent } from "mdast"; +import type { + Heading, + Link, + Paragraph, + PhrasingContent, + Root, + RootContent, + TableCell, + Text, +} from "mdast"; import { remarkKeepWindowsPaths } from "./markdownWindowsPaths.ts"; import { type PluggableList, type Processor, type Transformer, unified } from "unified"; import remarkParse from "remark-parse"; @@ -236,6 +245,7 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = { export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ remarkGfm, + remarkEndAutolinksAtCjkPunctuation, remarkKeepAutolinkSuffixes, remarkLinkAbsoluteFilePaths, remarkKeepWindowsPaths, @@ -250,6 +260,7 @@ export const CHAT_MARKDOWN_REMARK_PLUGINS: PluggableList = [ export const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS: PluggableList = [ remarkGfm, + remarkEndAutolinksAtCjkPunctuation, remarkKeepAutolinkSuffixes, remarkLinkAbsoluteFilePaths, remarkKeepWindowsPaths, @@ -453,6 +464,198 @@ function remarkKeepAutolinkSuffixes(): Transformer { }; } +// Punctuation and symbols from CJK Symbols and Punctuation and from Halfwidth and Fullwidth Forms. +const CJK_PUNCTUATION = /(?=[ -〿＀-￯])[\p{P}\p{S}]/u; + +/** + * GFM runs a bare URL on until whitespace, so Chinese and Japanese punctuation joins it, along with + * the rest of the sentence and any `**` that should have closed around it. A URL that is ASCII up to + * such a mark ends there. Unicode earlier in the URL means the mark may belong to it, so it stays. + */ +function cjkPunctuationIndex(link: Link): number { + const label = link.children.length === 1 ? link.children[0] : undefined; + if (label?.type !== "text" || !/^https?:\/\//i.test(link.url)) return -1; + if (link.url !== label.value && link.url !== `http://${label.value}`) return -1; + const index = label.value.search(/[^!-~]/u); + return index > 0 && CJK_PUNCTUATION.test(label.value.charAt(index)) ? index : -1; +} + +/** GFM's text pass links bare URLs without positions; its tokenizer's links span their URL. */ +function isBareLink(link: Link, source: string): boolean { + const start = link.position?.start.offset; + const end = link.position?.end.offset; + const label = link.children[0]; + return ( + !link.position || + (start !== undefined && + end !== undefined && + label?.type === "text" && + source.slice(start, end) === label.value) + ); +} + +/** Source offsets of the marks that tokenized bare URLs run past. */ +function cjkPunctuationOffsets(node: RootContent, source: string): number[] { + if (node.type === "link") { + const index = cjkPunctuationIndex(node); + const start = node.position?.start.offset; + return index > 0 && start !== undefined && isBareLink(node, source) ? [start + index] : []; + } + return "children" in node && node.type !== "linkReference" + ? (node.children as RootContent[]).flatMap((child) => cjkPunctuationOffsets(child, source)) + : []; +} + +const hasReference = (node: RootContent): boolean => + node.type === "linkReference" || + node.type === "imageReference" || + node.type === "footnoteReference" || + ("children" in node && (node.children as RootContent[]).some(hasReference)); + +/** How many of the ascending numbers are below `value`. */ +function countBelow(sorted: readonly number[], value: number): number { + let low = 0; + let high = sorted.length; + while (low < high) { + const middle = (low + high) >> 1; + if (sorted[middle]! < value) low = middle + 1; + else high = middle; + } + return low; +} + +/** + * Parses the block's text again with a tab before each mark. The tab ends the URL as a space would, + * so emphasis around the URL closes and later URLs and code get their own nodes. The tabs are then + * dropped and positions mapped back to the source. Returns false and leaves the block alone when its + * text would parse differently on its own, as a quote's continuation lines do. + */ +function reparseAtCjkPunctuation( + processor: Processor, + block: Paragraph | Heading | TableCell, + source: string, + offsets: number[], +): boolean { + // A task item's paragraph starts at its checkbox; its first child starts after it. + const from = block.children[0]?.position?.start; + const to = block.children.at(-1)?.position?.end; + if (from?.offset === undefined || to?.offset === undefined || hasReference(block)) return false; + const base = from.offset; + const text = source.slice(base, to.offset); + // A tab is the marker, a quote's `>` on a later line would read as a new quote, a list's + // indentation would join a code span, and only a table unescapes `\|` in code. + if ( + text.includes("\t") || + /[\r\n][ ]*>/.test(text) || + (/[\r\n] /.test(text) && text.includes("`")) || + (block.type === "tableCell" && text.includes("\\|")) + ) { + return false; + } + const marks = offsets.map((offset) => offset - base); + // Each pass finds the next URL in a run with no spaces, like `http://a,http://b,http://c`. + for (let attempt = 0; attempt < 16; attempt++) { + marks.sort((a, b) => a - b); + const tabs = marks.map((mark, index) => mark + index); + const unmarked = (offset: number) => offset - countBelow(tabs, offset); + const marked = [0, ...marks] + .map((start, index) => text.slice(start, marks[index] ?? text.length)) + .join("\t"); + const [paragraph, ...rest] = (processor.parse(marked) as Root).children; + if (paragraph?.type !== "paragraph" || rest.length > 0) return false; + const more = cjkPunctuationOffsets(paragraph, marked); + if (more.length > 0) { + marks.push(...more.map(unmarked)); + continue; + } + + let tabCount = 0; + const moved = new Set(); + const restore = (node: RootContent): boolean => { + for (const point of node.position ? [node.position.start, node.position.end] : []) { + const offset = point.offset; + if (offset === undefined || moved.has(point)) continue; + moved.add(point); + const tabsOnLine = countBelow(tabs, offset) - countBelow(tabs, offset - point.column + 1); + point.column = (point.line === 1 ? from.column - 1 : 0) + point.column - tabsOnLine; + point.line += from.line - 1; + point.offset = base + unmarked(offset); + } + if (node.type === "text") { + tabCount += node.value.split("\t").length - 1; + node.value = node.value.replaceAll("\t", ""); + } else if ( + ("value" in node && node.value.includes("\t")) || + ("url" in node && node.url.includes("\t")) + ) { + return false; + } + if (!("children" in node)) return true; + const children = node.children as RootContent[]; + if (!children.every(restore)) return false; + node.children = children.filter( + (child) => child.type !== "text" || child.value !== "", + ) as typeof node.children; + return true; + }; + if (!restore(paragraph) || tabCount !== tabs.length) return false; + block.children = paragraph.children; + return true; + } + return false; +} + +/** Ends the bare URLs a reparse could not, and those GFM's text pass linked after emphasis. */ +function splitAtCjkPunctuation(node: RootContent, source: string) { + if (!("children" in node) || node.type === "link" || node.type === "linkReference") return; + const children = node.children as RootContent[]; + for (let index = 0; index < children.length; index++) { + const child = children[index]!; + if (child.type !== "link") { + splitAtCjkPunctuation(child, source); + continue; + } + const at = isBareLink(child, source) ? cjkPunctuationIndex(child) : -1; + const label = child.children[0]; + if (at < 0 || label?.type !== "text") continue; + // GFM drops this punctuation from the end of a URL; remarkKeepAutolinkSuffixes restores `_` and `~`. + const length = label.value.slice(0, at).replace(/[!"'*,.:;?_~]+$/, "").length; + const tail: Text = { type: "text", value: label.value.slice(length) }; + const start = child.position?.start; + if (child.position && start?.offset !== undefined) { + const end = { + line: start.line, + column: start.column + length, + offset: start.offset + length, + }; + tail.position = { start: end, end: child.position.end }; + child.position = { start, end }; + label.position = { start, end }; + } + child.url = child.url.slice(0, child.url.length - label.value.length + length); + label.value = label.value.slice(0, length); + children.splice(index + 1, 0, tail); + index++; + } +} + +function remarkEndAutolinksAtCjkPunctuation(this: Processor): Transformer { + return (tree, file) => { + const source = String(file); + if (!CJK_PUNCTUATION.test(source)) return; + const visit = (node: RootContent) => { + if (node.type === "paragraph" || node.type === "heading" || node.type === "tableCell") { + const offsets = cjkPunctuationOffsets(node, source); + if (offsets.length > 0) reparseAtCjkPunctuation(this, node, source, offsets); + splitAtCjkPunctuation(node, source); + } else if ("children" in node) { + (node.children as RootContent[]).forEach(visit); + } + }; + tree.children.forEach(visit); + }; +} + function remarkLinkAbsoluteFilePaths(): Transformer { return (tree) => { // Raw `` tags are sibling html nodes, so text inside one is not under a link node. From 88bf393b30d031ad998651eb66f4df804442399c Mon Sep 17 00:00:00 2001 From: Sidhartha S <247517582+sidhartha1s@users.noreply.github.com> Date: Thu, 12 Nov 2026 22:51:30 +0530 Subject: [PATCH 33/56] fix(server): @ file search finds filenames containing literal braces (#35239) Co-authored-by: sidhartha1s Co-authored-by: Julius Marminge --- .../src/workspace/WorkspaceEntries.test.ts | 24 ++++++++++--- .../src/workspace/WorkspaceSearchIndex.ts | 35 ++++++++++++------- 2 files changed, 42 insertions(+), 17 deletions(-) diff --git a/apps/server/src/workspace/WorkspaceEntries.test.ts b/apps/server/src/workspace/WorkspaceEntries.test.ts index 62d6ab0a63b33..87cab4a2c88c3 100644 --- a/apps/server/src/workspace/WorkspaceEntries.test.ts +++ b/apps/server/src/workspace/WorkspaceEntries.test.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"]); }), ); diff --git a/apps/server/src/workspace/WorkspaceSearchIndex.ts b/apps/server/src/workspace/WorkspaceSearchIndex.ts index 11a19e1839861..23d17759c9fc1 100644 --- a/apps/server/src/workspace/WorkspaceSearchIndex.ts +++ b/apps/server/src/workspace/WorkspaceSearchIndex.ts @@ -447,32 +447,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 = hasIncompleteInitialScan(); if (kind === "file" || imageOnly) { const result = yield* runSearch(query, pageSize, "fileSearch", () => 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.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.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 }; }); From 2a1e43e89ebe9cfe75f07056f42469e2b1bb3a07 Mon Sep 17 00:00:00 2001 From: Joseph Vidal <135430578+josephv123@users.noreply.github.com> Date: Thu, 12 Nov 2026 12:23:36 -0500 Subject: [PATCH 34/56] fix(server): t3_thread_search says which thread is the caller's (#35377) Co-authored-by: Julius Marminge --- apps/server/src/mcp/toolkits/core.test.ts | 58 +++++++++++++++++++ .../src/mcp/toolkits/thread/handlers.ts | 1 + apps/server/src/mcp/toolkits/thread/tools.ts | 1 + 3 files changed, 60 insertions(+) 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, From a909ea423cbbea68db4b3eb4c6017e06ad6dd50d Mon Sep 17 00:00:00 2001 From: Theo Browne Date: Thu, 12 Nov 2026 09:28:37 -0800 Subject: [PATCH 35/56] perf(server): older history pages load without indexing the whole thread (#34573) Co-Authored-By: Claude Fable 5.2 --- .../orchestration-v2/ProjectionStore.test.ts | 490 ++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 808 +++++++++++++++--- .../threadHistoryPaging.test.ts | 32 + .../orchestration-v2/threadHistoryPaging.ts | 54 +- 4 files changed, 1245 insertions(+), 139 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 3f48cbf247fc7..fa670c448c898 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -3651,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", @@ -4050,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 ( @@ -4205,21 +4335,24 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => { window.projection.visibleTurnItems.find((row) => row.item.deferredWork)?.item.ordinal, 3, ); + 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(); - const page = yield* historyPage( + yield* historyPage( threadId, - encodeThreadHistoryCursor({ - snapshotSequence: 0, - sourceThreadId: threadId, - sourceItemId: "turn-item:bounded-sql-history:1000", - position: 1000, - }), - undefined, + newestCursor, + "turn-item:bounded-sql-history:2", false, "deferred", ).pipe(Effect.withTracer(pageRead.tracer)); - assert.isUndefined(page.items.find((row) => row.item.ordinal === 2)?.item.deferredWork); - // Tool payloads hold megabytes, so a page looks for inline output only in its own runs. const payloadScans = pageRead.statements.filter((statement) => statement.includes("LIKE '%htmlRender%'"), ); @@ -5558,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; diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 4ccb6bbf85ad8..22d8cfe25ddbb 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"; @@ -98,6 +99,7 @@ import { MCP_APP_OUTPUT_KEY } from "@t3tools/shared/mcpApp"; import { threadHtmlRenderAttachmentIds } from "../attachmentStore.ts"; import { readableSearchText } from "./messageSearchIndex.ts"; import { + isFoldableWorkItem, isThreadHistoryUserTurn, isConversationHistoryItem, THREAD_HISTORY_MAX_RAW_TURNS, @@ -114,6 +116,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()( @@ -6451,6 +6455,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, @@ -6461,8 +6918,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; @@ -6470,100 +6934,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 { olderPolicy, cursorPosition } = yield* Effect.try({ - try: () => ({ - olderPolicy: olderHistoryPagePolicy({ items: indexed, cursor, throughEntryId }), - // The cursor's own row, or the row its stale position falls back to. - cursorPosition: Math.min( - findCursorEndIndex(indexed, decodeThreadHistoryCursor(cursor)), - indexed.length - 1, - ), - }), - catch: (cause) => new ProjectionStoreReadError({ threadId, cause }), - }); - const selectPage = (rows: typeof indexed) => + const select = ( + indexed: ReadonlyArray, + prefix?: ThreadHistoryPrefix, + ) => Effect.try({ - try: () => - workMode === "work" - ? selectDeferredWorkPage({ - items: rows, - cursor, - throughEntryId, - snapshotSequence, - rowEncodedBytes: () => 0, - }) - : selectHistoryPageFromCursor({ - items: workMode === "deferred" ? deferWorkHistoryRows(rows) : rows, - cursor, - snapshotSequence, - rowEncodedBytes: () => 0, - policy: olderPolicy, - }), + 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 }), }); - let page = yield* selectPage(indexed); - // Inline output is found by scanning 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(); - while (workMode !== undefined) { - // Rows hidden in a work group move the page, so the scan always reaches the cursor. - 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 }>` + 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}`); - page = yield* selectPage( - indexed.map((row) => - persistentOutputs.has(`${row.sourceThreadId}:${row.sourceItemId}`) - ? { ...row, item: { ...row.item, persistentOutput: true } } - : row, - ), - ); - } - const policy = workMode === "work" ? THREAD_HISTORY_PAGE_POLICY : olderPolicy; + 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( @@ -6606,7 +7102,7 @@ export const layer: Layer.Layer = ); }); const items = yield* materialize( - conversationOnly && hasUserTurns + hasUserTurns ? page.items.filter((row) => isConversationHistoryItem(row.item)) : page.items, ); @@ -6614,7 +7110,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, @@ -6631,39 +7134,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 @@ -6713,11 +7295,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( 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 b79038a77a803..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 }), }; } @@ -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, }); } From f4cf69f522a9c7acc29a519debafad37db11f030 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:34:30 -0800 Subject: [PATCH 36/56] fix(server): selecting a remote branch lands on its local branch (#35400) --- apps/server/src/vcs/GitVcsDriverCore.test.ts | 130 ++++++++++++++----- apps/server/src/vcs/GitVcsDriverCore.ts | 33 +++-- 2 files changed, 123 insertions(+), 40 deletions(-) diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index 6dec0cf0207b8..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", () => diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index 5eae512995d3e..a0b99e6d6d7f5 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -5257,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, @@ -5265,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, ), ) @@ -5307,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 }, + ), + ), ); } From a2685e64d34945bed0f6317b48b38ef57a7cb558 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:34:44 -0800 Subject: [PATCH 37/56] fix(web): SCP-style Git remotes no longer become terminal file links (#35404) --- apps/web/src/terminal-links.test.ts | 11 +++++++++++ apps/web/src/terminal-links.ts | 12 +++++++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/apps/web/src/terminal-links.test.ts b/apps/web/src/terminal-links.test.ts index 130e4d276ef7c..a0fb98529cf05 100644 --- a/apps/web/src/terminal-links.test.ts +++ b/apps/web/src/terminal-links.test.ts @@ -64,6 +64,10 @@ describe("extractTerminalLinks", () => { expect(extractTerminalLinks(`see ${quote}${text}${quote}.`)).toEqual([ { kind: "path", text, start: 5, end: 5 + text.length }, ]); + const atText = "src/my contact@support.vue:12:3"; + expect(extractTerminalLinks(`see ${quote}${atText}${quote}.`)).toEqual([ + { kind: "path", text: atText, start: 5, end: 5 + atText.length }, + ]); }); it.each([ @@ -127,6 +131,11 @@ describe("extractTerminalLinks", () => { "src/𐐀.ts:12", "src/app/[id]/page.tsx:3:10", "src/routes/(app)/+page.svelte:12:4", + "src/routes/(app)/+page@.svelte:12:3", + "src/contact@support.vue:12:3", + String.raw`src\contact@support.ts:12:3`, + "src/équipe@home.ts:12:3", + "src/foo$contact@support.ts:12:3", "node_modules/.pnpm/react@18.3.1/node_modules/react/index.js:12:5", "app/routes/posts.$id.tsx:5", ])("keeps the complete relative path %s", (text) => { @@ -198,6 +207,8 @@ describe("extractTerminalLinks", () => { " at main (file:///Users/jane/app/src/index.mjs:3:7)", "+redis://localhost:6379/0", "-redis://localhost:6379/0", + "git clone git@github.com:acme/widgets.git", + "remote: git@gitlab.com:group/sub/project.git", ])("does not turn part of a non-web URL into an editor link: %s", (line) => { expect(extractTerminalLinks(line)).toEqual([]); }); diff --git a/apps/web/src/terminal-links.ts b/apps/web/src/terminal-links.ts index 114219e721eb0..d77848a8c26b3 100644 --- a/apps/web/src/terminal-links.ts +++ b/apps/web/src/terminal-links.ts @@ -46,6 +46,9 @@ const REQUEST_ROUTE_PATTERN = // The tail of `redis://host/0` or `file:///a.mjs` is not a path. One-letter schemes stay drives, // a diff's `+` or `-` may lead, and the lookbehind keeps runs from being rescanned at every suffix. const SCHEME_URL_PATTERN = /(?]+/gu; +// Nor is the tail of an SCP-style Git remote such as `git@github.com:acme/widgets.git`. Only a +// path wholly inside the tail is dropped, so `src/contact@support.vue:12:3` keeps its link. +const SCP_REMOTE_PATTERN = /(?]+/gu; function trimClosingDelimiters(value: string, kind: TerminalLinkKind): string { let output = value.replace( @@ -119,6 +122,10 @@ export function extractTerminalLinks(line: string): TerminalLinkMatch[] { [...line.matchAll(REQUEST_ROUTE_PATTERN), ...line.matchAll(SCHEME_URL_PATTERN)], (match) => ({ start: match.index, end: match.index + match[0].length }), ); + const remoteTails = Array.from(line.matchAll(SCP_REMOTE_PATTERN), (match) => ({ + start: match.index + match[0].indexOf(":") + 1, + end: match.index + match[0].length, + })); const urlMatches = collectMatches(line, "url", URL_PATTERN, promptMatches); const quotedMatches = collectMatches(line, "path", QUOTED_FILE_PATH_PATTERN, [ ...promptMatches, @@ -131,7 +138,10 @@ export function extractTerminalLinks(line: string): TerminalLinkMatch[] { ]); return [...promptMatches, ...urlMatches, ...quotedMatches, ...pathMatches] .filter( - (match) => match.kind === "url" || !nonPathRanges.some((range) => overlaps(match, range)), + (match) => + match.kind === "url" || + (!nonPathRanges.some((range) => overlaps(match, range)) && + !remoteTails.some((tail) => match.start >= tail.start && match.end <= tail.end)), ) .toSorted((a, b) => a.start - b.start); } From d0f9d4dcc01ba89f28c5cc3d948829dff6fcf6e5 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:37:01 -0800 Subject: [PATCH 38/56] fix(web): sidebar draft previews show cited assistant text, not the raw link (#35406) --- .../sidebar/SidebarDraftBlock.browser.test.tsx | 18 +++++++++++++++++- .../components/sidebar/SidebarDraftBlock.tsx | 5 ++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx index c29932f5757e1..41cd795013e45 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.browser.test.tsx @@ -1,9 +1,10 @@ import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment"; -import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, MessageId, ProjectId, ThreadId } from "@t3tools/contracts"; import { Profiler } from "react"; import { expect, it, vi } from "vite-plus/test"; import { act, render } from "../../../test/render"; +import { formatAssistantCitationForComposer } from "../../composer-logic"; import { DraftId, useComposerDraftStore } from "../../composerDraftStore"; import { SidebarDraftBlock } from "./SidebarDraftBlock"; @@ -53,6 +54,21 @@ it("keeps draft previews current through edits, promotion and removal", async () await act(() => initial.setPrompt(draftId, "Updated draft preview")); await expect.element(row).toHaveAccessibleName("Updated draft preview, Unsent draft"); + const quote = "Cache the parsed config per worktree."; + const citation = formatAssistantCitationForComposer({ + version: 1, + environmentId, + threadId: ThreadId.make("source-thread"), + messageId: MessageId.make("source-message"), + text: quote, + start: 0, + end: quote.length, + prefix: "", + suffix: "", + }); + await act(() => initial.setPrompt(draftId, `${citation}Why per worktree?`)); + await expect.element(row).toHaveAccessibleName(`${quote} Why per worktree?, Unsent draft`); + await act(() => initial.markDraftThreadPromoting(draftId)); await expect.element(row).not.toBeInTheDocument(); await act(() => initial.clearDraftThread(draftId)); diff --git a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx index bc15ca5945972..c4868c4776ea7 100644 --- a/apps/web/src/components/sidebar/SidebarDraftBlock.tsx +++ b/apps/web/src/components/sidebar/SidebarDraftBlock.tsx @@ -1,4 +1,5 @@ import { discardComposerDraft } from "../../lib/discardComposerDraft"; +import { assistantCitationsToPlainText } from "@t3tools/shared/assistantCitations"; import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences"; import { SquarePenIcon, XIcon } from "lucide-react"; import { @@ -34,7 +35,9 @@ const SidebarDraftRow = memo(function SidebarDraftRow(props: { }) { const { composer, draftId, onContextMenu, onDiscard, onNavigate } = props; const promptPreview = - replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label) + assistantCitationsToPlainText( + replaceComposerContextReferences(composer.prompt, (occurrence) => occurrence.label), + ) .trim() .split("\n", 1)[0] ?? ""; // images mirrors persistedAttachments once rehydration finishes; before From 0cd6a73433c3b9c1e328560d591fd297e72d7ef9 Mon Sep 17 00:00:00 2001 From: Srijan Dubey <87586713+Srijan-D@users.noreply.github.com> Date: Thu, 12 Nov 2026 23:08:37 +0530 Subject: [PATCH 39/56] fix(web): pasting an image the draft already has no longer flashes a preparing tile (#35265) Co-authored-by: Julius Marminge --- apps/web/src/components/chat/ChatComposer.tsx | 4 +- .../chat/composerAttachmentFiles.ts | 22 +++ .../chat/preparingComposerImages.ts | 10 +- ...eComposerAttachmentIntake.browser.test.tsx | 125 ++++++++++++++++++ .../chat/useComposerAttachmentIntake.ts | 24 +++- apps/web/src/composerDraftStore.ts | 10 +- apps/web/src/lib/imageCompression.test.ts | 8 +- apps/web/src/lib/imageCompression.ts | 8 +- 8 files changed, 191 insertions(+), 20 deletions(-) create mode 100644 apps/web/src/components/chat/useComposerAttachmentIntake.browser.test.tsx diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index bafafcb9612cf..6f6d4fbd50ffc 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -698,7 +698,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/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/composerDraftStore.ts b/apps/web/src/composerDraftStore.ts index 783338bc48e23..f719780357a2f 100644 --- a/apps/web/src/composerDraftStore.ts +++ b/apps/web/src/composerDraftStore.ts @@ -1,5 +1,8 @@ import { stripInlineContextReferences } from "./lib/composerContextReferences"; -import { composerFileAttachmentMimeType } from "./components/chat/composerAttachmentFiles"; +import { + composerFileAttachmentMimeType, + composerImageDedupKey, +} from "./components/chat/composerAttachmentFiles"; import { elementContextToPreviewAnnotation } from "./lib/elementContext"; import { ResponseContextRecord, @@ -907,11 +910,6 @@ function createEmptyThreadDraft(): ComposerThreadDraftState { }; } -function composerImageDedupKey(image: ComposerImageAttachment): string { - // Hydrated images get fresh lastModified values, so exclude it from dedupe. - return `${image.mimeType}\u0000${image.sizeBytes}\u0000${image.name}`; -} - export function composerFileDedupKey( file: Pick, ): string { diff --git a/apps/web/src/lib/imageCompression.test.ts b/apps/web/src/lib/imageCompression.test.ts index a8d4cfcc1d549..e40c3968bc850 100644 --- a/apps/web/src/lib/imageCompression.test.ts +++ b/apps/web/src/lib/imageCompression.test.ts @@ -254,11 +254,13 @@ describe("composer image thumbnails", () => { stubCanvasPipeline(() => 3); const source = makeFile(3); const compressed = makeFile(2, "image/webp"); - const sourceThumbnail = await createComposerImageThumbnail(source); - expect(sourceThumbnail).toMatch(/^data:image\/png;base64,/); + // Compression can finish before the placeholder's thumbnail does. + const pendingThumbnail = createComposerImageThumbnail(source); - inheritComposerImageThumbnail(source, compressed); + await inheritComposerImageThumbnail(source, compressed); + const sourceThumbnail = await pendingThumbnail; + expect(sourceThumbnail).toMatch(/^data:image\/png;base64,/); expect(readComposerImageThumbnail(compressed)).toBe(sourceThumbnail); expect(await createComposerImageThumbnail(compressed)).toBe(sourceThumbnail); expect(createImageBitmap).toHaveBeenCalledTimes(1); diff --git a/apps/web/src/lib/imageCompression.ts b/apps/web/src/lib/imageCompression.ts index e174bebf4b9e4..53e948e535b75 100644 --- a/apps/web/src/lib/imageCompression.ts +++ b/apps/web/src/lib/imageCompression.ts @@ -227,16 +227,18 @@ export function createComposerImageThumbnail(file: File): Promise /** * Pasted images are re-encoded after their placeholder already shows the source's thumbnail. * Reusing it keeps the tile from flashing back to its fallback while the new file is decoded. + * Resolves once the target's thumbnail is readable, so a tile swapped to it paints at once even + * when compression finished before the source's thumbnail did. */ -export function inheritComposerImageThumbnail(source: File, target: File): void { +export async function inheritComposerImageThumbnail(source: File, target: File): Promise { const sourceThumbnail = composerThumbnails.get(source); if (source === target || !sourceThumbnail || composerThumbnails.has(target)) return; - const settled = settledComposerThumbnails.get(source); - if (settled) settledComposerThumbnails.set(target, settled); cacheComposerImageThumbnail( target, sourceThumbnail.then((src) => src ?? renderComposerImageThumbnail(target)), ); + const src = await sourceThumbnail; + if (src) settledComposerThumbnails.set(target, src); } async function renderComposerImageThumbnail(file: File): Promise { From 0b21a82aa3761c6073a8a5282f4a598b9accd4be Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:48:56 -0800 Subject: [PATCH 40/56] fix(shared): pooled limits weight each account by its plan size (#35427) --- packages/shared/src/usageLimits.test.ts | 46 +++++++++++++++++++++++++ packages/shared/src/usageLimits.ts | 44 ++++++++++++++++++++--- 2 files changed, 85 insertions(+), 5 deletions(-) diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index bed48428a93c4..8f7fa26d7e728 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -804,6 +804,52 @@ describe("pools", () => { ).toEqual(["weekly", "weekly:secondary"]); }); + it("weights pooled Codex quota and resets by each account's plan capacity", () => { + const [pool] = collectLimitPools( + collectLimitAccounts( + new Map([ + [ + EnvironmentId.make("env-a"), + { + ...laptop, + serverConfig: { + providers: [], + usageLimitSources: [ + { + ...source, + accounts: [ + ["pro", "ChatGPT Pro 200 Subscription", 100], + ["plus", "ChatGPT Plus Subscription", 0], + ].map(([id, plan, usedPercent]) => ({ + id: String(id), + email: `${id}@example.com`, + driver: ProviderDriverKind.make("codex"), + plan: String(plan), + usageLimits: { + checkedAt, + windows: [{ ...weekly, id: "secondary", usedPercent: Number(usedPercent) }], + }, + })), + }, + ], + }, + }, + ], + ]), + ), + now, + ); + const [pooledWeekly] = pool?.windows ?? []; + // Pro 20x holds 20 of the pool's 21 capacity parts. + expect(pooledWeekly?.remainingPercent).toBe(5); + expect( + pooledWeekly?.resets.map(({ member, restoresPercent }) => [ + member.account.email, + restoresPercent, + ]), + ).toContainEqual(["pro@example.com", 95]); + }); + it("pools windows by id across accounts and orders resets by when they land", () => { const input = new Map([ [ diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 716103ac2fc9b..ed38fdeb45b4e 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -539,6 +539,25 @@ function accountSortName(account: LimitAccount): string { return (account.displayName ?? account.email ?? account.key).toLowerCase(); } +const CODEX_PLAN_CAPACITY: Record = { + "ChatGPT Plus Subscription": 1, + "ChatGPT Pro 100 Subscription": 5, + "ChatGPT Pro 200 Subscription": 20, +}; +// Claude's published plan multipliers describe the session allowance only. +const CLAUDE_SESSION_CAPACITY: Record = { Pro: 1, Max: 5, Ultra: 20 }; + +function planCapacity(account: LimitAccount, kind: ServerProviderUsageWindow["kind"]) { + if (!account.plan) return undefined; + if (account.driver === "codex" && (kind === "session" || kind === "weekly")) { + return CODEX_PLAN_CAPACITY[account.plan]; + } + if (account.driver === "claudeAgent" && kind === "session") { + return CLAUDE_SESSION_CAPACITY[account.plan]; + } + return undefined; +} + // Codex ids name slots, so pool by kind; other drivers' ids identify distinct allowances. function poolKey(driver: ServerProvider["driver"], window: ServerProviderUsageWindow): string { return driver === "codex" ? window.kind : `${window.kind}:${window.id}`; @@ -607,15 +626,28 @@ function poolWindows(accounts: readonly LimitAccount[], now: number): readonly L const memberByAccount = new Map(members.map((member) => [member.account.key, member])); const first = members[0]!.window; const id = members[0]!.account.driver === "codex" ? key : first.id; - const usedPercent = members.reduce((sum, m) => sum + m.window.usedPercent, 0) / members.length; + // One unknown plan makes the pool incomparable by plan, so every member then counts once. + const capacities = members.map((m) => planCapacity(m.account, first.kind)); + const weights = capacities.every((capacity) => capacity !== undefined) + ? capacities + : members.map(() => 1); + const weightOf = new Map(members.map((m, index) => [m, weights[index]!])); + const totalWeight = weights.reduce((sum, weight) => sum + weight, 0); + const usedPercent = + members.reduce((sum, m) => sum + m.window.usedPercent * weightOf.get(m)!, 0) / totalWeight; // Judge pace only for windows with reset clocks; others add spend without elapsed time. const timed = members.flatMap((m) => { const share = elapsedShare(m.window, now); - return share === null ? [] : [{ used: m.window.usedPercent, elapsed: share }]; + return share === null + ? [] + : [{ used: m.window.usedPercent, elapsed: share, weight: weightOf.get(m)! }]; }); - const timedUsed = timed.reduce((sum, t) => sum + t.used, 0) / timed.length; + const timedWeight = timed.reduce((sum, t) => sum + t.weight, 0); + const timedUsed = timed.reduce((sum, t) => sum + t.used * t.weight, 0) / timedWeight; const meanElapsed = - timed.length > 0 ? timed.reduce((sum, t) => sum + t.elapsed, 0) / timed.length : null; + timed.length > 0 + ? timed.reduce((sum, t) => sum + t.elapsed * t.weight, 0) / timedWeight + : null; const resets = members .flatMap((member) => { const at = resetMillis(member.window); @@ -625,7 +657,9 @@ function poolWindows(accounts: readonly LimitAccount[], now: number): readonly L { member, at, - restoresPercent: Math.round(member.refillPercent / members.length), + restoresPercent: Math.round( + (member.refillPercent * weightOf.get(member)!) / totalWeight, + ), }, ]; }) From 60c3b222db553796ef4c2b093691ad9b7ad6bf34 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:49:10 -0800 Subject: [PATCH 41/56] fix(mobile): browser and MCP-app links with blank IDs no longer crash the screen (#35415) --- .../browser/BrowserPreviewRouteScreen.tsx | 21 +++++++++- .../threads/McpAppFullscreenScreen.tsx | 39 +++++++++++++++++-- 2 files changed, 54 insertions(+), 6 deletions(-) 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/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, From 55081a1f7bcfed8a5ace034f03e6f39017b71979 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:50:27 -0800 Subject: [PATCH 42/56] fix(shared): thread search ignores the t3 prefix of flat temporary branches (#35430) --- packages/shared/src/paletteSearch.test.ts | 8 ++++++++ packages/shared/src/paletteSearch.ts | 17 ++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/paletteSearch.test.ts b/packages/shared/src/paletteSearch.test.ts index 4c00dd40571e2..14f7f37dc9205 100644 --- a/packages/shared/src/paletteSearch.test.ts +++ b/packages/shared/src/paletteSearch.test.ts @@ -333,6 +333,14 @@ describe("scoreThreadSearch beyond Latin text and titles", () => { ranges: [{ start: 0, end: 7 }], }); expect(scoreThreadSearch("trim", subject, NOW)?.explain?.()).toBeUndefined(); + // Nor is it in the flat t3- form used when a `t3` branch blocks nested refs. + const flat = thread("Add search", { branch: "t3-abcd1234" }); + expect(scoreThreadSearch("t3", flat, NOW)).toBeNull(); + expect(scoreThreadSearch("t3 connect", flat, NOW)).toBeNull(); + expect(scoreThreadSearch("abcd1234", flat, NOW)).not.toBeNull(); + for (const query of ["t3-abcd", "t3-abcd1234 connect", "connect t3-abcd1234"]) { + expect(scoreThreadSearch(query, { ...flat, projectTitle: "connect" }, NOW)).not.toBeNull(); + } }); it("reads letters and numbers typed together, without forgiving typos in numbers", () => { diff --git a/packages/shared/src/paletteSearch.ts b/packages/shared/src/paletteSearch.ts index c163482c3af73..02e29a02f2a5d 100644 --- a/packages/shared/src/paletteSearch.ts +++ b/packages/shared/src/paletteSearch.ts @@ -923,9 +923,19 @@ export interface SearchMatchHint { } // Most threads' branches start with the app's own worktree prefix ("t3/", and -// "t3code/" before it), so "t3 connect" would match nearly every thread. +// "t3code/" before it, "t3-" when a "t3" branch blocks nested refs), so +// "t3 connect" would match nearly every thread. // Only before more text, so typing "t3/" does not empty the list for a keystroke. -const WORKTREE_BRANCH_PREFIX_PATTERN = new RegExp(`^(?:${WORKTREE_BRANCH_PREFIX}|t3code)/(?=\\S)`); +const WORKTREE_BRANCH_PREFIX_PATTERN = new RegExp( + `^(?:(?:${WORKTREE_BRANCH_PREFIX}|t3code)/(?=\\S)|${WORKTREE_BRANCH_PREFIX}-(?=[0-9a-f]{8}$))`, +); + +// The flat prefix anywhere in a query, while its hex is still being typed, so +// "t3-abcd" and "connect t3-abcd1234" still reach the stripped branch field. +const FLAT_BRANCH_QUERY_PREFIX_PATTERN = new RegExp( + `(^| )${WORKTREE_BRANCH_PREFIX}-(?=[0-9a-f]{1,8}(?: |$))`, + "g", +); function searchableBranch(branch: string | null | undefined): string | null { return branch ? branch.replace(WORKTREE_BRANCH_PREFIX_PATTERN, "") : null; @@ -1005,7 +1015,8 @@ function threadFieldQuery(normalizedQuery: string): string { fieldQuery: normalizedQuery .replace(/^(?:pr|pull request|pull)\s*(?=#?\d)/, "") .replace(/^#\s*/, "") - .replace(WORKTREE_BRANCH_PREFIX_PATTERN, ""), + .replace(WORKTREE_BRANCH_PREFIX_PATTERN, "") + .replace(FLAT_BRANCH_QUERY_PREFIX_PATTERN, "$1"), }; } return lastFieldQuery.fieldQuery; From 841f98d4d80f88ce7218dc1d8dd388cd1e13aee4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 10:01:00 -0800 Subject: [PATCH 43/56] fix(mobile): a steer splits a settled turn's "Worked for" fold (#35408) --- .../src/features/threads/ThreadFeed.tsx | 2 +- apps/mobile/src/lib/threadActivity.test.ts | 74 ++++++++- apps/mobile/src/lib/threadActivity.ts | 149 +++++++++++++----- 3 files changed, 177 insertions(+), 48 deletions(-) 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/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]), From ddd02848e601e63e04686fa636a818df90a8a207 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 10:01:15 -0800 Subject: [PATCH 44/56] fix(shared): html_render pages show for Grok threads (#35434) --- packages/shared/src/htmlRender.test.ts | 10 ++++++++++ packages/shared/src/toolOutput.ts | 6 +++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/htmlRender.test.ts b/packages/shared/src/htmlRender.test.ts index 9f6315541547f..f76b1c8a56259 100644 --- a/packages/shared/src/htmlRender.test.ts +++ b/packages/shared/src/htmlRender.test.ts @@ -169,6 +169,16 @@ describe("htmlRenderFromToolItem", () => { ["html_render", result], // OpenCode 2 Code Mode reports a script's nested html_render call as one `execute` item. ["execute", JSON.stringify(result)], + // Grok CLI wraps MCP results as { type: "MCP", output: { OkayOutput: "" } }. + [ + "t3-code.html_render", + { + type: "MCP", + tool_name: "html_render", + server_name: "t3-code", + output: { OkayOutput: JSON.stringify(result) }, + }, + ], ] as const) { expect(htmlRenderFromToolItem({ toolName, output })).toEqual(reference); } diff --git a/packages/shared/src/toolOutput.ts b/packages/shared/src/toolOutput.ts index f2773b0045e4c..6d63d9425d768 100644 --- a/packages/shared/src/toolOutput.ts +++ b/packages/shared/src/toolOutput.ts @@ -100,7 +100,11 @@ function readResult(value: unknown, budget: ResultReadBudget, depth = 0): Result value.is_error === true || value._tag === "OrchestratorMcpFailure" || value.error != null; - const content = value.structuredContent ?? value.content; + // Grok CLI wraps MCP results as { type: "MCP", output: { OkayOutput: "" } }. + const content = + value.structuredContent ?? + value.content ?? + (Predicate.isObject(value.output) ? value.output.OkayOutput : undefined); if (content !== undefined) { const nested = readResult(content, budget, depth + 1); return { ...nested, failed: failed || nested.failed }; From 5ff3d3c0eccdc5aea62e177967c992fccddecb44 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 10:01:30 -0800 Subject: [PATCH 45/56] fix(server): Claude 1-hour cache writes are priced at the 1-hour rate (#35423) --- .../src/provider/Drivers/claudeUsage.test.ts | 48 +++++++++++- .../src/provider/Drivers/claudeUsage.ts | 9 +++ apps/server/src/usage/UsageService.test.ts | 2 +- .../server/src/usage/usageAggregation.test.ts | 2 + apps/server/src/usage/usageAggregation.ts | 6 ++ apps/server/src/usage/usagePricing.ts | 74 ++++++++++++------- apps/server/src/usage/usageScanCache.test.ts | 16 +++- apps/server/src/usage/usageScanCache.ts | 27 ++++--- packages/provider-core/src/server/usage.ts | 2 + 9 files changed, 143 insertions(+), 43 deletions(-) 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/usage/UsageService.test.ts b/apps/server/src/usage/UsageService.test.ts index ae0126d438254..3644a53bbc396 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/packages/provider-core/src/server/usage.ts b/packages/provider-core/src/server/usage.ts index eaed1d06ece4f..c2c75a641e53a 100644 --- a/packages/provider-core/src/server/usage.ts +++ b/packages/provider-core/src/server/usage.ts @@ -18,6 +18,8 @@ export interface UsageRecord { readonly rateModel?: string; readonly sessionId: string; readonly totals: UsageTokenTotals; + /** The part of `totals.cacheCreationTokens` written with a 1-hour TTL. */ + readonly cacheCreation1hTokens?: number; readonly reportedCostUsd: number | null; readonly speed: UsageSpeed; readonly unresolvedServiceTierTurnId?: string; From 662a1ce6e27c0384ac8a12b7b0c435285ace56e7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 10:01:43 -0800 Subject: [PATCH 46/56] fix(opencode): OpenCode Go threads no longer fail on a reasoning level the model lacks (#35432) --- .../Adapters/OpenCode2AdapterV2.test.ts | 15 ++++++++++ .../src/server/status.test.ts | 20 ++++++++++++- .../provider-opencode/src/server/status.ts | 2 +- .../src/server/v2/adapter.ts | 28 +++++++++++++------ 4 files changed, 55 insertions(+), 10 deletions(-) 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/packages/provider-opencode/src/server/status.test.ts b/packages/provider-opencode/src/server/status.test.ts index c07464f036411..4c4f61f03d681 100644 --- a/packages/provider-opencode/src/server/status.test.ts +++ b/packages/provider-opencode/src/server/status.test.ts @@ -850,6 +850,12 @@ it.layer(layerTest)("checkOpenCodeProviderStatus", (it) => { name: "Space Bunny Free", variants: [{ id: "low" }, { id: "medium" }, { id: "high" }], }, + { + providerID: "opencode-go", + id: "deepseek-v4.1-flash", + name: "DeepSeek V4.1 Flash", + variants: [{ id: "low" }, { id: "high" }, { id: "max" }], + }, ]), ); @@ -869,7 +875,7 @@ it.layer(layerTest)("checkOpenCodeProviderStatus", (it) => { ); NodeAssert.deepEqual( snapshot.models.map((model) => model.slug), - ["opencode/big-pickle", "opencode/space-bunny-free"], + ["opencode/big-pickle", "opencode-go/deepseek-v4.1-flash", "opencode/space-bunny-free"], ); const variant = snapshot.models.find((model) => model.slug === "opencode/space-bunny-free") ?.capabilities?.optionDescriptors?.[0]; @@ -877,6 +883,18 @@ it.layer(layerTest)("checkOpenCodeProviderStatus", (it) => { variant?.type === "select" ? variant.options.map((option) => option.id) : [], ["low", "medium", "high"], ); + const goVariant = snapshot.models.find( + (model) => model.slug === "opencode-go/deepseek-v4.1-flash", + )?.capabilities?.optionDescriptors?.[0]; + const goVariantIds = + goVariant?.type === "select" ? goVariant.options.map((option) => option.id) : []; + NodeAssert.deepEqual(goVariantIds, ["low", "high", "max"]); + NodeAssert.ok( + goVariant?.type === "select" && + goVariant.currentValue !== undefined && + goVariantIds.includes(goVariant.currentValue), + "an OpenCode Go model gets a default reasoning variant it lists", + ); NodeAssert.equal(runtimeMock.state.sdkClientInputs.length, 0); }), ); diff --git a/packages/provider-opencode/src/server/status.ts b/packages/provider-opencode/src/server/status.ts index 0f24b1e22f479..26f6380dc0ff6 100644 --- a/packages/provider-opencode/src/server/status.ts +++ b/packages/provider-opencode/src/server/status.ts @@ -193,7 +193,7 @@ function inferDefaultVariant( if (providerID === "anthropic" || providerID.startsWith("google")) { return variants.includes("high") ? "high" : undefined; } - if (providerID === "openai" || providerID === "opencode") { + if (providerID === "openai" || providerID === "opencode" || providerID === "opencode-go") { return variants.includes("medium") ? "medium" : variants.includes("high") ? "high" : undefined; } return undefined; diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index b13f6c361bacf..4ba6c2ed827cf 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -660,10 +660,18 @@ const boundaryAfter = ( const isProviderAdapterError = Schema.is(ProviderAdapter.ProviderAdapterV2Error); -const modelRef = (selection: ProviderAdapter.ProviderAdapterV2TurnInput["modelSelection"]) => { +// A saved or inherited variant the catalog model does not list makes OpenCode reject the turn. +const modelRef = ( + selection: ProviderAdapter.ProviderAdapterV2TurnInput["modelSelection"], + listedVariants: ReadonlySet | undefined, +) => { const parsed = OpenCodeRuntime.parseOpenCodeModelSlug(selection.model); if (parsed === null) return undefined; - const variant = getModelSelectionStringOptionValue(selection, "variant"); + const selected = getModelSelectionStringOptionValue(selection, "variant"); + const variant = + selected === undefined || listedVariants === undefined || listedVariants.has(selected) + ? selected + : undefined; return Model.Ref.make({ providerID: Provider.ID.make(parsed.providerID), id: Model.ID.make(parsed.modelID), @@ -765,9 +773,12 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const sessionScope = yield* Effect.scope; // Project config changes model limits; key by directory because this runtime serves all instance threads. const contextWindows = new Map>(); + const modelVariants = new Map>>(); const directoryOf = (cwd: string | null | undefined) => cwd ?? host.paths.cwd; const windowOf = (cwd: string | null | undefined, model: string) => contextWindows.get(directoryOf(cwd))?.get(model); + const listedModelRef = (selection: ModelSelection, cwd: string | null | undefined) => + modelRef(selection, modelVariants.get(directoryOf(cwd))?.get(selection.model)); const now = yield* DateTime.now; let session: OrchestrationV2ProviderSession = { id: input.providerSessionId, @@ -3699,15 +3710,16 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr Effect.suspend(() => { const windows = contextWindows.get(directory) ?? new Map(); contextWindows.set(directory, windows); + const variants = modelVariants.get(directory) ?? new Map>(); + modelVariants.set(directory, variants); return client.model.list({ location: { directory } }).pipe( Effect.timeout("5 seconds"), Effect.tap((models) => Effect.sync(() => { for (const model of models.data) { - windows.set( - `${model.providerID}/${model.id}`, - model.limit.input ?? model.limit.context, - ); + const slug = `${model.providerID}/${model.id}`; + windows.set(slug, model.limit.input ?? model.limit.context); + variants.set(slug, new Set(model.variants.map((variant) => variant.id))); } }), ), @@ -4434,7 +4446,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }); } yield* readModelsOnce(threadInput.runtimePolicy.cwd); - const model = modelRef(threadInput.modelSelection); + const model = listedModelRef(threadInput.modelSelection, threadInput.runtimePolicy.cwd); if (model === undefined) { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver: OPENCODE_PROVIDER, @@ -4611,7 +4623,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr }), }); } - const model = modelRef(turnInput.modelSelection); + const model = listedModelRef(turnInput.modelSelection, turnInput.runtimePolicy.cwd); if (model === undefined) { yield* begin; return yield* finishTurn(state, { From c58450f2cf11d1cee712967d36183b8f9fcc255d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 10:01:58 -0800 Subject: [PATCH 47/56] fix(ssh): SSH environments connect over links with about a second of round trip (#35418) --- packages/ssh/src/tunnel.test.ts | 49 +++++++++++++++++++++++++++++++++ packages/ssh/src/tunnel.ts | 4 ++- 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/packages/ssh/src/tunnel.test.ts b/packages/ssh/src/tunnel.test.ts index 03f8ebe2a62e1..06a99f0b0eb04 100644 --- a/packages/ssh/src/tunnel.test.ts +++ b/packages/ssh/src/tunnel.test.ts @@ -527,6 +527,55 @@ describe("ssh tunnel scripts", () => { }), ); + it.effect("connects through a tunnel whose responses take longer than a second", () => + Effect.gen(function* () { + // Over a ~1s RTT link each request through the forward takes a few round trips. + const RESPONSE_MS = 2_500; + const tunnelSpawned = yield* Deferred.make(); + const spawner = ChildProcessSpawner.make((command) => + commandArgs(command).includes("-N") + ? Deferred.succeed(tunnelSpawned, undefined).pipe( + Effect.as(makeRunningProcess(() => undefined)), + ) + : Effect.succeed(makeSuccessfulProcess('{"remotePort":3773}\n')), + ); + const httpClient = HttpClient.make((request) => + Effect.sleep(Duration.millis(RESPONSE_MS)).pipe( + Effect.as(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))), + ), + ); + const layer = Layer.mergeAll( + NodeServices.layer, + NodeCrypto.layer, + Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner), + Layer.succeed(HttpClient.HttpClient, httpClient), + Layer.succeed(NetService.NetService, testNetService), + SshAuth.SshPasswordPrompt.disabledLayer, + SshTunnel.SshEnvironmentManager.layer({ resolveCliRunner: Effect.succeed(ARCHIVE) }), + ); + yield* Effect.gen(function* () { + const manager = yield* SshTunnel.SshEnvironmentManager; + const ensure = yield* Effect.forkChild( + Effect.result( + manager.ensureEnvironment({ + alias: "devbox", + hostname: "devbox", + username: null, + port: null, + }), + ), + ); + yield* Deferred.await(tunnelSpawned); + yield* TestClock.adjust(Duration.seconds(60)); + const result = yield* Fiber.join(ensure); + assert.isTrue( + Result.isSuccess(result), + Result.isFailure(result) ? result.failure.message : undefined, + ); + }).pipe(Effect.provide(layer), Effect.scoped); + }), + ); + it.effect("reconnects a saved alias through the port its ssh config names now", () => Effect.gen(function* () { let configPort = 53_791; diff --git a/packages/ssh/src/tunnel.ts b/packages/ssh/src/tunnel.ts index 5d4ac857b17b7..be4c72b99223b 100644 --- a/packages/ssh/src/tunnel.ts +++ b/packages/ssh/src/tunnel.ts @@ -51,6 +51,8 @@ const DEFAULT_REMOTE_PORT = 3773; const REMOTE_PORT_SCAN_WINDOW = 200; const SSH_READY_TIMEOUT_MS = 20_000; const SSH_READY_PROBE_TIMEOUT_MS = 1_000; +// Probes through the forward pay several link round trips, about 4s at a 1s RTT. +const SSH_TUNNEL_READY_PROBE_TIMEOUT_MS = 5_000; const TUNNEL_SHUTDOWN_TIMEOUT_MS = 2_000; const TUNNEL_STDERR_TAIL_CHARS = 16_384; const REMOTE_READY_TIMEOUT_MS = 60_000; @@ -1159,7 +1161,7 @@ const waitForHttpReady = (input: { ...(input.path === undefined ? {} : { path: input.path }), ...(input.timeoutMs === undefined ? {} : { timeoutMs: input.timeoutMs }), ...(input.intervalMs === undefined ? {} : { intervalMs: input.intervalMs }), - probeTimeoutMs: input.probeTimeoutMs ?? SSH_READY_PROBE_TIMEOUT_MS, + probeTimeoutMs: input.probeTimeoutMs ?? SSH_TUNNEL_READY_PROBE_TIMEOUT_MS, makeError: ({ requestUrl, probeTimeoutMs, cause }) => { if (typeof cause === "object" && cause !== null && "kind" in cause) { const kind = (cause as { readonly kind?: unknown }).kind; From 315b06c5ecf6587acf53baa0a5691579e04c3f8c Mon Sep 17 00:00:00 2001 From: Wout Stiens <71498452+StiensWout@users.noreply.github.com> Date: Thu, 12 Nov 2026 19:03:48 +0100 Subject: [PATCH 48/56] feat(providers): managed Antigravity and Codex installs can update past their pin (#21249) Co-authored-by: Claude Opus 5.5 Co-authored-by: maria-rcks Co-authored-by: Yash Singh --- .../provider/AntigravityInstallation.test.ts | 231 +++++++++- .../src/provider/AntigravityInstallation.ts | 424 ++++++++++++++---- .../src/provider/CodexInstallation.test.ts | 216 ++++++++- apps/server/src/provider/CodexInstallation.ts | 178 +++++++- .../server/src/provider/antigravityRelease.ts | 12 + apps/server/src/provider/managedRelease.ts | 29 ++ .../src/provider/providerInstallation.test.ts | 2 + .../src/provider/providerInstallation.ts | 12 + .../components/settings/CodexSetupSection.tsx | 12 + docs/user/install.md | 4 + .../src/server/AcpRegistrySupport.ts | 7 +- 11 files changed, 1028 insertions(+), 99 deletions(-) create mode 100644 apps/server/src/provider/managedRelease.ts 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/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/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}