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