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

ScratchWorkspace.ts

228 lines8.9 KB

1import { CommandId, ProjectId, type ThreadId } from "@t3tools/contracts";
2import * as Cause from "effect/Cause";
3import * as Context from "effect/Context";
4import * as Crypto from "effect/Crypto";
5import * as DateTime from "effect/DateTime";
6import * as Duration from "effect/Duration";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Option from "effect/Option";
11import * as Path from "effect/Path";
12import * as Schema from "effect/Schema";
13​
14import * as ServerConfig from "../config.ts";
15import * as GitWorkflow from "../git/GitWorkflowService.ts";
16import * as ProjectService from "./ProjectService.ts";
17​
18export class ScratchWorkspaceUnavailableError extends Schema.TaggedError<ScratchWorkspaceUnavailableError>()(
19 "ScratchWorkspaceUnavailableError",
20 {},
21) {
22 override get message(): string {
23 return "Threads without a project are not available on this environment.";
24 }
26​
27export class ScratchWorkspaceFolderError extends Schema.TaggedError<ScratchWorkspaceFolderError>()(
28 "ScratchWorkspaceFolderError",
29 {
30 folder: Schema.String,
31 cause: Schema.Defect(),
32 },
33) {
34 override get message(): string {
35 return "Failed to create the folder for threads without a project.";
36 }
38​
39export class ScratchWorkspaceProjectError extends Schema.TaggedError<ScratchWorkspaceProjectError>()(
40 "ScratchWorkspaceProjectError",
41 {
42 workspaceRoot: Schema.String,
43 cause: Schema.Defect(),
44 },
45) {
46 override get message(): string {
47 return "Failed to create the project for threads without a project.";
48 }
50​
51export type ScratchWorkspaceError =
52 | ScratchWorkspaceUnavailableError
53 | ScratchWorkspaceFolderError
54 | ScratchWorkspaceProjectError;
55​
56/**
57 * Threads without a project. They live in the environment's Scratch project
58 * ("No project"), a plain folder under the data dir, and each thread gets a
59 * subfolder of its own so threads never share files.
60 */
61export class ScratchWorkspace extends Context.Service<
62 ScratchWorkspace,
63 {
64 /** The Scratch folder, or None when this environment does not offer one. */
65 readonly root: Effect.Effect<Option.Option<string>>;
66 /** Finds or creates the Scratch project and (re)creates its folder. */
67 readonly ensureProject: Effect.Effect<{ readonly projectId: ProjectId }, ScratchWorkspaceError>;
68 /**
69 * Claims a fresh folder for a new thread in the Scratch project, named from
70 * the date, its first message, and its id. None for every other project.
71 */
72 readonly folderForThread: (input: {
73 readonly projectId: ProjectId;
74 readonly threadId: ThreadId;
75 readonly text: string;
76 }) => Effect.Effect<Option.Option<string>, ScratchWorkspaceFolderError>;
77 }
78>()("t3/project/ScratchWorkspace") {}
79​
80// Only [a-z0-9] reaches a folder name, so it stays one path segment, and the
81// words are capped so a pasted blob cannot outgrow a file name.
82const folderWords = (text: string) =>
83 text
84 .toLowerCase()
85 .split(/[^a-z0-9]+/)
86 .filter(Boolean)
87 .slice(0, 5)
88 .join("-")
89 .slice(0, 48)
90 .replace(/-+$/, "");
91​
92const make = Effect.gen(function* () {
93 const config = yield* ServerConfig.ServerConfig;
94 const fileSystem = yield* FileSystem.FileSystem;
95 const path = yield* Path.Path;
96 const git = yield* GitWorkflow.GitWorkflowService;
97 const projects = yield* ProjectService.ProjectService;
98 const crypto = yield* Crypto.Crypto;
99​
100 // Inside a checkout (a dev worktree's .t3, a dotfiles home) the folder would
101 // inherit the repo's git status and checkpoints, so Scratch is offered only
102 // when the data dir is outside any work tree. Probed once; detection
103 // failures hide Scratch rather than failing callers. An interrupted probe
104 // invalidates the cache so the next caller probes again.
105 const [probe, invalidate] = yield* Effect.cachedInvalidateWithTTL(
106 git.isRepository(config.baseDir).pipe(
107 Effect.map((isRepository) =>
108 isRepository ? Option.none<string>() : Option.some(path.resolve(config.baseDir, "scratch")),
109 ),
110 Effect.catchCause((cause) =>
111 Cause.hasInterrupts(cause) ? Effect.interrupt : Effect.succeed(Option.none<string>()),
112 ),
113 ),
114 Duration.infinity,
115 );
116 const root = probe.pipe(Effect.onInterrupt(() => invalidate));
117​
118 const makeFolder = (folder: string, options?: { readonly recursive?: boolean }) =>
119 fileSystem
120 .makeDirectory(folder, options)
121 .pipe(Effect.mapError((cause) => new ScratchWorkspaceFolderError({ folder, cause })));
122​
123 const ensureProject: ScratchWorkspace["Service"]["ensureProject"] = Effect.gen(function* () {
124 const workspaceRoot = yield* root.pipe(
125 Effect.flatMap(
126 Option.match({
127 onNone: () => Effect.fail(new ScratchWorkspaceUnavailableError()),
128 onSome: Effect.succeed,
129 }),
130 ),
131 );
132 // Re-made on every call, so a deleted Scratch folder still runs threads.
133 yield* makeFolder(workspaceRoot, { recursive: true });
134 const id = yield* crypto.randomUUIDv4.pipe(
135 Effect.mapError((cause) => new ScratchWorkspaceProjectError({ workspaceRoot, cause })),
136 );
137 const bootstrapped = yield* projects
138 .bootstrap({
139 commandId: CommandId.make(`scratch-project:${id}`),
140 projectId: ProjectId.make(id),
141 title: "No project",
142 workspaceRoot,
143 })
144 .pipe(
145 // bootstrap looks the root up before taking the workspace lock, so a
146 // racing create loses with a conflict that names the winner.
147 Effect.catchTags({
148 ProjectConflictError: (conflict) =>
149 Effect.succeed({
150 project: { id: conflict.conflictingProjectId },
151 created: false,
152 }),
153 }),
154 Effect.mapError((cause) => new ScratchWorkspaceProjectError({ workspaceRoot, cause })),
155 );
156 if (bootstrapped.created) {
157 // A dashed chat bubble in neutral gray marks Scratch. Set once at
158 // create, so a user's own icon choice is never overwritten.
159 yield* projects
160 .update({
161 commandId: CommandId.make(`scratch-project-icon:${id}`),
162 projectId: bootstrapped.project.id,
163 projectIcon: { kind: "lucide", name: "message-square-dashed", color: "gray" },
164 })
165 .pipe(
166 Effect.mapError((cause) => new ScratchWorkspaceProjectError({ workspaceRoot, cause })),
167 );
168 }
169 return { projectId: bootstrapped.project.id };
170 });
171​
172 const isScratchProject = (projectId: ProjectId, scratchRoot: string) =>
173 projects.getById(projectId).pipe(
174 Effect.map(
175 Option.exists(
176 (project) => path.resolve(project.workspaceRoot) === path.resolve(scratchRoot),
177 ),
178 ),
179 // An unreadable project is not Scratch; the launch reports its own
180 // project lookup failure.
181 Effect.orElseSucceed(() => false),
182 );
183​
184 const folderForThread: ScratchWorkspace["Service"]["folderForThread"] = Effect.fn(
185 "ScratchWorkspace.folderForThread",
186 )(function* (input) {
187 const scratchRoot = yield* root;
188 if (Option.isNone(scratchRoot)) return Option.none();
189 if (!(yield* isScratchProject(input.projectId, scratchRoot.value))) return Option.none();
190 const date = DateTime.formatIso(yield* DateTime.now).slice(0, 10);
191 const words = folderWords(input.text);
192 const id = input.threadId.toLowerCase().replace(/[^a-z0-9]/g, "");
193 const folderFor = (idPart: string) =>
194 path.join(scratchRoot.value, [date, words, idPart].filter(Boolean).join("-"));
195 yield* makeFolder(scratchRoot.value, { recursive: true });
196 // Each leaf is created without `recursive`, so creating it claims it. A
197 // taken short name falls back to the full id, which only this thread holds.
198 const claim = (folder: string) =>
199 fileSystem.makeDirectory(folder).pipe(
200 Effect.as(true),
201 Effect.catchIf(
202 (error) => error.reason._tag === "AlreadyExists",
203 () => Effect.succeed(false),
204 ),
205 Effect.mapError((cause) => new ScratchWorkspaceFolderError({ folder, cause })),
206 );
207 // Thread ids often share a prefix ("thread:..."), so the short name uses
208 // the id's tail.
209 const shortFolder = folderFor(id.slice(-8));
210 if (yield* claim(shortFolder)) return Option.some(shortFolder);
211 const fullFolder = folderFor(id);
212 if (yield* claim(fullFolder)) return Option.some(fullFolder);
213 // Ids that normalize alike, or a launch retried without its receipt, can
214 // find the full name taken too. A folder is never shared, so claim a fresh
215 // suffixed one instead.
216 while (true) {
217 const suffix = (yield* crypto.randomUUIDv4.pipe(
218 Effect.mapError((cause) => new ScratchWorkspaceFolderError({ folder: fullFolder, cause })),
219 )).slice(0, 8);
220 const folder = `${fullFolder}-${suffix}`;
221 if (yield* claim(folder)) return Option.some(folder);
222 }
223 });
224​
225 return ScratchWorkspace.of({ root, ensureProject, folderForThread });
226});
227​
228export const layer = Layer.effect(ScratchWorkspace, make);