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 type OrchestrationV2ThreadProjection,
7 ProjectId,
8 ProviderInstanceId,
9 ProviderSessionId,
10 ProviderThreadId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
19import * as ServerConfig from "../config.ts";
20import * as ServerSettings from "../serverSettings.ts";
21import * as GitWorkflowService from "../git/GitWorkflowService.ts";
22import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
23import { isCheckpointRestoreIsolated } from "./CheckpointRestoreSafety.ts";
24import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
25import { CheckpointServiceV2 } from "./CheckpointService.ts";
26import { EventSinkV2 } from "./EventSink.ts";
27import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
28import { ProjectionStoreV2 } from "./ProjectionStore.ts";
29import * as ProjectStore from "./ProjectStore.ts";
30import { ProviderSessionManagerV2 } from "./ProviderSessionManager.ts";
31import { RuntimePolicyV2 } from "./RuntimePolicy.ts";
32
33it.effect.each([
34 "nested",
35 "ancestor",
36 "archived-nested",
37 ...(symlinksSupported ? (["aliased-nested"] as const) : []),
38 "project",
39 "provider",
40 "scope",
41 "sibling",
42 "stopped-provider",
43 "errored-provider",
44 "shared-provider",
45 "conversation",
46] as const)("preserves overlapping workspace files, owner=%s", (owner) =>
47 Effect.gen(function* () {
48 const fs = yield* FileSystem.FileSystem;
49 const path = yield* Path.Path;
50 const parent = yield* fs.makeTempDirectoryScoped({ prefix: "t3-v2-restore-" });
51 const cwd = path.join(parent, "worktree");
52 const nested = path.join(cwd, "nested");
53 const sibling = path.join(parent, "worktree2");
54 yield* fs.makeDirectory(nested, { recursive: true });
55 yield* fs.makeDirectory(sibling);
56 const otherFile = path.join(nested, "other-thread.txt");
57 yield* fs.writeFileString(otherFile, "other thread's uncommitted work");
58 const alias = path.join(parent, "alias");
59 if (owner === "aliased-nested") yield* fs.symlink(nested, alias);
60 const threadId = ThreadId.make("restore-current");
61 const otherId = ThreadId.make("restore-other");
62 const projectId = ProjectId.make("restore-project");
63 const providerThreadId = ProviderThreadId.make("restore-provider");
64 const providerSessionId = ProviderSessionId.make("restore-session");
65 const instanceId = ProviderInstanceId.make("restore-instance");
66 const checkpointId = CheckpointId.make("restore-checkpoint");
67 const scopeId = CheckpointScopeId.make("restore-scope");
68 const calls: string[] = [];
69 const providerThread = {
70 id: providerThreadId,
71 providerSessionId,
72 providerInstanceId: instanceId,
73 };
74 const otherThread = {
75 id: otherId,
76 projectId,
77 deletedAt: null,
78 worktreePath:
79 owner === "project"
80 ? null
81 : owner === "ancestor" || owner === "conversation"
82 ? parent
83 : owner === "nested" || owner === "archived-nested"
84 ? nested
85 : owner === "aliased-nested"
86 ? alias
87 : sibling,
88 };
89 const projection = {
90 thread: {
91 id: threadId,
92 projectId,
93 worktreePath: cwd,
94 activeProviderThreadId: providerThreadId,
95 modelSelection: { instanceId, model: "test" },
96 },
97 providerThreads: [providerThread],
98 providerSessions: [],
99 providerTurns: [],
100 nodes: [],
101 attempts: [],
102 checkpoints: [{ id: checkpointId, scopeId, status: "ready", appRunOrdinal: null }],
103 checkpointScopes: [{ id: scopeId, cwd }],
104 runs: [{ id: "later-run", ordinal: 1, status: "completed", rootNodeId: null }],
105 } as unknown as OrchestrationV2ThreadProjection;
106 const layerTest = CheckpointRollbackService.layer.pipe(
107 Layer.provide(
108 Layer.mergeAll(
109 NodeServices.layer,
110 Layer.mock(ServerConfig.ServerConfig)({ worktreesDir: "/synthetic-worktrees" } as never),
111 ServerSettings.layerTest(),
112 ThreadCommandExecutor.layer,
113 IdAllocator.layer,
114 Layer.mock(GitWorkflowService.GitWorkflowService)({}),
115 Layer.mock(ProjectStore.ProjectStoreV2)({
116 get: () => Effect.succeed(Option.some({ workspaceRoot: parent } as never)),
117 }),
118 Layer.mock(ProjectionStoreV2)({
119 getThreadRecords: () => Effect.succeed(projection),
120 getShellSnapshot: () =>
121 Effect.succeed({
122 schemaVersion: 1,
123 snapshotSequence: 0,
124 threads: owner === "archived-nested" ? [] : ([otherThread] as never),
125 archivedThreads: owner === "archived-nested" ? ([otherThread] as never) : [],
126 }),
127 getCheckpointContext: () =>
128 Effect.succeed({
129 runs: [],
130 checkpoints: [],
131 checkpointScopes: owner === "scope" ? ([{ cwd: nested }] as never) : [],
132 }),
133 getThreadProviderContext: () =>
134 Effect.succeed({
135 thread: otherThread as never,
136 providerThreads: [],
137 providerSessions: [
138 "provider",
139 "stopped-provider",
140 "errored-provider",
141 "shared-provider",
142 ].includes(owner)
143 ? ([
144 {
145 cwd: owner === "shared-provider" ? cwd : nested,
146 status:
147 owner === "provider" || owner === "shared-provider"
148 ? "running"
149 : owner === "errored-provider"
150 ? "error"
151 : "stopped",
152 capabilities: {
153 sessions: {
154 supportsMultipleProviderThreadsPerSession: owner === "shared-provider",
155 },
156 },
157 },
158 ] as never)
159 : [],
160 }),
161 }),
162 Layer.mock(CheckpointServiceV2)({
163 restore: () =>
164 Effect.gen(function* () {
165 calls.push("files");
166 yield* fs.remove(otherFile).pipe(Effect.orDie);
167 }),
168 }),
169 Layer.mock(EventSinkV2)({ write: () => Effect.succeed([]) }),
170 Layer.mock(ProviderSessionManagerV2)({
171 open: () =>
172 Effect.succeed({
173 rollbackThread: () =>
174 Effect.sync(() => {
175 calls.push("provider");
176 return { providerThread };
177 }),
178 } as never),
179 }),
180 Layer.mock(RuntimePolicyV2)({ resolve: () => Effect.succeed({} as never) }),
181 ),
182 ),
183 );
184 const service = yield* CheckpointRollbackService.CheckpointRollbackServiceV2.pipe(
185 Effect.provide(layerTest),
186 );
187 const restoreFiles = owner !== "conversation";
188 const rejected = !["sibling", "stopped-provider", "shared-provider", "conversation"].includes(
189 owner,
190 );
191 if (rejected) {
192 const error = yield* service
193 .execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles })
194 .pipe(Effect.flip);
195 assert.equal(error.reason, "shared-workspace");
196 assert.deepEqual(calls, []);
197 assert.equal(yield* fs.readFileString(otherFile), "other thread's uncommitted work");
198 } else {
199 yield* service.execute({ threadId, providerThreadId, checkpointId, scopeId, restoreFiles });
200 assert.deepEqual(calls, restoreFiles ? ["provider", "files"] : ["provider"]);
201 assert.equal(yield* fs.exists(otherFile), !restoreFiles);
202 }
203 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
204);
205
206it.effect("lets rollback recreate a worktree storage cleanup removed", () =>
207 Effect.gen(function* () {
208 const fileSystem = yield* FileSystem.FileSystem;
209 const path = yield* Path.Path;
210 const parent = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-v2-restore-removed-" });
211 const worktreePath = path.join(parent, "worktree");
212 const isolated = yield* isCheckpointRestoreIsolated(
213 { id: ThreadId.make("restore-removed"), worktreePath },
214 { cwd: worktreePath },
215 {
216 fileSystem,
217 path,
218 projections: {
219 getShellSnapshot: () => Effect.succeed({ threads: [], archivedThreads: [] }),
220 } as never,
221 projects: {} as never,
222 },
223 );
224 assert.isTrue(isolated);
225 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
226);