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

ManagedProjectFolders.ts

510 lines18.8 KB

1/**
2 * ManagedProjectFolders - the project folders T3 Code makes for the user under
3 * its data dir, rather than ones the user picks:
4 *
5 * - `<baseDir>/scratch`: the Scratch project ("No project"), with a folder of
6 * its own for each thread;
7 * - `<baseDir>/projects/<slug>`: projects started from just a name, each a new
8 * Git repository with a README, an icon, and a first commit.
9 *
10 * @module ManagedProjectFolders
11 */
12import { CommandId, ProjectId, type ThreadId } from "@t3tools/contracts";
13import { newProjectFolderName } from "@t3tools/shared/path";
14import * as Cause from "effect/Cause";
15import * as Context from "effect/Context";
16import * as Crypto from "effect/Crypto";
17import * as DateTime from "effect/DateTime";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as Exit from "effect/Exit";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as Option from "effect/Option";
24import * as Path from "effect/Path";
25import * as PlatformError from "effect/PlatformError";
26import * as Schema from "effect/Schema";
27​
28import * as ServerConfig from "../config.ts";
29import * as GitWorkflow from "../git/GitWorkflowService.ts";
30import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
31import * as ProjectService from "./ProjectService.ts";
32​
33export class ScratchUnavailableError extends Schema.TaggedError<ScratchUnavailableError>()(
34 "ScratchUnavailableError",
35 {},
36) {
37 override get message(): string {
38 return "Threads without a project are not available on this environment.";
39 }
41​
42export class ScratchFolderError extends Schema.TaggedError<ScratchFolderError>()(
43 "ScratchFolderError",
44 {
45 folder: Schema.String,
46 cause: Schema.Defect(),
47 },
48) {
49 override get message(): string {
50 return "Failed to create the folder for threads without a project.";
51 }
53​
54export class ScratchProjectError extends Schema.TaggedError<ScratchProjectError>()(
55 "ScratchProjectError",
56 {
57 workspaceRoot: Schema.String,
58 cause: Schema.Defect(),
59 },
60) {
61 override get message(): string {
62 return "Failed to create the project for threads without a project.";
63 }
65​
66export type ScratchError = ScratchUnavailableError | ScratchFolderError | ScratchProjectError;
67​
68export class NamedProjectFolderError extends Schema.TaggedError<NamedProjectFolderError>()(
69 "NamedProjectFolderError",
70 {
71 folder: Schema.String,
72 cause: Schema.Defect(),
73 },
74) {
75 override get message(): string {
76 return "Failed to create the project folder.";
77 }
79​
80export class NamedProjectCreateError extends Schema.TaggedError<NamedProjectCreateError>()(
81 "NamedProjectCreateError",
82 {
83 workspaceRoot: Schema.String,
84 cause: Schema.Defect(),
85 },
86) {
87 override get message(): string {
88 return "Failed to create the project.";
89 }
91​
92export type NamedProjectError = NamedProjectFolderError | NamedProjectCreateError;
93​
94export class ManagedProjectFolders extends Context.Service<
95 ManagedProjectFolders,
96 {
97 /** The Scratch folder, or None when this environment does not offer one. */
98 readonly scratchRoot: Effect.Effect<Option.Option<string>>;
99 /** Finds or creates the Scratch project and (re)creates its folder. */
100 readonly ensureScratchProject: Effect.Effect<{ readonly projectId: ProjectId }, ScratchError>;
101 /**
102 * Claims a fresh folder for a new thread in the Scratch project, named from
103 * the date, its first message, and its id. None for every other project.
104 */
105 readonly folderForThread: (input: {
106 readonly projectId: ProjectId;
107 readonly threadId: ThreadId;
108 readonly text: string;
109 }) => Effect.Effect<Option.Option<string>, ScratchFolderError>;
110 /** The folder that holds projects started from just a name. */
111 readonly namedProjectsRoot: string;
112 /**
113 * Starts a project from just a name: claims `<namedProjectsRoot>/<slug>`
114 * (adding `-2`, `-3`, ... when taken), makes it a Git repository with a
115 * README, an icon, and a first commit, then creates the project. A failed
116 * commit (no Git identity, a signing prompt) keeps the project and returns
117 * why in `commitError`. The folder is removed when the create fails or is
118 * cancelled before the project exists, never once another project owns it.
119 */
120 readonly createNamedProject: (input: { readonly name: string }) => Effect.Effect<
121 {
122 readonly projectId: ProjectId;
123 readonly workspaceRoot: string;
124 readonly commitError?: string;
125 },
126 NamedProjectError
127 >;
128 }
129>()("t3/project/ManagedProjectFolders") {}
130​
131// Only [a-z0-9] reaches a folder name, so it stays one path segment, and the
132// words are capped so a pasted blob cannot outgrow a file name.
133const folderWords = (text: string) =>
134 text
135 .toLowerCase()
136 .split(/[^a-z0-9]+/)
137 .filter(Boolean)
138 .slice(0, 5)
139 .join("-")
140 .slice(0, 48)
141 .replace(/-+$/, "");
142​
143// Tailwind 600 shades: dark enough for white initials on every hue.
144const ICON_BACKGROUNDS = [
145 "#dc2626",
146 "#ea580c",
147 "#d97706",
148 "#16a34a",
149 "#059669",
150 "#0d9488",
151 "#0891b2",
152 "#0284c7",
153 "#2563eb",
154 "#4f46e5",
155 "#7c3aed",
156 "#9333ea",
157 "#c026d3",
158 "#db2777",
159 "#e11d48",
160] as const;
161​
162const MAX_NAMED_FOLDER_ATTEMPTS = 100;
163​
164function escapeXml(value: string): string {
165 return value
166 .replaceAll("&", "&amp;")
167 .replaceAll("<", "&lt;")
168 .replaceAll(">", "&gt;")
169 .replaceAll('"', "&quot;");
171​
172/**
173 * A rounded square with the name's initials, colored by a hash of the name.
174 * It lives at `assets/icon.svg`, a path ProjectFaviconResolver already checks,
175 * so every machine that clones the project shows the same icon.
176 */
177function namedProjectIconSvg(name: string): string {
178 const words = name.split(/[^\p{L}\p{N}]+/u).filter(Boolean);
179 const initials =
180 words
181 .slice(0, 2)
182 .map((word) => Array.from(word)[0] ?? "")
183 .join("")
184 .toUpperCase() ||
185 Array.from(name.trim())[0] ||
186 "?";
187 let hash = 0;
188 for (const char of name) hash = (hash * 31 + (char.codePointAt(0) ?? 0)) >>> 0;
189 const background = ICON_BACKGROUNDS[hash % ICON_BACKGROUNDS.length];
190 return [
191 `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">`,
192 ` <rect width="64" height="64" rx="14" fill="${background}"/>`,
193 ` <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>`,
194 `</svg>`,
195 "",
196 ].join("\n");
198​
199function namedProjectReadme(name: string): string {
200 return [
201 `<img src="assets/icon.svg" width="64" height="64" alt="">`,
202 "",
203 `# ${name}`,
204 "",
205 "Created in [T3 Code](https://t3.codes).",
206 "",
207 ].join("\n");
209​
210// Git's own identity message runs several lines; say what to do instead.
211// Otherwise its last line ("error: gpg failed to sign the data") says enough.
212function describeCommitFailure(stderr: string): string {
213 if (/identity unknown|tell me who you are|no (name|email) was given/i.test(stderr)) {
214 return "Git has no name or email on this machine. Set user.name and user.email, then commit.";
215 }
216 const lines = stderr
217 .split("\n")
218 .map((line) => line.trim())
219 .filter(Boolean);
220 return lines.at(-1) ?? "Git could not make the first commit.";
222​
223const make = Effect.gen(function* () {
224 const config = yield* ServerConfig.ServerConfig;
225 const fileSystem = yield* FileSystem.FileSystem;
226 const path = yield* Path.Path;
227 const gitWorkflow = yield* GitWorkflow.GitWorkflowService;
228 const git = yield* GitVcsDriver.GitVcsDriver;
229 const projects = yield* ProjectService.ProjectService;
230 const crypto = yield* Crypto.Crypto;
231​
232 /**
233 * Claims the first free folder among `folderFor(1)`, `folderFor(2)`, ...,
234 * stopping with None when `folderFor` runs out of names. Each folder is
235 * created without `recursive`, so creating it is the claim: of two racers
236 * for one name, one gets AlreadyExists and moves on to the next. Scratch
237 * thread folders and named projects both claim through this, so no two
238 * threads or projects ever share a folder.
239 */
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 // Inside a checkout (a dev worktree's .t3, a dotfiles home) the folder would
260 // inherit the repo's git status and checkpoints, so Scratch is offered only
261 // when the data dir is outside any work tree. Probed once; detection
262 // failures hide Scratch rather than failing callers. An interrupted probe
263 // invalidates the cache so the next caller probes again.
264 const [probe, invalidate] = yield* Effect.cachedInvalidateWithTTL(
265 gitWorkflow.isRepository(config.baseDir).pipe(
266 Effect.map((isRepository) =>
267 isRepository ? Option.none<string>() : Option.some(path.resolve(config.baseDir, "scratch")),
268 ),
269 Effect.catchCause((cause) =>
270 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Option.none<string>()),
271 ),
272 ),
273 Duration.infinity,
274 );
275 const scratchRoot = probe.pipe(Effect.onInterrupt(() => invalidate));
276​
277 const makeScratchFolder = (folder: string) =>
278 fileSystem
279 .makeDirectory(folder, { recursive: true })
280 .pipe(Effect.mapError((cause) => new ScratchFolderError({ folder, cause })));
281​
282 const ensureScratchProject: ManagedProjectFolders["Service"]["ensureScratchProject"] = Effect.gen(
283 function* () {
284 const workspaceRoot = yield* scratchRoot.pipe(
285 Effect.flatMap(
286 Option.match({
287 onNone: () => Effect.fail(new ScratchUnavailableError()),
288 onSome: Effect.succeed,
289 }),
290 ),
291 );
292 // Re-made on every call, so a deleted Scratch folder still runs threads.
293 yield* makeScratchFolder(workspaceRoot);
294 const id = yield* crypto.randomUUIDv4.pipe(
295 Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })),
296 );
297 const bootstrapped = yield* projects
298 .bootstrap({
299 commandId: CommandId.make(`scratch-project:${id}`),
300 projectId: ProjectId.make(id),
301 title: "No project",
302 workspaceRoot,
303 })
304 .pipe(
305 // bootstrap looks the root up before taking the workspace lock, so a
306 // racing create loses with a conflict that names the winner.
307 Effect.catchTags({
308 ProjectConflictError: (conflict) =>
309 Effect.succeed({
310 project: { id: conflict.conflictingProjectId },
311 created: false,
312 }),
313 }),
314 Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })),
315 );
316 if (bootstrapped.created) {
317 // A dashed chat bubble in neutral gray marks Scratch. Set once at
318 // create, so a user's own icon choice is never overwritten.
319 yield* projects
320 .update({
321 commandId: CommandId.make(`scratch-project-icon:${id}`),
322 projectId: bootstrapped.project.id,
323 projectIcon: { kind: "lucide", name: "message-square-dashed", color: "gray" },
324 })
325 .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })));
326 }
327 return { projectId: bootstrapped.project.id };
328 },
329 );
330​
331 const isScratchProject = (projectId: ProjectId, root: string) =>
332 projects.getById(projectId).pipe(
333 Effect.map(
334 Option.exists((project) => path.resolve(project.workspaceRoot) === path.resolve(root)),
335 ),
336 // An unreadable project is not Scratch; the launch reports its own
337 // project lookup failure.
338 Effect.orElseSucceed(() => false),
339 );
340​
341 const folderForThread: ManagedProjectFolders["Service"]["folderForThread"] = Effect.fn(
342 "ManagedProjectFolders.folderForThread",
343 )(function* (input) {
344 const root = yield* scratchRoot;
345 if (Option.isNone(root)) return Option.none();
346 if (!(yield* isScratchProject(input.projectId, root.value))) return Option.none();
347 const date = DateTime.formatIso(yield* DateTime.now).slice(0, 10);
348 const words = folderWords(input.text);
349 const id = input.threadId.toLowerCase().replace(/[^a-z0-9]/g, "");
350 const folderFor = (idPart: string) =>
351 path.join(root.value, [date, words, idPart].filter(Boolean).join("-"));
352 yield* makeScratchFolder(root.value);
353 const fullFolder = folderFor(id);
354 // Thread ids often share a prefix ("thread:..."), so the first name uses
355 // the id's tail. A taken short name falls back to the full id, which only
356 // this thread holds. Ids that normalize alike, or a launch retried without
357 // its receipt, can find the full name taken too, so later attempts add a
358 // fresh random suffix; the names never run out.
359 return yield* claimFreeFolder(
360 (attempt) =>
361 attempt === 1
362 ? Effect.succeed(Option.some(folderFor(id.slice(-8))))
363 : attempt === 2
364 ? Effect.succeed(Option.some(fullFolder))
365 : crypto.randomUUIDv4.pipe(
366 Effect.map((uuid) => Option.some(`${fullFolder}-${uuid.slice(0, 8)}`)),
367 Effect.mapError((cause) => new ScratchFolderError({ folder: fullFolder, cause })),
368 ),
369 (folder, cause) => new ScratchFolderError({ folder, cause }),
370 );
371 });
372​
373 // Projects started from just a name live beside Scratch and worktrees, away
374 // from folders the user organizes by hand. A nested repository is fine here
375 // (unlike Scratch) because each project gets its own `git init`.
376 const namedProjectsRoot = path.resolve(config.baseDir, "projects");
377​
378 const claimNamedFolder = Effect.fn("ManagedProjectFolders.claimNamedFolder")(function* (
379 name: string,
380 ) {
381 yield* fileSystem
382 .makeDirectory(namedProjectsRoot, { recursive: true })
383 .pipe(
384 Effect.mapError(
385 (cause) => new NamedProjectFolderError({ folder: namedProjectsRoot, cause }),
386 ),
387 );
388 const folderName = newProjectFolderName(name);
389 const claimed = yield* claimFreeFolder(
390 (attempt) =>
391 Effect.succeed(
392 attempt > MAX_NAMED_FOLDER_ATTEMPTS
393 ? Option.none()
394 : Option.some(
395 path.join(
396 namedProjectsRoot,
397 attempt === 1 ? folderName : `${folderName}-${attempt}`,
398 ),
399 ),
400 ),
401 (folder, cause) => new NamedProjectFolderError({ folder, cause }),
402 );
403 if (Option.isSome(claimed)) return claimed.value;
404 return yield* new NamedProjectFolderError({
405 folder: path.join(namedProjectsRoot, folderName),
406 cause: `Every folder name for "${folderName}" is taken.`,
407 });
408 });
409​
410 // git init, the starter files, and the first commit. Only the commit may
411 // fail softly; everything before it fails the create.
412 const scaffoldRepository = Effect.fn("ManagedProjectFolders.scaffoldRepository")(function* (
413 cwd: string,
414 name: string,
415 ) {
416 const branch =
417 (yield* git
418 .readConfigValue(cwd, "init.defaultBranch")
419 .pipe(Effect.orElseSucceed(() => null))) ?? "main";
420 yield* git.execute({
421 operation: "ManagedProjectFolders.init",
422 cwd,
423 args: ["init", `--initial-branch=${branch}`],
424 timeoutMs: 10_000,
425 });
426 yield* fileSystem.writeFileString(path.join(cwd, "README.md"), namedProjectReadme(name));
427 yield* fileSystem.makeDirectory(path.join(cwd, "assets"));
428 yield* fileSystem.writeFileString(
429 path.join(cwd, "assets", "icon.svg"),
430 namedProjectIconSvg(name),
431 );
432 // Named and forced so a global ignore rule (say `*.svg`) cannot drop one.
433 yield* git.execute({
434 operation: "ManagedProjectFolders.add",
435 cwd,
436 args: ["add", "--force", "--", "README.md", "assets/icon.svg"],
437 timeoutMs: 10_000,
438 });
439 return yield* git
440 .execute({
441 operation: "ManagedProjectFolders.commit",
442 cwd,
443 args: ["commit", "--message", "Initial commit"],
444 allowNonZeroExit: true,
445 timeoutMs: 30_000,
446 })
447 .pipe(
448 Effect.map((result) =>
449 result.exitCode === 0 ? undefined : describeCommitFailure(result.stderr),
450 ),
451 Effect.catch((error) => Effect.succeed(error.message)),
452 );
453 });
454​
455 const createNamedProject: ManagedProjectFolders["Service"]["createNamedProject"] = Effect.fn(
456 "ManagedProjectFolders.createNamedProject",
457 )(function* (input) {
458 const workspaceRoot = yield* claimNamedFolder(input.name);
459 const removeFolder = fileSystem.remove(workspaceRoot, { recursive: true }).pipe(Effect.ignore);
460 // Until the create is dispatched nothing else can use the folder, so any
461 // exit but success removes it, an interrupt included.
462 const prepared = yield* Effect.all([
463 scaffoldRepository(workspaceRoot, input.name).pipe(
464 Effect.mapError((cause) => new NamedProjectFolderError({ folder: workspaceRoot, cause })),
465 ),
466 crypto.randomUUIDv4.pipe(
467 Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause })),
468 ),
469 ]).pipe(Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : removeFolder)));
470 const [commitError, id] = prepared;
471 const project = yield* projects
472 .create({
473 commandId: CommandId.make(`named-project:${id}`),
474 projectId: ProjectId.make(id),
475 title: input.name,
476 workspaceRoot,
477 })
478 .pipe(
479 // A rejected create leaves the folder unused, so remove it. An
480 // interrupt can land after the create is committed, and a conflict
481 // means another project owns the folder, so it stays then; the owner
482 // is checked again first, since deleting another project's files is
483 // never acceptable.
484 Effect.tapError((error) =>
485 error._tag === "ProjectConflictError"
486 ? Effect.void
487 : projects.getByWorkspaceRoot(workspaceRoot).pipe(
488 Effect.flatMap((owner) => (Option.isNone(owner) ? removeFolder : Effect.void)),
489 Effect.ignore,
490 ),
491 ),
492 Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause })),
493 );
494 return {
495 projectId: project.id,
496 workspaceRoot,
497 ...(commitError === undefined ? {} : { commitError }),
498 };
499 });
500​
501 return ManagedProjectFolders.of({
502 scratchRoot,
503 ensureScratchProject,
504 folderForThread,
505 namedProjectsRoot,
506 createNamedProject,
507 });
508});
509​
510export const layer = Layer.effect(ManagedProjectFolders, make);