@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, 03:37 UTC

main
ts 543 lines 21.1 KB
Raw
1 import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentThemeFile,
4 ServerSettingsError,
5 THEME_CSS_MAX_LENGTH,
6 } from "@t3tools/contracts";
7 import * as NodeServices from "@effect/platform-node/NodeServices";
8 import * as HostProcess from "@t3tools/shared/HostProcess";
9 import { assert, describe, it } from "@effect/vitest";
10 import * as Effect from "effect/Effect";
11 import * as FileSystem from "effect/FileSystem";
12 import * as Layer from "effect/Layer";
13 import * as Path from "effect/Path";
14 import * as Queue from "effect/Queue";
15 import * as Schema from "effect/Schema";
16 import * as Scope from "effect/Scope";
17 import * as Stream from "effect/Stream";
18
19 import * as ServerConfig from "./config.ts";
20 import * as EnvironmentTheme from "./environmentTheme.ts";
21 import { ServerSettingsService } from "./serverSettings.ts";
22 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
23
24 const encodeThemeFile = Schema.encodeSync(Schema.fromJsonString(EnvironmentThemeFile));
25 /** Writes non-ASCII characters as `\uXXXX` escapes, as encoders such as Python's json.dumps do. */
26 const encodeThemeFileEscaped = (theme: EnvironmentThemeFile) =>
27 encodeThemeFile(theme).replace(
28 /[\u0080-\uffff]/g,
29 (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`,
30 );
31
32 const NIGHTFALL_THEME: EnvironmentThemeFile = {
33 name: "Nightfall",
34 appearance: "dark",
35 canvas: "#1a1b26",
36 accent: "#7aa2f7",
37 };
38
39 const SHARED_THEME: EnvironmentThemeFile = {
40 version: 1,
41 name: "Shared Light",
42 appearance: "light",
43 colors: { canvas: "#eff1f5", accent: "#1e66f5" },
44 };
45
46 /** The settings mock refuses to make this theme the default, as a managed policy can. */
47 const REFUSED_THEME_ID = "refused";
48
49 const withEnvironmentThemes = <A, E>(
50 seeds: Readonly<Record<string, string>>,
51 body: Effect.Effect<
52 A,
53 E,
54 | EnvironmentTheme.EnvironmentThemeService
55 | ServerConfig.ServerConfig
56 | FileSystem.FileSystem
57 | Path.Path
58 | Scope.Scope
59 >,
60 /** Receives each theme and appearance the service makes the environment default. */
61 selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [],
62 ) =>
63 Effect.gen(function* () {
64 const fs = yield* FileSystem.FileSystem;
65 const path = yield* Path.Path;
66 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-environment-theme-" });
67 const themesDir = path.join(baseDir, "userdata", "themes");
68 yield* fs.makeDirectory(themesDir, { recursive: true });
69 for (const [filename, contents] of Object.entries(seeds)) {
70 yield* fs.writeFileString(path.join(themesDir, filename), contents);
71 }
72
73 return yield* body.pipe(
74 Effect.provide(
75 EnvironmentTheme.layer.pipe(
76 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
77 Layer.provideMerge(
78 Layer.mock(ServerSettingsService)({
79 updateSettings: (patch) =>
80 patch.defaultTheme === REFUSED_THEME_ID
81 ? Effect.fail(
82 new ServerSettingsError({
83 settingsPath: "settings.json",
84 operation: "write-managed-setting",
85 }),
86 )
87 : Effect.sync(() => {
88 selected.push({
89 ...(patch.defaultTheme === undefined ? {} : { theme: patch.defaultTheme }),
90 ...(patch.defaultAppearance === undefined
91 ? {}
92 : { appearance: patch.defaultAppearance }),
93 });
94 return DEFAULT_SERVER_SETTINGS;
95 }),
96 }),
97 ),
98 ),
99 ),
100 );
101 }).pipe(Effect.provide(NodeServices.layer));
102
103 const currentThemes = Effect.gen(function* () {
104 const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
105 return yield* environmentTheme.current;
106 });
107
108 describe("environment theme", () => {
109 it.effect("follows the directory rather than the set read at start", () =>
110 withEnvironmentThemes(
111 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
112 Effect.gen(function* () {
113 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
114 const fs = yield* FileSystem.FileSystem;
115 const path = yield* Path.Path;
116
117 yield* fs.writeFileString(
118 path.join(environmentThemesDir, "shared-light.json"),
119 encodeThemeFile(SHARED_THEME),
120 );
121 assert.equal((yield* currentThemes).length, 2);
122
123 yield* fs.remove(path.join(environmentThemesDir, "nightfall.json"));
124 assert.deepEqual(
125 (yield* currentThemes).map((theme) => theme.id),
126 ["shared-light"],
127 );
128 }),
129 ),
130 );
131
132 it.effect("never replays a set older than the snapshot it started from", () =>
133 withEnvironmentThemes(
134 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
135 Effect.gen(function* () {
136 const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
137 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
138 const fs = yield* FileSystem.FileSystem;
139 const path = yield* Path.Path;
140
141 yield* fs.writeFileString(
142 path.join(environmentThemesDir, "shared-light.json"),
143 encodeThemeFile(SHARED_THEME),
144 );
145 const seen = yield* Queue.unbounded<ReadonlyArray<{ readonly id: string }>>();
146 yield* Stream.runForEach(environmentTheme.streamChanges, (themes) =>
147 Queue.offer(seen, themes),
148 ).pipe(Effect.forkScoped);
149 assert.deepEqual(
150 (yield* Queue.take(seen)).map((theme) => theme.id),
151 ["nightfall", "shared-light"],
152 );
153 yield* fs.remove(path.join(environmentThemesDir, "nightfall.json"));
154 yield* currentThemes;
155 assert.deepEqual(
156 (yield* Queue.take(seen)).map((theme) => theme.id),
157 ["shared-light"],
158 );
159 }),
160 ),
161 );
162
163 it.live("publishes restored themes to subscribers that saw the directory disappear", () =>
164 withEnvironmentThemes(
165 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
166 Effect.gen(function* () {
167 const service = yield* EnvironmentTheme.EnvironmentThemeService;
168 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
169 const fs = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 const restored = path.join(path.dirname(environmentThemesDir), "themes-restored");
172 yield* fs.makeDirectory(restored);
173 yield* fs.writeFileString(
174 path.join(restored, "shared-light.json"),
175 encodeThemeFile(SHARED_THEME),
176 );
177
178 const snapshots = yield* service.streamChanges.pipe(
179 Stream.map((themes) => themes.map((theme) => theme.name)),
180 Stream.toQueue({ capacity: "unbounded" }),
181 );
182 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
183
184 yield* fs.rename(
185 environmentThemesDir,
186 path.join(path.dirname(restored), "themes-previous"),
187 );
188 assert.deepEqual(yield* Queue.take(snapshots), []);
189
190 yield* fs.rename(restored, environmentThemesDir);
191 assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]);
192
193 yield* fs.writeFileString(
194 path.join(environmentThemesDir, "nightfall.json"),
195 encodeThemeFile(NIGHTFALL_THEME),
196 );
197 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
198 }),
199 ),
200 );
201
202 it.live.skipIf(!symlinksSupported)(
203 "publishes edits after the target of a symlinked themes directory is restored",
204 () =>
205 withEnvironmentThemes(
206 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
207 Effect.gen(function* () {
208 const service = yield* EnvironmentTheme.EnvironmentThemeService;
209 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
210 const fs = yield* FileSystem.FileSystem;
211 const path = yield* Path.Path;
212 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" });
213 const targetParent = path.join(outside, "active-parent");
214 const target = path.join(targetParent, "active");
215 const restored = path.join(outside, "restored");
216 yield* fs.makeDirectory(target, { recursive: true });
217 yield* fs.makeDirectory(restored);
218 let linkTarget = target;
219 if ((yield* HostProcess.Platform) !== "win32") {
220 const userdata = path.dirname(environmentThemesDir);
221 const anchor = path.join(targetParent, "anchor");
222 yield* fs.makeDirectory(anchor);
223 yield* fs.makeDirectory(path.join(userdata, "active"));
224 yield* fs.symlink(anchor, path.join(userdata, "alias"));
225 linkTarget = "alias/../active";
226 }
227 yield* fs.writeFileString(
228 path.join(target, "shared-light.json"),
229 encodeThemeFile(SHARED_THEME),
230 );
231 yield* fs.writeFileString(
232 path.join(restored, "nightfall.json"),
233 encodeThemeFile(NIGHTFALL_THEME),
234 );
235
236 const snapshots = yield* service.streamChanges.pipe(
237 Stream.map((themes) => themes.map((theme) => theme.name)),
238 Stream.toQueue({ capacity: "unbounded" }),
239 );
240 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
241
242 yield* fs.rename(environmentThemesDir, path.join(outside, "original"));
243 yield* fs.symlink(linkTarget, environmentThemesDir);
244 assert.deepEqual(
245 yield* Stream.fromQueue(snapshots).pipe(
246 Stream.filter((names) => names.length > 0),
247 Stream.runHead,
248 Effect.map((names) => names.valueOrUndefined),
249 ),
250 ["Shared Light"],
251 );
252
253 yield* fs.writeFileString(
254 path.join(target, "nightfall.json"),
255 encodeThemeFile(NIGHTFALL_THEME),
256 );
257 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
258
259 yield* fs.rename(target, path.join(outside, "previous"));
260 assert.deepEqual(yield* Queue.take(snapshots), []);
261 yield* fs.rename(restored, target);
262 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
263
264 yield* fs.writeFileString(
265 path.join(target, "shared-light.json"),
266 encodeThemeFile(SHARED_THEME),
267 );
268 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
269
270 const restoredParent = path.join(outside, "restored-parent");
271 const restoredTarget = path.join(restoredParent, "active");
272 yield* fs.makeDirectory(restoredTarget, { recursive: true });
273 yield* fs.makeDirectory(path.join(restoredParent, "anchor"));
274 yield* fs.writeFileString(
275 path.join(restoredTarget, "shared-light.json"),
276 encodeThemeFile(SHARED_THEME),
277 );
278
279 yield* fs.rename(targetParent, path.join(outside, "previous-parent"));
280 assert.deepEqual(yield* Queue.take(snapshots), []);
281 yield* fs.rename(restoredParent, targetParent);
282 assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]);
283
284 yield* fs.writeFileString(
285 path.join(target, "nightfall.json"),
286 encodeThemeFile(NIGHTFALL_THEME),
287 );
288 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
289 }),
290 ),
291 );
292
293 it.effect("skips invalid files while keeping valid ones", () =>
294 withEnvironmentThemes(
295 {
296 "nightfall.json": encodeThemeFile(NIGHTFALL_THEME),
297 "notepad.json": `\uFEFF${encodeThemeFile(SHARED_THEME)}`,
298 "unresolved.json":
299 '{ "name": "X", "appearance": "dark", "canvas": "{{ background }}", "accent": "#7aa2f7" }',
300 "malformed.json": "{ not json",
301 "no-colors.json": '{ "name": "Empty", "appearance": "dark" }',
302 "Bad Name.json": encodeThemeFile(SHARED_THEME),
303 "ocean.json": encodeThemeFile(SHARED_THEME),
304 "dark.json": encodeThemeFile(SHARED_THEME),
305 "notes.txt": "not a theme",
306 },
307 Effect.gen(function* () {
308 assert.deepEqual(
309 (yield* currentThemes).map((theme) => theme.id),
310 ["nightfall", "notepad"],
311 );
312 }),
313 ),
314 );
315
316 it.effect("puts the previous theme back when the new one cannot be selected", () =>
317 withEnvironmentThemes(
318 { [`${REFUSED_THEME_ID}.json`]: encodeThemeFile(NIGHTFALL_THEME) },
319 Effect.gen(function* () {
320 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
321 const refused = yield* themes
322 .apply({ themeId: REFUSED_THEME_ID, theme: { ...NIGHTFALL_THEME, name: "Changed" } })
323 .pipe(Effect.flip);
324 assert.strictEqual(refused._tag, "EnvironmentThemeNotSelectedError");
325 assert.deepEqual(yield* themes.current, [{ id: REFUSED_THEME_ID, ...NIGHTFALL_THEME }]);
326 }),
327 ),
328 );
329
330 it.effect("does not replace a theme file it could not put back", () => {
331 const oversized = JSON.stringify({
332 ...NIGHTFALL_THEME,
333 padding: "x".repeat(EnvironmentTheme.MAX_THEME_FILE_BYTES),
334 });
335 return withEnvironmentThemes(
336 { [`${REFUSED_THEME_ID}.json`]: oversized },
337 Effect.gen(function* () {
338 const fs = yield* FileSystem.FileSystem;
339 const config = yield* ServerConfig.ServerConfig;
340 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
341 const refused = yield* themes
342 .apply({ themeId: REFUSED_THEME_ID, theme: NIGHTFALL_THEME })
343 .pipe(Effect.flip);
344 assert.match(refused.message, /could not be backed up/);
345 assert.strictEqual(
346 yield* fs.readFileString(`${config.environmentThemesDir}/${REFUSED_THEME_ID}.json`),
347 oversized,
348 );
349 }),
350 );
351 });
352
353 it.effect.skipIf(!symlinksSupported)("does not write through a symlink at its staging path", () =>
354 withEnvironmentThemes(
355 {},
356 Effect.gen(function* () {
357 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
358 const fs = yield* FileSystem.FileSystem;
359 const path = yield* Path.Path;
360 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
361 const outside = path.join(environmentThemesDir, "..", "outside.txt");
362 yield* fs.writeFileString(outside, "keep");
363 yield* fs.symlink(
364 outside,
365 path.join(environmentThemesDir, `look.json.staging-${process.pid}`),
366 );
367
368 yield* themes.apply({ themeId: "look", theme: NIGHTFALL_THEME });
369 assert.strictEqual(yield* fs.readFileString(outside), "keep");
370 assert.deepEqual(yield* themes.current, [{ id: "look", ...NIGHTFALL_THEME }]);
371 }),
372 ),
373 );
374
375 it.effect.skipIf(!symlinksSupported)("ignores a symlinked theme file", () =>
376 withEnvironmentThemes(
377 {},
378 Effect.gen(function* () {
379 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
380 const fs = yield* FileSystem.FileSystem;
381 const path = yield* Path.Path;
382 const outside = path.join(environmentThemesDir, "..", "outside.json");
383 yield* fs.writeFileString(outside, encodeThemeFile(NIGHTFALL_THEME));
384 yield* fs.symlink(outside, path.join(environmentThemesDir, "nightfall.json"));
385 assert.deepEqual(yield* currentThemes, []);
386 }),
387 ),
388 );
389
390 it.effect("publishes and selects a theme, and refuses unsafe CSS and unknown ids", () => {
391 const selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [];
392 return withEnvironmentThemes(
393 {},
394 Effect.gen(function* () {
395 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
396 // A comment may name an address. Only a rule that loads one is refused.
397 const css =
398 "/* from url(https://example.com/guide) */ [data-chat-header] { border-bottom: 1px solid red; }";
399 yield* themes.apply({ themeId: "agent-look", theme: { ...NIGHTFALL_THEME, css } });
400 assert.deepEqual(yield* themes.current, [{ id: "agent-look", ...NIGHTFALL_THEME, css }]);
401
402 const leaky = yield* themes
403 .apply({
404 themeId: "leaky",
405 theme: {
406 ...NIGHTFALL_THEME,
407 css: 'input[value^="a"] { background: url(https://example.com/a); }',
408 },
409 })
410 .pipe(Effect.flip);
411 assert.match(leaky.message, /loads files/);
412 const reserved = yield* themes
413 .apply({ themeId: "dark", theme: NIGHTFALL_THEME })
414 .pipe(Effect.flip);
415 assert.match(reserved.message, /not a valid theme id/);
416 const unknown = yield* themes.apply({ themeId: "missing" }).pipe(Effect.flip);
417 assert.match(unknown.message, /not a built-in or published theme/);
418 yield* themes.apply({ themeId: "grove" });
419 yield* themes.apply({ themeId: "grove", appearance: "dark" });
420 yield* themes.apply({ appearance: "light" });
421
422 assert.deepEqual(
423 (yield* themes.current).map((theme) => theme.id),
424 ["agent-look"],
425 );
426 // Only a theme that was published or already exists becomes the environment theme.
427 assert.deepEqual(selected, [
428 { theme: "agent-look" },
429 { theme: "grove" },
430 { theme: "grove", appearance: "dark" },
431 { appearance: "light" },
432 ]);
433 }),
434 selected,
435 );
436 });
437
438 it.effect("switches back to the stock theme after selecting another", () => {
439 const selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [];
440 return withEnvironmentThemes(
441 {},
442 Effect.gen(function* () {
443 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
444 yield* themes.apply({ themeId: "agent-look", theme: NIGHTFALL_THEME });
445 yield* themes.apply({ themeId: "t3-code" });
446 assert.deepEqual(selected, [{ theme: "agent-look" }, { theme: "" }]);
447 }),
448 selected,
449 );
450 });
451
452 it.effect(
453 "reports the image beside a theme as its background, with a new revision per file",
454 () =>
455 withEnvironmentThemes(
456 { "look.json": encodeThemeFile(NIGHTFALL_THEME), "look.png": "first" },
457 Effect.gen(function* () {
458 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
459 const fs = yield* FileSystem.FileSystem;
460 const path = yield* Path.Path;
461 const background = Effect.map(currentThemes, (themes) => themes[0]?.background);
462 const image = path.join(environmentThemesDir, "look.png");
463
464 const first = yield* background;
465 assert.isDefined(first);
466 yield* fs.writeFileString(image, "a longer second image");
467 assert.notStrictEqual(yield* background, first);
468
469 yield* fs.remove(image);
470 assert.isUndefined(yield* background);
471 if (symlinksSupported) {
472 const outside = path.join(environmentThemesDir, "..", "outside.png");
473 yield* fs.writeFileString(outside, "outside");
474 yield* fs.symlink(outside, image);
475 assert.isUndefined(yield* background);
476 }
477 }),
478 ),
479 );
480
481 it.effect("keeps the served theme when an update does not fit the size limit", () => {
482 const large = (name: string): EnvironmentThemeFile => ({
483 ...NIGHTFALL_THEME,
484 name,
485 css: `/* ${"界".repeat(THEME_CSS_MAX_LENGTH - 6)} */`,
486 });
487 return withEnvironmentThemes(
488 {
489 ...Object.fromEntries(
490 Array.from({ length: 3 }, (_, index) => [
491 `aa-${index}.json`,
492 encodeThemeFileEscaped(large(`Large ${index}`)),
493 ]),
494 ),
495 "zz-look.json": encodeThemeFile(NIGHTFALL_THEME),
496 },
497 Effect.gen(function* () {
498 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
499 const served = Effect.map(themes.current, (all) =>
500 all.find((theme) => theme.id === "zz-look"),
501 );
502 assert.deepEqual(yield* served, { id: "zz-look", ...NIGHTFALL_THEME });
503
504 const refused = yield* themes
505 .apply({ themeId: "zz-look", theme: large("Too much") })
506 .pipe(Effect.flip);
507 assert.match(refused.message, /could not be published/);
508 assert.deepEqual(yield* served, { id: "zz-look", ...NIGHTFALL_THEME });
509
510 // A new theme that sorts first fits, and the last large one no longer does.
511 const before = (yield* themes.current).map((theme) => theme.id);
512 const displacing = yield* themes
513 .apply({ themeId: "a0-first", theme: large("Displacing") })
514 .pipe(Effect.flip);
515 assert.match(displacing.message, /could not be published/);
516 assert.deepEqual(
517 (yield* themes.current).map((theme) => theme.id),
518 before,
519 );
520 }),
521 );
522 });
523
524 it.effect("does not charge skipped files against the total size limit", () =>
525 withEnvironmentThemes(
526 {
527 ...Object.fromEntries(
528 Array.from({ length: 7 }, (_, index) => [
529 `junk-${index}.json`,
530 "{".repeat(EnvironmentTheme.MAX_THEME_FILE_BYTES),
531 ]),
532 ),
533 "zz-valid.json": encodeThemeFile(NIGHTFALL_THEME),
534 },
535 Effect.gen(function* () {
536 assert.deepEqual(
537 (yield* currentThemes).map((theme) => theme.id),
538 ["zz-valid"],
539 );
540 }),
541 ),
542 );
543 });