fix(threads): keep subagent worktrees visible to cleanup

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
Shivam SharmaandClaude Fable 5 authored and T3 Code Test committed 2026-08-14 15:04:12 +05:30
1 parent b8c54e76a3
commit 3a74176b65
15 files changed
+251 -25

No files matched your search

@@ -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 (
<SubagentThreadRedirect
environmentId={selectedThread.environmentId}
@@ -5,6 +5,7 @@ import {
CommandId,
EnvironmentId,
MessageId,
NodeId,
ProjectId,
ProviderInstanceId,
RunId,
@@ -271,6 +272,7 @@ describe("buildThreadListV2Items", () => {
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: "",
@@ -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;
@@ -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);
});
});
@@ -0,0 +1,5 @@
import type { OrchestrationV2ThreadShell } from "@t3tools/contracts";
export const isInternalSubagentThread = (
thread: Pick<OrchestrationV2ThreadShell, "forkedFrom" | "lineage">,
) => thread.lineage.relationshipToParent === "subagent" || thread.forkedFrom?.type === "node";
+1
View File
@@ -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,
@@ -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));
});
@@ -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,
+14
View File
@@ -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,
+24 -11
View File
@@ -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>()(
"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,
-12
View File
@@ -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<ScopedThreadRef> {
return appAtomRegistry
.get(environmentThreadShells.threadShellsAtom)
.filter((thread) => thread.environmentId === environmentId)
.map((thread) => scopeThreadRef(thread.environmentId, thread.id));
}
export function readThreadRefs(): ReadonlyArray<ScopedThreadRef> {
return appAtomRegistry
.get(environmentThreadShells.threadShellsAtom)
@@ -17,6 +17,10 @@ export function createOrchestrationEnvironmentAtoms<R, E>(
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,
@@ -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",
+18
View File
@@ -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,
+10
View File
@@ -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,