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