TypeScript
perf(server): sidebar shell loads 3x faster and startup thread counts 80x faster (#27106)
Julius Marminge8bf4822f5eb5
diff --git a/apps/server/integration/transferBudgetV2.integration.test.ts b/apps/server/integration/transferBudgetV2.integration.test.tsindex 22db0e643db..68a622c541f 100644--- a/apps/server/integration/transferBudgetV2.integration.test.ts+++ b/apps/server/integration/transferBudgetV2.integration.test.ts@@ -117,6 +117,7 @@ const layerManagement = Layer.unwrap(.pipe(Effect.orDie),getThreadShell: (id) => projections.getThreadShell(id).pipe(Effect.orDie),getShellSnapshot: (options) => projections.getShellSnapshot(options).pipe(Effect.orDie),+ listActiveShellIndex: () => projections.listActiveShellIndex().pipe(Effect.orDie),listActiveSubagentThreadIds: () =>projections.listActiveSubagentThreadIds().pipe(Effect.orDie),readShellSnapshot: (options) =>diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 76bcc00bbcb..c464a8743f3 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -141,6 +141,7 @@ import {type ProjectionRecords,type ProjectionCheckpointContext,type OlderSettledThreadsListing,+ type ActiveShellIndexEntry,type OlderSettledThreadsQuery,type ShellSnapshotOptions,} from "./ProjectionStore.ts";@@ -392,6 +393,11 @@ export interface OrchestratorV2Shape {ReadonlyArray<ThreadId>,OrchestratorV2Error>;+ readonly countThreads: () => Effect.Effect<number, OrchestratorV2Error>;+ readonly listActiveShellIndex: () => Effect.Effect<+ ReadonlyArray<ActiveShellIndexEntry>,+ OrchestratorV2Error+ >;readonly listOlderSettledThreads: (query: OlderSettledThreadsQuery,) => Effect.Effect<OlderSettledThreadsListing, OrchestratorV2Error>;@@ -13434,6 +13440,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio.pipe(Effect.mapError(shellProjectionError));},),+ countThreads: Effect.fn("OrchestratorV2.countThreads")(function () {+ return projectionStore.countThreads().pipe(Effect.mapError(shellProjectionError));+ }),+ listActiveShellIndex: Effect.fn("OrchestratorV2.listActiveShellIndex")(function () {+ return projectionStore.listActiveShellIndex().pipe(Effect.mapError(shellProjectionError));+ }),listOlderSettledThreads: Effect.fn("OrchestratorV2.listOlderSettledThreads")(function (query) {return projectionStore.listOlderSettledThreads(query)diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 8d46b510315..1dc7c912e77 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -26,6 +26,7 @@ import {ThreadId,TurnItemId,type ThreadPullRequestLink,+ isLiveSubagentShell,} from "@t3tools/contracts";import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";@@ -76,6 +77,33 @@ const traceSqlStatements = () => {return { statements, tracer };};+/** The shell index flags every live shell and matches its shells on the fields subscriber trims read. */+const assertShellIndexCoversShells = Effect.fnUntraced(function* () {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const shells = (yield* store.getShellSnapshot({ location: "active" })).threads;+ const index = yield* store.listActiveShellIndex();+ const iso = (value: DateTime.Utc | null | undefined) =>+ value == null ? null : DateTime.formatIso(value);+ const trimmed = (+ row: Pick<+ ProjectionStore.ActiveShellIndexEntry,+ "id" | "projectId" | "lineage" | "settledOverride" | "settledAt" | "pinnedAt" | "snoozedUntil"+ >,+ ) => ({+ id: row.id,+ projectId: row.projectId,+ lineage: row.lineage,+ settledOverride: row.settledOverride,+ settledAt: iso(row.settledAt),+ pinnedAt: iso(row.pinnedAt),+ snoozedUntil: iso(row.snoozedUntil),+ });+ assert.deepEqual(index.map(trimmed), shells.map(trimmed));+ shells.forEach((shell, position) => {+ if (isLiveSubagentShell(shell)) assert.isTrue(index[position]?.mayBeLive, shell.id);+ });+});+const addRolledBackRecoveryCandidate = Effect.fn("addRolledBackRecoveryCandidate")(function* (suffix: string,) {@@ -272,6 +300,7 @@ it.effect("SQL shells flag only an active turn blocked solely on T3 thread waitsassert.equal(shell?.status, "running");assert.equal(shell?.blockedOnThreadWait ?? false, expected);}+ yield* assertShellIndexCoversShells();});const wait = {...itemBase,@@ -531,6 +560,7 @@ it.effect("SQL shells use the latest subagent owner for duplicate provider-threaconst listed = (yield* store.getShellSnapshot()).threads.find((thread) => thread.id === targetThreadId,);+ yield* assertShellIndexCoversShells();for (const shell of [yield* store.getThreadShell(targetThreadId), listed]) {assert.equal(shell?.providerInstanceId, otherInstanceId);assert.equal(shell?.activeRunId, null);@@ -1336,6 +1366,7 @@ it.effect("SQL list older settled threads below a cursor", () =>const next = yield* list({ settledAt: DateTime.formatIso(at(4)), threadId: id("b") }, 10);assert.deepEqual(next.threadIds, [id("c"), id("d"), id("snoozed")]);assert.deepEqual(yield* list(before, 25, []), { threadIds: [], counts: [] });+ yield* assertShellIndexCoversShells();const scoped = yield* list(before, 0, [ProjectId.make("project:b")]);assert.deepEqual(scoped, {threadIds: [],@@ -3798,6 +3829,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {const sqlShell = (yield* projectionStore.getShellSnapshot()).threads.find((row) => row.id === threadId,)!;+ yield* assertShellIndexCoversShells();for (const questionShell of [sqlShell,ProjectionStore.threadShellFromProjection(projection),@@ -4860,6 +4892,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {SET status = 'running', payload_json = json_set(payload_json, '$.status', 'running')WHERE run_id = ${runId}`;+ yield* assertShellIndexCoversShells();const secretOnlyShell = (yield* projectionStore.getShellSnapshot()).threads.find((thread) => thread.id === threadId,);@@ -6466,6 +6499,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {(candidate) => candidate.id === threadId,);assert.deepEqual(listed?.pendingBackgroundTasks, shell?.pendingBackgroundTasks);+ yield* assertShellIndexCoversShells();return shell && projectThreadAwarenessV2({ environmentId, project, thread: shell })?.phase;});diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex 287a30a9d90..6bb04041c75 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -393,6 +393,15 @@ export interface ShellSnapshotOptions {readonly threadIds?: ReadonlyArray<ThreadId>;}+/** What a shell subscriber's trims read from an active thread, without building its shell. */+export interface ActiveShellIndexEntry extends Pick<+ OrchestrationV2ThreadShell,+ "id" | "projectId" | "lineage" | "settledOverride" | "settledAt" | "pinnedAt" | "snoozedUntil"+> {+ /** False only when no run, request, work item, or watch can make the shell live. */+ readonly mayBeLive: boolean;+}+export interface OlderSettledThreadsQuery {readonly before: OrchestrationV2OlderSettledCursor;readonly projectIds?: ReadonlyArray<ProjectId> | undefined;@@ -450,6 +459,13 @@ export interface ProjectionStoreV2Shape {ReadonlyArray<ThreadId>,ProjectionStoreV2Error>;+ /** Threads that are not deleted, archived ones included. */+ readonly countThreads: () => Effect.Effect<number, ProjectionStoreV2Error>;+ /** Every active thread, in shell order. */+ readonly listActiveShellIndex: () => Effect.Effect<+ ReadonlyArray<ActiveShellIndexEntry>,+ ProjectionStoreV2Error+ >;/** Older settled thread ids below a cursor, newest settle first, and per-project counts. */readonly listOlderSettledThreads: (query: OlderSettledThreadsQuery,@@ -6614,6 +6630,98 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =Effect.mapError(shellSnapshotReadError),);+ const countThreads = Effect.fn("ProjectionStore.countThreads")(function* () {+ const rows = yield* sql<{ readonly count: number }>`+ SELECT COUNT(*) AS count FROM orchestration_v2_projection_threads WHERE deleted_at IS NULL+ `;+ return rows[0]?.count ?? 0;+ }, Effect.mapError(shellSnapshotReadError));++ const listActiveShellIndex = Effect.fn("ProjectionStore.listActiveShellIndex")(function* () {+ const rows = yield* sql<{+ readonly thread_id: string;+ readonly project_id: string;+ readonly relationship_to_parent: string | null;+ readonly parent_thread_id: string | null;+ readonly root_thread_id: string;+ readonly settled_override: string | null;+ readonly settled_at: string | null;+ readonly pinned_at: string | null;+ readonly snoozed_until: string | null;+ readonly may_be_live: number;+ }>`+ SELECT+ t.thread_id,+ t.project_id,+ json_extract(t.payload_json, '$.lineage.relationshipToParent') AS relationship_to_parent,+ json_extract(t.payload_json, '$.lineage.parentThreadId') AS parent_thread_id,+ json_extract(t.payload_json, '$.lineage.rootThreadId') AS root_thread_id,+ json_extract(t.payload_json, '$.settledOverride') AS settled_override,+ json_extract(t.payload_json, '$.settledAt') AS settled_at,+ json_extract(t.payload_json, '$.pinnedAt') AS pinned_at,+ json_extract(t.payload_json, '$.snoozedUntil') AS snoozed_until,+ -- A superset of isLiveSubagentShell: the sources of its run status, pending request,+ -- and pending background work.+ (+ EXISTS (+ SELECT 1 FROM orchestration_v2_projection_runs r+ WHERE r.thread_id = t.thread_id+ AND r.status IN ('queued', 'preparing', 'starting', 'running', 'waiting')+ )+ OR EXISTS (+ SELECT 1 FROM orchestration_v2_projection_runtime_requests request+ WHERE request.thread_id = t.thread_id AND request.status = 'pending'+ )+ -- Same predicates as the shell's pending item and link reads, for their partial indexes.+ OR EXISTS (+ SELECT 1 FROM orchestration_v2_projection_turn_items item+ WHERE item.thread_id = t.thread_id+ AND item.type IN ('command_execution', 'dynamic_tool', 'subagent')+ AND item.status NOT IN ('completed', 'interrupted', 'failed', 'cancelled')+ )+ OR EXISTS (+ SELECT 1 FROM orchestration_v2_projection_turn_items link_request+ WHERE link_request.thread_id = t.thread_id+ AND link_request.type = 'link_request' AND link_request.status = 'waiting'+ )+ OR EXISTS (+ SELECT 1 FROM orchestration_v2_projection_provider_threads provider_thread+ WHERE provider_thread.thread_id = t.thread_id+ AND json_array_length(provider_thread.payload_json, '$.pendingBackgroundTasks') > 0+ )+ OR EXISTS (+ SELECT 1 FROM json_each(t.payload_json, '$.pullRequests') link+ WHERE json_type(link.value, '$.watch') IS NOT NULL+ )+ ) AS may_be_live+ FROM orchestration_v2_projection_threads t+ WHERE t.deleted_at IS NULL+ AND json_extract(t.payload_json, '$.archivedAt') IS NULL+ ORDER BY t.updated_at ASC, t.thread_id ASC+ `;+ return rows.map((row): ActiveShellIndexEntry => ({+ id: ThreadId.make(row.thread_id),+ projectId: ProjectId.make(row.project_id),+ lineage: {+ parentThreadId:+ row.parent_thread_id === null ? null : ThreadId.make(row.parent_thread_id),+ relationshipToParent:+ row.relationship_to_parent === "fork" || row.relationship_to_parent === "subagent"+ ? row.relationship_to_parent+ : null,+ rootThreadId: ThreadId.make(row.root_thread_id),+ },+ settledOverride:+ row.settled_override === "settled" || row.settled_override === "active"+ ? row.settled_override+ : null,+ settledAt: row.settled_at === null ? null : DateTime.makeUnsafe(row.settled_at),+ 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,+ }));+ }, Effect.mapError(shellSnapshotReadError));+const findGuestShareThreadId = Effect.fn("ProjectionStore.findGuestShareThreadId")(function* (shareId: GuestShareId,) {@@ -6768,6 +6876,8 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =apply,getShellSnapshot: readOnReader(getShellSnapshot),listActiveSubagentThreadIds: readOnReader(listActiveSubagentThreadIds),+ countThreads: readOnReader(countThreads),+ listActiveShellIndex: readOnReader(listActiveShellIndex),readShellSnapshot: readOnReader(readShellSnapshot),listOlderSettledThreads: readOnReader(listOlderSettledThreads),getThreadShell: readOnReader(getThreadShell),diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.tsindex a39f6b7f036..1d79e87eb9b 100644--- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts@@ -213,6 +213,8 @@ it.effect(getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"),getShellSnapshot: () => Effect.die("unused getShellSnapshot"),listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),+ countThreads: () => Effect.die("unused countThreads"),+ listActiveShellIndex: () => Effect.die("unused listActiveShellIndex"),listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"),readShellSnapshot: () => Effect.die("unused readShellSnapshot"),getThreadShell: () => Effect.die("unused getThreadShell"),diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.tsindex 8a075e13c52..67d07d6684c 100644--- a/apps/server/src/orchestration-v2/ShellStream.ts+++ b/apps/server/src/orchestration-v2/ShellStream.ts@@ -31,6 +31,7 @@ import type * as SqlClient from "effect/sql/SqlClient";import * as Stream from "effect/Stream";import { bufferLatestLiveStream } from "./LiveStreamBudget.ts";+import type { ActiveShellIndexEntry } from "./ProjectionStore.ts";type ShellDelta = Extract<OrchestrationV2ShellStreamItem, { readonly sequence: number }>;@@ -56,7 +57,7 @@ export const bufferShellLiveStream = <E, R>(limits,);-export function buildActiveShellSnapshot(input: {+function buildActiveShellSnapshot(input: {readonly projects: ReadonlyArray<OrchestrationProjectShell>;readonly threads: OrchestrationV2ThreadShellSnapshot;readonly snapshotSequence: number;@@ -70,26 +71,119 @@ export function buildActiveShellSnapshot(input: {};}+type ShellTrimRow = Pick<+ OrchestrationV2ThreadShell,+ "id" | "projectId" | "lineage" | "settledOverride" | "settledAt"+>;+/**- * 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.+ * What a subscriber's trims read across every active row. Computed from full shells or from the+ * store's index, so a snapshot read only for the rows it sends trims the same way.*/-export function omitIdleSubagentShells(- threads: ReadonlyArray<OrchestrationV2ThreadShell>,-): ReadonlyArray<OrchestrationV2ThreadShell> {- const parentIds = new Set<string>();- for (const thread of threads) {- if (thread.lineage.relationshipToParent === "subagent" && thread.lineage.parentThreadId) {- parentIds.add(thread.lineage.parentThreadId);+interface ShellTrimFacts {+ readonly subagentParentIds: ReadonlySet<string>;+ readonly subagentThreadIds: Set<string>;+ /** Undefined when no thread is settled, so none is older. */+ readonly olderSettledBeforeMs: number | undefined;+ readonly olderSettledCounts: ReadonlyArray<OrchestrationV2OlderSettledCount>;+}++const NEWEST_SETTLED_KEPT = 25;++function shellTrimFacts(rows: ReadonlyArray<ShellTrimRow>): ShellTrimFacts {+ const subagentParentIds = new Set<string>();+ const subagentThreadIds = new Set<string>();+ const settledTimes: Array<number> = [];+ for (const row of rows) {+ if (row.lineage.relationshipToParent === "subagent") {+ subagentThreadIds.add(row.id);+ if (row.lineage.parentThreadId) subagentParentIds.add(row.lineage.parentThreadId);+ } else if (row.settledOverride === "settled" && row.settledAt !== null) {+ settledTimes.push(DateTime.toEpochMillis(row.settledAt));+ }+ }+ settledTimes.sort((left, right) => right - left);+ // With fewer than 25, the oldest one is the cut, so nothing is older.+ const olderSettledBeforeMs = settledTimes[NEWEST_SETTLED_KEPT - 1] ?? settledTimes.at(-1);+ const counts = new Map<ProjectId, number>();+ if (olderSettledBeforeMs !== undefined) {+ for (const row of rows) {+ if (isOlderSettledThreadShell(row, olderSettledBeforeMs)) {+ counts.set(row.projectId, (counts.get(row.projectId) ?? 0) + 1);+ }}}+ return {+ subagentParentIds,+ subagentThreadIds,+ olderSettledBeforeMs,+ olderSettledCounts: Array.from(counts, ([projectId, count]) => ({ projectId, count })),+ };+}++function subagentAncestorIds(threads: ReadonlyArray<Pick<OrchestrationV2ThreadShell, "lineage">>) {+ const ancestorIds = new Set<string>();+ for (const thread of threads) {+ if (thread.lineage.relationshipToParent !== "subagent") continue;+ if (thread.lineage.parentThreadId !== null) ancestorIds.add(thread.lineage.parentThreadId);+ ancestorIds.add(thread.lineage.rootThreadId);+ }+ return ancestorIds;+}++function omitIdleSubagentShellsWith(+ threads: ReadonlyArray<OrchestrationV2ThreadShell>,+ facts: Pick<ShellTrimFacts, "subagentParentIds">,+): ReadonlyArray<OrchestrationV2ThreadShell> {return threads.filter((thread) =>thread.lineage.relationshipToParent !== "subagent" ||isLiveSubagentShell(thread) ||- parentIds.has(thread.id),+ facts.subagentParentIds.has(thread.id),+ );+}++function omitOlderSettledShellsWith(+ input: {+ readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;+ readonly snapshotSequence: number;+ readonly now: DateTime.Utc;+ },+ facts: Pick<ShellTrimFacts, "olderSettledBeforeMs" | "olderSettledCounts">,+): {+ readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;+ readonly olderSettled: OrchestrationV2OlderSettledThreads;+} {+ const nowMs = DateTime.toEpochMillis(input.now);+ const beforeMs = facts.olderSettledBeforeMs ?? nowMs;+ const ancestorIds = subagentAncestorIds(input.threads);+ const threads = input.threads.filter(+ (thread) =>+ !isOlderSettledThreadShell(thread, beforeMs) ||+ thread.pinnedAt != null ||+ (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) ||+ isLiveSubagentShell(thread) ||+ ancestorIds.has(thread.id),);+ return {+ threads,+ olderSettled: {+ before: DateTime.formatIso(DateTime.makeUnsafe(beforeMs)),+ asOfSequence: input.snapshotSequence,+ counts: facts.olderSettledCounts,+ },+ };+}++/**+ * 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.+ */+export function omitIdleSubagentShells(+ threads: ReadonlyArray<OrchestrationV2ThreadShell>,+): ReadonlyArray<OrchestrationV2ThreadShell> {+ return omitIdleSubagentShellsWith(threads, shellTrimFacts(threads));}/**@@ -103,18 +197,13 @@ export function activeShellRowsForSubscriber(readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;readonly subagentThreadIds: Set<string>;} {+ const facts = shellTrimFacts(threads);return {- threads: omitIdleSubagents ? omitIdleSubagentShells(threads) : threads,- subagentThreadIds: new Set(- threads- .filter((thread) => thread.lineage.relationshipToParent === "subagent")- .map((thread) => thread.id),- ),+ threads: omitIdleSubagents ? omitIdleSubagentShellsWith(threads, facts) : threads,+ subagentThreadIds: facts.subagentThreadIds,};}-const NEWEST_SETTLED_KEPT = 25;-/*** 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@@ -128,77 +217,107 @@ export function omitOlderSettledShells(input: {readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;readonly olderSettled: OrchestrationV2OlderSettledThreads;} {- const nowMs = DateTime.toEpochMillis(input.now);- const settledTimes = input.threads- .flatMap((thread) =>- thread.lineage.relationshipToParent !== "subagent" &&- thread.settledOverride === "settled" &&- thread.settledAt !== null- ? [DateTime.toEpochMillis(thread.settledAt)]+ return omitOlderSettledShellsWith(input, shellTrimFacts(input.threads));+}++interface ShellSubscriberOptions {+ readonly omitIdleSubagents: boolean;+ readonly omitOlderSettled: boolean;+}++function trimShellSnapshot(+ base: OrchestrationV2ShellSnapshot,+ facts: ShellTrimFacts,+ options: ShellSubscriberOptions & { readonly now: DateTime.Utc },+): OrchestrationV2ShellSnapshot {+ const threads = options.omitIdleSubagents+ ? omitIdleSubagentShellsWith(base.threads, facts)+ : base.threads;+ if (!options.omitOlderSettled) return { ...base, threads };+ const older = omitOlderSettledShellsWith(+ { threads, snapshotSequence: base.snapshotSequence, now: options.now },+ facts,+ );+ return { ...base, threads: older.threads, olderSettled: older.olderSettled };+}++/**+ * The threads whose shells a trimmed snapshot can contain: a superset of what the trims keep, so+ * trimming the shells read for these ids gives the snapshot trimming every shell would.+ */+function shellSubscriberThreadIds(+ index: ReadonlyArray<ActiveShellIndexEntry>,+ options: ShellSubscriberOptions,+): ReadonlyArray<ThreadId> {+ const facts = shellTrimFacts(index);+ const subagents = index.filter(+ (entry) =>+ entry.lineage.relationshipToParent === "subagent" &&+ (!options.omitIdleSubagents || entry.mayBeLive || facts.subagentParentIds.has(entry.id)),+ );+ const ancestorIds = subagentAncestorIds(subagents);+ const keptSubagentIds = new Set(subagents.map((entry) => entry.id));+ const beforeMs = facts.olderSettledBeforeMs;+ return index.flatMap((entry) =>+ entry.lineage.relationshipToParent === "subagent"+ ? keptSubagentIds.has(entry.id)+ ? [entry.id]+ : []+ : !options.omitOlderSettled ||+ beforeMs === undefined ||+ !isOlderSettledThreadShell(entry, beforeMs) ||+ entry.pinnedAt != null ||+ entry.snoozedUntil != null ||+ entry.mayBeLive ||+ ancestorIds.has(entry.id)+ ? [entry.id]: [],- )- .sort((left, right) => right - left);- // With fewer than 25, the oldest one is the cut, so nothing is older.- const beforeMs = settledTimes[NEWEST_SETTLED_KEPT - 1] ?? settledTimes.at(-1) ?? nowMs;- const ancestorIds = new Set<string>();- for (const thread of input.threads) {- if (thread.lineage.relationshipToParent !== "subagent") continue;- if (thread.lineage.parentThreadId !== null) ancestorIds.add(thread.lineage.parentThreadId);- ancestorIds.add(thread.lineage.rootThreadId);- }- const counts = new Map<ProjectId, number>();- const threads = input.threads.filter((thread) => {- if (!isOlderSettledThreadShell(thread, beforeMs)) return true;- counts.set(thread.projectId, (counts.get(thread.projectId) ?? 0) + 1);- return (- thread.pinnedAt != null ||- (thread.snoozedUntil != null && DateTime.toEpochMillis(thread.snoozedUntil) > nowMs) ||- isLiveSubagentShell(thread) ||- ancestorIds.has(thread.id)- );- });- return {- threads,- olderSettled: {- before: DateTime.formatIso(DateTime.makeUnsafe(beforeMs)),- asOfSequence: input.snapshotSequence,- counts: Array.from(counts, ([projectId, count]) => ({ projectId, count })),- },- };+ );}/**- * The snapshot a shell subscriber gets for its opt-ins, and the subagent ids whose transcript- * events its stream drops (from every row, so an omitted child that wakes keeps that filter).+ * A subscriber's active shell snapshot, read like `loadShellSnapshotParts`. With an opt-in, the+ * store's index decides which shells to read, so threads the trims drop are never built.*/-export function shellSnapshotForSubscriber(- base: OrchestrationV2ShellSnapshot,- options: {- readonly omitIdleSubagents: boolean;- readonly omitOlderSettled: boolean;- readonly now: DateTime.Utc;- },-): {- readonly snapshot: OrchestrationV2ShellSnapshot;- readonly subagentThreadIds: Set<string>;-} {- const rows = activeShellRowsForSubscriber(base.threads, options.omitIdleSubagents);- if (!options.omitOlderSettled) {+export const loadSubscriberShellSnapshot = Effect.fn("ShellStream.loadSubscriberShellSnapshot")(+ function* <E1, E2, E3, E4, E5>(input: {+ readonly sql: SqlClient.SqlClient;+ readonly listShellIndex: Effect.Effect<ReadonlyArray<ActiveShellIndexEntry>, E1>;+ readonly readThreads: (+ threadIds: ReadonlyArray<ThreadId> | undefined,+ ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, E3>, E2>;+ readonly listProjects: Effect.Effect<ReadonlyArray<OrchestrationProjectShell>, E4>;+ readonly latestSequence: Effect.Effect<number, E5>;+ readonly options: ShellSubscriberOptions;+ }) {+ const trims = input.options.omitIdleSubagents || input.options.omitOlderSettled;+ const read = yield* input.sql+ .withTransaction(+ Effect.gen(function* () {+ const index = trims ? yield* input.listShellIndex : null;+ return {+ index,+ decodeThreads: yield* input.readThreads(+ index === null ? undefined : shellSubscriberThreadIds(index, input.options),+ ),+ projects: yield* input.listProjects,+ snapshotSequence: yield* input.latestSequence,+ };+ }),+ )+ .pipe(NodeSqliteClient.readOnly);+ const base = buildActiveShellSnapshot({+ projects: read.projects,+ threads: yield* read.decodeThreads,+ snapshotSequence: read.snapshotSequence,+ });+ const facts = shellTrimFacts(read.index ?? base.threads);return {- snapshot: { ...base, threads: rows.threads },- subagentThreadIds: rows.subagentThreadIds,+ snapshot: trimShellSnapshot(base, facts, { ...input.options, now: yield* DateTime.now }),+ subagentThreadIds: facts.subagentThreadIds,};- }- const older = omitOlderSettledShells({- threads: rows.threads,- snapshotSequence: base.snapshotSequence,- now: options.now,- });- return {- snapshot: { ...base, threads: older.threads, olderSettled: older.olderSettled },- subagentThreadIds: rows.subagentThreadIds,- };-}+ },+);/*** One transaction covers the reads so they agree; the threads are decoded after it commits,diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.tsindex 7a45a54a312..5c51b8c48b8 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.ts@@ -514,12 +514,9 @@ const make = Effect.gen(function* () {// Update parents first so children inherit names; reread each pass for newly updated descendants.const visited = new Set([threadId]);while (true) {- const snapshot = yield* threads.getShellSnapshot();+ const snapshot = yield* threads.getShellSnapshot({ worktreePath: worktreeCwd });const sharing = [...snapshot.threads, ...snapshot.archivedThreads].filter(- (thread) =>- !visited.has(thread.id) &&- thread.worktreePath === worktreeCwd &&- thread.branch === oldBranch,+ (thread) => !visited.has(thread.id) && thread.branch === oldBranch,);if (sharing.length === 0) break;for (const thread of sharing) {diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex cfbbd4a68a5..7b79b21e881 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -394,10 +394,15 @@ export interface ThreadManagementServiceShape {ProjectionRecords<K>,ThreadManagementProjectionLoadError | ThreadManagementThreadNotFoundError>;- readonly getShellSnapshot: (options?: {- readonly location?: "active" | "archive";- }) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;+ readonly getShellSnapshot: (+ options?: Pick<+ ShellSnapshotOptions,+ "location" | "projectId" | "unsettledOnly" | "worktreePath" | "threadIds"+ >,+ ) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;readonly listActiveSubagentThreadIds: Orchestrator.OrchestratorV2["Service"]["listActiveSubagentThreadIds"];+ readonly countThreads: Orchestrator.OrchestratorV2["Service"]["countThreads"];+ readonly listActiveShellIndex: Orchestrator.OrchestratorV2["Service"]["listActiveShellIndex"];readonly listOlderSettledThreads: Orchestrator.OrchestratorV2["Service"]["listOlderSettledThreads"];readonly readShellSnapshot: (options?: Pick<ShellSnapshotOptions, "location" | "familyOf" | "worktreePath" | "threadIds">,@@ -1333,6 +1338,8 @@ const make = Effect.gen(function* () {getProjectThreadRecords,getShellSnapshot: orchestrator.getShellSnapshot,listActiveSubagentThreadIds: orchestrator.listActiveSubagentThreadIds,+ countThreads: orchestrator.countThreads,+ listActiveShellIndex: orchestrator.listActiveShellIndex,listOlderSettledThreads: orchestrator.listOlderSettledThreads,readShellSnapshot: orchestrator.readShellSnapshot,getThreadShell: orchestrator.getThreadShell,diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.tsindex 61ff54d0c79..c2c67eb04d9 100644--- a/apps/server/src/orchestration-v2/http.ts+++ b/apps/server/src/orchestration-v2/http.ts@@ -3,7 +3,6 @@ import {EnvironmentHttpApi,type OrchestrationProjectShell,} from "@t3tools/contracts";-import * as DateTime from "effect/DateTime";import * as Effect from "effect/Effect";import * as Result from "effect/Result";import * as Predicate from "effect/Predicate";@@ -32,11 +31,7 @@ import {} from "./threadHistoryPaging.ts";import * as ThreadManagementService from "./ThreadManagementService.ts";import * as ProjectStore from "./ProjectStore.ts";-import {- buildActiveShellSnapshot,- loadShellSnapshotParts,- shellSnapshotForSubscriber,-} from "./ShellStream.ts";+import { loadSubscriberShellSnapshot } from "./ShellStream.ts";import { boundedSnapshotResponseFields } from "./ThreadStream.ts";import { projectThreadProjectionForWire } from "./WireProjection.ts";@@ -84,19 +79,19 @@ export const layer = HttpApiBuilder.group(readonly omitIdleSubagents: boolean;readonly omitOlderSettled: boolean;}) {- const base = buildActiveShellSnapshot(- yield* loadShellSnapshotParts({- sql,- readThreads: threadManagement.readShellSnapshot({ location: "active" }),- listProjects: projectStore.listShells(),- latestSequence: applicationEvents.latestApplicationSequence,- }),- );- const { snapshot } = shellSnapshotForSubscriber(base, {- ...options,- now: yield* DateTime.now,+ const { snapshot } = yield* loadSubscriberShellSnapshot({+ sql,+ listShellIndex: threadManagement.listActiveShellIndex(),+ readThreads: (threadIds) =>+ threadManagement.readShellSnapshot({+ location: "active",+ ...(threadIds === undefined ? {} : { threadIds }),+ }),+ listProjects: projectStore.listShells(),+ latestSequence: applicationEvents.latestApplicationSequence,+ options,});- const projects = yield* enrichProjectShells(base.projects);+ const projects = yield* enrichProjectShells(snapshot.projects);return { ...snapshot, projects };},);diff --git a/apps/server/src/project/ProjectService.ts b/apps/server/src/project/ProjectService.tsindex 18004510baa..3ba57db6d7e 100644--- a/apps/server/src/project/ProjectService.ts+++ b/apps/server/src/project/ProjectService.ts@@ -457,15 +457,13 @@ export const make = Effect.gen(function* () {) {const { projectId } = input;const snapshot = yield* threadProjections- .getShellSnapshot()+ .getShellSnapshot({ projectId }).pipe(Effect.mapError((cause) => new ProjectOperationError({ operation: "list-threads", projectId, cause }),),);- const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads].filter(- (thread) => thread.projectId === projectId,- );+ const projectThreads = [...snapshot.threads, ...snapshot.archivedThreads];if (projectThreads.length > 0 && input.force !== true) {return yield* new ProjectNotEmptyError({ projectId });}diff --git a/apps/server/src/relay/AgentAwarenessRelay.test.ts b/apps/server/src/relay/AgentAwarenessRelay.test.tsindex 7f0e86bd6cf..48c4a5c240e 100644--- a/apps/server/src/relay/AgentAwarenessRelay.test.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.test.ts@@ -190,6 +190,8 @@ const makeTestRelay = Effect.fnUntraced(function* (return { schemaVersion: 2, snapshotSequence: 1, threads: [], archivedThreads: [] };}),listActiveSubagentThreadIds: unused,+ countThreads: unused,+ listActiveShellIndex: () => Effect.succeed([]),listOlderSettledThreads: unused,readShellSnapshot: unused,ensureLegacyTranscript: unused,diff --git a/apps/server/src/relay/AgentAwarenessRelay.ts b/apps/server/src/relay/AgentAwarenessRelay.tsindex cbe7b35ef40..54742a0af7d 100644--- a/apps/server/src/relay/AgentAwarenessRelay.ts+++ b/apps/server/src/relay/AgentAwarenessRelay.ts@@ -726,10 +726,15 @@ export const make = Effect.gen(function* () {return "unlinked" as const;}const environmentId = yield* serverEnvironment.getEnvironmentId;- const [projectSnapshot, shellSnapshot] = yield* Effect.all([- projects.snapshot,- threads.getShellSnapshot(),- ]);+ const projectSnapshot = yield* projects.snapshot;+ // Subagents never publish awareness, and they are most threads.+ const topLevelThreadIds = (yield* threads.listActiveShellIndex()).flatMap((thread) =>+ thread.lineage.relationshipToParent === "subagent" ? [] : [thread.id],+ );+ const shellSnapshot = yield* threads.getShellSnapshot({+ location: "active",+ threadIds: topLevelThreadIds,+ });const activeThreadIds = resolveAgentAwarenessRelayActiveThreadIds({environmentId,startedAt,diff --git a/apps/server/src/serverRuntimeStartup.autoPull.test.ts b/apps/server/src/serverRuntimeStartup.autoPull.test.tsindex 59f6b67f045..549aae79e8b 100644--- a/apps/server/src/serverRuntimeStartup.autoPull.test.ts+++ b/apps/server/src/serverRuntimeStartup.autoPull.test.ts@@ -141,13 +141,7 @@ it.effect("parks automatic pull until activation without delaying command readin}),Layer.mock(ProjectService.ProjectService)({ snapshot: Effect.succeed(snapshot) }),Layer.mock(ThreadManagement.ThreadManagementService)({- getShellSnapshot: () =>- Effect.succeed({- schemaVersion: 1,- snapshotSequence: 0,- threads: [],- archivedThreads: [],- }),+ countThreads: () => Effect.succeed(0),}),Layer.mock(ThreadLaunch.ThreadLaunchService)({}),Layer.mock(ServiceLauncherClient.ServiceLauncherClient)({diff --git a/apps/server/src/serverRuntimeStartup.test.ts b/apps/server/src/serverRuntimeStartup.test.tsindex 274b149c66e..bef61bbca56 100644--- a/apps/server/src/serverRuntimeStartup.test.ts+++ b/apps/server/src/serverRuntimeStartup.test.ts@@ -176,13 +176,8 @@ it.effect.each([}),}),Layer.mock(ThreadManagement.ThreadManagementService)({- getShellSnapshot: () =>- Effect.succeed({- threads: [],- archivedThreads: [],- schemaVersion: 1,- snapshotSequence: 0,- }),+ countThreads: () => Effect.succeed(0),+ listActiveShellIndex: () => Effect.succeed([]),}),Layer.mock(ThreadLaunch.ThreadLaunchService)({launch: (input) => {diff --git a/apps/server/src/serverRuntimeStartup.ts b/apps/server/src/serverRuntimeStartup.tsindex d8d62dc029c..b812ad07fa6 100644--- a/apps/server/src/serverRuntimeStartup.ts+++ b/apps/server/src/serverRuntimeStartup.ts@@ -153,11 +153,11 @@ const recordStartupHeartbeat = Effect.gen(function* () {const { threadCount, projectCount } = yield* Effect.all({projects: projects.snapshot,- threads: threads.getShellSnapshot(),+ threadCount: threads.countThreads(),}).pipe(- Effect.map(({ projects: projectSnapshot, threads: shellSnapshot }) => ({+ Effect.map(({ projects: projectSnapshot, threadCount }) => ({projectCount: projectSnapshot.projects.length,- threadCount: shellSnapshot.threads.length + shellSnapshot.archivedThreads.length,+ threadCount,})),Effect.catch((cause) =>Effect.logWarning("failed to gather V2 startup counts for telemetry", {@@ -279,8 +279,7 @@ const resolveAutoBootstrapWelcomeTargets = Effect.gen(function* () {title: path.basename(serverConfig.cwd) || "project",workspaceRoot: serverConfig.cwd,});- const shell = yield* threads.getShellSnapshot();- const existingThread = shell.threads.find(+ const existingThread = (yield* threads.listActiveShellIndex()).find((thread) =>thread.projectId === project.id && thread.lineage.relationshipToParent !== "subagent",);diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.tsindex bce94507787..2c6adce82f3 100644--- a/apps/server/src/ws.test.ts+++ b/apps/server/src/ws.test.ts@@ -412,12 +412,23 @@ it.effect("shell snapshots omit idle children and older settled threads only onEffect.flatMap((stream) => stream.pipe(Stream.take(1), Stream.runCollect)),Effect.map(([item]) => (item?.kind === "snapshot" ? item.snapshot : null)),Effect.provideService(ThreadManagement.ThreadManagementService, {- readShellSnapshot: () =>+ listActiveShellIndex: () =>+ Effect.succeed(+ threads.map((thread) => ({+ ...thread,+ pinnedAt: null,+ snoozedUntil: null,+ mayBeLive: thread.activityRunStatus !== null,+ })),+ ),+ readShellSnapshot: (options?: { readonly threadIds?: ReadonlyArray<string> }) =>Effect.succeed(Effect.succeed({schemaVersion: 1,snapshotSequence: 0,- threads,+ threads: threads.filter(+ (thread) => options?.threadIds?.includes(thread.id) ?? true,+ ),archivedThreads: [],}),),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 86c7a4db56a..a7ef5dedf24 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -124,7 +124,6 @@ import * as ScheduledTasks from "./scheduledTasks/ScheduledTaskService.ts";import * as SecretRequests from "./secrets/SecretRequests.ts";import * as GuestShareService from "./guest/GuestShareService.ts";import {- buildActiveShellSnapshot,bufferShellLiveStream,coalesceShellApplicationEvents,composeShellStreamWithEnrichment,@@ -134,7 +133,7 @@ import {shellStreamItemFromEnrichmentRefresh,shellStreamItemFromThreadShell,shellStreamItemsFromInitialSnapshot,- shellSnapshotForSubscriber,+ loadSubscriberShellSnapshot,shellStreamItemsFromResumeSnapshot,shouldPublishShellApplicationEvent,skipUnchangedThreadShells,@@ -1010,21 +1009,23 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsc},);const loadSnapshot = Effect.fn("ws.orchestrationV2.loadShellSnapshot")(function* () {- const base = buildActiveShellSnapshot(- yield* loadShellSnapshotParts({- sql,- readThreads: threadManagement.readShellSnapshot({ location: "active" }),- listProjects: projects.listShells(),- latestSequence: applicationEvents.latestApplicationSequence,- }),- );- const forSubscriber = shellSnapshotForSubscriber(base, {- omitIdleSubagents: input.omitIdleSubagents === true,- omitOlderSettled: input.omitOlderSettled === true,- now: yield* DateTime.now,+ const forSubscriber = yield* loadSubscriberShellSnapshot({+ sql,+ listShellIndex: threadManagement.listActiveShellIndex(),+ readThreads: (threadIds) =>+ threadManagement.readShellSnapshot({+ location: "active",+ ...(threadIds === undefined ? {} : { threadIds }),+ }),+ listProjects: projects.listShells(),+ latestSequence: applicationEvents.latestApplicationSequence,+ options: {+ omitIdleSubagents: input.omitIdleSubagents === true,+ omitOlderSettled: input.omitOlderSettled === true,+ },});subagentThreadIds = forSubscriber.subagentThreadIds;- const enriched = yield* enrichProjectShells(base.projects);+ const enriched = yield* enrichProjectShells(forSubscriber.snapshot.projects);return {snapshot: {...forSubscriber.snapshot,