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

ThreadWorkspaceService.ts

398 lines15.8 KB

1import {
2 CommandId,
3 type OrchestrationV2ThreadShell,
4 ProjectId,
5 type ThreadId,
6 type ThreadWorkspaceDestination,
7} from "@t3tools/contracts";
8import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import * as KeyedLock from "@t3tools/shared/KeyedLock";
11import * as Context from "effect/Context";
12import * as SecureRandom from "effect/crypto/SecureRandom";
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 * as Schema from "effect/Schema";
19​
20import {
21 OrchestratorDispatchError,
22 threadHasUnfinishedWork,
23} from "../orchestration-v2/Orchestrator.ts";
24import { userFacingDispatchErrorMessage } from "../orchestration-v2/UserFacingErrors.ts";
25import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
26import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
27import * as ManagedProjectFolders from "./ManagedProjectFolders.ts";
28import * as ProjectService from "./ProjectService.ts";
29​
30export class ThreadWorkspaceError extends Schema.TaggedError<ThreadWorkspaceError>()(
31 "ThreadWorkspaceError",
32 {
33 reason: Schema.String,
34 cause: Schema.optional(Schema.Defect()),
35 },
36) {
37 override get message(): string {
38 return this.reason;
39 }
41​
42// Project refusals and the orchestrator's own string rejections are written for users;
43// wrapped lower-level failures are not.
44const isProjectInvalid = Schema.is(ProjectService.ProjectInvalidError);
45const isDispatchError = Schema.is(OrchestratorDispatchError);
46const workspaceFailure = (fallback: string) => (cause: unknown) =>
47 new ThreadWorkspaceError({
48 reason: isProjectInvalid(cause)
49 ? cause.detail
50 : isDispatchError(cause) && typeof cause.cause === "string"
51 ? (userFacingDispatchErrorMessage(cause.cause) ?? fallback)
52 : fallback,
53 cause,
54 });
55​
56export class ThreadWorkspaceService extends Context.Service<
57 ThreadWorkspaceService,
58 {
59 readonly moveWorkspace: (input: {
60 readonly threadId: ThreadId;
61 readonly target: ThreadWorkspaceDestination;
62 }) => Effect.Effect<
63 { readonly projectId: ProjectId; readonly cwd: string },
64 ThreadWorkspaceError
65 >;
66 /**
67 * Turns a No project thread's folder into a project, in place, and moves every
68 * thread working in that folder into it. Running it again finishes a partial move.
69 */
70 readonly promote: (input: {
71 readonly threadId: ThreadId;
72 }) => Effect.Effect<{ readonly projectId: ProjectId }, ThreadWorkspaceError>;
73 }
74>()("t3/project/ThreadWorkspaceService") {}
75​
76const make = Effect.gen(function* () {
77 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
78 const projects = yield* ProjectService.ProjectService;
79 const threads = yield* ThreadManagementService.ThreadManagementService;
80 const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
81 const random = yield* SecureRandom.SecureRandom;
82 const path = yield* Path.Path;
83 const fileSystem = yield* FileSystem.FileSystem;
84 const realPath = (folder: string) =>
85 fileSystem.realPath(folder).pipe(Effect.orElseSucceed(() => folder));
86​
87 const fail = (reason: string) => (cause: unknown) => new ThreadWorkspaceError({ reason, cause });
88​
89 const promote: ThreadWorkspaceService["Service"]["promote"] = Effect.fn(
90 "ThreadWorkspaceService.promote",
91 )(function* (input) {
92 const thread = yield* threads.getThreadShell(input.threadId).pipe(
93 Effect.mapError(fail("Could not read the thread.")),
94 Effect.filterOrFail(
95 (shell) => shell !== null,
96 () => new ThreadWorkspaceError({ reason: "Thread not found." }),
97 ),
98 );
99 const project = yield* projects
100 .getById(thread.projectId)
101 .pipe(Effect.mapError(fail("Could not read the thread's project.")));
102 const folder = thread.worktreePath ?? Option.getOrUndefined(project)?.workspaceRoot;
103 const scratchRoot = Option.getOrUndefined(yield* managedFolders.scratchRoot);
104 const isScratch = yield* managedFolders.isScratchProject(thread.projectId);
105 // A thread already rooted at its folder is a partial earlier promotion; finish it.
106 const alreadyPromoted =
107 Option.isSome(project) && project.value.workspaceRoot === folder && !isScratch;
108 if (
109 folder === undefined ||
110 scratchRoot === undefined ||
111 (yield* realPath(path.dirname(folder))) !== (yield* realPath(scratchRoot)) ||
112 !(isScratch || alreadyPromoted)
113 ) {
114 return yield* new ThreadWorkspaceError({
115 reason: "Only a No project thread with its own folder can become a project.",
116 });
117 }
118​
119 const snapshot = yield* Effect.flatten(
120 threads.readShellSnapshot({ worktreePath: folder }),
121 ).pipe(Effect.mapError(fail("Could not read the threads in this folder.")));
122 const moveSet = new Map<ThreadId, OrchestrationV2ThreadShell>();
123 if (isScratch) moveSet.set(thread.id, thread);
124 for (const candidate of [...snapshot.threads, ...snapshot.archivedThreads]) {
125 if (yield* managedFolders.isScratchProject(candidate.projectId)) {
126 moveSet.set(candidate.id, candidate);
127 }
128 }
129​
130 for (const candidate of moveSet.values()) {
131 const records = yield* threads
132 .getThreadRecords(candidate.id, ["runs", "runtimeRequests"], { turnItemTypes: [] })
133 .pipe(Effect.mapError(fail(`Could not read "${candidate.title}".`)));
134 if (threadHasUnfinishedWork(records)) {
135 return yield* new ThreadWorkspaceError({
136 reason: `"${candidate.title}" is still working. Finish or stop it first.`,
137 });
138 }
139 }
140​
141 return yield* Effect.uninterruptible(
142 Effect.gen(function* () {
143 const projectId = yield* createProject(thread.title, folder);
144 yield* scheduledTasks
145 .moveThreadTasks({ threadIds: [...moveSet.keys()], projectId })
146 .pipe(Effect.mapError(fail("Could not move the thread's scheduled tasks.")));
147 for (const candidate of moveSet.values()) {
148 const commandId = CommandId.make(`scratch-promotion:${yield* randomId}`);
149 yield* threads
150 .dispatch({
151 type: "thread.project.adopt-folder",
152 commandId,
153 threadId: candidate.id,
154 projectId,
155 })
156 .pipe(Effect.mapError(fail(`Could not move "${candidate.title}". Try again.`)));
157 }
158 return { projectId };
159 }),
160 );
161 });
162​
163 const randomId = random.uuidV4();
164​
165 // bootstrap returns the project that already owns the folder, so retries reuse it.
166 const createProject = Effect.fn("ThreadWorkspaceService.createProject")(function* (
167 title: string,
168 workspaceRoot: string,
169 ) {
170 const id = yield* randomId;
171 return yield* projects
172 .bootstrap({
173 commandId: CommandId.make(`scratch-promotion-project:${id}`),
174 projectId: ProjectId.make(id),
175 title,
176 workspaceRoot,
177 })
178 .pipe(
179 Effect.map(({ project }) => project.id),
180 // bootstrap reads before locking; racing creates return the winner in a conflict.
181 Effect.catchTags({
182 ProjectConflictError: (conflict) => Effect.succeed(conflict.conflictingProjectId),
183 }),
184 Effect.mapError(fail("Could not create the project.")),
185 );
186 });
187​
188 const moves = yield* KeyedLock.make<ThreadId>();
189 const moveWorkspace: ThreadWorkspaceService["Service"]["moveWorkspace"] = Effect.fn(
190 "ThreadWorkspaceService.moveWorkspace",
191 )(
192 function* ({ threadId, target }) {
193 const thread = yield* threads
194 .getThreadShell(threadId)
195 .pipe(Effect.mapError(fail("Could not read the thread.")));
196 if (thread === null || thread.deletedAt !== null || thread.archivedAt !== null) {
197 return yield* new ThreadWorkspaceError({ reason: "Thread is unavailable." });
198 }
199 if (
200 thread.lineage.relationshipToParent === "subagent" ||
201 thread.handoff?.state === "pending" ||
202 thread.handoff?.state === "departing" ||
203 thread.handoff?.state === "departed"
204 ) {
205 return yield* new ThreadWorkspaceError({
206 reason: "This thread cannot change workspace.",
207 });
208 }
209 const blocker = yield* threads
210 .getThreadRecords(threadId, ["runs", "runtimeRequests"], {
211 turnItemTypes: [],
212 })
213 .pipe(
214 Effect.flatMap(threads.getWorkspaceMoveBlocker),
215 Effect.mapError(fail("Could not read the thread's activity.")),
216 );
217 if (blocker !== null) {
218 return yield* new ThreadWorkspaceError({
219 reason:
220 blocker === "unfinished-work"
221 ? "Finish or stop the thread's current work before moving it."
222 : "This thread is still saving a checkpoint. Try again after it finishes.",
223 });
224 }
225 const projectId =
226 target.type === "scratch"
227 ? (yield* managedFolders.ensureScratchProject.pipe(
228 Effect.mapError(fail("Could not open No project.")),
229 )).projectId
230 : target.type === "project"
231 ? target.projectId
232 : thread.projectId;
233 const project = Option.getOrUndefined(
234 yield* projects
235 .getById(projectId)
236 .pipe(Effect.mapError(fail("Could not read the project."))),
237 );
238 if (project === undefined || project.archivedAt != null) {
239 return yield* new ThreadWorkspaceError({
240 reason: "The destination project is unavailable.",
241 });
242 }
243 const isScratch = yield* managedFolders.isScratchProject(projectId);
244 const directoryTarget =
245 target.type === "directory" || target.type === "project-directory"
246 ? {
247 type: target.type,
248 path: expandHomePath(target.path, yield* HostProcess.HomeDirectory),
249 }
250 : null;
251 if (directoryTarget !== null && !path.isAbsolute(directoryTarget.path)) {
252 return yield* new ThreadWorkspaceError({
253 reason: "Enter an absolute path on the thread's machine.",
254 });
255 }
256 if (directoryTarget?.type === "project-directory") {
257 if (isScratch || thread.worktreePath !== null) {
258 return yield* new ThreadWorkspaceError({
259 reason: "This thread does not use the project directory.",
260 });
261 }
262 // A capture can still read the project's tracked folders after its thread is archived.
263 const rooted = yield* threads.getShellSnapshot({ projectId }).pipe(
264 Effect.map(({ threads, archivedThreads }) =>
265 [...threads, ...archivedThreads].filter(
266 (candidate) =>
267 candidate.worktreePath === null &&
268 candidate.lineage.relationshipToParent !== "subagent",
269 ),
270 ),
271 Effect.mapError(fail("Could not read the project's threads.")),
272 );
273 for (const candidate of rooted) {
274 if (candidate.id === threadId) continue;
275 const candidateBlocker = yield* (
276 candidate.archivedAt === null
277 ? threads
278 .getThreadRecords(candidate.id, ["runs", "runtimeRequests"], {
279 turnItemTypes: [],
280 })
281 .pipe(Effect.flatMap(threads.getWorkspaceMoveBlocker))
282 : threads
283 .hasUnsettledCheckpointCapture(candidate.id)
284 .pipe(Effect.map((pending) => (pending ? "checkpoint-capture" : null)))
285 ).pipe(Effect.mapError(fail(`Could not read "${candidate.title}".`)));
286 if (candidateBlocker !== null) {
287 return yield* new ThreadWorkspaceError({
288 reason:
289 candidateBlocker === "unfinished-work"
290 ? `"${candidate.title}" is still working in this project. Finish or stop it first.`
291 : `"${candidate.title}" is still saving a checkpoint. Try again after it finishes.`,
292 });
293 }
294 }
295 const repaired = yield* projects
296 .update({
297 commandId: CommandId.make(`repair-project-directory:${yield* randomId}`),
298 projectId,
299 workspaceRoot: directoryTarget.path,
300 expectedMissingWorkspaceRoot: project.workspaceRoot,
301 })
302 .pipe(Effect.mapError(workspaceFailure("Could not change the project folder.")));
303 for (const candidate of rooted) {
304 if (candidate.archivedAt !== null) continue;
305 yield* threads
306 .dispatch({
307 type: "thread.workspace.move",
308 commandId: CommandId.make(`repair-project-directory-session:${yield* randomId}`),
309 threadId: candidate.id,
310 projectId,
311 worktreePath: null,
312 expectedProjectId: projectId,
313 expectedWorktreePath: null,
314 })
315 .pipe(
316 Effect.catch((cause) =>
317 Effect.logWarning("thread-workspace.repair-session-detach-failed", {
318 threadId: candidate.id,
319 cause,
320 }),
321 ),
322 );
323 }
324 return { projectId, cwd: repaired.workspaceRoot };
325 }
326 const worktreePath = yield* Effect.gen(function* () {
327 if (directoryTarget?.type === "directory") {
328 return yield* fileSystem
329 .realPath(directoryTarget.path)
330 .pipe(
331 Effect.mapError(
332 fail(`The destination directory is unavailable: ${directoryTarget.path}`),
333 ),
334 );
335 }
336 if (!isScratch) return null;
337 if (thread.projectId === projectId && thread.worktreePath !== null) {
338 const worktreePath = thread.worktreePath;
339 const exists = yield* fileSystem.stat(worktreePath).pipe(
340 Effect.map((stat) => stat.type === "Directory"),
341 Effect.catch((error) =>
342 error.reason._tag === "NotFound"
343 ? Effect.succeed(false)
344 : Effect.fail(
345 new ThreadWorkspaceError({
346 reason: `Could not check the thread's folder: ${worktreePath}`,
347 cause: error,
348 }),
349 ),
350 ),
351 );
352 if (exists) return worktreePath;
353 }
354 return yield* managedFolders
355 .folderForThread({ threadId, projectId, text: thread.title })
356 .pipe(
357 Effect.map(Option.getOrNull),
358 Effect.filterOrFail(
359 (folder) => folder !== null,
360 () => new ThreadWorkspaceError({ reason: "Could not create a No project folder." }),
361 ),
362 Effect.mapError(fail("Could not create a No project folder.")),
363 );
364 });
365 const commandId = CommandId.make(`thread-workspace-move:${yield* randomId}`);
366 yield* Effect.uninterruptible(
367 Effect.gen(function* () {
368 yield* threads
369 .dispatch({
370 type: "thread.workspace.move",
371 commandId,
372 threadId,
373 projectId,
374 worktreePath,
375 expectedProjectId: thread.projectId,
376 expectedWorktreePath: thread.worktreePath,
377 })
378 .pipe(Effect.mapError(workspaceFailure("Could not change the thread's workspace.")));
379 yield* scheduledTasks
380 .moveThreadTasks({ threadIds: [threadId], projectId })
381 .pipe(
382 Effect.mapError(
383 fail(
384 "The thread moved, but its scheduled tasks could not be updated. Retry the move.",
385 ),
386 ),
387 );
388 }),
389 );
390 return { projectId, cwd: worktreePath ?? project.workspaceRoot };
391 },
392 (effect, input) => moves.withLock(input.threadId, effect),
393 );
394​
395 return ThreadWorkspaceService.of({ promote, moveWorkspace });
396});
397​
398export const layer = Layer.effect(ThreadWorkspaceService, make);