TypeScript
perf(shell): cold connects skip idle subagent threads, a third of the thread list (#24648)
Theo Browne67c3afbd58e7
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsxindex d47e3455181..b82cccfc294 100644--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx@@ -77,7 +77,7 @@ import { useSelectedThreadWorktree } from "../../state/use-selected-thread-worktimport { useThreadComposerState } from "../../state/use-thread-composer-state";import { resolveMergeBackTargetThreadId } from "@t3tools/client-runtime/state/thread-relationships";import { resolveLatestMergeBackRun } from "@t3tools/client-runtime/state/thread-workflows";-import { threadEnvironment } from "../../state/threads";+import { threadEnvironment, useThreadFamily } from "../../state/threads";import { projectThreadContentPresentation } from "./threadContentPresentation";import { useAppearancePreferences } from "../settings/appearance/AppearancePreferencesProvider";import {@@ -205,6 +205,12 @@ function LiveThreadRouteController(props: ThreadRouteScreenProps) {const connectionsReady = useConnectionsReady();const { connectionState } = useRemoteConnectionStatus();const { selectedThread } = useThreadSelection();+ // Subagent rows, the open child's own row and its ancestors come from the family when the+ // shell leaves idle children out.+ useThreadFamily(+ selectedThread?.environmentId ?? null,+ selectedThread?.lineage.rootThreadId ?? null,+ );const params = props.route.params ?? {};const environmentIdRaw = firstRouteParam(params.environmentId);const threadIdRaw = firstRouteParam(params.threadId);diff --git a/apps/mobile/src/state/shell.ts b/apps/mobile/src/state/shell.tsindex f62c78dace7..dc1bbf967e8 100644--- a/apps/mobile/src/state/shell.ts+++ b/apps/mobile/src/state/shell.ts@@ -3,6 +3,7 @@ import {createEnvironmentShellSummaryAtom,createEnvironmentSnapshotAtom,createShellEnvironmentAtoms,+ EMPTY_SHELL_STATE,type EnvironmentShellState,} from "@t3tools/client-runtime/state/shell";import { useAtomValue } from "@effect/atom-react";@@ -21,11 +22,7 @@ export const environmentShellSummaryAtom = createEnvironmentShellSummaryAtom({shellStateValueAtom: environmentShell.stateValueAtom,});-const EMPTY_ENVIRONMENT_SHELL_STATE_ATOM = Atom.make<EnvironmentShellState>({- snapshot: Option.none(),- status: "empty",- error: Option.none(),-});+const EMPTY_ENVIRONMENT_SHELL_STATE_ATOM = Atom.make<EnvironmentShellState>(EMPTY_SHELL_STATE);const shellStatus = (state: EnvironmentShellState) => state.status;const shellHasError = (state: EnvironmentShellState) => Option.isSome(state.error);diff --git a/apps/mobile/src/state/thread-outbox-model.ts b/apps/mobile/src/state/thread-outbox-model.tsindex 9fece231582..55d5c10110a 100644--- a/apps/mobile/src/state/thread-outbox-model.ts+++ b/apps/mobile/src/state/thread-outbox-model.ts@@ -4,6 +4,7 @@ import {fileAttachmentTooLargeMessage,} from "@t3tools/client-runtime/state/attachments";import type { EnvironmentShellStatus } from "@t3tools/client-runtime/state/shell";+import type { ThreadFamilyRead } from "@t3tools/client-runtime/state/threads";import {CommandId,EnvironmentId,@@ -176,6 +177,11 @@ export function resolveThreadOutboxDeliveryAction(input: {readonly shellStatus: EnvironmentShellStatus;readonly environmentConnected: boolean;readonly threadBusy: boolean;+ /**+ * Set when the shell can leave idle subagent children out: absence alone is not deletion there,+ * only a settled family read without the row is.+ */+ readonly familyRead?: ThreadFamilyRead;}): ThreadOutboxDeliveryAction {if (input.isCreation) {if (input.threadExists) {@@ -187,7 +193,10 @@ export function resolveThreadOutboxDeliveryAction(input: {return input.environmentConnected && input.shellStatus === "live" ? "send" : "wait";}if (!input.threadExists) {- return input.shellStatus === "live" ? "remove" : "wait";+ return input.shellStatus === "live" &&+ (input.familyRead === undefined || input.familyRead === "settled")+ ? "remove"+ : "wait";}return input.environmentConnected ? "send" : "wait";}diff --git a/apps/mobile/src/state/thread-outbox.test.ts b/apps/mobile/src/state/thread-outbox.test.tsindex 0d08c2af107..66bd21b2d9b 100644--- a/apps/mobile/src/state/thread-outbox.test.ts+++ b/apps/mobile/src/state/thread-outbox.test.ts@@ -1124,6 +1124,19 @@ describe("thread outbox", () => {).toBe("send");});+ it("removes a missing-thread message only after a settled family read when idle children can be omitted", () => {+ const missing = {+ isCreation: false,+ threadExists: false,+ shellStatus: "live",+ environmentConnected: true,+ threadBusy: false,+ } as const;+ expect(resolveThreadOutboxDeliveryAction({ ...missing, familyRead: "pending" })).toBe("wait");+ expect(resolveThreadOutboxDeliveryAction({ ...missing, familyRead: "failed" })).toBe("wait");+ expect(resolveThreadOutboxDeliveryAction({ ...missing, familyRead: "settled" })).toBe("remove");+ });+it("sends existing-thread messages whenever connected so queued messages can steer", () => {expect(resolveThreadOutboxDeliveryAction({diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.tsindex c056ce417f9..2b7d4db5b99 100644--- a/apps/mobile/src/state/threads.ts+++ b/apps/mobile/src/state/threads.ts@@ -6,18 +6,25 @@ import {EMPTY_ENVIRONMENT_THREAD_STATE,type EnvironmentThreadState,createThreadEnvironmentAtoms,+ createThreadFamilyAtoms,} from "@t3tools/client-runtime/state/threads";import type { EnvironmentId, ThreadId } from "@t3tools/contracts";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/reactivity";+import { useEffect } from "react";import { environmentCatalog } from "../connection/catalog";import { connectionAtomRuntime } from "../connection/runtime";-import { environmentSnapshotAtom } from "./shell";+import { appAtomRegistry } from "./atom-registry";+import { environmentShell } from "./shell";+export const threadFamilies = createThreadFamilyAtoms(+ connectionAtomRuntime,+ environmentShell.stateAtom,+);export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime,- environmentSnapshotAtom,+ threadFamilies.snapshotAtom,);export const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(@@ -28,6 +35,17 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({snapshotAtom: threadEnvironment.snapshotAtom,});+/** Keeps the subagent tree under `rootThreadId` in the thread list while the caller shows it. */+export function useThreadFamily(+ environmentId: EnvironmentId | null,+ rootThreadId: ThreadId | null,+): void {+ useEffect(() => {+ if (environmentId === null || rootThreadId === null) return;+ return threadFamilies.mount(appAtomRegistry, environmentId, rootThreadId);+ }, [environmentId, rootThreadId]);+}+const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(Atom.withLabel("mobile-environment-thread:empty"),);diff --git a/apps/mobile/src/state/use-composer-drafts.test.ts b/apps/mobile/src/state/use-composer-drafts.test.tsindex 94dc617a50d..02d68745d9e 100644--- a/apps/mobile/src/state/use-composer-drafts.test.ts+++ b/apps/mobile/src/state/use-composer-drafts.test.ts@@ -3,6 +3,7 @@ import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/stateimport {applyShellStreamEvent,createEnvironmentSnapshotAtom,+ EMPTY_SHELL_STATE,type EnvironmentShellState,type EnvironmentShellStatus,} from "@t3tools/client-runtime/state/shell";@@ -284,9 +285,9 @@ function modelReconciliationHarness(],};const shellStateAtom = Atom.make<EnvironmentShellState>({+ ...EMPTY_SHELL_STATE,snapshot: Option.some(initialSnapshot),status: initialStatus,- error: Option.none(),});const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);diff --git a/apps/mobile/src/state/use-thread-outbox-drain.ts b/apps/mobile/src/state/use-thread-outbox-drain.tsindex 47c76d72136..1f473f6039f 100644--- a/apps/mobile/src/state/use-thread-outbox-drain.ts+++ b/apps/mobile/src/state/use-thread-outbox-drain.ts@@ -7,6 +7,7 @@ import {type EnvironmentThreadShell,} from "@t3tools/client-runtime/state/shell";import type { AtomCommandResult } from "@t3tools/client-runtime/state/runtime";+import { threadFamilyRead, type ThreadFamilyRead } from "@t3tools/client-runtime/state/threads";import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";import {AuthOrchestrationOperateScope,@@ -66,7 +67,7 @@ import {type ThreadOutboxCommandStage,type ThreadOutboxFailureAction,} from "./thread-outbox-model";-import { environmentThreadShells, threadEnvironment } from "./threads";+import { environmentThreadShells, threadEnvironment, threadFamilies } from "./threads";import {appendComposerDraftAttachments,composerDraftsAtom,@@ -614,6 +615,16 @@ export function useThreadOutboxDrain(): void {const retryNotBeforeRef = useRef(new Map<MessageId, number>());const retryTimersRef = useRef(new Map<MessageId, ReturnType<typeof setTimeout>>());const acknowledgedExistingThreadMessageIdsRef = useRef(new Set<MessageId>());+ // Targets the shell may have left out hold their thread family until they leave the queue, so+ // the row stays readable through dispatch.+ const familyMountsRef = useRef(new Map<MessageId, () => void>());+ useEffect(+ () => () => {+ for (const release of familyMountsRef.current.values()) release();+ familyMountsRef.current.clear();+ },+ [],+ );const blockedRecoverySubscriptionsRef = useRef(new Map<MessageId,@@ -1102,6 +1113,12 @@ export function useThreadOutboxDrain(): void {acknowledgedExistingThreadMessageIdsRef.current.delete(messageId);}}+ for (const [messageId, release] of familyMountsRef.current) {+ if (!queuedMessageIds.has(messageId)) {+ release();+ familyMountsRef.current.delete(messageId);+ }+ }for (const [threadKey, queuedMessages] of Object.entries(queuedMessagesByThreadKey)) {const nextQueuedMessage = queuedMessages[0];@@ -1153,7 +1170,7 @@ export function useThreadOutboxDrain(): void {continue;}- const thread = findThread(threads, nextQueuedMessage);+ let thread = findThread(threads, nextQueuedMessage);if (thread && scopedThreadKey(thread.environmentId, thread.id) !== threadKey) {continue;}@@ -1163,17 +1180,66 @@ export function useThreadOutboxDrain(): void {(candidate) => candidate.environmentId === nextQueuedMessage.environmentId,);const shellStatus = shellStatuses.get(nextQueuedMessage.environmentId) ?? "empty";+ const serverConfig = serverConfigs.get(nextQueuedMessage.environmentId);+ let familyRead: ThreadFamilyRead | undefined;+ if (+ thread === undefined &&+ creation === undefined &&+ serverConfig?.shellThreadFamilies === true+ ) {+ // The family keeps the row readable through dispatch once it loads; the current shell+ // generation's read decides whether the thread is gone.+ if (!familyMountsRef.current.has(nextQueuedMessage.messageId)) {+ familyMountsRef.current.set(+ nextQueuedMessage.messageId,+ threadFamilies.mount(+ appAtomRegistry,+ nextQueuedMessage.environmentId,+ nextQueuedMessage.threadId,+ ),+ );+ }+ familyRead = threadFamilyRead(+ appAtomRegistry.get(+ threadFamilies.familyAtom(nextQueuedMessage.environmentId, nextQueuedMessage.threadId),+ ),+ );+ if (familyRead === "settled") {+ // The rows from this render can lag the family that just settled; decide from the+ // merged rows as they are now.+ thread = findThread(+ appAtomRegistry.get(environmentThreadShells.threadShellsAtom),+ nextQueuedMessage,+ );+ } else if (familyRead === "failed") {+ threadFamilies.refresh(+ appAtomRegistry,+ nextQueuedMessage.environmentId,+ nextQueuedMessage.threadId,+ );+ }+ }const deliveryAction = resolveThreadOutboxDeliveryAction({isCreation: creation !== undefined,threadExists: thread !== undefined,shellStatus,environmentConnected: environment?.connectionState === "connected",threadBusy: threadRuntimeIsActive(thread?.runtime),+ ...(familyRead === undefined ? {} : { familyRead }),});+ if (+ deliveryAction === "wait" &&+ shellStatus === "live" &&+ familyRead !== undefined &&+ familyRead !== "settled"+ ) {+ // An empty family read changes no merged row, so nothing else would wake the drain.+ scheduleQueuedMessageRetry(nextQueuedMessage.messageId);+ continue;+ }if (deliveryAction === "send" && !operableEnvironments.has(nextQueuedMessage.environmentId)) {continue;}- const serverConfig = serverConfigs.get(nextQueuedMessage.environmentId);const dispatchStep = resolveThreadOutboxDispatchStep({deliveryAction,fileAttachments: nextQueuedMessage.attachments.filter(diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.tsindex 3f007b19059..447b4e8e22e 100644--- a/apps/server/src/auth/RpcAuthorization.ts+++ b/apps/server/src/auth/RpcAuthorization.ts@@ -48,6 +48,8 @@ export const RPC_REQUIRED_SCOPES = {[ORCHESTRATION_V2_WS_METHODS.searchThread]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope,+ [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: AuthOrchestrationReadScope,+ [ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.getTurnItem]: AuthOrchestrationReadScope,[ORCHESTRATION_V2_WS_METHODS.launchThread]: AuthOrchestrationOperateScope,diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.tsindex 0c018691e10..769fc2d1feb 100644--- a/apps/server/src/observability/RpcInstrumentation.ts+++ b/apps/server/src/observability/RpcInstrumentation.ts@@ -24,6 +24,8 @@ const RPC_AGGREGATES = {[ORCHESTRATION_V2_WS_METHODS.searchThread]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.searchThreadStream]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: "orchestration",+ [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: "orchestration",+ [ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: "orchestrationV2",[ORCHESTRATION_V2_WS_METHODS.launchThread]: "orchestration",[ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: "orchestration",diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 98d6e4c2e81..b2268d9a81f 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -1107,6 +1107,92 @@ const assertProjectScopedShells = Effect.fn("assertProjectScopedShells")(functioreturn { projectId, activeThreadId, forkThreadId, otherThreadId };});+it.effect.each([+ ["memory", ProjectionStore.layerMemory],+ ["SQL", layerTest],+] as const)("%s shells read a subagent family and a worktree's threads", ([, layer]) =>+ Effect.gen(function* () {+ const store = yield* ProjectionStore.ProjectionStoreV2;+ const now = yield* DateTime.now;+ const projectId = ProjectId.make("project:family");+ const worktreePath = "/repo/.t3/worktrees/family";+ const id = (name: string) => ThreadId.make(`thread:family:${name}`);+ const payloadOf = (input: {+ readonly name: string;+ readonly parent?: string;+ readonly root?: string;+ readonly worktreePath?: string;+ readonly archived?: boolean;+ }) =>+ ({+ createdBy: "user",+ creationSource: input.parent === undefined ? "web" : "mcp",+ id: id(input.name),+ projectId,+ title: input.name,+ providerInstanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: input.worktreePath ?? null,+ activeProviderThreadId: null,+ lineage: {+ parentThreadId: input.parent === undefined ? null : id(input.parent),+ relationshipToParent: input.parent === undefined ? null : "subagent",+ rootThreadId: id(input.root ?? input.name),+ },+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: input.archived === true ? now : null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ }) as const;+ const createThread = (input: Parameters<typeof payloadOf>[0]) =>+ store.apply({+ id: EventId.make(`event:family:${input.name}`),+ type: "thread.created",+ threadId: id(input.name),+ occurredAt: now,+ payload: payloadOf(input),+ });+ yield* createThread({ name: "root", worktreePath });+ yield* createThread({ name: "child", parent: "root", root: "root", worktreePath });+ yield* createThread({ name: "grandchild", parent: "child", root: "root" });+ yield* createThread({ name: "archived-child", parent: "root", root: "root", archived: true });+ yield* createThread({ name: "other", worktreePath: "/repo" });+ yield* createThread({ name: "other-child", parent: "other", root: "other", worktreePath });++ const family = (threadId: ThreadId) =>+ store+ .getShellSnapshot({ location: "active", subagentFamilyOf: threadId })+ .pipe(Effect.map((snapshot) => snapshot.threads.map((thread) => thread.id)));+ // Any member, or the root itself, names the same active subagent tree.+ assert.sameMembers([...(yield* family(id("root")))], [id("child"), id("grandchild")]);+ assert.sameMembers([...(yield* family(id("grandchild")))], [id("child"), id("grandchild")]);+ assert.deepEqual([...(yield* family(id("missing")))], []);++ // Includes another root's idle child on the same path, which a shell may leave out.+ const onWorktree = yield* store.getShellSnapshot({ location: "active", worktreePath });+ assert.sameMembers(+ onWorktree.threads.map((thread) => thread.id),+ [id("root"), id("child"), id("other-child")],+ );+ // A fork keeps its deleted source's root, so the deleted root still names the live tree.+ yield* store.apply({+ id: EventId.make("event:family:root-deleted"),+ type: "thread.deleted",+ threadId: id("root"),+ occurredAt: now,+ payload: { ...payloadOf({ name: "root", worktreePath }), deletedAt: now },+ });+ assert.sameMembers([...(yield* family(id("root")))], [id("child"), id("grandchild")]);+ }).pipe(Effect.provide(layer)),+);+it.effect("lists only active subagent IDs without loading shell data", () =>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.tsindex 4ddc34ae4a4..84ec210dc39 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -406,6 +406,12 @@ export interface ShellSnapshotOptions {readonly location?: "active" | "archive";readonly projectId?: ProjectId;readonly unsettledOnly?: boolean;+ /**+ * Only the subagent threads sharing this thread's `lineage.rootThreadId`. The thread may be+ * deleted: forks keep a deleted source's root, and their subagent trees still need it.+ */+ readonly subagentFamilyOf?: ThreadId;+ readonly worktreePath?: string;}export interface ProjectionStoreV2Shape {@@ -5697,7 +5703,13 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =const selectShellThreadRows = (threadId?: ThreadId,- { location, projectId, unsettledOnly = false }: ShellSnapshotOptions = {},+ {+ location,+ projectId,+ unsettledOnly = false,+ subagentFamilyOf,+ worktreePath,+ }: ShellSnapshotOptions = {},) =>sql<ShellThreadRow>`SELECT@@ -5898,6 +5910,18 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =unsettledOnly? sql` AND json_extract(t.payload_json, '$.settledAt') IS NULL AND json_extract(t.payload_json, '$.settledOverride') IS NOT 'settled'`: sql``+ }${+ subagentFamilyOf === undefined+ ? sql``+ : sql` AND json_extract(t.payload_json, '$.lineage.relationshipToParent') = 'subagent' AND json_extract(t.payload_json, '$.lineage.rootThreadId') = (+ SELECT json_extract(member.payload_json, '$.lineage.rootThreadId')+ FROM orchestration_v2_projection_threads member+ WHERE member.thread_id = ${subagentFamilyOf}+ )`+ }${+ worktreePath === undefined+ ? sql``+ : sql` AND json_extract(t.payload_json, '$.worktreePath') = ${worktreePath}`}ORDER BY t.updated_at ASC, t.thread_id ASC`;@@ -6712,6 +6736,22 @@ export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect() {return false;}+ if (options?.subagentFamilyOf !== undefined) {+ const member = existing.get(options.subagentFamilyOf)?.thread;+ if (+ member === undefined ||+ projection.thread.lineage.relationshipToParent !== "subagent" ||+ projection.thread.lineage.rootThreadId !== member.lineage.rootThreadId+ ) {+ return false;+ }+ }+ if (+ options?.worktreePath !== undefined &&+ projection.thread.worktreePath !== options.worktreePath+ ) {+ return false;+ }if (options?.location === "active") return projection.thread.archivedAt === null;if (options?.location === "archive") return projection.thread.archivedAt !== null;return true;diff --git a/apps/server/src/orchestration-v2/ShellStream.test.ts b/apps/server/src/orchestration-v2/ShellStream.test.tsindex fcfaf8298f5..229400dd8ce 100644--- a/apps/server/src/orchestration-v2/ShellStream.test.ts+++ b/apps/server/src/orchestration-v2/ShellStream.test.ts@@ -17,9 +17,11 @@ import * as Stream from "effect/Stream";import * as TestClock from "effect/testing/TestClock";import {+ activeShellRowsForSubscriber,bufferShellLiveStream,composeShellStreamWithEnrichment,dedupeShellEnrichment,+ omitIdleSubagentShells,shellStreamItemFromEnrichmentRefresh,shellStreamItemsFromInitialSnapshot,shouldPublishShellApplicationEvent,@@ -139,6 +141,69 @@ function shellFixture(overrides: Partial<OrchestrationV2ThreadShell>): Orchestrareturn { id: "thread-a", archivedAt: null, ...overrides } as OrchestrationV2ThreadShell;}+describe("omitIdleSubagentShells", () => {+ const row = (+ id: string,+ parent: string | null,+ overrides: Partial<OrchestrationV2ThreadShell> = {},+ ) =>+ shellFixture({+ id: ThreadId.make(id),+ lineage: {+ parentThreadId: parent === null ? null : ThreadId.make(parent),+ relationshipToParent: parent === null ? null : "subagent",+ rootThreadId: ThreadId.make("root"),+ },+ status: "completed",+ activityRunStatus: null,+ pendingRuntimeRequest: null,+ pendingBackgroundTasks: [],+ ...overrides,+ });++ it("drops idle leaf children but keeps live ones and the middle of nested chains", () => {+ const threads = [+ row("root", null),+ row("idle", "root"),+ row("running", "root", { activityRunStatus: "running" }),+ row("queued", "root", { status: "queued" }),+ row("asking", "root", {+ pendingRuntimeRequest: {+ id: "request" as never,+ kind: "user_input",+ createdAt: DateTime.makeUnsafe(0),+ },+ }),+ row("background", "root", {+ pendingBackgroundTasks: [{ kind: "subagent" } as never],+ }),+ // Idle, but a woken grandchild walks through it to reach the root's badge.+ row("middle", "root"),+ row("grandchild", "middle"),+ ];+ expect(omitIdleSubagentShells(threads).map((thread) => thread.id)).toEqual([+ "root",+ "running",+ "queued",+ "asking",+ "background",+ "middle",+ ]);+ });++ it("still filters the transcript events of omitted children for a subscriber that opts in", () => {+ const threads = [row("root", null), row("idle", "root")];+ const omitted = activeShellRowsForSubscriber(threads, true);+ expect(omitted.threads.map((thread) => thread.id)).toEqual(["root"]);+ expect(+ shouldPublishShellApplicationEvent(+ { event: { threadId: "idle", type: "turn-item.updated" } } as ApplicationStoredEvent,+ omitted.subagentThreadIds,+ ),+ ).toBe(false);+ });+});+describe("shellStreamItemsFromInitialSnapshot", () => {it("keeps thread rows out of the metadata-only enrichment frame", () => {const snapshot = {diff --git a/apps/server/src/orchestration-v2/ShellStream.ts b/apps/server/src/orchestration-v2/ShellStream.tsindex 7a1367aa679..9985c779b9a 100644--- a/apps/server/src/orchestration-v2/ShellStream.ts+++ b/apps/server/src/orchestration-v2/ShellStream.ts@@ -9,6 +9,7 @@ import type {OrchestrationV2StoredEvent,} from "@t3tools/contracts";import {+ isLiveSubagentShell,OrchestrationProjectShell as ProjectShellSchema,OrchestrationV2ThreadShell as ThreadShellSchema,} from "@t3tools/contracts";@@ -64,6 +65,49 @@ export function buildActiveShellSnapshot(input: {};}+/**+ * 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> {+ const parentIds = new Set<string>();+ for (const thread of threads) {+ if (thread.lineage.relationshipToParent === "subagent" && thread.lineage.parentThreadId) {+ parentIds.add(thread.lineage.parentThreadId);+ }+ }+ return threads.filter(+ (thread) =>+ thread.lineage.relationshipToParent !== "subagent" ||+ isLiveSubagentShell(thread) ||+ parentIds.has(thread.id),+ );+}++/**+ * The active rows a shell subscriber gets, and the subagent ids whose transcript events its stream+ * drops. The ids come from every row, so an omitted child that wakes keeps that filter.+ */+export function activeShellRowsForSubscriber(+ threads: ReadonlyArray<OrchestrationV2ThreadShell>,+ omitIdleSubagents: boolean,+): {+ readonly threads: ReadonlyArray<OrchestrationV2ThreadShell>;+ readonly subagentThreadIds: Set<string>;+} {+ return {+ threads: omitIdleSubagents ? omitIdleSubagentShells(threads) : threads,+ subagentThreadIds: new Set(+ threads+ .filter((thread) => thread.lineage.relationshipToParent === "subagent")+ .map((thread) => thread.id),+ ),+ };+}+/*** One transaction covers the reads so they agree; the threads are decoded after it commits,* because the server shares one SQLite connection and decoding a large shell takes longer thandiff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.tsindex f4c79c27215..6fe1ee2fae6 100644--- a/apps/server/src/orchestration-v2/ThreadManagementService.ts+++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts@@ -6,6 +6,7 @@ import type {ProjectionRecordField,ProjectionRecordFilter,ProjectionRecords,+ ShellSnapshotOptions,} from "./ProjectionStore.ts";import {type ChatAttachment,@@ -383,9 +384,9 @@ export interface ThreadManagementServiceShape {readonly location?: "active" | "archive";}) => Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>;readonly listActiveSubagentThreadIds: Orchestrator.OrchestratorV2["Service"]["listActiveSubagentThreadIds"];- readonly readShellSnapshot: (options?: {- readonly location?: "active" | "archive";- }) => Effect.Effect<+ readonly readShellSnapshot: (+ options?: Pick<ShellSnapshotOptions, "location" | "subagentFamilyOf" | "worktreePath">,+ ) => Effect.Effect<Effect.Effect<OrchestrationV2ThreadShellSnapshot, Orchestrator.OrchestratorV2Error>,Orchestrator.OrchestratorV2Error>;diff --git a/apps/server/src/orchestration-v2/http.ts b/apps/server/src/orchestration-v2/http.tsindex cc8e987880d..d4ee3a6cc45 100644--- a/apps/server/src/orchestration-v2/http.ts+++ b/apps/server/src/orchestration-v2/http.ts@@ -30,7 +30,11 @@ import {} from "./threadHistoryPaging.ts";import * as ThreadManagementService from "./ThreadManagementService.ts";import * as ProjectStore from "./ProjectStore.ts";-import { buildActiveShellSnapshot, loadShellSnapshotParts } from "./ShellStream.ts";+import {+ buildActiveShellSnapshot,+ loadShellSnapshotParts,+ omitIdleSubagentShells,+} from "./ShellStream.ts";import { boundedSnapshotResponseFields } from "./ThreadStream.ts";import { projectThreadProjectionForWire } from "./WireProjection.ts";@@ -75,7 +79,9 @@ export const layer = HttpApiBuilder.group(),);- const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* () {+ const loadShellSnapshot = Effect.fn("http.orchestration.loadShellSnapshot")(function* (+ omitIdleSubagents: boolean,+ ) {const base = buildActiveShellSnapshot(yield* loadShellSnapshotParts({sql,@@ -85,7 +91,11 @@ export const layer = HttpApiBuilder.group(}),);const projects = yield* enrichProjectShells(base.projects);- return { ...base, projects };+ return {+ ...base,+ threads: omitIdleSubagents ? omitIdleSubagentShells(base.threads) : base.threads,+ projects,+ };});const loadThreadSnapshot = Effect.fn("http.orchestration.loadThreadSnapshot")(function* (@@ -154,7 +164,7 @@ export const layer = HttpApiBuilder.group(Effect.fn("environment.orchestration.shellSnapshot")(function* (args) {yield* annotateEnvironmentRequest(args.endpoint.name);yield* requireEnvironmentScope(AuthOrchestrationReadScope);- return yield* loadShellSnapshot().pipe(+ return yield* loadShellSnapshot(args.query.omitIdleSubagents === "1").pipe(traceLocalHandlerWork,Effect.catch((cause) =>failEnvironmentInternal("orchestration_snapshot_failed", cause),diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.tsindex 787fdc268f4..894f95c0d82 100644--- a/apps/server/src/ws.test.ts+++ b/apps/server/src/ws.test.ts@@ -8,6 +8,7 @@ import {WS_METHODS,WsSubscribeServerConfigRpc,type OrchestrationV2StoredEvent,+ type OrchestrationV2ThreadShell,type OrchestrationProjectShell,type ServerConfig,type ServerConfigStreamEvent,@@ -290,6 +291,71 @@ it.live.each(["thread", "shell"] as const)(}).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),);+it.effect("shell snapshots leave idle subagent children out only for clients that ask", () =>+ Effect.gen(function* () {+ const shell = (id: string, parent: string | null, activityRunStatus: "running" | null) =>+ ({+ id: ThreadId.make(id),+ archivedAt: null,+ status: activityRunStatus ?? "completed",+ activityRunStatus,+ pendingRuntimeRequest: null,+ pendingBackgroundTasks: [],+ lineage: {+ parentThreadId: parent === null ? null : ThreadId.make(parent),+ relationshipToParent: parent === null ? null : "subagent",+ rootThreadId: ThreadId.make("parent"),+ },+ }) as unknown as OrchestrationV2ThreadShell;+ const threads = [+ shell("parent", null, null),+ shell("idle", "parent", null),+ shell("live", "parent", "running"),+ ];+ const firstSnapshotThreadIds = (input: { readonly omitIdleSubagents?: boolean }) =>+ subscribeOrchestrationV2Shell(input).pipe(+ Effect.flatMap((stream) => stream.pipe(Stream.take(1), Stream.runCollect)),+ Effect.map(([item]) =>+ item?.kind === "snapshot" ? item.snapshot.threads.map((thread) => thread.id) : [],+ ),+ Effect.provideService(ThreadManagement.ThreadManagementService, {+ readShellSnapshot: () =>+ Effect.succeed(+ Effect.succeed({+ schemaVersion: 1,+ snapshotSequence: 0,+ threads,+ archivedThreads: [],+ }),+ ),+ } as unknown as ThreadManagement.ThreadManagementService["Service"]),+ Effect.provideService(ProjectStore.ProjectStoreV2, {+ listShells: () => Effect.succeed([]),+ } as unknown as ProjectStore.ProjectStoreV2["Service"]),+ Effect.provideService(ProjectService.ProjectService, {+ getShell: () => Effect.succeedNone,+ } as unknown as ProjectService.ProjectService["Service"]),+ Effect.provideServiceEffect(+ ProjectEnrichment.ProjectEnrichmentService,+ PubSub.unbounded().pipe(+ Effect.map(+ (changes) =>+ ({+ subscribeChanges: PubSub.subscribe(changes),+ }) as unknown as ProjectEnrichment.ProjectEnrichmentService["Service"],+ ),+ ),+ ),+ );++ assert.deepEqual(yield* firstSnapshotThreadIds({}), ["parent", "idle", "live"]);+ assert.deepEqual(yield* firstSnapshotThreadIds({ omitIdleSubagents: true }), [+ "parent",+ "live",+ ]);+ }).pipe(Effect.scoped, Effect.provide(ReplayTestLayer)),+);+// Build the production RPC layer; unrelated capabilities fail if this test calls them.const layerUnusedConfigRpcServices = Layer.mergeAll(Layer.mock(ServerSecretStore.ServerSecretStore)({}),diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex f9f289ea30a..3316829f483 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -129,6 +129,7 @@ import {coalesceStoredThreadEvents,composeShellStreamWithEnrichment,dedupeShellEnrichment,+ activeShellRowsForSubscriber,loadShellSnapshotParts,shellStreamItemFromEnrichmentRefresh,shellStreamItemFromThreadShell,@@ -979,6 +980,7 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subscfunction* (input: {readonly afterSequence?: number;readonly requestCompletionMarker?: boolean;+ readonly omitIdleSubagents?: boolean;}) {const sql = yield* SqlClient.SqlClient;const threadManagement = yield* ThreadManagementService.ThreadManagementService;@@ -1015,14 +1017,15 @@ export const subscribeOrchestrationV2Shell = Effect.fn("ws.orchestrationV2.subsclatestSequence: applicationEvents.latestApplicationSequence,}),);- subagentThreadIds = new Set(- base.threads- .filter((thread) => thread.lineage.relationshipToParent === "subagent")- .map((thread) => thread.id),- );+ const rows = activeShellRowsForSubscriber(base.threads, input.omitIdleSubagents === true);+ subagentThreadIds = rows.subagentThreadIds;const enriched = yield* enrichProjectShells(base.projects);return {- snapshot: { ...base, projects: enriched.projects } as OrchestrationV2ShellSnapshot,+ snapshot: {+ ...base,+ threads: rows.threads,+ projects: enriched.projects,+ } as OrchestrationV2ShellSnapshot,resolvedRepositoryIdentityRoots: enriched.resolvedRepositoryIdentityRoots,};});@@ -1772,6 +1775,7 @@ export const layerWsRpc = (},settings,shellResumeCompletionMarker: true,+ shellThreadFamilies: true,threadResumeCompletionMarker: true,threadSnapshotPagination: true,threadFind: true,@@ -1818,6 +1822,26 @@ export const layerWsRpc = (),);+ // Rows the shell can omit, read with the same snapshot sequence the shell uses.+ const readOmittableShellRows = Effect.fn("ws.orchestrationV2.readOmittableShellRows")(+ function* (+ options: { readonly subagentFamilyOf: ThreadId } | { readonly worktreePath: string },+ message: string,+ ) {+ const { threads, snapshotSequence } = yield* loadShellSnapshotParts({+ sql,+ readThreads: threadManagement.readShellSnapshot({ location: "active", ...options }),+ listProjects: Effect.succeed([]),+ latestSequence: applicationEvents.latestApplicationSequence,+ }).pipe(+ Effect.mapError(+ (cause) => new OrchestrationV2GetShellSnapshotError({ message, cause }),+ ),+ );+ return { snapshotSequence, threads: threads.threads };+ },+ );+const subscribeOrchestrationV2ArchivedShell = Effect.fn("ws.orchestrationV2.subscribeArchivedShell",)(function* () {@@ -1966,6 +1990,16 @@ export const layerWsRpc = (),[ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: (_input) =>getOrchestrationV2ArchivedShellSnapshot,+ [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: (input) =>+ readOmittableShellRows(+ { subagentFamilyOf: input.threadId },+ "Failed to load the thread family",+ ),+ [ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds]: (input) =>+ readOmittableShellRows(+ { worktreePath: input.worktreePath },+ "Failed to load the worktree's threads",+ ).pipe(Effect.map(({ threads }) => ({ threadIds: threads.map((thread) => thread.id) }))),[ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) =>Effect.annotateCurrentSpan({ "orchestration_v2.thread_id": input.threadId }).pipe(Effect.andThen(diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex 6252b087abe..800998728cf 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -222,7 +222,7 @@ import {primaryServerKeybindingsAtom,serverEnvironment,} from "../state/server";-import { threadEnvironment } from "../state/threads";+import { threadEnvironment, useThreadFamily } from "../state/threads";import { resolveProviderSkillsForCwd } from "@t3tools/client-runtime/providerSkills";import { vcsEnvironment } from "../state/vcs";import {@@ -466,6 +466,14 @@ export default function ChatView(props: ChatViewProps) {});const serverThreadProjection = useQuietThreadProjection(routeThreadDetailRef);const serverProjection = serverThreadProjection?.projection ?? null;+ // Subagent rows, an open child's own row and its ancestors come from the family when the shell+ // leaves idle children out. Every source agrees on the root, so the key never flips.+ useThreadFamily(+ routeKind === "server" ? environmentId : null,+ serverThreadShell?.lineage.rootThreadId ??+ serverProjection?.thread.lineage.rootThreadId ??+ null,+ );// Only the shell-less fallback needs these; with a shell, the shell carries them.const fallbackDetailRef = serverThreadShell === null ? routeThreadDetailRef : null;const fallbackUpdatedAt = useThreadUpdatedAt(fallbackDetailRef);diff --git a/apps/web/src/components/chat/useThreadLifecycle.tsx b/apps/web/src/components/chat/useThreadLifecycle.tsxindex 8d90dbc31d1..8e9af1b2d89 100644--- a/apps/web/src/components/chat/useThreadLifecycle.tsx+++ b/apps/web/src/components/chat/useThreadLifecycle.tsx@@ -418,8 +418,11 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {const threadRef = scopeThreadRef(environmentId, threadId);const isEnvironmentLive = () =>appAtomRegistry.get(environmentShell.stateValueAtom(environmentId)).status === "live";+ // The shell can leave idle subagent children out, so absence is not deletion there: the+ // route decides from the thread's own detail.+ const shellOmitsChildren = serverConfig?.shellThreadFamilies === true;// A just-launched child can reach this timeline before its shell syncs.- if (isEnvironmentLive() && readThreadShell(threadRef) === null) {+ if (!shellOmitsChildren && isEnvironmentLive() && readThreadShell(threadRef) === null) {const location = router.latestLocation;await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS);if (@@ -431,7 +434,7 @@ export function useThreadLifecycle(input: ThreadLifecycleInput) {}}const shell = readThreadShell(threadRef);- if (shell === null ? isEnvironmentLive() : shell.deletedAt != null) {+ if (shell === null ? !shellOmitsChildren && isEnvironmentLive() : shell.deletedAt != null) {toastManager.add({ type: "info", title: "This thread is no longer available" });return;}diff --git a/apps/web/src/composerDraftStore.test.ts b/apps/web/src/composerDraftStore.test.tsindex a7eb9b1c1a0..238cd866351 100644--- a/apps/web/src/composerDraftStore.test.ts+++ b/apps/web/src/composerDraftStore.test.ts@@ -3,6 +3,7 @@ import { createEnvironmentThreadShellAtoms } from "@t3tools/client-runtime/stateimport {applyShellStreamEvent,createEnvironmentSnapshotAtom,+ EMPTY_SHELL_STATE,type EnvironmentShellState,type EnvironmentShellStatus,} from "@t3tools/client-runtime/state/shell";@@ -1238,9 +1239,9 @@ function modelReconciliationHarness(],};const shellStateAtom = Atom.make<EnvironmentShellState>({+ ...EMPTY_SHELL_STATE,snapshot: Option.some(initialSnapshot),status: initialStatus,- error: Option.none(),});const shellResultAtom = Atom.map(shellStateAtom, AsyncResult.success);const snapshotAtom = createEnvironmentSnapshotAtom(() => shellResultAtom)(environmentId);diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.tsindex 26adcfcd612..7796502826d 100644--- a/apps/web/src/hooks/useThreadActions.ts+++ b/apps/web/src/hooks/useThreadActions.ts@@ -28,6 +28,7 @@ import { environmentSession, readEnvironmentScope } from "../state/session";import { appAtomRegistry } from "../rpc/atomRegistry";import { environmentServerConfigsAtom } from "../state/server";import { isScratchProject } from "@t3tools/client-runtime/state/projects";+import { orchestrationEnvironment } from "../state/orchestration";import { threadEnvironment } from "../state/threads";import { vcsEnvironment } from "../state/vcs";import { useNewThreadHandler } from "./useHandleNewThread";@@ -290,6 +291,10 @@ export function useThreadActions() {const loadSessionState = useAtomQueryRunner(environmentSession.sessionStateAtom, {reportFailure: false,});+ const loadWorktreeThreadIds = useAtomQueryRunner(orchestrationEnvironment.worktreeThreadIds, {+ reportFailure: false,+ refresh: true,+ });const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {reportFailure: false,});@@ -435,16 +440,32 @@ export function useThreadActions() {deletedIds && deletedIds.size > 0? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id)): threads;- const orphanedWorktreePath = getOrphanedWorktreePathForThread(+ const environmentConfig = appAtomRegistry+ .get(environmentServerConfigsAtom)+ .get(threadRef.environmentId);+ let orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads,threadRef.threadId,);+ // A shell that leaves idle subagent children out cannot prove nobody else uses the worktree,+ // so the server's list decides. A failed read keeps the worktree.+ if (orphanedWorktreePath !== null && environmentConfig?.shellThreadFamilies === true) {+ const occupants = await loadWorktreeThreadIds({+ environmentId: threadRef.environmentId,+ input: { worktreePath: orphanedWorktreePath },+ });+ if (+ occupants._tag !== "Success" ||+ occupants.value.threadIds.some(+ (threadId) => threadId !== threadRef.threadId && deletedIds?.has(threadId) !== true,+ )+ ) {+ orphanedWorktreePath = null;+ }+ }const displayWorktreePath = orphanedWorktreePath? formatWorktreePathForDisplay(orphanedWorktreePath): null;- const environmentConfig = appAtomRegistry- .get(environmentServerConfigsAtom)- .get(threadRef.environmentId);const localApi = readLocalApi();let canDeleteWorktree = false;if (diff --git a/apps/web/src/state/shell.test.ts b/apps/web/src/state/shell.test.tsindex 670566616a3..4d5920a94ad 100644--- a/apps/web/src/state/shell.test.ts+++ b/apps/web/src/state/shell.test.ts@@ -3,7 +3,7 @@ import {PrimaryConnectionTarget,} from "@t3tools/client-runtime/connection";import type { EnvironmentCatalogState } from "@t3tools/client-runtime/state/connections";-import type { EnvironmentShellState } from "@t3tools/client-runtime/state/shell";+import { EMPTY_SHELL_STATE, type EnvironmentShellState } from "@t3tools/client-runtime/state/shell";import { EnvironmentId } from "@t3tools/contracts";import * as Option from "effect/Option";import { Atom, AtomRegistry } from "effect/reactivity";@@ -16,6 +16,7 @@ const REMOTE = EnvironmentId.make("remote");function shellState(status: EnvironmentShellState["status"]): EnvironmentShellState {return {+ ...EMPTY_SHELL_STATE,status,snapshot:status === "empty"diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.tsindex 2bf5c26c6ab..99b67bc2b6b 100644--- a/apps/web/src/state/threads.ts+++ b/apps/web/src/state/threads.ts@@ -8,18 +8,22 @@ import {EMPTY_ENVIRONMENT_THREAD_STATE,type EnvironmentThreadState,createThreadEnvironmentAtoms,+ createThreadFamilyAtoms,} from "@t3tools/client-runtime/state/threads";import type { EnvironmentId, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/reactivity";+import { useEffect } from "react";import { environmentCatalog } from "../connection/catalog";import { connectionAtomRuntime } from "../connection/runtime";-import { environmentSnapshotAtom } from "./shell";+import { appAtomRegistry } from "../rpc/atomRegistry";+import { environmentShell } from "./shell";+const threadFamilies = createThreadFamilyAtoms(connectionAtomRuntime, environmentShell.stateAtom);export const threadEnvironment = createThreadEnvironmentAtoms(connectionAtomRuntime,- environmentSnapshotAtom,+ threadFamilies.snapshotAtom,);const environmentThreads = createEnvironmentThreadStateAtoms(connectionAtomRuntime);export const environmentThreadDetails = createEnvironmentThreadDetailAtoms(@@ -30,6 +34,17 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({snapshotAtom: threadEnvironment.snapshotAtom,});+/** Keeps the subagent tree under `rootThreadId` in the thread list while the caller shows it. */+export function useThreadFamily(+ environmentId: EnvironmentId | null,+ rootThreadId: ThreadId | null,+): void {+ useEffect(() => {+ if (environmentId === null || rootThreadId === null) return;+ return threadFamilies.mount(appAtomRegistry, environmentId, rootThreadId);+ }, [environmentId, rootThreadId]);+}+const EMPTY_THREAD_STATE_ATOM = Atom.make(AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE)).pipe(Atom.withLabel("web-environment-thread:empty"),);diff --git a/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.mdindex 35c8b0a7365..8bd6a950d96 100644--- a/docs/internals/connection-runtime.md+++ b/docs/internals/connection-runtime.md@@ -59,6 +59,15 @@ connection nor overwrite newer live data during a reconnect. Loading andresuming snapshots belongs to the shared state services, so every view agreeson which data is current.+Servers that advertise `shellThreadFamilies` leave idle subagent children out of+shell snapshots when the client asks. A child stays while it has a live or+queued run, a pending request or background work, or a subagent child of its+own, so badge and working walks never meet a gap. Other child rows come from the+[thread family](../../packages/client-runtime/src/state/threadFamilies.ts) that+a thread view or a queued message mounts. A missing shell row therefore does not+prove a thread is gone: code that deletes data or a worktree on absence must+check the family or the server first.+[Thread detail](../../packages/client-runtime/src/state/threads.ts) separatessubscription lifetime from cache lifetime. Mounted consumers share one livestream, which stops when the last consumer unmounts; hidden mounted routes stilldiff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.tsindex 8bef9762a29..24ec67e5b38 100644--- a/packages/client-runtime/src/state/orchestration.ts+++ b/packages/client-runtime/src/state/orchestration.ts@@ -128,5 +128,12 @@ export function createOrchestrationEnvironmentAtoms<R, E>(label: "environment-data:orchestration:archived-shell-snapshot",tag: ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot,}),+ // Read right before deleting a worktree, so never served from cache.+ worktreeThreadIds: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:orchestration:worktree-thread-ids",+ tag: ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds,+ staleTimeMs: 0,+ idleTtlMs: 0,+ }),};}diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.tsindex 5ce6d7dbaa2..0e76e321bf3 100644--- a/packages/client-runtime/src/state/shell-sync.test.ts+++ b/packages/client-runtime/src/state/shell-sync.test.ts@@ -27,7 +27,7 @@ import * as EnvironmentSupervisor from "../connection/supervisor.ts";import * as Persistence from "../platform/persistence.ts";import * as RpcSession from "../rpc/session.ts";import type { WsRpcProtocolClient } from "../rpc/protocol.ts";-import { makeEnvironmentShellState } from "./shell.ts";+import { type EnvironmentShellState, makeEnvironmentShellState } from "./shell.ts";import * as ShellSnapshotLoader from "./shellSnapshotHttp.ts";import { v2Project, v2ShellSnapshot, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";@@ -478,6 +478,98 @@ describe("environment shell synchronization", () => {}),);+ it.effect("opts in to idle-child omission and counts authoritative snapshots and removals", () =>+ Effect.gen(function* () {+ const events = yield* Queue.unbounded<OrchestrationV2ShellStreamItem>();+ const subscribeInput = yield* Deferred.make<unknown>();+ const loadOptions = yield* Ref.make<ReadonlyArray<unknown>>([]);+ const client = {+ [ORCHESTRATION_V2_WS_METHODS.subscribeShell]: (input: unknown) =>+ Stream.unwrap(+ Deferred.succeed(subscribeInput, input).pipe(Effect.as(Stream.fromQueue(events))),+ ),+ } as unknown as WsRpcProtocolClient;+ const familySession: RpcSession.RpcSession = {+ ...session(client),+ initialConfig: Effect.succeed({+ shellResumeCompletionMarker: true,+ shellThreadFamilies: true,+ } as never),+ };+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({+ target: TARGET,+ state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE),+ session: yield* SubscriptionRef.make(Option.some(familySession)),+ prepared: yield* SubscriptionRef.make(Option.some(PREPARED)),+ connect: Effect.void,+ disconnect: Effect.void,+ retryNow: Effect.void,+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);+ const cache = Persistence.EnvironmentCacheStore.of({+ loadShell: () => Effect.succeed(Option.none()),+ saveShell: () => Effect.void,+ loadThread: () => Effect.succeed(Option.none()),+ saveThread: () => Effect.void,+ removeThread: () => Effect.void,+ loadServerConfig: () => Effect.succeed(Option.none()),+ saveServerConfig: () => Effect.void,+ loadVcsRefs: () => Effect.succeed(Option.none()),+ saveVcsRefs: () => Effect.void,+ removeVcsRefs: () => Effect.void,+ clearVcsRefs: () => Effect.void,+ clear: () => Effect.void,+ });+ const snapshotLoader = ShellSnapshotLoader.ShellSnapshotLoader.of({+ load: (_prepared, options) =>+ Ref.update(loadOptions, (all) => [...all, options]).pipe(+ Effect.as(Option.some(LIVE_SHELL_SNAPSHOT)),+ ),+ });+ const shellState = yield* makeEnvironmentShellState().pipe(+ Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor),+ Effect.provideService(Persistence.EnvironmentCacheStore, cache),+ Effect.provideService(ShellSnapshotLoader.ShellSnapshotLoader, snapshotLoader),+ );+ const stateWhere = (predicate: (state: EnvironmentShellState) => boolean) =>+ SubscriptionRef.changes(shellState).pipe(Stream.filter(predicate), Stream.runHead);++ // Both transports must omit, or omitted children would come back through the socket.+ expect(yield* Deferred.await(subscribeInput)).toMatchObject({+ afterSequence: 1,+ omitIdleSubagents: true,+ });+ expect(yield* Ref.get(loadOptions)).toEqual([{ omitIdleSubagents: true }]);+ const loaded = Option.getOrThrow(yield* stateWhere((state) => state.generation > 0));+ expect(loaded.removedAt.size).toBe(0);++ const gone = ThreadId.make("thread-gone");+ yield* Queue.offer(events, {+ kind: "snapshot",+ snapshot: { ...LIVE_SHELL_SNAPSHOT, threads: [] },+ resolvedRepositoryIdentityRoots: [],+ });+ yield* Queue.offer(events, {+ kind: "thread.removed",+ sequence: 2,+ location: "active",+ threadId: gone,+ });+ const removed = Option.getOrThrow(yield* stateWhere((state) => state.removedAt.size > 0));+ // An enrichment refresh is not authoritative.+ expect(removed.generation).toBe(loaded.generation);+ expect(removed.removedAt.get(gone)).toBe(2);++ yield* Queue.offer(events, {+ kind: "snapshot",+ snapshot: { ...LIVE_SHELL_SNAPSHOT, snapshotSequence: 5 },+ });+ const reset = Option.getOrThrow(+ yield* stateWhere((state) => state.generation > loaded.generation),+ );+ expect(reset.removedAt.size).toBe(0);+ }),+ );+it.effect("fills deferred cached pull request links without overwriting newer rows", () =>Effect.gen(function* () {const link = (number: number): ThreadPullRequestLink => ({diff --git a/packages/client-runtime/src/state/shell.ts b/packages/client-runtime/src/state/shell.tsindex 0a7e2aa7c66..a01465d2dc7 100644--- a/packages/client-runtime/src/state/shell.ts+++ b/packages/client-runtime/src/state/shell.ts@@ -45,12 +45,26 @@ export interface EnvironmentShellState {readonly snapshot: Option.Option<OrchestrationV2ShellSnapshot>;readonly status: EnvironmentShellStatus;readonly error: Option.Option<string>;+ /**+ * Changes with each authoritative snapshot (not enrichment refreshes); 0 until the first one.+ * Thread families read for an older generation may miss changes from before the latest snapshot,+ * so they are read again.+ */+ readonly generation: number;+ /** Sequences of the thread removals applied since the latest authoritative snapshot. */+ readonly removedAt: ReadonlyMap<ThreadId, number>;}-const EMPTY_SHELL_STATE: EnvironmentShellState = {+const EMPTY_REMOVALS: ReadonlyMap<ThreadId, number> = new Map();+// Shared by every shell state, so a rebuilt one never reuses a generation another already used.+let lastShellGeneration = 0;++export const EMPTY_SHELL_STATE: EnvironmentShellState = {snapshot: Option.none(),status: "empty",error: Option.none(),+ generation: 0,+ removedAt: EMPTY_REMOVALS,};function shellStatusForSnapshot(@@ -86,9 +100,9 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make"));const cachedSnapshot = Option.map(cached, withoutDeferredPullRequests);const state = yield* SubscriptionRef.make<EnvironmentShellState>({+ ...EMPTY_SHELL_STATE,snapshot: cachedSnapshot,status: shellStatusForSnapshot(cachedSnapshot),- error: Option.none(),});const awaitingCompletion = yield* Ref.make(false);const lastAuthoritativeSession = yield* Ref.make<RpcSession | null>(null);@@ -194,6 +208,8 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")}continue;}+ const authoritative =+ item.kind === "snapshot" && item.resolvedRepositoryIdentityRoots === undefined;const nextSnapshot =item.kind === "snapshot"? mergeShellSnapshotProjects(@@ -214,10 +230,21 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")});if (nextSnapshot === null) continue;receivedSnapshot ||= item.kind === "snapshot";+ const removal =+ item.kind === "thread.removed" &&+ Option.exists(next.snapshot, (snapshot) => item.sequence > snapshot.snapshotSequence)+ ? item+ : null;next = {snapshot: Option.some(nextSnapshot),status: waiting ? "synchronizing" : "live",error: Option.none(),+ generation: authoritative ? ++lastShellGeneration : next.generation,+ removedAt: authoritative+ ? EMPTY_REMOVALS+ : removal === null+ ? next.removedAt+ : new Map(next.removedAt).set(removal.threadId, removal.sequence),};}yield* Ref.set(awaitingCompletion, waiting);@@ -321,9 +348,15 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")ORCHESTRATION_V2_WS_METHODS.subscribeShell,Effect.fn("EnvironmentShellState.makeSubscribeInput")(function* (session) {yield* Ref.set(activeSubscriptionSession, session);- const supportsCompletionMarker = yield* session.initialConfig.pipe(- Effect.map((config) => config.shellResumeCompletionMarker === true),- Effect.orElseSucceed(() => false),+ const { supportsCompletionMarker, omitIdleSubagents } = yield* session.initialConfig.pipe(+ Effect.map((config) => ({+ supportsCompletionMarker: config.shellResumeCompletionMarker === true,+ omitIdleSubagents: config.shellThreadFamilies === true,+ })),+ Effect.orElseSucceed(() => ({+ supportsCompletionMarker: false,+ omitIdleSubagents: false,+ })),);yield* Ref.set(awaitingCompletion, supportsCompletionMarker);yield* setSynchronizing;@@ -349,7 +382,8 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")}),),);- const httpSnapshot = yield* snapshotLoader.load(prepared);+ // HTTP and the socket must agree, or omitted children would return through the socket.+ const httpSnapshot = yield* snapshotLoader.load(prepared, { omitIdleSubagents });if (Option.isSome(httpSnapshot)) {yield* cancelActiveFill;const previous = yield* SubscriptionRef.get(state);@@ -371,8 +405,12 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")}}+ const omission = omitIdleSubagents ? { omitIdleSubagents: true as const } : {};if (!canResume || Option.isNone(current.snapshot)) {- return supportsCompletionMarker ? { requestCompletionMarker: true as const } : {};+ return {+ ...omission,+ ...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),+ };}if (!supportsCompletionMarker) {yield* SubscriptionRef.update(state, (value) => ({@@ -383,6 +421,7 @@ export const makeEnvironmentShellState = Effect.fn("EnvironmentShellState.make")}return {afterSequence: current.snapshot.value.snapshotSequence,+ ...omission,...(supportsCompletionMarker ? { requestCompletionMarker: true as const } : {}),};}),diff --git a/packages/client-runtime/src/state/shellSnapshotHttp.ts b/packages/client-runtime/src/state/shellSnapshotHttp.tsindex cdb5ca77db5..cacab7b6724 100644--- a/packages/client-runtime/src/state/shellSnapshotHttp.ts+++ b/packages/client-runtime/src/state/shellSnapshotHttp.ts@@ -33,17 +33,22 @@ export const fetchEnvironmentShellSnapshot = Effect.fn(RemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization["Service"]>;readonly timeoutMs?: number;+ readonly omitIdleSubagents?: boolean;}) {+ const endpoint = {+ query: input.omitIdleSubagents === true ? { omitIdleSubagents: "1" } : {},+ };return yield* executeAuthenticatedEnvironmentHttpRequest({...input,group: "orchestration",method: "GET",- url: (urls) => urls.shellSnapshot(),+ url: (urls) => urls.shellSnapshot(endpoint),timeoutMs: input.timeoutMs ?? DEFAULT_SHELL_SNAPSHOT_TIMEOUT_MS,request: ({ client, headers }) =>client.shellSnapshot({headers: withOrchestrationProtocolHeader(headers),+ ...endpoint,responseMode: "response-only",}).pipe(Effect.flatMap(decodeShellSnapshotResponse)),@@ -80,6 +85,7 @@ export class ShellSnapshotLoader extends Context.Service<{readonly load: (prepared: PreparedConnection,+ options?: { readonly omitIdleSubagents?: boolean },) => Effect.Effect<Option.Option<DeferredShellSnapshot>>;}>()("@t3tools/client-runtime/state/shellSnapshotHttp/ShellSnapshotLoader") {}@@ -95,8 +101,13 @@ export const layer: Layer.Layer<ShellSnapshotLoader, never, HttpClient.HttpClienRemoteEnvironmentAuthorization.RemoteEnvironmentAuthorization,);return ShellSnapshotLoader.of({- load: (prepared: PreparedConnection) =>- fetchEnvironmentShellSnapshot({ prepared, signer, remoteAuthorization }).pipe(+ load: (prepared, options) =>+ fetchEnvironmentShellSnapshot({+ prepared,+ signer,+ remoteAuthorization,+ ...(options?.omitIdleSubagents === true ? { omitIdleSubagents: true } : {}),+ }).pipe(Effect.map(Option.some<DeferredShellSnapshot>),Effect.provideService(HttpClient.HttpClient, httpClient),Effect.catchCause((cause) =>diff --git a/packages/client-runtime/src/state/threadFamilies.test.ts b/packages/client-runtime/src/state/threadFamilies.test.tsnew file mode 100644index 00000000000..e6d284edee3--- /dev/null+++ b/packages/client-runtime/src/state/threadFamilies.test.ts@@ -0,0 +1,193 @@+import {+ EnvironmentId,+ ORCHESTRATION_V2_WS_METHODS,+ OrchestrationV2GetShellSnapshotError,+ ThreadId,+ type OrchestrationV2ShellSnapshot,+ type OrchestrationV2ThreadFamily,+ type OrchestrationV2ThreadShell,+} from "@t3tools/contracts";+import { describe, expect, it } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";+import * as Option from "effect/Option";+import * as Queue from "effect/Queue";+import * as Stream from "effect/Stream";+import * as SubscriptionRef from "effect/SubscriptionRef";+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";++import {+ AVAILABLE_CONNECTION_STATE,+ PrimaryConnectionTarget,+ type PreparedConnection,+ type SupervisorConnectionState,+} from "../connection/model.ts";+import * as EnvironmentRegistry from "../connection/registry.ts";+import * as EnvironmentSupervisor from "../connection/supervisor.ts";+import type { WsRpcProtocolClient } from "../rpc/protocol.ts";+import type * as RpcSession from "../rpc/session.ts";+import { EMPTY_SHELL_STATE, type EnvironmentShellState } from "./shell.ts";+import {+ createThreadFamilyAtoms,+ threadFamilyRead,+ threadFamilyRowsMissingFromShell,+} from "./threadFamilies.ts";++const row = (id: string, title = id) =>+ ({ id: ThreadId.make(id), title }) as unknown as OrchestrationV2ThreadShell;++describe("threadFamilyRowsMissingFromShell", () => {+ it("adds only the rows the shell left out, once, with shell rows winning", () => {+ const missing = threadFamilyRowsMissingFromShell({+ shellThreads: [row("parent"), row("live", "live from shell")],+ families: [+ { snapshotSequence: 4, threads: [row("live", "stale family copy"), row("idle")] },+ { snapshotSequence: 4, threads: [row("idle"), row("other")] },+ ],+ removedAt: new Map(),+ });+ expect(missing.map((thread) => thread.id)).toEqual(["idle", "other"]);+ });++ it("drops a family copy read before the shell removed that thread", () => {+ const missing = threadFamilyRowsMissingFromShell({+ shellThreads: [],+ families: [+ {+ snapshotSequence: 5,+ threads: [row("archived-after-read"), row("removed-before-read")],+ },+ ],+ removedAt: new Map([+ [ThreadId.make("archived-after-read"), 7],+ [ThreadId.make("removed-before-read"), 3],+ ]),+ });+ expect(missing.map((thread) => thread.id)).toEqual(["removed-before-read"]);+ });+});++const TARGET = new PrimaryConnectionTarget({+ environmentId: EnvironmentId.make("environment-family"),+ label: "Family environment",+ httpBaseUrl: "https://family.example.test",+ wsBaseUrl: "wss://family.example.test",+});++describe("createThreadFamilyAtoms", () => {+ it.effect("reads a family per shell generation and retries a failed read", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const replies =+ yield* Queue.unbounded<+ Effect.Effect<OrchestrationV2ThreadFamily, OrchestrationV2GetShellSnapshotError>+ >();+ const client = {+ [ORCHESTRATION_V2_WS_METHODS.getThreadFamily]: () => Effect.flatten(Queue.take(replies)),+ } as unknown as WsRpcProtocolClient;+ const session = {+ client,+ initialConfig: Effect.succeed({ shellThreadFamilies: true } as never),+ ready: Effect.void,+ probe: Effect.void,+ closed: Effect.never,+ } as unknown as RpcSession.RpcSession;+ const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({+ target: TARGET,+ state: yield* SubscriptionRef.make<SupervisorConnectionState>({+ ...AVAILABLE_CONNECTION_STATE,+ desired: true,+ network: "online",+ phase: "connected",+ attempt: 1,+ generation: 1,+ }),+ session: yield* SubscriptionRef.make(Option.some(session)),+ prepared: yield* SubscriptionRef.make(Option.none<PreparedConnection>()),+ connect: Effect.void,+ disconnect: Effect.void,+ retryNow: Effect.void,+ } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]);+ const run: EnvironmentRegistry.EnvironmentRegistry["Service"]["run"] = (+ _environmentId,+ effect,+ ) => Effect.provideService(effect, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);+ const followStream: EnvironmentRegistry.EnvironmentRegistry["Service"]["followStream"] = (+ _environmentId,+ stream,+ ) => Stream.provideService(stream, EnvironmentSupervisor.EnvironmentSupervisor, supervisor);+ const runtime = Atom.runtime(+ Layer.succeed(+ EnvironmentRegistry.EnvironmentRegistry,+ EnvironmentRegistry.EnvironmentRegistry.of({+ run,+ followStream,+ } as unknown as EnvironmentRegistry.EnvironmentRegistry["Service"]),+ ),+ );+ const parent = row("parent");+ const child = row("idle-child");+ const shellSnapshot = {+ schemaVersion: 1,+ snapshotSequence: 3,+ projects: [],+ threads: [parent],+ archivedThreads: [],+ } as OrchestrationV2ShellSnapshot;+ const shellAt = (generation: number): EnvironmentShellState => ({+ ...EMPTY_SHELL_STATE,+ status: "live",+ snapshot: Option.some(shellSnapshot),+ generation,+ });+ const shellState = Atom.make<AsyncResult.AsyncResult<EnvironmentShellState>>(+ AsyncResult.success(shellAt(0)),+ );+ const families = createThreadFamilyAtoms(runtime, () => shellState);+ const registry = yield* Effect.acquireRelease(Effect.sync(AtomRegistry.make), (registry) =>+ Effect.sync(() => registry.dispose()),+ );+ const family = families.familyAtom(TARGET.environmentId, parent.id);+ const mergedIds = () =>+ registry.get(families.snapshotAtom(TARGET.environmentId))?.threads.map(({ id }) => id);+ // Waits for the read to finish either way; the assertions read its outcome.+ const settle = AtomRegistry.getResult(registry, family, { suspendOnWaiting: true }).pipe(+ Effect.ignore,+ Effect.tap(() => Effect.yieldNow),+ );+ registry.mount(families.snapshotAtom(TARGET.environmentId));+ families.mount(registry, TARGET.environmentId, parent.id);++ // A cached shell from before this session's first snapshot reads nothing.+ expect(threadFamilyRead(registry.get(family))).toBe("pending");+ expect(yield* Queue.size(replies)).toBe(0);++ registry.set(shellState, AsyncResult.success(shellAt(1)));+ yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 3, threads: [child] }));+ yield* settle;+ expect(threadFamilyRead(registry.get(family))).toBe("settled");+ expect(mergedIds()).toEqual(["parent", "idle-child"]);++ // A new authoritative snapshot never reuses the old read, even while the next one waits+ // or fails.+ registry.set(shellState, AsyncResult.success(shellAt(2)));+ expect(threadFamilyRead(registry.get(family))).toBe("pending");+ expect(mergedIds()).toEqual(["parent"]);+ yield* Queue.offer(+ replies,+ Effect.fail(new OrchestrationV2GetShellSnapshotError({ message: "read failed" })),+ );+ yield* settle;+ expect(threadFamilyRead(registry.get(family))).toBe("failed");+ expect(mergedIds()).toEqual(["parent"]);++ families.refresh(registry, TARGET.environmentId, parent.id);+ expect(threadFamilyRead(registry.get(family))).toBe("pending");+ yield* Queue.offer(replies, Effect.succeed({ snapshotSequence: 5, threads: [child] }));+ yield* settle;+ expect(threadFamilyRead(registry.get(family))).toBe("settled");+ expect(mergedIds()).toEqual(["parent", "idle-child"]);+ }),+ ),+ );+});diff --git a/packages/client-runtime/src/state/threadFamilies.ts b/packages/client-runtime/src/state/threadFamilies.tsnew file mode 100644index 00000000000..84b511f16a2--- /dev/null+++ b/packages/client-runtime/src/state/threadFamilies.ts@@ -0,0 +1,226 @@+import {+ ORCHESTRATION_V2_WS_METHODS,+ type EnvironmentId,+ type OrchestrationV2ShellSnapshot,+ type OrchestrationV2ThreadFamily,+ type OrchestrationV2ThreadShell,+ type ThreadId,+} from "@t3tools/contracts";+import * as Effect from "effect/Effect";+import * as Option from "effect/Option";+import * as SubscriptionRef from "effect/SubscriptionRef";+import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";++import * as EnvironmentSupervisor from "../connection/supervisor.ts";+import type * as EnvironmentRegistry from "../connection/registry.ts";+import { EnvironmentRpcUnavailableError, request } from "../rpc/client.ts";+import { arrayElementsEqual } from "./entities.ts";+import { createEnvironmentQueryAtomFamily, selectEnvironmentQueryData } from "./runtime.ts";+import type { EnvironmentShellState } from "./shell.ts";++const EMPTY_FAMILY: OrchestrationV2ThreadFamily = { snapshotSequence: 0, threads: [] };+const EMPTY_MOUNTS: ReadonlyMap<ThreadId, number> = new Map();+// Generation 0 is the cached shell from before this session's first authoritative snapshot. A read+// for it would be thrown away once that snapshot lands, so it waits instead.+const AWAITING_AUTHORITATIVE_SHELL = AsyncResult.initial<never, never>(true);++/** Whether a family read can decide anything yet. Only a settled read can prove a thread is gone. */+export type ThreadFamilyRead = "pending" | "failed" | "settled";++export function threadFamilyRead(+ result: AsyncResult.AsyncResult<OrchestrationV2ThreadFamily, unknown>,+): ThreadFamilyRead {+ // A failure whose retry is in flight is pending, so callers do not restart that retry.+ if (result.waiting) return "pending";+ if (AsyncResult.isFailure(result)) return "failed";+ return AsyncResult.isSuccess(result) ? "settled" : "pending";+}++/**+ * Family rows the shell does not have. A shell row is at least as new as any family copy, since+ * shell deltas carry every change; a family copy read before the shell removed that thread is+ * stale.+ */+export function threadFamilyRowsMissingFromShell(input: {+ readonly shellThreads: ReadonlyArray<OrchestrationV2ThreadShell>;+ readonly families: ReadonlyArray<OrchestrationV2ThreadFamily>;+ readonly removedAt: ReadonlyMap<ThreadId, number>;+}): ReadonlyArray<OrchestrationV2ThreadShell> {+ const present = new Set<ThreadId>(input.shellThreads.map((thread) => thread.id));+ const missing: OrchestrationV2ThreadShell[] = [];+ for (const family of input.families) {+ for (const thread of family.threads) {+ if (present.has(thread.id)) continue;+ if ((input.removedAt.get(thread.id) ?? -1) > family.snapshotSequence) continue;+ present.add(thread.id);+ missing.push(thread);+ }+ }+ return missing;+}++/**+ * Shells that omit idle subagent children (`omitIdleSubagents`) leave those rows to thread+ * families: the active subagent tree that shares a thread's `lineage.rootThreadId`. A view, or a+ * queued message, mounts the family it needs; it is read once per shell generation. Family rows+ * merge behind shell rows and are never persisted. Shell deltas still carry every change, so a+ * changed child always arrives as a shell row, which wins.+ */+export function createThreadFamilyAtoms<R, ER, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry.EnvironmentRegistry | R, ER>,+ shellStateAtom: (+ environmentId: EnvironmentId,+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentShellState, E>>,+) {+ const shellStateValue = (state: AsyncResult.AsyncResult<EnvironmentShellState, E>) =>+ Option.getOrNull(AsyncResult.value(state));+ const generationAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make((get) => shellStateValue(get(shellStateAtom(environmentId)))?.generation ?? 0).pipe(+ Atom.withLabel(`environment-shell-generation:${environmentId}`),+ ),+ );++ // The generation is part of the key, so a read from before the latest authoritative snapshot is+ // never used again, even while a new read is pending or failed.+ const familyQueryAtom = createEnvironmentQueryAtomFamily(runtime, {+ label: "environment-data:orchestration:thread-family",+ staleTimeMs: Number.POSITIVE_INFINITY,+ idleTtlMs: 60_000,+ execute: Effect.fn("ThreadFamilies.read")(function* (input: {+ readonly threadId: ThreadId;+ readonly generation: number;+ }) {+ const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;+ const session = yield* SubscriptionRef.get(supervisor.session);+ if (Option.isNone(session)) {+ return yield* new EnvironmentRpcUnavailableError({+ environmentId: supervisor.target.environmentId,+ message: "The environment has no session.",+ });+ }+ // A config failure fails the read: an empty family would read as "the thread is gone".+ const config = yield* session.value.initialConfig;+ // Servers without families send every child in the shell, so absent means gone.+ if (config.shellThreadFamilies !== true) return EMPTY_FAMILY;+ return yield* request(ORCHESTRATION_V2_WS_METHODS.getThreadFamily, {+ threadId: input.threadId,+ });+ }),+ });+ const queryFor = (environmentId: EnvironmentId, threadId: ThreadId, generation: number) =>+ familyQueryAtom({ environmentId, input: { threadId, generation } });++ const familyAtom = Atom.family((key: string) => {+ const [environmentId, threadId] = JSON.parse(key) as [EnvironmentId, ThreadId];+ return Atom.make((get) => {+ const generation = get(generationAtom(environmentId));+ return generation === 0+ ? AWAITING_AUTHORITATIVE_SHELL+ : get(queryFor(environmentId, threadId, generation));+ }).pipe(Atom.withLabel(`environment-thread-family:${key}`));+ });+ const familyKey = (environmentId: EnvironmentId, threadId: ThreadId) =>+ JSON.stringify([environmentId, threadId]);++ /** Reads the current generation's family again, so a failed read does not last the session. */+ const refresh = (+ registry: AtomRegistry.AtomRegistry,+ environmentId: EnvironmentId,+ threadId: ThreadId,+ ) => {+ const generation = registry.get(generationAtom(environmentId));+ if (generation !== 0) registry.refresh(queryFor(environmentId, threadId, generation));+ };++ const mountsAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make(EMPTY_MOUNTS).pipe(+ Atom.keepAlive,+ Atom.withLabel(`environment-thread-family-mounts:${environmentId}`),+ ),+ );++ /** Keeps a thread's family in the merged rows until the returned release runs. */+ const mount = (+ registry: AtomRegistry.AtomRegistry,+ environmentId: EnvironmentId,+ threadId: ThreadId,+ ): (() => void) => {+ const atom = mountsAtom(environmentId);+ const mounts = registry.get(atom);+ registry.set(atom, new Map(mounts).set(threadId, (mounts.get(threadId) ?? 0) + 1));+ // Mounting again after a failure retries instead of keeping the failure until reconnect.+ if (+ threadFamilyRead(registry.get(familyAtom(familyKey(environmentId, threadId)))) === "failed"+ ) {+ refresh(registry, environmentId, threadId);+ }+ let released = false;+ return () => {+ if (released) return;+ released = true;+ const next = new Map(registry.get(atom));+ const count = (next.get(threadId) ?? 0) - 1;+ if (count > 0) next.set(threadId, count);+ else next.delete(threadId);+ registry.set(atom, next);+ };+ };++ const snapshotAtom = Atom.family((environmentId: EnvironmentId) => {+ let previous: {+ readonly snapshot: OrchestrationV2ShellSnapshot;+ readonly removedAt: ReadonlyMap<ThreadId, number>;+ readonly families: ReadonlyArray<OrchestrationV2ThreadFamily>;+ readonly merged: OrchestrationV2ShellSnapshot;+ } | null = null;+ return Atom.make((get): OrchestrationV2ShellSnapshot | null => {+ const state = shellStateValue(get(shellStateAtom(environmentId)));+ const snapshot = state === null ? null : Option.getOrNull(state.snapshot);+ const mounts = get(mountsAtom(environmentId));+ if (snapshot === null || state === null || mounts.size === 0) return snapshot;+ const families = [...mounts.keys()].flatMap((threadId) => {+ const family = selectEnvironmentQueryData(+ get(familyAtom(familyKey(environmentId, threadId))),+ );+ return family === null ? [] : [family];+ });+ // Most shell updates move only the cursor. With the same rows, removals and families, keep+ // the merged rows so thread lists skip their rebuild.+ const unchanged =+ previous !== null &&+ previous.snapshot.threads === snapshot.threads &&+ previous.removedAt === state.removedAt &&+ arrayElementsEqual(previous.families, families);+ if (unchanged && previous !== null && previous.snapshot === snapshot) return previous.merged;+ let merged: OrchestrationV2ShellSnapshot;+ if (unchanged && previous !== null) {+ merged =+ previous.merged === previous.snapshot+ ? snapshot+ : { ...snapshot, threads: previous.merged.threads };+ } else {+ const extras = threadFamilyRowsMissingFromShell({+ shellThreads: snapshot.threads,+ removedAt: state.removedAt,+ families,+ });+ merged =+ extras.length === 0+ ? snapshot+ : { ...snapshot, threads: [...snapshot.threads, ...extras] };+ }+ previous = { snapshot, removedAt: state.removedAt, families, merged };+ return merged;+ }).pipe(Atom.withLabel(`environment-snapshot-with-families:${environmentId}`));+ });++ return {+ /** The shell snapshot plus the rows of every mounted family. */+ snapshotAtom,+ /** The current generation's family read, for decisions that need a settled answer. */+ familyAtom: (environmentId: EnvironmentId, threadId: ThreadId) =>+ familyAtom(familyKey(environmentId, threadId)),+ mount,+ refresh,+ };+}diff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.tsindex 31985507aac..e060433d41a 100644--- a/packages/client-runtime/src/state/threads.ts+++ b/packages/client-runtime/src/state/threads.ts@@ -1047,5 +1047,6 @@ export * from "./composerPathSearch.ts";export * from "./threadCommands.ts";export * from "./threadFeedback.ts";export * from "./threadDetail.ts";+export * from "./threadFamilies.ts";export * from "./threadShell.ts";export * from "./threadState.ts";diff --git a/packages/contracts/src/environmentHttp.ts b/packages/contracts/src/environmentHttp.tsindex e7c057ea0cf..9e2ce04272a 100644--- a/packages/contracts/src/environmentHttp.ts+++ b/packages/contracts/src/environmentHttp.ts@@ -667,6 +667,10 @@ const EnvironmentOrchestrationThreadSnapshotParams = Schema.Struct({threadId: ThreadId,});+const EnvironmentOrchestrationShellSnapshotQuery = Schema.Struct({+ omitIdleSubagents: Schema.optionalKey(Schema.String),+});+const EnvironmentOrchestrationThreadBoundedSnapshotQuery = Schema.Struct({compactTurnItems: Schema.optionalKey(Schema.String),});@@ -688,6 +692,7 @@ class EnvironmentOrchestrationHttpApi extends HttpApiGroup.make("orchestration").add(HttpApiEndpoint.get("shellSnapshot", "/api/orchestration/shell", {headers: OrchestrationProtocolHeaders,+ query: EnvironmentOrchestrationShellSnapshotQuery,success: OrchestrationV2ShellSnapshot,error: EnvironmentOrchestrationSnapshotErrors,}).middleware(EnvironmentAuthenticatedAuth),diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.tsindex 61b21a97ddc..8897ead60f9 100644--- a/packages/contracts/src/orchestrationV2.ts+++ b/packages/contracts/src/orchestrationV2.ts@@ -1962,6 +1962,33 @@ export const OrchestrationV2ThreadShell = Schema.Struct({});export type OrchestrationV2ThreadShell = typeof OrchestrationV2ThreadShell.Type;+const LIVE_SHELL_STATUSES: ReadonlySet<OrchestrationV2ShellThreadStatus> = new Set([+ "queued",+ "preparing",+ "starting",+ "running",+ "waiting",+]);++/**+ * A subagent child that can still need the user or hold its parent. Shells that omit idle children+ * keep these, so every reader of live child rows (pending requests, working parents, background+ * work) still finds them.+ */+export function isLiveSubagentShell(+ thread: Pick<+ OrchestrationV2ThreadShell,+ "activityRunStatus" | "status" | "pendingRuntimeRequest" | "pendingBackgroundTasks"+ >,+): boolean {+ return (+ (thread.activityRunStatus ?? null) !== null ||+ LIVE_SHELL_STATUSES.has(thread.status) ||+ thread.pendingRuntimeRequest !== null ||+ (thread.pendingBackgroundTasks?.length ?? 0) > 0+ );+}+export const OrchestrationV2ThreadShellSnapshot = Schema.Struct({schemaVersion: PositiveInt,snapshotSequence: NonNegativeInt,@@ -3190,6 +3217,8 @@ export const ORCHESTRATION_V2_WS_METHODS = {searchThread: "orchestration.searchThread",searchThreadStream: "orchestration.searchThreadStream",getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot",+ getThreadFamily: "orchestration.getThreadFamily",+ getWorktreeThreadIds: "orchestration.getWorktreeThreadIds",getThreadProjection: "orchestration.getThreadProjection",getWorkflowScript: "orchestration.getWorkflowScript",stopWorkflow: "orchestration.stopWorkflow",@@ -3307,9 +3336,42 @@ export type OrchestrationV2GetThreadProjectionInput =export const OrchestrationV2SubscribeShellInput = Schema.Struct({afterSequence: Schema.optionalKey(NonNegativeInt),requestCompletionMarker: Schema.optionalKey(Schema.Boolean),+ /**+ * Snapshots leave out idle subagent children; read them with `getThreadFamily`. Send only to+ * servers that advertise `shellThreadFamilies`.+ */+ omitIdleSubagents: Schema.optionalKey(Schema.Boolean),});export type OrchestrationV2SubscribeShellInput = typeof OrchestrationV2SubscribeShellInput.Type;+export const OrchestrationV2GetThreadFamilyInput = Schema.Struct({+ threadId: ThreadId,+});+export type OrchestrationV2GetThreadFamilyInput = typeof OrchestrationV2GetThreadFamilyInput.Type;++/**+ * The active subagent threads that share the requested thread's `lineage.rootThreadId`: its whole+ * subagent tree, in any run state. An unknown thread has an empty family; a deleted one still+ * names its root.+ */+export const OrchestrationV2ThreadFamily = Schema.Struct({+ snapshotSequence: NonNegativeInt,+ threads: Schema.Array(OrchestrationV2ThreadShell),+});+export type OrchestrationV2ThreadFamily = typeof OrchestrationV2ThreadFamily.Type;++export const OrchestrationV2GetWorktreeThreadIdsInput = Schema.Struct({+ worktreePath: TrimmedNonEmptyString,+});+export type OrchestrationV2GetWorktreeThreadIdsInput =+ typeof OrchestrationV2GetWorktreeThreadIdsInput.Type;++/** Active threads on a worktree path, including subagent children a shell may leave out. */+export const OrchestrationV2WorktreeThreadIds = Schema.Struct({+ threadIds: Schema.Array(ThreadId),+});+export type OrchestrationV2WorktreeThreadIds = typeof OrchestrationV2WorktreeThreadIds.Type;+export const OrchestrationV2SubscribeThreadInput = Schema.Struct({threadId: ThreadId,afterSequence: Schema.optionalKey(NonNegativeInt),@@ -3679,6 +3741,14 @@ export const OrchestrationV2RpcSchemas = {input: Schema.Struct({}),output: OrchestrationV2ArchivedShellSnapshot,},+ getThreadFamily: {+ input: OrchestrationV2GetThreadFamilyInput,+ output: OrchestrationV2ThreadFamily,+ },+ getWorktreeThreadIds: {+ input: OrchestrationV2GetWorktreeThreadIdsInput,+ output: OrchestrationV2WorktreeThreadIds,+ },getThreadProjection: {input: OrchestrationV2GetThreadProjectionInput,output: OrchestrationV2ThreadProjection,diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.tsindex 9723ea5a872..9257872ffab 100644--- a/packages/contracts/src/rpc.ts+++ b/packages/contracts/src/rpc.ts@@ -1681,6 +1681,21 @@ const WsOrchestrationV2GetArchivedShellSnapshotRpc = Rpc.make(},);+const WsOrchestrationV2GetThreadFamilyRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.getThreadFamily, {+ payload: OrchestrationV2RpcSchemas.getThreadFamily.input,+ success: OrchestrationV2RpcSchemas.getThreadFamily.output,+ error: Schema.Union([OrchestrationV2GetShellSnapshotError, EnvironmentAuthorizationError]),+});++const WsOrchestrationV2GetWorktreeThreadIdsRpc = Rpc.make(+ ORCHESTRATION_V2_WS_METHODS.getWorktreeThreadIds,+ {+ payload: OrchestrationV2RpcSchemas.getWorktreeThreadIds.input,+ success: OrchestrationV2RpcSchemas.getWorktreeThreadIds.output,+ error: Schema.Union([OrchestrationV2GetShellSnapshotError, EnvironmentAuthorizationError]),+ },+);+const WsOrchestrationV2GetThreadProjectionRpc = Rpc.make(ORCHESTRATION_V2_WS_METHODS.getThreadProjection,{@@ -2082,6 +2097,8 @@ export const WsRpcGroup = RpcGroup.make(WsOrchestrationV2SearchThreadRpc,WsOrchestrationV2SearchThreadStreamRpc,WsOrchestrationV2GetArchivedShellSnapshotRpc,+ WsOrchestrationV2GetThreadFamilyRpc,+ WsOrchestrationV2GetWorktreeThreadIdsRpc,WsOrchestrationV2GetThreadProjectionRpc,WsOrchestrationV2LaunchThreadRpc,WsOrchestrationV2SubscribeArchivedShellRpc,diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.tsindex af8e6df5f76..3faa049acc1 100644--- a/packages/contracts/src/server.ts+++ b/packages/contracts/src/server.ts@@ -626,6 +626,11 @@ export const ServerConfig = Schema.Struct({observability: ServerObservability,settings: ServerSettings,shellResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),+ /**+ * The shell can leave idle subagent children out of snapshots (`omitIdleSubagents`), and+ * `getThreadFamily` and `getWorktreeThreadIds` serve the rows it leaves out.+ */+ shellThreadFamilies: Schema.optionalKey(Schema.Boolean),shellRevealInFileManager: Schema.optionalKey(Schema.Boolean),shellRevealInFileManagerKind: Schema.optionalKey(FileManagerRevealKind),threadResumeCompletionMarker: Schema.optionalKey(Schema.Boolean),