@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 521 lines 18.4 KB
Raw
1 import {
2 CommandId,
3 GitCommandError,
4 type GitManagerServiceError,
5 ProjectId,
6 type ThreadId,
7 VcsProcessSpawnError,
8 } from "@t3tools/contracts";
9 import { foldLatinDiacritics, newProjectFolderName } from "@t3tools/shared/path";
10 import * as Cause from "effect/Cause";
11 import * as Context from "effect/Context";
12 import * as SecureRandom from "effect/crypto/SecureRandom";
13 import * as DateTime from "effect/DateTime";
14 import * as Duration from "effect/Duration";
15 import * as Effect from "effect/Effect";
16 import * as Exit from "effect/Exit";
17 import * as FileSystem from "effect/FileSystem";
18 import * as Layer from "effect/Layer";
19 import * as Option from "effect/Option";
20 import * as Path from "effect/Path";
21 import * as PlatformError from "effect/PlatformError";
22 import * as Result from "effect/Result";
23 import * as Schema from "effect/Schema";
24
25 import * as ServerConfig from "../config.ts";
26 import * as GitWorkflow from "../git/GitWorkflowService.ts";
27 import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
28 import * as ProjectService from "./ProjectService.ts";
29
30 export 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 }
43 }
44
45 export 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 }
55 }
56
57 export 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 }
67 }
68
69 /** Where No project threads keep their folders, whether or not this T3 home allows them. */
70 export const scratchFolderRoot = (baseDir: string, path: Path.Path) =>
71 path.resolve(baseDir, "scratch");
72
73 export type ScratchError = ScratchUnavailableError | ScratchFolderError | ScratchProjectError;
74
75 // The spawner checks cwd before spawning, so NotFound from spawn itself means a missing executable.
76 const isMissingExecutable = (cause: unknown) =>
77 PlatformError.isPlatformError(cause) &&
78 cause.reason._tag === "NotFound" &&
79 cause.reason.method === "spawn";
80
81 const isGitCommandError = Schema.is(GitCommandError);
82
83 export 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 }
95 }
96
97 export 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 }
107 }
108
109 export type NamedProjectError = NamedProjectFolderError | NamedProjectCreateError;
110
111 export 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
135 const folderWords = (text: string) =>
136 foldLatinDiacritics(text)
137 .toLowerCase()
138 .split(/[^a-z0-9]+/)
139 .filter(Boolean)
140 .slice(0, 5)
141 .join("-")
142 .slice(0, 48)
143 .replace(/-+$/, "");
144
145 const 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
163 const MAX_NAMED_FOLDER_ATTEMPTS = 100;
164
165 function escapeXml(value: string): string {
166 return value
167 .replaceAll("&", "&amp;")
168 .replaceAll("<", "&lt;")
169 .replaceAll(">", "&gt;")
170 .replaceAll('"', "&quot;");
171 }
172
173 // ProjectFaviconResolver finds assets/icon.svg on every clone.
174 function 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");
194 }
195
196 function 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");
205 }
206
207 function 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.";
216 }
217
218 const isVcsProcessSpawnError = Schema.is(VcsProcessSpawnError);
219
220 const 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
226 const 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 ),
272 // A failed git check (say, a timeout on a busy machine) is not an answer; ask again next time.
273 Exit.match({ onSuccess: () => Duration.infinity, onFailure: () => Duration.zero }),
274 );
275 const scratchProbe = probe.pipe(
276 Effect.catchCause((cause) =>
277 Cause.hasInterrupts(cause)
278 ? Effect.interrupt
279 : Effect.succeed(Result.fail(new ScratchUnavailableError({ baseDir: config.baseDir }))),
280 ),
281 Effect.onInterrupt(() => invalidate),
282 );
283 // A symlinked scratch folder lets the No project live at either the link or its target.
284 const scratchProjectRoot = (root: string) =>
285 fileSystem.realPath(root).pipe(
286 Effect.flatMap((target) =>
287 target === root
288 ? Effect.succeed(root)
289 : projects
290 .getByWorkspaceRoot(target)
291 .pipe(Effect.map((project) => (Option.isSome(project) ? target : root))),
292 ),
293 Effect.orElseSucceed(() => root),
294 );
295 const scratchRoot = scratchProbe.pipe(
296 Effect.flatMap((probed) =>
297 Result.isSuccess(probed)
298 ? scratchProjectRoot(probed.success).pipe(Effect.asSome)
299 : Effect.succeedNone,
300 ),
301 );
302
303 const makeScratchFolder = (folder: string) =>
304 fileSystem
305 .makeDirectory(folder, { recursive: true })
306 .pipe(Effect.mapError((cause) => new ScratchFolderError({ folder, cause })));
307
308 const ensureScratchProject: ManagedProjectFolders["Service"]["ensureScratchProject"] = Effect.gen(
309 function* () {
310 const probedRoot = yield* scratchProbe.pipe(Effect.flatMap(Effect.fromResult));
311 yield* makeScratchFolder(probedRoot);
312 const workspaceRoot = yield* scratchProjectRoot(probedRoot);
313 const id = yield* random
314 .uuidV4()
315 .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })));
316 const bootstrapped = yield* projects
317 .bootstrap({
318 commandId: CommandId.make(`scratch-project:${id}`),
319 projectId: ProjectId.make(id),
320 title: "No project",
321 workspaceRoot,
322 })
323 .pipe(
324 // bootstrap reads before locking; racing creates return the winner in a conflict.
325 Effect.catchTags({
326 ProjectConflictError: (conflict) =>
327 Effect.succeed({
328 project: { id: conflict.conflictingProjectId },
329 created: false,
330 }),
331 }),
332 Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })),
333 );
334 if (bootstrapped.created) {
335 // Set once at create, so a user's own icon choice is never overwritten.
336 yield* projects
337 .update({
338 commandId: CommandId.make(`scratch-project-icon:${id}`),
339 projectId: bootstrapped.project.id,
340 projectIcon: { kind: "lucide", name: "message-square-dashed", color: "gray" },
341 })
342 .pipe(Effect.mapError((cause) => new ScratchProjectError({ workspaceRoot, cause })));
343 }
344 return { projectId: bootstrapped.project.id };
345 },
346 );
347
348 const isScratchRoot = (projectId: ProjectId, root: string) =>
349 projects.getById(projectId).pipe(
350 Effect.map(
351 Option.exists((project) => path.resolve(project.workspaceRoot) === path.resolve(root)),
352 ),
353 Effect.orElseSucceed(() => false),
354 );
355
356 const isScratchProject: ManagedProjectFolders["Service"]["isScratchProject"] = (projectId) =>
357 scratchRoot.pipe(
358 Effect.flatMap(
359 Option.match({
360 onNone: () => Effect.succeed(false),
361 onSome: (root) => isScratchRoot(projectId, root),
362 }),
363 ),
364 );
365
366 const folderForThread: ManagedProjectFolders["Service"]["folderForThread"] = Effect.fn(
367 "ManagedProjectFolders.folderForThread",
368 )(function* (input) {
369 const root = yield* scratchRoot;
370 if (Option.isNone(root)) return Option.none();
371 if (!(yield* isScratchRoot(input.projectId, root.value))) return Option.none();
372 const date = DateTime.formatIso(yield* DateTime.now).slice(0, 10);
373 const words = folderWords(input.text);
374 const id = input.threadId.toLowerCase().replace(/[^a-z0-9]/g, "");
375 const folderFor = (idPart: string) =>
376 path.join(root.value, [date, words, idPart].filter(Boolean).join("-"));
377 yield* makeScratchFolder(root.value);
378 const fullFolder = folderFor(id);
379 return yield* claimFreeFolder(
380 (attempt) =>
381 attempt === 1
382 ? Effect.succeedSome(folderFor(id.slice(-8)))
383 : attempt === 2
384 ? Effect.succeedSome(fullFolder)
385 : random.uuidV4().pipe(
386 Effect.map((uuid) => Option.some(`${fullFolder}-${uuid.slice(0, 8)}`)),
387 Effect.mapError((cause) => new ScratchFolderError({ folder: fullFolder, cause })),
388 ),
389 (folder, cause) => new ScratchFolderError({ folder, cause }),
390 );
391 });
392
393 const namedProjectsRoot = path.resolve(config.baseDir, "projects");
394
395 const claimNamedFolder = Effect.fn("ManagedProjectFolders.claimNamedFolder")(function* (
396 name: string,
397 ) {
398 yield* fileSystem
399 .makeDirectory(namedProjectsRoot, { recursive: true })
400 .pipe(
401 Effect.mapError(
402 (cause) => new NamedProjectFolderError({ folder: namedProjectsRoot, cause }),
403 ),
404 );
405 const folderName = newProjectFolderName(name);
406 const claimed = yield* claimFreeFolder(
407 (attempt) =>
408 Effect.succeed(
409 attempt > MAX_NAMED_FOLDER_ATTEMPTS
410 ? Option.none()
411 : Option.some(
412 path.join(
413 namedProjectsRoot,
414 attempt === 1 ? folderName : `${folderName}-${attempt}`,
415 ),
416 ),
417 ),
418 (folder, cause) => new NamedProjectFolderError({ folder, cause }),
419 );
420 if (Option.isSome(claimed)) return claimed.value;
421 return yield* new NamedProjectFolderError({
422 folder: path.join(namedProjectsRoot, folderName),
423 cause: `Every folder name for "${folderName}" is taken.`,
424 });
425 });
426
427 const scaffoldRepository = Effect.fn("ManagedProjectFolders.scaffoldRepository")(function* (
428 cwd: string,
429 name: string,
430 ) {
431 const branch =
432 (yield* git
433 .readConfigValue(cwd, "init.defaultBranch")
434 .pipe(Effect.orElseSucceed(() => null))) ?? "main";
435 yield* git.execute({
436 operation: "ManagedProjectFolders.init",
437 cwd,
438 args: ["init", `--initial-branch=${branch}`],
439 timeoutMs: 10_000,
440 });
441 yield* fileSystem.writeFileString(path.join(cwd, "README.md"), namedProjectReadme(name));
442 yield* fileSystem.makeDirectory(path.join(cwd, "assets"));
443 yield* fileSystem.writeFileString(
444 path.join(cwd, "assets", "icon.svg"),
445 namedProjectIconSvg(name),
446 );
447 // Force explicit filenames so global ignore rules cannot drop them, and keep
448 // core.safecrlf=true from refusing the LF files under CRLF conversion.
449 yield* git.execute({
450 operation: "ManagedProjectFolders.add",
451 cwd,
452 args: ["-c", "core.safecrlf=false", "add", "--force", "--", "README.md", "assets/icon.svg"],
453 timeoutMs: 10_000,
454 });
455 return yield* git
456 .execute({
457 operation: "ManagedProjectFolders.commit",
458 cwd,
459 args: ["commit", "--message", "Initial commit"],
460 allowNonZeroExit: true,
461 timeoutMs: 30_000,
462 })
463 .pipe(
464 Effect.map((result) =>
465 result.exitCode === 0 ? undefined : describeCommitFailure(result.stderr),
466 ),
467 Effect.catch((error) => Effect.succeed(error.message)),
468 );
469 });
470
471 const createNamedProject: ManagedProjectFolders["Service"]["createNamedProject"] = Effect.fn(
472 "ManagedProjectFolders.createNamedProject",
473 )(function* (input) {
474 const workspaceRoot = yield* claimNamedFolder(input.name);
475 const removeFolder = fileSystem.remove(workspaceRoot, { recursive: true }).pipe(Effect.ignore);
476 const prepared = yield* Effect.all([
477 scaffoldRepository(workspaceRoot, input.name).pipe(
478 Effect.mapError((cause) => new NamedProjectFolderError({ folder: workspaceRoot, cause })),
479 ),
480 random
481 .uuidV4()
482 .pipe(Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause }))),
483 ]).pipe(Effect.onExit((exit) => (Exit.isSuccess(exit) ? Effect.void : removeFolder)));
484 const [commitError, id] = prepared;
485 const project = yield* projects
486 .create({
487 commandId: CommandId.make(`named-project:${id}`),
488 projectId: ProjectId.make(id),
489 title: input.name,
490 workspaceRoot,
491 })
492 .pipe(
493 // Re-check ownership before deleting rejected creations; interruption after commit or conflicts can leave an owner.
494 Effect.tapError((error) =>
495 error._tag === "ProjectConflictError"
496 ? Effect.void
497 : projects.getByWorkspaceRoot(workspaceRoot).pipe(
498 Effect.flatMap((owner) => (Option.isNone(owner) ? removeFolder : Effect.void)),
499 Effect.ignore,
500 ),
501 ),
502 Effect.mapError((cause) => new NamedProjectCreateError({ workspaceRoot, cause })),
503 );
504 return {
505 projectId: project.id,
506 workspaceRoot,
507 ...(commitError === undefined ? {} : { commitError }),
508 };
509 });
510
511 return ManagedProjectFolders.of({
512 scratchRoot,
513 ensureScratchProject,
514 isScratchProject,
515 folderForThread,
516 namedProjectsRoot,
517 createNamedProject,
518 });
519 });
520
521 export const layer = Layer.effect(ManagedProjectFolders, make);