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

ManagedProjectFolders.ts

526 lines18.6 KB

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