Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 CheckpointId,
5 CheckpointScopeId,
6 ProjectId,
7 ProviderInstanceId,
8 ProviderSessionId,
9 ProviderThreadId,
10 ThreadId,
11} from "@t3tools/contracts";
12import * as Effect from "effect/Effect";
13import * as FileSystem from "effect/FileSystem";
14import * as Layer from "effect/Layer";
15import * as Path from "effect/Path";
16import * as ServerConfig from "../config.ts";
17import * as ServerSettings from "../serverSettings.ts";
18import * as GitWorkflowService from "../git/GitWorkflowService.ts";
19import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
20import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts";
21import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
22import { CheckpointServiceV2 } from "./CheckpointService.ts";
23import { EventSinkV2 } from "./EventSink.ts";
24import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
25import { ProjectionStoreV2, type ProjectionCheckpointRollbackContext } from "./ProjectionStore.ts";
26import * as ProjectStore from "./ProjectStore.ts";
27import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
28import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
29import { layerNoTaskFolders } from "./ProviderTurnStartService.testkit.ts";
30
31it.effect.each([
32 "nested",
33 "ancestor",
34 "provider",
35 "sibling",
36 "shared-provider",
37 "conversation",
38] as const)("preserves overlapping workspace files, owner=%s", (owner) =>
39 Effect.gen(function* () {
40 const fs = yield* FileSystem.FileSystem;
41 const path = yield* Path.Path;
42 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-restore-" });
43 const cwd = path.join(parent, "worktree");
44 const nested = path.join(cwd, "nested");
45 const sibling = path.join(parent, "worktree2");
46 yield* fs.makeDirectory(nested, { recursive: true });
47 yield* fs.makeDirectory(sibling);
48 const otherFile = path.join(nested, "other-thread.txt");
49 yield* fs.writeFileString(otherFile, "other thread's uncommitted work");
50 const threadId = ThreadId.make("restore-current");
51 const otherId = ThreadId.make("restore-other");
52 const projectId = ProjectId.make("restore-project");
53 const providerThreadId = ProviderThreadId.make("restore-provider");
54 const providerSessionId = ProviderSessionId.make("restore-session");
55 const instanceId = ProviderInstanceId.make("restore-instance");
56 const checkpointId = CheckpointId.make("restore-checkpoint");
57 const scopeId = CheckpointScopeId.make("restore-scope");
58 const calls: string[] = [];
59 const providerThread = {
60 id: providerThreadId,
61 providerSessionId,
62 providerInstanceId: instanceId,
63 };
64 const otherThread = {
65 id: otherId,
66 projectId,
67 deletedAt: null,
68 lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: otherId },
69 worktreePath:
70 owner === "ancestor" || owner === "conversation"
71 ? parent
72 : owner === "nested"
73 ? nested
74 : sibling,
75 };
76 const projection = {
77 thread: {
78 id: threadId,
79 projectId,
80 worktreePath: cwd,
81 activeProviderThreadId: providerThreadId,
82 modelSelection: { instanceId, model: "test" },
83 },
84 providerThread,
85 providerSession: undefined,
86 providerTurns: [],
87 rootNodes: [],
88 targetAttempt: undefined,
89 rolledBackAttemptIds: [],
90 staleCheckpoints: [],
91 checkpoint: { id: checkpointId, scopeId, status: "ready", appRunOrdinal: null },
92 scope: { id: scopeId, cwd },
93 runsToRollback: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
94 } as unknown as ProjectionCheckpointRollbackContext;
95 const layerTest = CheckpointRollbackService.layer.pipe(
96 Layer.provide(
97 Layer.mergeAll(
98 NodeServices.layer,
99 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
100 ServerSettings.layerTest(),
101 ThreadCommandExecutor.layer,
102 IdAllocator.layer,
103 layerNoTaskFolders,
104 Layer.mock(GitWorkflowService.GitWorkflowService)({}),
105 Layer.mock(ProjectStore.ProjectStoreV2)({
106 get: () => Effect.succeedSome({ workspaceRoot: parent } as never),
107 }),
108 Layer.mock(ProjectionStoreV2)({
109 getThread: () => Effect.succeed(projection.thread),
110 getCheckpointRollbackContext: () => Effect.succeed(projection),
111 getShellSnapshot: () =>
112 Effect.succeed({
113 schemaVersion: 1,
114 snapshotSequence: 0,
115 threads: [otherThread] as never,
116 archivedThreads: [],
117 }),
118 getCheckpointContext: () =>
119 Effect.succeed({
120 runs: [],
121 checkpoints: [],
122 checkpointScopes: [],
123 }),
124 getThreadProviderContext: () =>
125 Effect.succeed({
126 thread: otherThread as never,
127 providerThreads: [],
128 providerSessions:
129 owner === "provider" || owner === "shared-provider"
130 ? ([
131 {
132 cwd: owner === "shared-provider" ? cwd : nested,
133 status: "running",
134 capabilities: {
135 sessions: {
136 supportsMultipleProviderThreadsPerSession:
137 owner === "shared-provider",
138 },
139 },
140 },
141 ] as never)
142 : [],
143 }),
144 }),
145 Layer.mock(CheckpointServiceV2)({
146 discardRepositorySnapshots: () => Effect.void,
147 restore: () =>
148 Effect.gen(function* () {
149 calls.push("files");
150 yield* fs.remove(otherFile).pipe(Effect.orDie);
151 }),
152 }),
153 Layer.mock(EventSinkV2)({ write: () => Effect.succeed([]) }),
154 Layer.mock(ProviderSessionManagerV2)({
155 open: () =>
156 Effect.succeed({
157 rollbackThread: () =>
158 Effect.sync(() => {
159 calls.push("provider");
160 return { providerThread };
161 }),
162 } as never),
163 }),
164 Layer.mock(RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
165 ),
166 ),
167 );
168 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2.pipe(
169 Effect.provide(layerTest),
170 );
171 const restoreFiles = owner !== "conversation";
172 const rejected = !["sibling", "shared-provider", "conversation"].includes(owner);
173 if (rejected) {
174 const error = yield* service
175 .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
176 .pipe(Effect.flip);
177 assert.equal(error.reason, "shared-workspace");
178 assert.deepEqual(calls, []);
179 assert.equal(yield* fs.readFileString(otherFile), "other thread's uncommitted work");
180 } else {
181 yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles });
182 assert.deepEqual(calls, restoreFiles ? ["provider", "files"] : ["provider"]);
183 assert.equal(yield* fs.exists(otherFile), !restoreFiles);
184 }
185 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
186);
187
188it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
189 Effect.gen(function* () {
190 const fileSystem = yield* FileSystem.FileSystem;
191 const path = yield* Path.Path;
192 const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-v2-restore-removed-" });
193 const worktreePath = path.join(parent, "worktree");
194 const isolated = yield* isCheckpointRestoreIsolated(
195 { id: ThreadId.make("restore-removed"), worktreePath },
196 { cwd: worktreePath },
197 null,
198 {
199 fileSystem,
200 path,
201 projections: {
202 getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }),
203 } as never,
204 projects: {} as never,
205 },
206 );
207 assert.isTrue(isolated);
208 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
209);
210
211it.effect("counts a task folder's repository worktrees as part of what a restore changes", () =>
212 Effect.gen(function* () {
213 const fileSystem = yield* FileSystem.FileSystem;
214 const path = yield* Path.Path;
215 const parent = yield* fileSystem.realPath(
216 yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-v2-restore-task-folder-" }),
217 );
218 // The worktrees directory is reached through a symlink; the other thread holds the real path.
219 const real = path.join(parent, "real", "task");
220 const named = path.join(parent, "linked", "task");
221 yield* fileSystem.makeDirectory(path.join(real, "shop"), { recursive: true });
222 yield* fileSystem.makeDirectory(path.join(real, "web"));
223 yield* fileSystem.symlink(path.join(parent, "real"), path.join(parent, "linked"));
224 const worktreePath = path.join(named, "shop");
225 const other = {
226 id: ThreadId.make("restore-task-folder-other"),
227 projectId: ProjectId.make("restore-project"),
228 deletedAt: null,
229 worktreePath: path.join(real, "web"),
230 activeRunId: null,
231 lineage: {},
232 };
233 const isolated = (repositories: ReadonlyArray<string>) =>
234 isCheckpointRestoreIsolated(
235 { id: ThreadId.make("restore-task-folder"), worktreePath },
236 { cwd: path.join(real, "shop") },
237 {
238 repositories: repositories.map((folder) => ({
239 repositoryPath: "/tracked/web",
240 worktreePath: folder,
241 name: "web",
242 })),
243 },
244 {
245 fileSystem,
246 path,
247 projections: {
248 getShellSnapshot: () => Effect.succeed({ threads: [other], archivedThreads: [] }),
249 getCheckpointContext: () => Effect.succeed({ checkpointScopes: [] }),
250 getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),
251 } as never,
252 projects: {} as never,
253 },
254 );
255
256 assert.isTrue(yield* isolated([]));
257 assert.isFalse(yield* isolated([path.join(named, "web")]));
258 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
259);
260
261it.effect.each([
262 { sideChat: "answering questions", running: false, toolItems: 0, isolated: true },
263 { sideChat: "running", running: true, toolItems: 0, isolated: false },
264 { sideChat: "after running tools", running: false, toolItems: 1, isolated: false },
265] as const)(
266 "a side chat $sideChat shares the parent's worktree: $isolated",
267 ({ running, toolItems, isolated }) =>
268 Effect.gen(function* () {
269 const fileSystem = yield* FileSystem.FileSystem;
270 const path = yield* Path.Path;
271 const worktreePath = yield* fileSystem.makeTempDirectoryScoped({
272 prefix: "t3-v2-restore-side-chat-",
273 });
274 const parentId = ThreadId.make("restore-side-chat-parent");
275 const sideChat = {
276 id: ThreadId.make("restore-side-chat"),
277 projectId: ProjectId.make("restore-project"),
278 deletedAt: null,
279 worktreePath,
280 activeRunId: running ? "side-chat-run" : null,
281 lineage: {
282 parentThreadId: parentId,
283 relationshipToParent: "fork",
284 rootThreadId: parentId,
285 sideChat: true,
286 },
287 };
288 const result = yield* isCheckpointRestoreIsolated(
289 { id: parentId, worktreePath },
290 { cwd: worktreePath },
291 null,
292 {
293 fileSystem,
294 path,
295 projections: {
296 getShellSnapshot: () => Effect.succeed({ threads: [sideChat], archivedThreads: [] }),
297 getThreadRecords: () =>
298 Effect.succeed({
299 turnItems: Array.from({ length: toolItems }, () => ({ type: "command_execution" })),
300 }),
301 getCheckpointContext: () => Effect.succeed({ checkpointScopes: [] }),
302 getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),
303 } as never,
304 projects: {} as never,
305 },
306 );
307 assert.equal(result, isolated);
308 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
309);
310
311it.effect.each([
312 { name: "completed child", isolated: true },
313 { name: "completed native child", isolated: true },
314 { name: "native child with running tool", isolated: false },
315 { name: "native child with provider background task", isolated: false },
316 { name: "native child with parent background task", isolated: false },
317 { name: "native child with another provider parent task", isolated: true },
318 { name: "native child grandchild with root background task", isolated: false },
319 { name: "missing task record", isolated: false },
320 { name: "task belongs to another child", isolated: false },
321 { name: "completed child with pending task", isolated: false },
322 { name: "grandchild through fork", isolated: false },
323 { name: "completed grandchild", isolated: true },
324 { name: "unrelated child", isolated: false },
325 { name: "running child", isolated: false },
326 { name: "held queue", isolated: false },
327 { name: "failed child", isolated: false },
328 { name: "cyclic ancestry", isolated: false },
329] as const)("parent file restore with $name: $isolated", ({ name, isolated }) =>
330 Effect.gen(function* () {
331 const fileSystem = yield* FileSystem.FileSystem;
332 const path = yield* Path.Path;
333 const worktreePath = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-restore-child-" });
334 const parentId = ThreadId.make("restore-parent");
335 const childId = ThreadId.make("restore-child");
336 const ancestorId = ThreadId.make("restore-ancestor");
337 const child = {
338 id: childId,
339 projectId: ProjectId.make("restore-project"),
340 deletedAt: null,
341 worktreePath,
342 activeRunId: name === "running child" ? "child-run" : null,
343 activityRunStatus: null,
344 latestRunId: name.includes("native child") ? null : "child-run",
345 creationSource: name.includes("native child") ? "provider" : "user",
346 forkedFrom: { type: "node", nodeId: "child-task" },
347 status: name.includes("native child")
348 ? "idle"
349 : name === "running child"
350 ? "running"
351 : name === "failed child"
352 ? "failed"
353 : "completed",
354 pendingRuntimeRequest: null,
355 pendingBackgroundTasks: [],
356 lineage: {
357 parentThreadId:
358 name === "completed grandchild" ||
359 name === "native child grandchild with root background task" ||
360 name === "grandchild through fork" ||
361 name === "cyclic ancestry"
362 ? ancestorId
363 : name === "unrelated child"
364 ? ThreadId.make("another-parent")
365 : parentId,
366 relationshipToParent: "subagent",
367 rootThreadId: parentId,
368 },
369 };
370 const ancestor = {
371 ...child,
372 id: ancestorId,
373 forkedFrom: { type: "node", nodeId: "ancestor-task" },
374 lineage: {
375 ...child.lineage,
376 relationshipToParent: name === "grandchild through fork" ? "fork" : "subagent",
377 parentThreadId: name === "cyclic ancestry" ? childId : parentId,
378 },
379 };
380 const children =
381 name === "completed grandchild" ||
382 name === "native child grandchild with root background task" ||
383 name === "grandchild through fork" ||
384 name === "cyclic ancestry"
385 ? [child, ancestor]
386 : [child];
387 const projections = {
388 getShellSnapshot: () =>
389 Effect.succeed({
390 threads: children,
391 archivedThreads: [],
392 }),
393 getCheckpointContext: () =>
394 Effect.succeed({
395 checkpointScopes: [],
396 runs: name === "held queue" ? [{ status: "queued" }] : [],
397 }),
398 getThreadProviderContext: () => Effect.succeed({ providerSessions: [] }),
399 getThreadRecords: (
400 _threadId: unknown,
401 _fields: readonly string[],
402 filter: { subagentIds?: string[]; turnItemStatuses?: string[] } = {},
403 ) =>
404 Effect.succeed({
405 providerThreads:
406 _threadId === parentId &&
407 (name.includes("parent") ||
408 name === "native child grandchild with root background task") &&
409 name.includes("native child")
410 ? [
411 {
412 providerInstanceId:
413 name === "native child with another provider parent task"
414 ? "other-provider"
415 : "claude",
416 status: "idle",
417 pendingBackgroundTasks: [{ taskId: "background", kind: "command" }],
418 },
419 ]
420 : name === "native child with provider background task"
421 ? [{ status: "idle", pendingBackgroundTasks: [{ taskId: "background" }] }]
422 : [],
423 turnItems:
424 filter.turnItemStatuses !== undefined && name === "native child with running tool"
425 ? [{ type: "command_execution", status: "running" }]
426 : [],
427 subagents:
428 name === "missing task record"
429 ? []
430 : [
431 {
432 id: filter.subagentIds?.[0],
433 providerInstanceId: "claude",
434 nativeTaskRef: { nativeId: "native-task" },
435 childThreadId:
436 name === "task belongs to another child"
437 ? "another-child"
438 : filter.subagentIds?.[0] === "ancestor-task"
439 ? ancestorId
440 : childId,
441 origin: name.includes("native child") ? "provider_native" : "app_owned",
442 status: name === "completed child with pending task" ? "running" : "completed",
443 },
444 ],
445 }),
446 };
447 const result = yield* isCheckpointRestoreIsolated(
448 { id: parentId, worktreePath },
449 { cwd: worktreePath },
450 null,
451 { fileSystem, path, projections: projections as never, projects: {} as never },
452 );
453 assert.equal(result, isolated);
454 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
455);