@devries-cameron20 / t3code Mirror · read-only / commits / a8b57b07ea
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

fix(server): let parents revert after their subagents complete (#31874)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Kwan Li committed Nov 20, 2026 at 06:16 UTC a8b57b07ea8dc1cd27caedc668eb9a534c6d736b
3 files changed +253 -4
apps/server/src/orchestration-v2/CheckpointRestoreSafety.test.ts
+145
@@ -252,3 +252,148 @@ it.effect.each([
252 assert.equal(result, isolated);
253 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
254 );
255 +
256 +it.effect.each([
257 + { name: "completed child", isolated: true },
258 + { name: "completed native child", isolated: true },
259 + { name: "native child with running tool", isolated: false },
260 + { name: "native child with provider background task", isolated: false },
261 + { name: "native child with parent background task", isolated: false },
262 + { name: "native child with another provider parent task", isolated: true },
263 + { name: "native child grandchild with root background task", isolated: false },
264 + { name: "missing task record", isolated: false },
265 + { name: "task belongs to another child", isolated: false },
266 + { name: "completed child with pending task", isolated: false },
267 + { name: "grandchild through fork", isolated: false },
268 + { name: "completed grandchild", isolated: true },
269 + { name: "unrelated child", isolated: false },
270 + { name: "running child", isolated: false },
271 + { name: "held queue", isolated: false },
272 + { name: "failed child", isolated: false },
273 + { name: "cyclic ancestry", isolated: false },
274 +] as const)("parent file restore with $name: $isolated", ({ name, isolated }) =>
275 + Effect.gen(function* () {
276 + const fileSystem = yield* FileSystem.FileSystem;
277 + const path = yield* Path.Path;
278 + const worktreePath = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-restore-child-" });
279 + const parentId = ThreadId.make("restore-parent");
280 + const childId = ThreadId.make("restore-child");
281 + const ancestorId = ThreadId.make("restore-ancestor");
282 + const child = {
283 + id: childId,
284 + projectId: ProjectId.make("restore-project"),
285 + deletedAt: null,
286 + worktreePath,
287 + activeRunId: name === "running child" ? "child-run" : null,
288 + activityRunStatus: null,
289 + latestRunId: name.includes("native child") ? null : "child-run",
290 + creationSource: name.includes("native child") ? "provider" : "user",
291 + forkedFrom: { type: "node", nodeId: "child-task" },
292 + status: name.includes("native child")
293 + ? "idle"
294 + : name === "running child"
295 + ? "running"
296 + : name === "failed child"
297 + ? "failed"
298 + : "completed",
299 + pendingRuntimeRequest: null,
300 + pendingBackgroundTasks: [],
301 + lineage: {
302 + parentThreadId:
303 + name === "completed grandchild" ||
304 + name === "native child grandchild with root background task" ||
305 + name === "grandchild through fork" ||
306 + name === "cyclic ancestry"
307 + ? ancestorId
308 + : name === "unrelated child"
309 + ? ThreadId.make("another-parent")
310 + : parentId,
311 + relationshipToParent: "subagent",
312 + rootThreadId: parentId,
313 + },
314 + };
315 + const ancestor = {
316 + ...child,
317 + id: ancestorId,
318 + forkedFrom: { type: "node", nodeId: "ancestor-task" },
319 + lineage: {
320 + ...child.lineage,
321 + relationshipToParent: name === "grandchild through fork" ? "fork" : "subagent",
322 + parentThreadId: name === "cyclic ancestry" ? childId : parentId,
323 + },
324 + };
325 + const children =
326 + name === "completed grandchild" ||
327 + name === "native child grandchild with root background task" ||
328 + name === "grandchild through fork" ||
329 + name === "cyclic ancestry"
330 + ? [child, ancestor]
331 + : [child];
332 + const projections = {
333 + getShellSnapshot: () =>
334 + Effect.succeed({
335 + threads: children,
336 + archivedThreads: [],
337 + }),
338 + getCheckpointContext: () =>
339 + Effect.succeed({
340 + checkpointScopes: [],
341 + runs: name === "held queue" ? [{ status: "queued" }] : [],
342 + }),
343 + getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),
344 + getThreadRecords: (
345 + _threadId: unknown,
346 + _fields: readonly string[],
347 + filter: { subagentIds?: string[]; turnItemStatuses?: string[] } = {},
348 + ) =>
349 + Effect.succeed({
350 + providerThreads:
351 + _threadId === parentId &&
352 + (name.includes("parent") ||
353 + name === "native child grandchild with root background task") &&
354 + name.includes("native child")
355 + ? [
356 + {
357 + providerInstanceId:
358 + name === "native child with another provider parent task"
359 + ? "other-provider"
360 + : "claude",
361 + status: "idle",
362 + pendingBackgroundTasks: [{ taskId: "background", kind: "command" }],
363 + },
364 + ]
365 + : name === "native child with provider background task"
366 + ? [{ status: "idle", pendingBackgroundTasks: [{ taskId: "background" }] }]
367 + : [],
368 + turnItems:
369 + filter.turnItemStatuses !== undefined && name === "native child with running tool"
370 + ? [{ type: "command_execution", status: "running" }]
371 + : [],
372 + subagents:
373 + name === "missing task record"
374 + ? []
375 + : [
376 + {
377 + id: filter.subagentIds?.[0],
378 + providerInstanceId: "claude",
379 + nativeTaskRef: { nativeId: "native-task" },
380 + childThreadId:
381 + name === "task belongs to another child"
382 + ? "another-child"
383 + : filter.subagentIds?.[0] === "ancestor-task"
384 + ? ancestorId
385 + : childId,
386 + origin: name.includes("native child") ? "provider_native" : "app_owned",
387 + status: name === "completed child with pending task" ? "running" : "completed",
388 + },
389 + ],
390 + }),
391 + };
392 + const result = yield* isCheckpointRestoreIsolated(
393 + { id: parentId, worktreePath },
394 + { cwd: worktreePath },
395 + { fileSystem, path, projections: projections as never, projects: {} as never },
396 + );
397 + assert.equal(result, isolated);
398 + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
399 +);
apps/server/src/orchestration-v2/CheckpointRestoreSafety.ts
+104 -2
@@ -1,4 +1,11 @@
1 -import type { OrchestrationV2AppThread, OrchestrationV2CheckpointScope } from "@t3tools/contracts";
1 +import {
2 + isLiveSubagentShell,
3 + isProviderNativeSubagentThread,
4 + type OrchestrationV2AppThread,
5 + type OrchestrationV2CheckpointScope,
6 + type OrchestrationV2ProviderThread,
7 + type OrchestrationV2ThreadShell,
8 +} from "@t3tools/contracts";
9 import * as Effect from "effect/Effect";
10 import type * as FileSystem from "effect/FileSystem";
11 import * as Option from "effect/Option";
@@ -6,6 +13,8 @@ import type * as Path from "effect/Path";
13 import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
14 import type * as ProjectStore from "./ProjectStore.ts";
15
16 +const UNFINISHED_RUN_STATUSES = new Set(["queued", "preparing", "starting", "running", "waiting"]);
17 +
18 export const SHARED_WORKSPACE_RESTORE_MESSAGE =
19 "File restore requires an isolated worktree. This workspace may contain changes from another thread or a side chat. Rewind the conversation without restoring files instead, or delete side chats you no longer need.";
20
@@ -45,8 +54,29 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi
54 shared = cwd !== worktreeCwd;
55 if (!shared) {
56 const shell = yield* projections.getShellSnapshot();
57 + const threads = [...shell.threads, ...shell.archivedThreads];
58 + const threadsById = new Map(threads.map((candidate) => [candidate.id, candidate]));
59 + const subagentAncestors = (candidate: OrchestrationV2ThreadShell) => {
60 + const ancestors: OrchestrationV2AppThread["id"][] = [];
61 + const seen = new Set<string>();
62 + let current: OrchestrationV2ThreadShell | undefined = candidate;
63 + while (current !== undefined && !seen.has(current.id)) {
64 + seen.add(current.id);
65 + if (current.lineage.relationshipToParent !== "subagent") return undefined;
66 + const parentId: OrchestrationV2AppThread["id"] | null = current.lineage.parentThreadId;
67 + if (parentId === null) return undefined;
68 + ancestors.push(parentId);
69 + if (parentId === thread.id) return ancestors;
70 + current = threadsById.get(parentId);
71 + }
72 + return undefined;
73 + };
74 + const ancestorProviders = new Map<
75 + OrchestrationV2AppThread["id"],
76 + ReadonlyArray<OrchestrationV2ProviderThread>
77 + >();
78 const checkedPaths = new Set<string>();
49 - for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {
79 + for (const otherThread of threads) {
80 if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
81 // An idle side chat that only answered questions never touched the shared worktree.
82 if (
@@ -64,6 +94,78 @@ export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpoi
94 if (turnItems.length === 0) continue;
95 }
96 const other = yield* projections.getCheckpointContext(otherThread.id);
97 + const nativeSubagent = isProviderNativeSubagentThread(otherThread);
98 + const ancestors = subagentAncestors(otherThread);
99 + // Native children can be runless; their completion lives on the parent's task record.
100 + if (
101 + otherThread.worktreePath === worktreePath &&
102 + (otherThread.status === "completed" ||
103 + (nativeSubagent && otherThread.status === "idle" && other.runs.length === 0)) &&
104 + otherThread.activeRunId === null &&
105 + !isLiveSubagentShell(otherThread) &&
106 + ancestors !== undefined &&
107 + !other.runs.some((run) => UNFINISHED_RUN_STATUSES.has(run.status)) &&
108 + otherThread.lineage.parentThreadId !== null &&
109 + otherThread.forkedFrom?.type === "node"
110 + ) {
111 + const taskNodeId = otherThread.forkedFrom.nodeId;
112 + const { subagents } = yield* projections.getThreadRecords(
113 + otherThread.lineage.parentThreadId,
114 + ["subagents"],
115 + { subagentIds: [taskNodeId] },
116 + );
117 + const task = subagents.find(
118 + (candidate) =>
119 + candidate.id === taskNodeId && candidate.childThreadId === otherThread.id,
120 + );
121 + if (
122 + task?.status === "completed" &&
123 + task.origin === (nativeSubagent ? "provider_native" : "app_owned")
124 + ) {
125 + if (!nativeSubagent) continue;
126 + // Runless shells omit background work; inspect the raw records before restoring files.
127 + const { providerThreads, turnItems } = yield* projections.getThreadRecords(
128 + otherThread.id,
129 + ["providerThreads", "turnItems"],
130 + {
131 + turnItemTypes: ["command_execution", "file_change", "dynamic_tool", "subagent"],
132 + turnItemStatuses: ["pending", "running", "waiting"],
133 + },
134 + );
135 + if (
136 + turnItems.length === 0 &&
137 + !providerThreads.some(
138 + (providerThread) =>
139 + providerThread.status === "active" ||
140 + (providerThread.pendingBackgroundTasks?.length ?? 0) > 0,
141 + )
142 + ) {
143 + // Claude can keep a child's unattributed background commands on an ancestor session.
144 + let pendingAncestorWork = false;
145 + for (const ancestorId of ancestors) {
146 + let providers = ancestorProviders.get(ancestorId);
147 + if (providers === undefined) {
148 + const records = yield* projections.getThreadRecords(ancestorId, [
149 + "providerThreads",
150 + ]);
151 + providers = records.providerThreads;
152 + ancestorProviders.set(ancestorId, providers);
153 + }
154 + if (
155 + providers.some(
156 + (provider) =>
157 + provider.providerInstanceId === task.providerInstanceId &&
158 + (provider.pendingBackgroundTasks?.length ?? 0) > 0,
159 + )
160 + ) {
161 + pendingAncestorWork = true;
162 + break;
163 + }
164 + }
165 + if (!pendingAncestorWork) continue;
166 + }
167 + }
168 + }
169 const providerContext = yield* projections.getThreadProviderContext(otherThread.id);
170 const paths = [
171 otherThread.worktreePath,
docs/user/composer.md
+4 -2
@@ -181,8 +181,10 @@ to its checkpoint from before that message. That also undoes edits you made your
181 File restore is only offered for threads running in a worktree, and it is
182 refused when another thread or agent session also uses that directory, a folder
183 inside it, or a folder that contains it, since
184 -restoring would erase their changes. A thread that works in the project directory
185 -rewinds the conversation only. The selected prompt and its attachments return to the composer for editing and
184 +restoring would erase their changes. Completed subagents belonging to the reverting
185 +thread do not block restoring that same worktree, provided they have no queued or
186 +active work, pending requests, or background tasks. A thread that works in the project
187 +directory rewinds the conversation only. The selected prompt and its attachments return to the composer for editing and
188 resending. Any unsent draft stays above the restored prompt.
189
190 This removes the selected message and later conversation from the active thread