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

ManagedProjectFolders.ts

484 lines16.9 KB

1import {
2 CommandId,
3 type GitManagerServiceError,
4 ProjectId,
5 type ThreadId,
6 VcsProcessSpawnError,
7} from "@t3tools/contracts";
8import { newProjectFolderName } from "@t3tools/shared/path";
9import * as Cause from "effect/Cause";
10import * as Context from "effect/Context";
11import * as SecureRandom from "effect/crypto/SecureRandom";
12import * as DateTime from "effect/DateTime";
13import * as Duration from "effect/Duration";
14import * as Effect from "effect/Effect";
15import * as Exit from "effect/Exit";
16import * as FileSystem from "effect/FileSystem";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Path from "effect/Path";
20import * as PlatformError from "effect/PlatformError";
21import * as Result from "effect/Result";
22import * as Schema from "effect/Schema";
23​
24import * as ServerConfig from "../config.ts";
25import * as GitWorkflow from "../git/GitWorkflowService.ts";
26import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
27import * as ProjectService from "./ProjectService.ts";
28​
29export class ScratchUnavailableError extends Schema.TaggedError<ScratchUnavailableError>()(
30 "ScratchUnavailableError",
31 {
32 baseDir: Schema.String,
33 repositoryRoot: Schema.optional(Schema.String),
34 },
35) {
36 override get message(): string {
37 if (this.repositoryRoot === undefined) {
38 return "Threads without a project are not available on this environment.";
39 }
40 return `Threads without a project are off because the T3 home ${this.baseDir} is inside the Git repository ${this.repositoryRoot}. If that repository was created by mistake, move ${this.repositoryRoot}/.git out of the way; otherwise point T3CODE_HOME (or --base-dir) at a folder outside it. Then restart T3 Code.`;
41 }
43​
44export class ScratchFolderError extends Schema.TaggedError<ScratchFolderError>()(
45 "ScratchFolderError",
46 {
47 folder: Schema.String,
48 cause: Schema.Defect(),
49 },
50) {
51 override get message(): string {
52 return "Failed to create the folder for threads without a project.";
53 }
55​
56export class ScratchProjectError extends Schema.TaggedError<ScratchProjectError>()(
57 "ScratchProjectError",
58 {
59 workspaceRoot: Schema.String,
60 cause: Schema.Defect(),
61 },
62) {
63 override get message(): string {
64 return "Failed to create the project for threads without a project.";
65 }
67​
68export type ScratchError = ScratchUnavailableError | ScratchFolderError | ScratchProjectError;
69​
70export class NamedProjectFolderError extends Schema.TaggedError<NamedProjectFolderError>()(
71 "NamedProjectFolderError",
72 {
73 folder: Schema.String,
74 cause: Schema.Defect(),
75 },
76) {
77 override get message(): string {
78 return "Failed to create the project folder.";
79 }
81​
82export class NamedProjectCreateError extends Schema.TaggedError<NamedProjectCreateError>()(
83 "NamedProjectCreateError",
84 {
85 workspaceRoot: Schema.String,
86 cause: Schema.Defect(),
87 },
88) {
89 override get message(): string {
90 return "Failed to create the project.";
91 }
93​
94export type NamedProjectError = NamedProjectFolderError | NamedProjectCreateError;
95​
96export class ManagedProjectFolders extends Context.Service<
97 ManagedProjectFolders,
98 {
99 readonly scratchRoot: Effect.Effect<Option.Option<string>>;
100 readonly ensureScratchProject: Effect.Effect<{ readonly projectId: ProjectId }, ScratchError>;
101 readonly isScratchProject: (projectId: ProjectId) => Effect.Effect<boolean>;
102 readonly folderForThread: (input: {
103 readonly projectId: ProjectId;
104 readonly threadId: ThreadId;
105 readonly text: string;
106 }) => Effect.Effect<Option.Option<string>, ScratchFolderError>;
107 readonly namedProjectsRoot: string;
108 /** Removes failed/cancelled creations' folders only while no project owns them. */
109 readonly createNamedProject: (input: { readonly name: string }) => Effect.Effect<
110 {
111 readonly projectId: ProjectId;
112 readonly workspaceRoot: string;
113 readonly commitError?: string;
114 },
115 NamedProjectError
116 >;
117 }
118>()("t3/project/ManagedProjectFolders") {}
119​
120const folderWords = (text: string) =>
121 text
122 .toLowerCase()
123 .split(/[^a-z0-9]+/)
124 .filter(Boolean)
125 .slice(0, 5)
126 .join("-")
127 .slice(0, 48)
128 .replace(/-+$/, "");
129​
130const ICON_BACKGROUNDS = [
131 "#dc2626",
132 "#ea580c",
133 "#d97706",
134 "#16a34a",
135 "#059669",
136 "#0d9488",
137 "#0891b2",
138 "#0284c7",
139 "#2563eb",
140 "#4f46e5",
141 "#7c3aed",
142 "#9333ea",
143 "#c026d3",
144 "#db2777",
145 "#e11d48",
146] as const;
147​
148const MAX_NAMED_FOLDER_ATTEMPTS = 100;
149​
150function escapeXml(value: string): string {
151 return value
152 .replaceAll("&", "&amp;")
153 .replaceAll("<", "&lt;")
154 .replaceAll(">", "&gt;")
155 .replaceAll('"', "&quot;");
157​
158// ProjectFaviconResolver finds assets/icon.svg on every clone.
159function namedProjectIconSvg(name: string): string {
160 const words = name.split(/[^\p{L}\p{N}]+/u).filter(Boolean);
161 const initials =
162 words
163 .slice(0, 2)
164 .map((word) => Array.from(word)[0] ?? "")
165 .join("")
166 .toUpperCase() ||
167 Array.from(name.trim())[0] ||
168 "?";
169 let hash = 0;
170 for (const char of name) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) >>> 0;
171 const background = ICON_BACKGROUNDS[hash % ICON_BACKGROUNDS.length];
172 return [
173 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">`,
174 ` <rect width="64" height="64" rx="14" fill="${background}"/>`,
175 ` <text x="32" y="32" dy="0.35em" text-anchor="middle" font-family="ui-sans-serif, system-ui, -apple-system, sans-serif" font-size="${initials.length > 1 ? 26 : 32}" font-weight="600" fill="#ffffff">${escapeXml(initials)}</text>`,
176 `</svg>`,
177 "",
178 ].join("\n");
180​
181function namedProjectReadme(name: string): string {
182 return [
183 `<img src="assets/icon.svg" width="64" height="64" alt="">`,
184 "",
185 `# ${name}`,
186 "",
187 "Created in [T3 Code](https://t3.codes).",
188 "",
189 ].join("\n");
191​
192function describeCommitFailure(stderr: string): string {
193 if (/identity unknown|tell me who you are|no (name|email) was given/i.test(stderr)) {
194 return "Git has no name or email on this machine. Set user.name and user.email, then commit.";
195 }
196 const lines = stderr
197 .split("\n")
198 .map((line) => line.trim())
199 .filter(Boolean);
200 return lines.at(-1) ?? "Git could not make the first commit.";
202​
203const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError);
204​
205const isGitMissing = (error: GitManagerServiceError) =>
206 error._tag === "GitManagerError" &&
207 isVcsProcessSpawnError(error.cause) &&
208 PlatformError.isPlatformError(error.cause.cause) &&
209 error.cause.cause.reason._tag === "NotFound";
210​
211const make = Effect.gen(function* () {
212 const config = yield* ServerConfig.ServerConfig;
213 const fileSystem = yield* FileSystem.FileSystem;
214 const path = yield* Path.Path;
215 const gitWorkflow = yield* GitWorkflow.GitWorkflowService;
216 const git = yield* GitVcsDriver.GitVcsDriver;
217 const projects = yield* ProjectService.ProjectService;
218 const random = yield* SecureRandom.SecureRandom;
219​
220 // Non-recursive mkdir atomically claims a name; racers move on after AlreadyExists.
221 const claimFreeFolder = Effect.fnUntraced(function* <E>(
222 folderFor: (attempt: number) => Effect.Effect<Option.Option<string>, E>,
223 onError: (folder: string, cause: PlatformError.PlatformError) => E,
224 ) {
225 for (let attempt = 1; ; attempt++) {
226 const folder = yield* folderFor(attempt);
227 if (Option.isNone(folder)) return folder;
228 const claimed = yield* fileSystem.makeDirectory(folder.value).pipe(
229 Effect.as(true),
230 Effect.catchIf(
231 (error) => error.reason._tag === "AlreadyExists",
232 () => Effect.succeed(false),
233 ),
234 Effect.mapError((cause) => onError(folder.value, cause)),
235 );
236 if (claimed) return folder;
237 }
238 });
239​
240 // Scratch inside a checkout would inherit its git status and checkpoints; require a data dir outside work trees.
241 const [probe, invalidate] = yield* Effect.cachedInvalidateWithTTL(
242 gitWorkflow.repositoryRoot(config.baseDir).pipe(
243 Effect.catchIf(isGitMissing, () => Effect.succeed(null)),
244 Effect.flatMap(
245 (repositoryRoot): Effect.Effect<Result.Result<string, ScratchUnavailableError>> => {
246 if (repositoryRoot === null) {
247 return Effect.succeed(Result.succeed(path.resolve(config.baseDir, "scratch")));
248 }
249 const unavailable = new ScratchUnavailableError({
250 baseDir: config.baseDir,
251 repositoryRoot,
252 });
253 return Effect.logWarning(unavailable.message).pipe(Effect.as(Result.fail(unavailable)));
254 },
255 ),
256 Effect.catchCause((cause) =>
257 Cause.hasInterrupts(cause)
258 ? Effect.interrupt
259 : Effect.succeed(Result.fail(new ScratchUnavailableError({ baseDir: config.baseDir }))),
260 ),
261 ),
262 Duration.infinity,
263 );
264 const scratchProbe = probe.pipe(Effect.onInterrupt(() => invalidate));
265 const scratchRoot = scratchProbe.pipe(Effect.map(Result.getSuccess));
266​
267 const makeScratchFolder = (folder: string) =>
268 fileSystem
269 .makeDirectory(folder, { recursive: true })
270 .pipe(Effect.mapError((cause) => new ScratchFolderError({ folder, cause })));
271​
272 const ensureScratchProject: ManagedProjectFolders["Service"]["ensureScratchProject"] = Effect.gen(
273 function* () {
274 const workspaceRoot = yield* scratchProbe.pipe(Effect.flatMap(Effect.fromResult));
275 yield* makeScratchFolder(workspaceRoot);
276 const id = yield* random
277 .uuidV4()
278 .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })));
279 const bootstrapped = yield* projects
280 .bootstrap({
281 commandId: CommandId.make(`scratch-project:${id}`),
282 projectId: ProjectId.make(id),
283 title: "No project",
284 workspaceRoot,
285 })
286 .pipe(
287 // bootstrap reads before locking; racing creates return the winner in a conflict.
288 Effect.catchTags({
289 ProjectConflictError: (conflict) =>
290 Effect.succeed({
291 project: { id: conflict.conflictingProjectId },
292 created: false,
293 }),
294 }),
295 Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })),
296 );
297 if (bootstrapped.created) {
298 // Set once at create, so a user's own icon choice is never overwritten.
299 yield* projects
300 .update({
301 commandId: CommandId.make(`scratch-project-icon:${id}`),
302 projectId: bootstrapped.project.id,
303 projectIcon: { kind: "lucide", name: "message-square-dashed", color: "gray" },
304 })
305 .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })));
306 }
307 return { projectId: bootstrapped.project.id };
308 },
309 );
310​
311 const isScratchRoot = (projectId: ProjectId, root: string) =>
312 projects.getById(projectId).pipe(
313 Effect.map(
314 Option.exists((project) => path.resolve(project.workspaceRoot) === path.resolve(root)),
315 ),
316 Effect.orElseSucceed(() => false),
317 );
318​
319 const isScratchProject: ManagedProjectFolders["Service"]["isScratchProject"] = (projectId) =>
320 scratchRoot.pipe(
321 Effect.flatMap(
322 Option.match({
323 onNone: () => Effect.succeed(false),
324 onSome: (root) => isScratchRoot(projectId, root),
325 }),
326 ),
327 );
328​
329 const folderForThread: ManagedProjectFolders["Service"]["folderForThread"] = Effect.fn(
330 "ManagedProjectFolders.folderForThread",
331 )(function* (input) {
332 const root = yield* scratchRoot;
333 if (Option.isNone(root)) return Option.none();
334 if (!(yield* isScratchRoot(input.projectId, root.value))) return Option.none();
335 const date = DateTime.formatIso(yield* DateTime.now).slice(0, 10);
336 const words = folderWords(input.text);
337 const id = input.threadId.toLowerCase().replace(/[^a-z0-9]/g, "");
338 const folderFor = (idPart: string) =>
339 path.join(root.value, [date, words, idPart].filter(Boolean).join("-"));
340 yield* makeScratchFolder(root.value);
341 const fullFolder = folderFor(id);
342 return yield* claimFreeFolder(
343 (attempt) =>
344 attempt === 1
345 ? Effect.succeedSome(folderFor(id.slice(-8)))
346 : attempt === 2
347 ? Effect.succeedSome(fullFolder)
348 : random.uuidV4().pipe(
349 Effect.map((uuid) => Option.some(`${fullFolder}-${uuid.slice(0, 8)}`)),
350 Effect.mapError((cause) => new ScratchFolderError({ folder: fullFolder, cause })),
351 ),
352 (folder, cause) => new ScratchFolderError({ folder, cause }),
353 );
354 });
355​
356 const namedProjectsRoot = path.resolve(config.baseDir, "projects");
357​
358 const claimNamedFolder = Effect.fn("ManagedProjectFolders.claimNamedFolder")(function* (
359 name: string,
360 ) {
361 yield* fileSystem
362 .makeDirectory(namedProjectsRoot, { recursive: true })
363 .pipe(
364 Effect.mapError(
365 (cause) => new NamedProjectFolderError({ folder: namedProjectsRoot, cause }),
366 ),
367 );
368 const folderName = newProjectFolderName(name);
369 const claimed = yield* claimFreeFolder(
370 (attempt) =>
371 Effect.succeed(
372 attempt > MAX_NAMED_FOLDER_ATTEMPTS
373 ? Option.none()
374 : Option.some(
375 path.join(
376 namedProjectsRoot,
377 attempt === 1 ? folderName : `${folderName}-${attempt}`,
378 ),
379 ),
380 ),
381 (folder, cause) => new NamedProjectFolderError({ folder, cause }),
382 );
383 if (Option.isSome(claimed)) return claimed.value;
384 return yield* new NamedProjectFolderError({
385 folder: path.join(namedProjectsRoot, folderName),
386 cause: `Every folder name for "${folderName}" is taken.`,
387 });
388 });
389​
390 const scaffoldRepository = Effect.fn("ManagedProjectFolders.scaffoldRepository")(function* (
391 cwd: string,
392 name: string,
393 ) {
394 const branch =
395 (yield* git
396 .readConfigValue(cwd, "init.defaultBranch")
397 .pipe(Effect.orElseSucceed(() => null))) ?? "main";
398 yield* git.execute({
399 operation: "ManagedProjectFolders.init",
400 cwd,
401 args: ["init", `--initial-branch=${branch}`],
402 timeoutMs: 10_000,
403 });
404 yield* fileSystem.writeFileString(path.join(cwd, "README.md"), namedProjectReadme(name));
405 yield* fileSystem.makeDirectory(path.join(cwd, "assets"));
406 yield* fileSystem.writeFileString(
407 path.join(cwd, "assets", "icon.svg"),
408 namedProjectIconSvg(name),
409 );
410 // Force explicit filenames so global ignore rules cannot drop them, and keep
411 // core.safecrlf=true from refusing the LF files under CRLF conversion.
412 yield* git.execute({
413 operation: "ManagedProjectFolders.add",
414 cwd,
415 args: ["-c", "core.safecrlf=false", "add", "--force", "--", "README.md", "assets/icon.svg"],
416 timeoutMs: 10_000,
417 });
418 return yield* git
419 .execute({
420 operation: "ManagedProjectFolders.commit",
421 cwd,
422 args: ["commit", "--message", "Initial commit"],
423 allowNonZeroExit: true,
424 timeoutMs: 30_000,
425 })
426 .pipe(
427 Effect.map((result) =>
428 result.exitCode === 0 ? undefined : describeCommitFailure(result.stderr),
429 ),
430 Effect.catch((error) => Effect.succeed(error.message)),
431 );
432 });
433​
434 const createNamedProject: ManagedProjectFolders["Service"]["createNamedProject"] = Effect.fn(
435 "ManagedProjectFolders.createNamedProject",
436 )(function* (input) {
437 const workspaceRoot = yield* claimNamedFolder(input.name);
438 const removeFolder = fileSystem.remove(workspaceRoot, { recursive: true }).pipe(Effect.ignore);
439 const prepared = yield* Effect.all([
440 scaffoldRepository(workspaceRoot, input.name).pipe(
441 Effect.mapError((cause) => new NamedProjectFolderError({ folder: workspaceRoot, cause })),
442 ),
443 random
444 .uuidV4()
445 .pipe(Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause }))),
446 ]).pipe(Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : removeFolder)));
447 const [commitError, id] = prepared;
448 const project = yield* projects
449 .create({
450 commandId: CommandId.make(`named-project:${id}`),
451 projectId: ProjectId.make(id),
452 title: input.name,
453 workspaceRoot,
454 })
455 .pipe(
456 // Re-check ownership before deleting rejected creations; interruption after commit or conflicts can leave an owner.
457 Effect.tapError((error) =>
458 error._tag === "ProjectConflictError"
459 ? Effect.void
460 : projects.getByWorkspaceRoot(workspaceRoot).pipe(
461 Effect.flatMap((owner) => (Option.isNone(owner) ? removeFolder : Effect.void)),
462 Effect.ignore,
463 ),
464 ),
465 Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause })),
466 );
467 return {
468 projectId: project.id,
469 workspaceRoot,
470 ...(commitError === undefined ? {} : { commitError }),
471 };
472 });
473​
474 return ManagedProjectFolders.of({
475 scratchRoot,
476 ensureScratchProject,
477 isScratchProject,
478 folderForThread,
479 namedProjectsRoot,
480 createNamedProject,
481 });
482});
483​
484export const layer = Layer.effect(ManagedProjectFolders, make);