From 3a74176b6507283edb651748a1d9f820bed56125 Mon Sep 17 00:00:00 2001 From: Shivam Sharma <91240327+shivamhwp@users.noreply.github.com> Date: Sat, 1 Aug 2026 14:21:12 +0530 Subject: [PATCH] fix(threads): keep subagent worktrees visible to cleanup Co-Authored-By: Claude Fable 5 --- .../features/threads/ThreadRouteScreen.tsx | 3 +- .../src/features/threads/threadListV2.test.ts | 10 ++++ .../src/features/threads/threadListV2.ts | 3 +- .../features/threads/threadVisibility.test.ts | 53 +++++++++++++++++ .../src/features/threads/threadVisibility.ts | 5 ++ apps/server/src/auth/RpcAuthorization.ts | 1 + .../ThreadManagementService.test.ts | 59 +++++++++++++++++++ .../ThreadManagementService.ts | 17 ++++++ apps/server/src/ws.ts | 14 +++++ apps/web/src/hooks/useThreadActions.ts | 35 +++++++---- apps/web/src/state/entities.ts | 12 ---- .../client-runtime/src/state/orchestration.ts | 4 ++ .../contracts/src/orchestrationV2.test.ts | 32 ++++++++++ packages/contracts/src/orchestrationV2.ts | 18 ++++++ packages/contracts/src/rpc.ts | 10 ++++ 15 files changed, 251 insertions(+), 25 deletions(-) create mode 100644 apps/mobile/src/features/threads/threadVisibility.test.ts create mode 100644 apps/mobile/src/features/threads/threadVisibility.ts diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 716fcc6bf4..fab699c255 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -71,6 +71,7 @@ import { ThreadInspectorContentStack, type ThreadInspectorMode, } from "./thread-inspector-content-stack"; +import { isInternalSubagentThread } from "./threadVisibility"; interface ThreadInspectorSelection { readonly routeThreadIdentity: string | null; @@ -182,7 +183,7 @@ export function ThreadRouteScreen(props: ThreadRouteScreenProps) { // Internal subagent threads are hidden from user-facing lists; a deep // link or stale selection still lands here, so send it to the parent // thread instead of exposing the hidden transcript. - if (selectedThread.lineage.relationshipToParent === "subagent") { + if (isInternalSubagentThread(selectedThread)) { return ( { const forkId = ThreadId.make("fork"); const settledChildId = ThreadId.make("settled-child"); const snoozedChildId = ThreadId.make("snoozed-child"); + const nodeChildId = ThreadId.make("node-child"); const layout = buildThreadListV2Items({ threads: [ makeThread({ id: rootThreadId, title: "Root" }), @@ -314,6 +316,14 @@ describe("buildThreadListV2Items", () => { snoozedUntil: "2026-06-03T09:00:00.000Z", snoozedAt: "2026-06-01T12:00:00.000Z", }), + makeThread({ + id: nodeChildId, + title: "Node child", + forkedFrom: { + type: "node", + nodeId: NodeId.make("node:mobile-thread-list:child"), + }, + }), ], environmentId: null, searchQuery: "", diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index a91d379d8f..7c67d067a0 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -13,6 +13,7 @@ import { sortPinnedThreadsByOrderKey } from "@t3tools/client-runtime/state/threa import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; import type { PendingNewTask } from "../../state/use-pending-new-tasks"; +import { isInternalSubagentThread } from "./threadVisibility"; export { snoozeWakeLabel }; @@ -390,7 +391,7 @@ export function buildThreadListV2Items(input: { const snoozed: EnvironmentThreadShell[] = []; let nextSnoozeWakeAt: string | null = null; for (const thread of input.threads) { - if (thread.lineage.relationshipToParent === "subagent") continue; + if (isInternalSubagentThread(thread)) continue; // Callers pass live (unarchived) shells; settled threads are among them // and partition into the tail via effectiveSettled. if (input.environmentId !== null && thread.environmentId !== input.environmentId) continue; diff --git a/apps/mobile/src/features/threads/threadVisibility.test.ts b/apps/mobile/src/features/threads/threadVisibility.test.ts new file mode 100644 index 0000000000..dd7167e4b6 --- /dev/null +++ b/apps/mobile/src/features/threads/threadVisibility.test.ts @@ -0,0 +1,53 @@ +import { NodeId, RunId, ThreadId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { isInternalSubagentThread } from "./threadVisibility"; + +const rootId = ThreadId.make("thread:visibility:root"); +const rootLineage = { + rootThreadId: rootId, + parentThreadId: null, + relationshipToParent: null, +} as const; + +describe("thread visibility", () => { + it("keeps roots and user forks visible", () => { + expect(isInternalSubagentThread({ lineage: rootLineage, forkedFrom: null })).toBe(false); + expect( + isInternalSubagentThread({ + lineage: { + rootThreadId: rootId, + parentThreadId: rootId, + relationshipToParent: "fork", + }, + forkedFrom: { + type: "run", + threadId: rootId, + runId: RunId.make("run:visibility:fork"), + }, + }), + ).toBe(false); + }); + + it("hides explicit and node-owned subagent children", () => { + expect( + isInternalSubagentThread({ + lineage: { + rootThreadId: rootId, + parentThreadId: rootId, + relationshipToParent: "subagent", + }, + forkedFrom: null, + }), + ).toBe(true); + expect( + isInternalSubagentThread({ + lineage: rootLineage, + forkedFrom: { + type: "node", + nodeId: NodeId.make("node:visibility:subagent"), + }, + }), + ).toBe(true); + }); +}); diff --git a/apps/mobile/src/features/threads/threadVisibility.ts b/apps/mobile/src/features/threads/threadVisibility.ts new file mode 100644 index 0000000000..ff39d4dd4f --- /dev/null +++ b/apps/mobile/src/features/threads/threadVisibility.ts @@ -0,0 +1,5 @@ +import type { OrchestrationV2ThreadShell } from "@t3tools/contracts"; + +export const isInternalSubagentThread = ( + thread: Pick, +) => thread.lineage.relationshipToParent === "subagent" || thread.forkedFrom?.type === "node"; diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index d8ae17419a..6f8affb713 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -27,6 +27,7 @@ export const RPC_REQUIRED_SCOPES = { [ORCHESTRATION_V2_WS_METHODS.getFullThreadDiff]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.searchThreads]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.getArchivedShellSnapshot]: AuthOrchestrationReadScope, + [ORCHESTRATION_V2_WS_METHODS.listAllThreadRefs]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: AuthOrchestrationReadScope, [ORCHESTRATION_V2_WS_METHODS.launchThread]: AuthOrchestrationOperateScope, [ORCHESTRATION_V2_WS_METHODS.subscribeArchivedShell]: AuthOrchestrationReadScope, diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts index 5fa8a05514..b494a637c4 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.test.ts @@ -376,3 +376,62 @@ it("removes internal subagent children from active and archived shell collection expect(snapshot.threads.map((thread) => thread.id)).toEqual([rootId, forkId]); expect(snapshot.archivedThreads).toEqual([]); }); + +it.effect("lists compact references for every active thread, including hidden subagents", () => { + const projectId = ProjectId.make("project:thread-management:refs"); + const rootId = ThreadId.make("thread:thread-management:refs-root"); + const lineageChildId = ThreadId.make("thread:thread-management:refs-lineage-child"); + const nodeChildId = ThreadId.make("thread:thread-management:refs-node-child"); + const worktreePath = "/workspace/project/.worktrees/feature"; + const shell = ( + id: ThreadId, + lineage: OrchestrationV2ThreadShell["lineage"], + forkedFrom: OrchestrationV2ThreadShell["forkedFrom"], + ) => ({ id, projectId, worktreePath, lineage, forkedFrom }) as OrchestrationV2ThreadShell; + const rootLineage = { + rootThreadId: rootId, + parentThreadId: null, + relationshipToParent: null, + } as const; + const threads = [ + shell(rootId, rootLineage, null), + shell( + lineageChildId, + { + rootThreadId: rootId, + parentThreadId: rootId, + relationshipToParent: "subagent", + }, + null, + ), + shell(nodeChildId, rootLineage, { + type: "node", + nodeId: NodeId.make("node:thread-management:refs-child"), + }), + ]; + const testLayer = layer.pipe( + Layer.provide( + Layer.mock(OrchestratorV2)({ + getShellSnapshot: () => + Effect.succeed({ + schemaVersion: 3, + snapshotSequence: 10, + threads, + archivedThreads: [], + }), + }), + ), + ); + + return Effect.gen(function* () { + const service = yield* ThreadManagementService; + + expect(yield* service.listAllThreadRefs()).toEqual({ + threadRefs: threads.map((thread) => ({ + threadId: thread.id, + projectId, + worktreePath, + })), + }); + }).pipe(Effect.provide(testLayer)); +}); diff --git a/apps/server/src/orchestration-v2/ThreadManagementService.ts b/apps/server/src/orchestration-v2/ThreadManagementService.ts index 9611591091..3ef3deb727 100644 --- a/apps/server/src/orchestration-v2/ThreadManagementService.ts +++ b/apps/server/src/orchestration-v2/ThreadManagementService.ts @@ -7,6 +7,7 @@ import { type OrchestrationV2Command, type OrchestrationV2ConversationMessage, type OrchestrationV2CreationSource, + type OrchestrationV2ListAllThreadRefsResult, type OrchestrationV2Run, type OrchestrationV2ThreadShellSnapshot, type OrchestrationV2ThreadProjection, @@ -283,6 +284,10 @@ export interface ThreadManagementServiceShape { OrchestrationV2ThreadShellSnapshot, OrchestratorV2Error >; + readonly listAllThreadRefs: () => Effect.Effect< + OrchestrationV2ListAllThreadRefsResult, + OrchestratorV2Error + >; readonly getThreadShell: OrchestratorV2["Service"]["getThreadShell"]; readonly listProjectThreads: (input: { readonly projectId: ProjectId; @@ -471,6 +476,17 @@ const make = Effect.gen(function* () { ), ); + const listAllThreadRefs: ThreadManagementServiceShape["listAllThreadRefs"] = () => + orchestrator.getShellSnapshot().pipe( + Effect.map((snapshot) => ({ + threadRefs: snapshot.threads.map(({ id, projectId, worktreePath }) => ({ + threadId: id, + projectId, + worktreePath, + })), + })), + ); + const sendToThread: ThreadManagementServiceShape["sendToThread"] = (input) => Effect.gen(function* () { const target = yield* getProjectThread(input); @@ -657,6 +673,7 @@ const make = Effect.gen(function* () { getThreadSnapshot, getProjectThread, getShellSnapshot: orchestrator.getShellSnapshot, + listAllThreadRefs, getThreadShell: orchestrator.getThreadShell, listProjectThreads, sendToThread, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 43424f6880..c44cfd623c 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -1170,6 +1170,20 @@ const makeWsRpcLayer = ( getOrchestrationV2ArchivedShellSnapshot, { "rpc.aggregate": "orchestration" }, ), + [ORCHESTRATION_V2_WS_METHODS.listAllThreadRefs]: (_input) => + observeRpcEffect( + ORCHESTRATION_V2_WS_METHODS.listAllThreadRefs, + threadManagement.listAllThreadRefs().pipe( + Effect.mapError( + (cause) => + new OrchestrationV2GetShellSnapshotError({ + message: "Failed to list orchestration V2 thread references", + cause, + }), + ), + ), + { "rpc.aggregate": "orchestrationV2" }, + ), [ORCHESTRATION_V2_WS_METHODS.getThreadProjection]: (input) => observeRpcEffect( ORCHESTRATION_V2_WS_METHODS.getThreadProjection, diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts index 6bba221e4e..acddcefe24 100644 --- a/apps/web/src/hooks/useThreadActions.ts +++ b/apps/web/src/hooks/useThreadActions.ts @@ -27,7 +27,6 @@ import { readEnvironmentSupportsSettlement, readEnvironmentSupportsSnooze, readEnvironmentSupportsVisitedTracking, - readEnvironmentAllThreadRefs, readEnvironmentThreadRefs, readProject, readThreadShell, @@ -40,6 +39,7 @@ import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from " import { stackedThreadToast, toastManager } from "../components/ui/toast"; import { useClientSettings } from "./useSettings"; import { useAtomCommand } from "../state/use-atom-command"; +import { orchestrationEnvironment } from "../state/orchestration"; export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass()( "ThreadArchiveBlockedError", @@ -174,6 +174,10 @@ export function useThreadActions() { const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, { reportFailure: false, }); + const listAllThreadRefs = useAtomCommand(orchestrationEnvironment.v2.listAllThreadRefs, { + reportFailure: false, + reportDefect: false, + }); const settleThreadMutation = useAtomCommand(threadEnvironment.settle, { reportFailure: false, }); @@ -317,12 +321,20 @@ export function useThreadActions() { const shell = readThreadShell(ref); return shell === null ? [] : [shell]; }); - // Worktree bookkeeping must include hidden subagent threads: deleting a - // parent does not cascade to them, so they can still hold the worktree. - const allThreads = readEnvironmentAllThreadRefs(threadRef.environmentId).flatMap((ref) => { - const shell = readThreadShell(ref); - return shell === null ? [] : [shell]; + // Worktree bookkeeping must include hidden subagent threads. Older + // servers do not expose this unfiltered query, so failure conservatively + // disables cleanup instead of guessing from the user-facing snapshot. + const allThreadRefsResult = await listAllThreadRefs({ + environmentId: threadRef.environmentId, + input: {}, }); + const allThreads = + allThreadRefsResult._tag === "Success" + ? allThreadRefsResult.value.threadRefs.map((ref) => ({ + id: ref.threadId, + worktreePath: ref.worktreePath, + })) + : null; const threadProject = readProject({ environmentId: threadRef.environmentId, projectId: thread.projectId, @@ -337,15 +349,15 @@ export function useThreadActions() { ) : undefined; const survivingThreads = - deletedIds && deletedIds.size > 0 + allThreads !== null && deletedIds && deletedIds.size > 0 ? allThreads.filter( (entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id), ) : allThreads; - const orphanedWorktreePath = getOrphanedWorktreePathForThread( - survivingThreads, - threadRef.threadId, - ); + const orphanedWorktreePath = + survivingThreads === null + ? null + : getOrphanedWorktreePathForThread(survivingThreads, threadRef.threadId); const displayWorktreePath = orphanedWorktreePath ? formatWorktreePathForDisplay(orphanedWorktreePath) : null; @@ -496,6 +508,7 @@ export function useThreadActions() { closeTerminal, deleteThreadMutation, getCurrentRouteThreadRef, + listAllThreadRefs, refreshVcsStatus, removeWorktree, router, diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index e14a0c1b25..8d0b44b624 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -263,18 +263,6 @@ export function readEnvironmentThreadRefs( .map((thread) => scopeThreadRef(thread.environmentId, thread.id)); } -/** Every thread in the environment, including internal subagent threads. - Worktree bookkeeping must see all threads that can hold a worktree - reference, or deleting a parent reads its subagents' worktree as orphaned. */ -export function readEnvironmentAllThreadRefs( - environmentId: EnvironmentId, -): ReadonlyArray { - return appAtomRegistry - .get(environmentThreadShells.threadShellsAtom) - .filter((thread) => thread.environmentId === environmentId) - .map((thread) => scopeThreadRef(thread.environmentId, thread.id)); -} - export function readThreadRefs(): ReadonlyArray { return appAtomRegistry .get(environmentThreadShells.threadShellsAtom) diff --git a/packages/client-runtime/src/state/orchestration.ts b/packages/client-runtime/src/state/orchestration.ts index 728c085937..118fed05f7 100644 --- a/packages/client-runtime/src/state/orchestration.ts +++ b/packages/client-runtime/src/state/orchestration.ts @@ -17,6 +17,10 @@ export function createOrchestrationEnvironmentAtoms( label: "environment-data:orchestration-v2:dispatch-command", tag: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, }), + listAllThreadRefs: createEnvironmentRpcCommand(runtime, { + label: "environment-data:orchestration-v2:list-all-thread-refs", + tag: ORCHESTRATION_V2_WS_METHODS.listAllThreadRefs, + }), threadProjection: createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:orchestration-v2:thread-projection", tag: ORCHESTRATION_V2_WS_METHODS.getThreadProjection, diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index 731f657152..284c361a47 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -27,6 +27,7 @@ import { OrchestrationV2ProviderThread, OrchestrationV2ProviderThreadJson, OrchestrationV2DomainEventJson, + OrchestrationV2ListAllThreadRefsResult, OrchestrationV2ShellSnapshot, OrchestrationV2Subagent, OrchestrationV2SubagentActivation, @@ -65,8 +66,39 @@ const decodeOrchestrationV2ProviderThreadJson = Schema.decodeUnknownSync( ); const decodeOrchestrationV2ProviderThread = Schema.decodeUnknownSync(OrchestrationV2ProviderThread); const decodeOrchestrationV2ThreadShell = Schema.decodeUnknownSync(OrchestrationV2ThreadShell); +const decodeOrchestrationV2SubagentActivation = Schema.decodeUnknownSync( + OrchestrationV2SubagentActivation, +); +const decodeOrchestrationV2ListAllThreadRefsResult = Schema.decodeUnknownSync( + OrchestrationV2ListAllThreadRefsResult, +); +const decodeOrchestrationV2DomainEventJson = Schema.decodeUnknownSync( + OrchestrationV2DomainEventJson, +); +const decodeStoredOrchestrationV2Subagent = Schema.decodeUnknownSync( + Schema.fromJsonString(OrchestrationV2SubagentJson), +); describe("orchestration V2 contracts", () => { + it("decodes compact unfiltered thread references", () => { + expect( + decodeOrchestrationV2ListAllThreadRefsResult({ + threadRefs: [ + { + threadId: "thread-1", + projectId: "project-1", + worktreePath: "/workspace/project/.worktrees/feature", + }, + { + threadId: "thread-2", + projectId: "project-1", + worktreePath: null, + }, + ], + }).threadRefs, + ).toHaveLength(2); + }); + it("lets legacy snapshot decoders ignore enrichment metadata", () => { const decoded = decodeLegacyShellStreamItem({ kind: "snapshot", diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 28decf070b..d10fda1e76 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2426,6 +2426,7 @@ export const ORCHESTRATION_V2_WS_METHODS = { getFullThreadDiff: "orchestration.getFullThreadDiff", searchThreads: "orchestration.searchThreads", getArchivedShellSnapshot: "orchestration.getArchivedShellSnapshot", + listAllThreadRefs: "orchestration.listAllThreadRefs", getThreadProjection: "orchestration.getThreadProjection", getWorkflowScript: "orchestration.getWorkflowScript", launchThread: "orchestration.launchThread", @@ -2461,6 +2462,19 @@ export const OrchestrationV2ArchivedShellStreamItem = Schema.Union([ export type OrchestrationV2ArchivedShellStreamItem = typeof OrchestrationV2ArchivedShellStreamItem.Type; +export const OrchestrationV2ThreadRef = Schema.Struct({ + threadId: ThreadId, + projectId: ProjectId, + worktreePath: Schema.NullOr(TrimmedNonEmptyString), +}); +export type OrchestrationV2ThreadRef = typeof OrchestrationV2ThreadRef.Type; + +export const OrchestrationV2ListAllThreadRefsResult = Schema.Struct({ + threadRefs: Schema.Array(OrchestrationV2ThreadRef), +}); +export type OrchestrationV2ListAllThreadRefsResult = + typeof OrchestrationV2ListAllThreadRefsResult.Type; + export const OrchestrationV2ThreadLaunchWorkspaceStrategy = Schema.Union([ Schema.Struct({ type: Schema.Literal("root"), @@ -2727,6 +2741,10 @@ export const OrchestrationV2RpcSchemas = { input: Schema.Struct({}), output: OrchestrationV2ArchivedShellSnapshot, }, + listAllThreadRefs: { + input: Schema.Struct({}), + output: OrchestrationV2ListAllThreadRefsResult, + }, getThreadProjection: { input: OrchestrationV2GetThreadProjectionInput, output: OrchestrationV2ThreadProjection, diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index dad02192a6..52a1fd4b40 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -945,6 +945,15 @@ export const WsOrchestrationV2GetArchivedShellSnapshotRpc = Rpc.make( }, ); +export const WsOrchestrationV2ListAllThreadRefsRpc = Rpc.make( + ORCHESTRATION_V2_WS_METHODS.listAllThreadRefs, + { + payload: OrchestrationV2RpcSchemas.listAllThreadRefs.input, + success: OrchestrationV2RpcSchemas.listAllThreadRefs.output, + error: Schema.Union([OrchestrationV2GetShellSnapshotError, EnvironmentAuthorizationError]), + }, +); + export const WsOrchestrationV2GetThreadProjectionRpc = Rpc.make( ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { @@ -1191,6 +1200,7 @@ export const WsRpcGroup = RpcGroup.make( WsOrchestrationV2GetFullThreadDiffRpc, WsOrchestrationV2SearchThreadsRpc, WsOrchestrationV2GetArchivedShellSnapshotRpc, + WsOrchestrationV2ListAllThreadRefsRpc, WsOrchestrationV2GetThreadProjectionRpc, WsOrchestrationV2LaunchThreadRpc, WsOrchestrationV2SubscribeArchivedShellRpc,