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

main
ts 208 lines 9.32 KB
Raw
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";
12 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
21 // Check isolation at admission and rollback; checkpoints restore whole checkouts, which may become shared.
22 export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpointRestoreIsolated")(
23 function* (
24 thread: Pick<OrchestrationV2AppThread, "id" | "worktreePath">,
25 scope: Pick<OrchestrationV2CheckpointScope, "cwd">,
26 dependencies: {
27 readonly fileSystem: FileSystem.FileSystem;
28 readonly projections: ProjectionStoreV2["Service"];
29 readonly projects: ProjectStore.ProjectStoreV2["Service"];
30 readonly path: Path.Path;
31 },
32 ) {
33 const { fileSystem, projections, projects, path } = dependencies;
34 const contains = (parent: string, child: string) => {
35 const relative = path.relative(parent, child);
36 return (
37 relative === "" ||
38 (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
39 );
40 };
41 const worktreePath = thread.worktreePath;
42 let shared = worktreePath == null;
43 if (!shared && worktreePath !== null) {
44 // Storage cleanup may have removed the worktree; rollback recreates it.
45 const resolve = (target: string) =>
46 fileSystem.realPath(target).pipe(
47 Effect.catchIf(
48 (error) => error.reason._tag === "NotFound",
49 (_error) => Effect.succeed(path.resolve(target)),
50 ),
51 );
52 const cwd = yield* resolve(scope.cwd);
53 const worktreeCwd = yield* resolve(worktreePath);
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>();
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 (
83 otherThread.lineage.sideChat === true &&
84 otherThread.activeRunId === null &&
85 otherThread.worktreePath === worktreePath
86 ) {
87 const { turnItems } = yield* projections.getThreadRecords(
88 otherThread.id,
89 ["turnItems"],
90 {
91 turnItemTypes: ["command_execution", "file_change", "dynamic_tool"],
92 },
93 );
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,
172 ...other.checkpointScopes.map((candidate) => candidate.cwd),
173 // Errored sessions can still stream. Shared sessions retain another thread's opening cwd;
174 // turn worktrees and project roots are already covered here.
175 ...providerContext.providerSessions
176 .filter(
177 (session) =>
178 session.status !== "stopped" &&
179 !session.capabilities.sessions.supportsMultipleProviderThreadsPerSession,
180 )
181 .map((session) => session.cwd),
182 ].filter((value): value is string => value !== null);
183 if (otherThread.worktreePath === null) {
184 const project = yield* projects.get(otherThread.projectId, { includeDeleted: true });
185 if (Option.isNone(project)) return false;
186 paths.push(project.value.workspaceRoot);
187 }
188 for (const candidate of paths) {
189 if (checkedPaths.has(candidate)) continue;
190 checkedPaths.add(candidate);
191 const otherCwd = yield* fileSystem.realPath(candidate).pipe(
192 Effect.catchIf(
193 (error) => error.reason._tag === "NotFound",
194 (_error) => Effect.succeed(null),
195 ),
196 );
197 if (otherCwd !== null && (contains(cwd, otherCwd) || contains(otherCwd, cwd))) {
198 shared = true;
199 break;
200 }
201 }
202 if (shared) break;
203 }
204 }
205 }
206 return !shared;
207 },
208 );