@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 553 lines 20 KB
Raw
1 // @effect-diagnostics nodeBuiltinImport:off - publish commits and rollbacks
2 // move exact directory entries with rename, which the FileSystem service does
3 // not expose atomically.
4 import * as NodeCrypto from "node:crypto";
5 import * as NodeFS from "node:fs";
6
7 import {
8 EnvironmentThemeFile,
9 EnvironmentThemeId,
10 environmentThemeFileHasColors,
11 } from "@t3tools/contracts";
12 import { fromJsonStringPretty, fromLenientJson } from "@t3tools/shared/schemaJson";
13 import { BUILT_IN_THEME_IDS, UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
14 import * as Config from "effect/Config";
15 import * as Console from "effect/Console";
16 import * as DateTime from "effect/DateTime";
17 import * as Effect from "effect/Effect";
18 import * as FileSystem from "effect/FileSystem";
19 import * as Option from "effect/Option";
20 import * as Path from "effect/Path";
21 import * as Schema from "effect/Schema";
22 import { Argument, Command, Flag } from "effect/cli";
23
24 import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
25 import * as ServerConfig from "../config.ts";
26 import {
27 MAX_THEME_FILE_BYTES,
28 readPublishedThemes,
29 readThemeFileGuarded,
30 } from "../environmentTheme.ts";
31 import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
32 import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
33 import { baseDirFlag } from "./config.ts";
34
35 const SparseSettings = Schema.Record(Schema.String, Schema.Unknown);
36 const decodeSettingsJson = Schema.decodeUnknownEffect(fromLenientJson(SparseSettings));
37 const encodeSettingsJson = Schema.encodeEffect(fromJsonStringPretty(SparseSettings));
38 const decodeThemeFileJsonExit = Schema.decodeUnknownExit(
39 Schema.fromJsonString(EnvironmentThemeFile),
40 );
41 const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
42
43 export class ThemeSettingsUnreadableError extends Schema.TaggedError<ThemeSettingsUnreadableError>()(
44 "ThemeSettingsUnreadableError",
45 { settingsPath: Schema.String, cause: Schema.Defect() },
46 ) {
47 override get message(): string {
48 return `Could not read ${this.settingsPath}. Fix its permissions, then run this again.`;
49 }
50 }
51
52 export class ThemeSettingsMalformedError extends Schema.TaggedError<ThemeSettingsMalformedError>()(
53 "ThemeSettingsMalformedError",
54 { settingsPath: Schema.String, cause: Schema.Defect() },
55 ) {
56 override get message(): string {
57 return `${this.settingsPath} is not a JSON object. Fix or remove it, then run this again.`;
58 }
59 }
60
61 export class ThemeSettingsBusyError extends Schema.TaggedError<ThemeSettingsBusyError>()(
62 "ThemeSettingsBusyError",
63 { settingsPath: Schema.String, attempts: Schema.Number },
64 ) {
65 override get message(): string {
66 return `${this.settingsPath} kept changing while writing (gave up after ${this.attempts} attempts). Try again.`;
67 }
68 }
69
70 export class ThemeSettingsWriteError extends Schema.TaggedError<ThemeSettingsWriteError>()(
71 "ThemeSettingsWriteError",
72 { settingsPath: Schema.String, cause: Schema.Defect() },
73 ) {
74 override get message(): string {
75 return `Could not write ${this.settingsPath}.`;
76 }
77 }
78
79 export class ThemeFileUnreadableError extends Schema.TaggedError<ThemeFileUnreadableError>()(
80 "ThemeFileUnreadableError",
81 { filePath: Schema.String, cause: Schema.optional(Schema.Defect()) },
82 ) {
83 override get message(): string {
84 return `Could not read ${this.filePath}.`;
85 }
86 }
87
88 export class ThemeFileInvalidError extends Schema.TaggedError<ThemeFileInvalidError>()(
89 "ThemeFileInvalidError",
90 { filePath: Schema.String, cause: Schema.Defect() },
91 ) {
92 override get message(): string {
93 return `${this.filePath} is not a valid theme file. Use a theme exported from T3 Code, or a seeded file with name, appearance, canvas, and accent.`;
94 }
95 }
96
97 export class ThemeFileTooLargeError extends Schema.TaggedError<ThemeFileTooLargeError>()(
98 "ThemeFileTooLargeError",
99 { filePath: Schema.String, limit: Schema.Number },
100 ) {
101 override get message(): string {
102 return `${this.filePath} is larger than ${this.limit} bytes, which is more than a theme can publish.`;
103 }
104 }
105
106 export class ThemeFileColorlessError extends Schema.TaggedError<ThemeFileColorlessError>()(
107 "ThemeFileColorlessError",
108 { filePath: Schema.String },
109 ) {
110 override get message(): string {
111 return `${this.filePath} has no colors to publish.`;
112 }
113 }
114
115 export class ThemePublishError extends Schema.TaggedError<ThemePublishError>()(
116 "ThemePublishError",
117 { themesDir: Schema.String, cause: Schema.Defect() },
118 ) {
119 override get message(): string {
120 return `Could not publish the theme into ${this.themesDir}.`;
121 }
122 }
123
124 export class ThemeDestinationDirectoryError extends Schema.TaggedError<ThemeDestinationDirectoryError>()(
125 "ThemeDestinationDirectoryError",
126 { themeId: Schema.String, destinationPath: Schema.String },
127 ) {
128 override get message(): string {
129 return `${this.destinationPath} is a directory, so the theme cannot be published as "${this.themeId}". Move it, or pass another id with --id.`;
130 }
131 }
132
133 const isThemeDestinationDirectoryError = Schema.is(ThemeDestinationDirectoryError);
134
135 const INVALID_THEME_ID_REASON =
136 "is not a valid theme id (lowercase letters, digits, and hyphens; not an appearance keyword)";
137
138 export class ThemeIdUnknownError extends Schema.TaggedError<ThemeIdUnknownError>()(
139 "ThemeIdUnknownError",
140 { themeId: Schema.String, known: Schema.Array(Schema.String) },
141 ) {
142 override get message(): string {
143 return `No theme named "${this.themeId}". Available: ${this.known.join(", ")}. Publish one by passing a theme file instead of an id.`;
144 }
145 }
146
147 export class ThemeIdInvalidError extends Schema.TaggedError<ThemeIdInvalidError>()(
148 "ThemeIdInvalidError",
149 { themeId: Schema.String },
150 ) {
151 override get message(): string {
152 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}.`;
153 }
154 }
155
156 export class ThemeFileIdInvalidError extends Schema.TaggedError<ThemeFileIdInvalidError>()(
157 "ThemeFileIdInvalidError",
158 { themeId: Schema.String, filePath: Schema.String },
159 ) {
160 override get message(): string {
161 return `"${this.themeId}" ${INVALID_THEME_ID_REASON}. Pass one with --id.`;
162 }
163 }
164
165 export class ThemeTargetMissingError extends Schema.TaggedError<ThemeTargetMissingError>()(
166 "ThemeTargetMissingError",
167 {},
168 ) {
169 override get message(): string {
170 return "Provide a theme id or file, or run `t3 theme clear` to remove the theme.";
171 }
172 }
173
174 const envT3Home = Config.String("T3CODE_HOME").pipe(Config.option);
175 const DEV_STATE_PLACEHOLDER_URL = new URL("http://localhost");
176
177 const hasLiveServer = (statePath: string) =>
178 readPersistedServerRuntimeState(statePath).pipe(
179 Effect.map((state) => Option.isSome(state) && isProcessAlive(state.value.pid)),
180 Effect.orElseSucceed(() => false),
181 );
182
183 const resolveThemePaths = Effect.fn(function* (explicitBaseDir: Option.Option<string>) {
184 const envHome = Option.filter(yield* envT3Home, (value) => value.trim().length > 0);
185 const configuredBaseDir = Option.orElse(explicitBaseDir, () => envHome);
186 const baseDir = yield* resolveBaseDir(Option.getOrUndefined(configuredBaseDir));
187 const userdataPaths = yield* ServerConfig.deriveServerPaths(baseDir, undefined, {
188 baseDirIsExplicit: Option.isSome(configuredBaseDir),
189 });
190 // A dev server with an implicit home keeps its state in `dev`; follow it unless a
191 // `userdata` server is running too, the same order `t3 pair` checks.
192 let derivedPaths = userdataPaths;
193 if (
194 Option.isNone(configuredBaseDir) &&
195 !(yield* hasLiveServer(userdataPaths.serverRuntimeStatePath))
196 ) {
197 const devPaths = yield* ServerConfig.deriveServerPaths(baseDir, DEV_STATE_PLACEHOLDER_URL);
198 if (yield* hasLiveServer(devPaths.serverRuntimeStatePath)) derivedPaths = devPaths;
199 }
200 return {
201 settingsPath: derivedPaths.settingsPath,
202 themesDir: derivedPaths.environmentThemesDir,
203 };
204 });
205
206 /** Propagate read errors to avoid overwriting unread settings with a sparse file. */
207 const readSettingsObject = Effect.fn(function* (settingsPath: string) {
208 const fs = yield* FileSystem.FileSystem;
209 const exists = yield* fs
210 .exists(settingsPath)
211 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
212 if (!exists) return { raw: "", settings: {} };
213
214 const raw = yield* fs
215 .readFileString(settingsPath)
216 .pipe(Effect.mapError((cause) => new ThemeSettingsUnreadableError({ settingsPath, cause })));
217 if (raw.trim().length === 0) return { raw, settings: {} };
218
219 const settings = yield* decodeSettingsJson(raw).pipe(
220 Effect.mapError((cause) => new ThemeSettingsMalformedError({ settingsPath, cause })),
221 );
222 return { raw, settings };
223 });
224
225 /** The server's in-process semaphore cannot serialize writes from this process. */
226 const CONCURRENT_WRITE_ATTEMPTS = 5;
227
228 const writeDefaultTheme = Effect.fn(function* (input: {
229 readonly settingsPath: string;
230 readonly themeId: string;
231 }) {
232 const fs = yield* FileSystem.FileSystem;
233
234 for (let attempt = 1; ; attempt++) {
235 const { raw, settings } = yield* readSettingsObject(input.settingsPath);
236 const setAt = DateTime.formatIso(yield* DateTime.now);
237 const next =
238 input.themeId.length > 0
239 ? // The timestamp lets clients reapply the same theme.
240 { ...settings, defaultTheme: input.themeId, defaultThemeSetAt: setAt }
241 : Object.fromEntries(
242 Object.entries(settings).filter(
243 ([key]) => key !== "defaultTheme" && key !== "defaultThemeSetAt",
244 ),
245 );
246
247 const contents = yield* encodeSettingsJson(next);
248 const current = yield* fs
249 .readFileString(input.settingsPath)
250 .pipe(Effect.orElseSucceed(() => ""));
251 if (current !== raw) {
252 if (attempt >= CONCURRENT_WRITE_ATTEMPTS) {
253 return yield* new ThemeSettingsBusyError({
254 settingsPath: input.settingsPath,
255 attempts: CONCURRENT_WRITE_ATTEMPTS,
256 });
257 }
258 continue;
259 }
260
261 yield* writeFileStringAtomically({
262 filePath: input.settingsPath,
263 contents: `${contents}\n`,
264 }).pipe(
265 Effect.mapError(
266 (cause) => new ThemeSettingsWriteError({ settingsPath: input.settingsPath, cause }),
267 ),
268 );
269 return;
270 }
271 });
272
273 const publishThemeFile = Effect.fn(function* (input: {
274 readonly themesDir: string;
275 readonly filePath: string;
276 readonly explicitId: Option.Option<string>;
277 }) {
278 const fs = yield* FileSystem.FileSystem;
279 const path = yield* Path.Path;
280 const info = yield* fs
281 .stat(input.filePath)
282 .pipe(
283 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
284 );
285 if (info.type !== "File") {
286 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
287 }
288 if (Number(info.size) > MAX_THEME_FILE_BYTES) {
289 return yield* new ThemeFileTooLargeError({
290 filePath: input.filePath,
291 limit: MAX_THEME_FILE_BYTES,
292 });
293 }
294
295 const resolvedSource = yield* fs
296 .realPath(input.filePath)
297 .pipe(
298 Effect.mapError((cause) => new ThemeFileUnreadableError({ filePath: input.filePath, cause })),
299 );
300 const raw = readThemeFileGuarded(resolvedSource, MAX_THEME_FILE_BYTES);
301 if (raw === null) {
302 return yield* new ThemeFileUnreadableError({ filePath: input.filePath });
303 }
304
305 const decoded = decodeThemeFileJsonExit(raw);
306 if (decoded._tag === "Failure") {
307 return yield* new ThemeFileInvalidError({ filePath: input.filePath, cause: decoded.cause });
308 }
309 if (!environmentThemeFileHasColors(decoded.value)) {
310 return yield* new ThemeFileColorlessError({ filePath: input.filePath });
311 }
312
313 const fileBasename = path.basename(input.filePath, ".json");
314 const themeId = Option.getOrElse(input.explicitId, () => fileBasename);
315 // Match watcher validation so published files will not be skipped.
316 if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {
317 return yield* new ThemeFileIdInvalidError({ themeId, filePath: input.filePath });
318 }
319
320 const destinationPath = path.join(input.themesDir, `${themeId}.json`);
321 const stagingPath = `${destinationPath}.staging-${process.pid}`;
322 yield* fs
323 .makeDirectory(input.themesDir, { recursive: true })
324 .pipe(Effect.mapError((cause) => new ThemePublishError({ themesDir: input.themesDir, cause })));
325
326 const publishFailure = (cause: unknown) =>
327 new ThemePublishError({ themesDir: input.themesDir, cause });
328
329 const destinationIsDirectory = yield* Effect.try({
330 try: () => NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory() ?? false,
331 catch: publishFailure,
332 });
333 if (destinationIsDirectory) {
334 return yield* new ThemeDestinationDirectoryError({ themeId, destinationPath });
335 }
336
337 // O_EXCL prevents following a symlink at the predictable staging path.
338 // Preserve bytes exactly: even an added newline could exceed the watcher's size limit.
339 const stagedIno = yield* Effect.try({
340 try: () => {
341 try {
342 NodeFS.unlinkSync(stagingPath);
343 } catch {}
344 const fd = NodeFS.openSync(
345 stagingPath,
346 NodeFS.constants.O_WRONLY | NodeFS.constants.O_CREAT | NodeFS.constants.O_EXCL,
347 0o644,
348 );
349 try {
350 NodeFS.writeFileSync(fd, raw);
351 return NodeFS.fstatSync(fd).ino;
352 } finally {
353 NodeFS.closeSync(fd);
354 }
355 },
356 catch: publishFailure,
357 });
358
359 const backupPath = yield* Effect.try({
360 try: () => {
361 // A fresh path leaves any backup from a crashed publish intact.
362 const rollbackPath = `${destinationPath}.rollback-${NodeCrypto.randomUUID()}`;
363 // A rename onto a regular file rejects a directory even if it appeared after lstat.
364 const fd = NodeFS.openSync(rollbackPath, "wx", 0o600);
365 let saved = false;
366 try {
367 NodeFS.closeSync(fd);
368 NodeFS.renameSync(destinationPath, rollbackPath);
369 saved = true;
370 return rollbackPath;
371 } catch (error) {
372 if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
373 if (NodeFS.lstatSync(destinationPath, { throwIfNoEntry: false })?.isDirectory()) {
374 throw new ThemeDestinationDirectoryError({ themeId, destinationPath });
375 }
376 throw error;
377 } finally {
378 if (!saved) {
379 try {
380 NodeFS.unlinkSync(rollbackPath);
381 } catch {}
382 }
383 }
384 },
385 catch: (cause) => (isThemeDestinationDirectoryError(cause) ? cause : publishFailure(cause)),
386 }).pipe(
387 Effect.onError(() =>
388 Effect.sync(() => {
389 try {
390 NodeFS.unlinkSync(stagingPath);
391 } catch {}
392 }),
393 ),
394 );
395
396 const revert = Effect.sync(() => {
397 try {
398 NodeFS.unlinkSync(stagingPath);
399 } catch {}
400 try {
401 // Only replace this process's inode or an empty destination; concurrent publishers win.
402 const destinationIno = (() => {
403 try {
404 return NodeFS.lstatSync(destinationPath).ino;
405 } catch {
406 return null;
407 }
408 })();
409 if (backupPath !== null) {
410 if (destinationIno === null || destinationIno === stagedIno) {
411 NodeFS.renameSync(backupPath, destinationPath);
412 } else {
413 NodeFS.unlinkSync(backupPath);
414 }
415 } else if (destinationIno === stagedIno) {
416 NodeFS.unlinkSync(destinationPath);
417 }
418 } catch {}
419 });
420 const cleanup = Effect.sync(() => {
421 try {
422 if (backupPath !== null) NodeFS.unlinkSync(backupPath);
423 } catch {}
424 });
425
426 yield* Effect.try({
427 try: () => NodeFS.renameSync(stagingPath, destinationPath),
428 catch: publishFailure,
429 }).pipe(Effect.onError(() => revert));
430
431 return { themeId, revert, cleanup };
432 });
433
434 /** Web and desktop cannot resolve the mobile default, and mobile does not follow this setting. */
435 const resolvableThemeIds = Effect.fn(function* (themesDir: string) {
436 const published = yield* readPublishedThemes(themesDir);
437 return [...BUILT_IN_THEME_IDS, ...published.map((theme) => theme.id)].toSorted();
438 });
439
440 const themeSetCommand = Command.make("set", {
441 baseDir: baseDirFlag,
442 id: Flag.String("id").pipe(
443 Flag.withDescription("Theme id to publish a file under, instead of its filename."),
444 Flag.optional,
445 ),
446 theme: Argument.String("theme").pipe(
447 Argument.withDescription(
448 'A theme id (a built-in, or one this machine publishes, where themes/nightfall.json is "nightfall"), or a path to a theme JSON file to publish and set in one step.',
449 ),
450 ),
451 }).pipe(
452 Command.withDescription(
453 "Set the environment's theme. The web app this server serves and the desktop app on this machine switch to it; a desktop app connected from another machine does not.",
454 ),
455 Command.withHandler((flags) =>
456 Effect.gen(function* () {
457 const fs = yield* FileSystem.FileSystem;
458 const target = yield* expandHomePath(flags.theme.trim());
459 if (target.length === 0) {
460 return yield* new ThemeTargetMissingError();
461 }
462 const paths = yield* resolveThemePaths(flags.baseDir);
463
464 // A bare theme id must not publish a same-named file that happens to exist in cwd.
465 const looksLikePath =
466 target.endsWith(".json") ||
467 target.includes("/") ||
468 target.includes("\\") ||
469 target.startsWith("~");
470 const targetIsFile =
471 looksLikePath && (yield* fs.exists(target).pipe(Effect.orElseSucceed(() => false)));
472 let themeId: string;
473 let revertPublish: Effect.Effect<void> = Effect.void;
474 let cleanupPublish: Effect.Effect<void> = Effect.void;
475 if (targetIsFile) {
476 yield* readSettingsObject(paths.settingsPath);
477 const published = yield* publishThemeFile({
478 themesDir: paths.themesDir,
479 filePath: target,
480 explicitId: flags.id,
481 });
482 themeId = published.themeId;
483 revertPublish = published.revert;
484 cleanupPublish = published.cleanup;
485 } else if (looksLikePath) {
486 return yield* new ThemeFileUnreadableError({ filePath: target });
487 } else if (isEnvironmentThemeId(target)) {
488 const known = yield* resolvableThemeIds(paths.themesDir);
489 if (!known.includes(target)) {
490 return yield* new ThemeIdUnknownError({ themeId: target, known });
491 }
492 themeId = target;
493 } else {
494 return yield* new ThemeIdInvalidError({ themeId: target });
495 }
496
497 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId }).pipe(
498 Effect.onError(() => revertPublish),
499 );
500 yield* cleanupPublish;
501 yield* Console.log(
502 targetIsFile
503 ? `Published ${target} as "${themeId}" and set it as the environment theme.\n`
504 : `Environment theme set to "${themeId}" in ${paths.settingsPath}.\n`,
505 );
506 }),
507 ),
508 );
509
510 const themeClearCommand = Command.make("clear", { baseDir: baseDirFlag }).pipe(
511 Command.withDescription("Remove the environment's theme; clients keep what they have."),
512 Command.withHandler((flags) =>
513 Effect.gen(function* () {
514 const paths = yield* resolveThemePaths(flags.baseDir);
515 yield* writeDefaultTheme({ settingsPath: paths.settingsPath, themeId: "" });
516 yield* Console.log(`Environment theme cleared in ${paths.settingsPath}.\n`);
517 }),
518 ),
519 );
520
521 const themeShowCommand = Command.make("show", { baseDir: baseDirFlag }).pipe(
522 Command.withDescription("Show the environment's theme and its published themes."),
523 Command.withHandler((flags) =>
524 Effect.gen(function* () {
525 const paths = yield* resolveThemePaths(flags.baseDir);
526 const { settings } = yield* readSettingsObject(paths.settingsPath);
527 const defaultTheme =
528 typeof settings.defaultTheme === "string" && settings.defaultTheme.length > 0
529 ? settings.defaultTheme
530 : null;
531
532 const published = (yield* readPublishedThemes(paths.themesDir))
533 .map((theme) => theme.id)
534 .toSorted();
535
536 yield* Console.log(
537 defaultTheme === null
538 ? "Environment theme: not set.\n"
539 : `Environment theme: "${defaultTheme}".\n`,
540 );
541 yield* Console.log(
542 published.length === 0
543 ? `Published themes: none (publish into ${paths.themesDir}).\n`
544 : `Published themes: ${published.join(", ")}.\n`,
545 );
546 }),
547 ),
548 );
549
550 export const themeCommand = Command.make("theme").pipe(
551 Command.withDescription("Inspect and set environment-wide theme defaults."),
552 Command.withSubcommands([themeSetCommand, themeClearCommand, themeShowCommand]),
553 );