Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CheckpointRestoreSafety.ts

88 lines4.1 KB

1import type { OrchestrationV2AppThread, OrchestrationV2CheckpointScope } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import type * as FileSystem from "effect/FileSystem";
4import * as Option from "effect/Option";
5import type * as Path from "effect/Path";
6import type { ProjectionStoreV2 } from "./ProjectionStore.ts";
7import type * as ProjectStore from "./ProjectStore.ts";
8​
9export const SHARED_WORKSPACE_RESTORE_MESSAGE =
10 "File restore requires an isolated worktree. This workspace may contain changes from another thread. Rewind the conversation without restoring files instead.";
11​
12// A checkpoint snapshots the whole checkout. Check at command admission and
13// again before provider rollback so a newly shared worktree is rejected too.
14export const isCheckpointRestoreIsolated = Effect.fn("orchestrationV2.isCheckpointRestoreIsolated")(
15 function* (
16 thread: Pick<OrchestrationV2AppThread, "id" | "worktreePath">,
17 scope: Pick<OrchestrationV2CheckpointScope, "cwd">,
18 dependencies: {
19 readonly fileSystem: FileSystem.FileSystem;
20 readonly projections: ProjectionStoreV2["Service"];
21 readonly projects: ProjectStore.ProjectStoreV2["Service"];
22 readonly path: Path.Path;
23 },
24 ) {
25 const { fileSystem, projections, projects, path } = dependencies;
26 const contains = (parent: string, child: string) => {
27 const relative = path.relative(parent, child);
28 return (
29 relative === "" ||
30 (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`))
31 );
32 };
33 const worktreePath = thread.worktreePath;
34 let shared = worktreePath == null;
35 if (!shared && worktreePath !== null) {
36 const cwd = yield* fileSystem.realPath(scope.cwd);
37 const worktreeCwd = yield* fileSystem.realPath(worktreePath);
38 shared = cwd !== worktreeCwd;
39 if (!shared) {
40 const shell = yield* projections.getShellSnapshot();
41 const checkedPaths = new Set<string>();
42 for (const otherThread of [...shell.threads, ...shell.archivedThreads]) {
43 if (otherThread.id === thread.id || otherThread.deletedAt !== null) continue;
44 const other = yield* projections.getCheckpointContext(otherThread.id);
45 const providerContext = yield* projections.getThreadProviderContext(otherThread.id);
46 const paths = [
47 otherThread.worktreePath,
48 ...other.checkpointScopes.map((candidate) => candidate.cwd),
49 // A failed turn can leave an errored session with a live event stream.
50 // A session shared across threads keeps the cwd it was opened with,
51 // often another thread's; each turn runs in the thread's own
52 // worktree or project root, which this list already covers.
53 ...providerContext.providerSessions
54 .filter(
55 (session) =>
56 session.status !== "stopped" &&
57 !session.capabilities.sessions.supportsMultipleProviderThreadsPerSession,
58 )
59 .map((session) => session.cwd),
60 ].filter((value): value is string => value !== null);
61 if (otherThread.worktreePath === null) {
62 // A thread without a worktree works in its project's checkout.
63 const project = yield* projects.get(otherThread.projectId, { includeDeleted: true });
64 if (Option.isNone(project)) return false;
65 paths.push(project.value.workspaceRoot);
66 }
67 for (const candidate of paths) {
68 if (checkedPaths.has(candidate)) continue;
69 checkedPaths.add(candidate);
70 const otherCwd = yield* fileSystem
71 .realPath(candidate)
72 .pipe(
73 Effect.catch((error) =>
74 error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error),
75 ),
76 );
77 if (otherCwd !== null && (contains(cwd, otherCwd) || contains(otherCwd, cwd))) {
78 shared = true;
79 break;
80 }
81 }
82 if (shared) break;
83 }
84 }
85 }
86 return !shared;
87 },
88);