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

HandoffImport.ts

132 lines4.9 KB

1import { OrchestratorMcpFailure } from "@t3tools/contracts";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5import * as Layer from "effect/Layer";
6import * as Path from "effect/Path";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8​
9import { deletePendingAttachment } from "../../assets/AttachmentUpload.ts";
10import {
11 parseThreadSegmentFromAttachmentId,
12 resolveAttachmentPathById,
13} from "../../attachmentStore.ts";
14import * as ServerConfig from "../../config.ts";
15import type * as ThreadImportService from "../../orchestration-v2/ThreadImportService.ts";
16import * as ServerSettings from "../../serverSettings.ts";
17import { resolveWorktreesDirectory } from "../../worktreesDirectory.ts";
18import * as HandoffGit from "./HandoffGit.ts";
19​
20/**
21 * The checkout a handed-off thread works in here: its bundle, uploaded as a
22 * pending attachment, applied in a new worktree of the project. The upload is
23 * spent either way; the worktree and branch are undone if the import fails.
24 */
25export class HandoffImport extends Context.Service<
26 HandoffImport,
27 {
28 readonly applyBundle: (input: {
29 readonly repoRoot: string;
30 readonly handoffId: string;
31 readonly bundle: {
32 readonly attachmentId: string;
33 readonly branch: string | null;
34 readonly tip: string;
35 readonly snapshot: string;
36 };
37 }) => Effect.Effect<ThreadImportService.ImportedWorkspace, OrchestratorMcpFailure>;
38 }
39>()("t3/peer/handoff/HandoffImport") {}
40​
41const make = Effect.gen(function* () {
42 const config = yield* ServerConfig.ServerConfig;
43 const settings = yield* ServerSettings.ServerSettingsService;
44 const path = yield* Path.Path;
45 const fileSystem = yield* FileSystem.FileSystem;
46 const git = yield* HandoffGit.HandoffGit;
47​
48 const applyBundle: HandoffImport["Service"]["applyBundle"] = Effect.fn(
49 "HandoffImport.applyBundle",
50 )(function* (input) {
51 if (parseThreadSegmentFromAttachmentId(input.bundle.attachmentId) !== "pending") {
52 return yield* new OrchestratorMcpFailure({
53 code: "invalid_request",
54 message: "The bundle must be a pending upload from t3_attachment_prepare_upload.",
55 });
56 }
57 const bundlePath = resolveAttachmentPathById({
58 attachmentsDir: config.attachmentsDir,
59 attachmentId: input.bundle.attachmentId,
60 });
61 if (bundlePath === null) {
62 return yield* new OrchestratorMcpFailure({
63 code: "invalid_request",
64 message: "The bundle upload was not found. Upload it again.",
65 });
66 }
67 const worktreesSetting = yield* settings.getSettings.pipe(
68 Effect.map((current) => current.worktreesDirectory),
69 Effect.orElseSucceed(() => ""),
70 );
71 const parent = resolveWorktreesDirectory(
72 worktreesSetting,
73 config.worktreesDir,
74 path,
75 yield* HostProcess.HomeDirectory,
76 );
77 if (parent === null) {
78 return yield* new OrchestratorMcpFailure({
79 code: "invalid_request",
80 message:
81 "This environment's worktree location is not usable. Fix it in Settings → Storage.",
82 });
83 }
84 // Thread worktree paths are stored trimmed, so the folder must not end in whitespace the branch
85 // keeps. A branch like "\u00a0.\u00a0" trims to ".", which would name the parent itself.
86 const trimmed = (input.bundle.branch ?? "").replace(/\//g, "-").trim();
87 const name = trimmed === "" || trimmed === "." ? `handoff-${input.handoffId}` : trimmed;
88 const preferred = path.join(parent, path.basename(input.repoRoot), name);
89 // An earlier move of the same branch may still have its checkout there.
90 const worktreePath = (yield* fileSystem
91 .exists(preferred)
92 .pipe(Effect.orElseSucceed(() => true)))
93 ? `${preferred}-${input.handoffId.slice(0, 8)}`
94 : preferred;
95 const applied = yield* git
96 .apply({
97 repoRoot: input.repoRoot,
98 worktreePath,
99 handoffId: input.handoffId,
100 bundlePath,
101 branch: input.bundle.branch,
102 tip: input.bundle.tip,
103 snapshot: input.bundle.snapshot,
104 })
105 .pipe(
106 Effect.mapError(
107 (error) =>
108 new OrchestratorMcpFailure({
109 // Git setup failures occur before the imported thread is written.
110 code: "invalid_request",
111 message: error.message,
112 }),
113 ),
114 Effect.ensuring(
115 deletePendingAttachment(input.bundle.attachmentId).pipe(
116 Effect.provideService(ServerConfig.ServerConfig, config),
117 Effect.provideService(FileSystem.FileSystem, fileSystem),
118 Effect.ignore,
119 ),
120 ),
121 );
122 return {
123 worktreePath,
124 branch: applied.branch,
125 undo: applied.undo,
126 } satisfies ThreadImportService.ImportedWorkspace;
127 });
128​
129 return HandoffImport.of({ applyBundle });
130});
131​
132export const layer = Layer.effect(HandoffImport, make);