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

ManagedProjectFolders.ts

518 lines18.2 KB

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