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

environmentTheme.test.ts

750 lines30.2 KB

1import {
2 DEFAULT_SERVER_SETTINGS,
3 EnvironmentThemeFile,
4 ServerSettingsError,
5 THEME_CSS_MAX_LENGTH,
6} from "@t3tools/contracts";
7import * as NodeServices from "@effect/platform-node/NodeServices";
8import * as HostProcess from "@t3tools/shared/HostProcess";
9import { assert, describe, it } from "@effect/vitest";
10import * as Deferred from "effect/Deferred";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as Path from "effect/Path";
15import * as Queue from "effect/Queue";
16import * as Schema from "effect/Schema";
17import * as Scope from "effect/Scope";
18import * as Stream from "effect/Stream";
19​
20import * as ServerConfig from "./config.ts";
21import * as EnvironmentTheme from "./environmentTheme.ts";
22import { ServerSettingsService } from "./serverSettings.ts";
23import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
24​
25const encodeThemeFile = Schema.encodeSync(Schema.fromJsonString(EnvironmentThemeFile));
26/** Writes non-ASCII characters as `\uXXXX` escapes, as encoders such as Python's json.dumps do. */
27const encodeThemeFileEscaped = (theme: EnvironmentThemeFile) =>
28 encodeThemeFile(theme).replace(
29 /[\u0080-\uffff]/g,
30 (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`,
31 );
32​
33const NIGHTFALL_THEME: EnvironmentThemeFile = {
34 name: "Nightfall",
35 appearance: "dark",
36 canvas: "#1a1b26",
37 accent: "#7aa2f7",
38};
39​
40const SHARED_THEME: EnvironmentThemeFile = {
41 version: 1,
42 name: "Shared Light",
43 appearance: "light",
44 colors: { canvas: "#eff1f5", accent: "#1e66f5" },
45};
46​
47/** The settings mock refuses to make this theme the default, as a managed policy can. */
48const REFUSED_THEME_ID = "refused";
49​
50const withEnvironmentThemes = <A, E>(
51 seeds: Readonly<Record<string, string>>,
52 body: Effect.Effect<
53 A,
54 E,
55 | EnvironmentTheme.EnvironmentThemeService
56 | ServerConfig.ServerConfig
57 | FileSystem.FileSystem
58 | Path.Path
59 | Scope.Scope
60 >,
61 options: {
62 /** Receives each theme and appearance the service makes the environment default. */
63 selected?: Array<{ readonly theme?: string; readonly appearance?: string }>;
64 wrapFileSystem?: (fs: FileSystem.FileSystem) => FileSystem.FileSystem;
65 } = {},
66) =>
67 Effect.gen(function* () {
68 const fs = yield* FileSystem.FileSystem;
69 const path = yield* Path.Path;
70 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-environment-theme-" });
71 const themesDir = path.join(baseDir, "userdata", "themes");
72 yield* fs.makeDirectory(themesDir, { recursive: true });
73 for (const [filename, contents] of Object.entries(seeds)) {
74 yield* fs.writeFileString(path.join(themesDir, filename), contents);
75 }
76​
77 return yield* body.pipe(
78 Effect.provide(
79 EnvironmentTheme.layer.pipe(
80 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
81 Layer.provideMerge(
82 Layer.mock(ServerSettingsService)({
83 updateSettings: (patch) =>
84 patch.defaultTheme === REFUSED_THEME_ID
85 ? Effect.fail(
86 new ServerSettingsError({
87 settingsPath: "settings.json",
88 operation: "write-managed-setting",
89 }),
90 )
91 : Effect.sync(() => {
92 options.selected?.push({
93 ...(patch.defaultTheme === undefined ? {} : { theme: patch.defaultTheme }),
94 ...(patch.defaultAppearance === undefined
95 ? {}
96 : { appearance: patch.defaultAppearance }),
97 });
98 return DEFAULT_SERVER_SETTINGS;
99 }),
100 }),
101 ),
102 Layer.provide(Layer.succeed(FileSystem.FileSystem, options.wrapFileSystem?.(fs) ?? fs)),
103 ),
104 ),
105 );
106 }).pipe(Effect.provide(NodeServices.layer));
107​
108const currentThemes = Effect.gen(function* () {
109 const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
110 return yield* environmentTheme.current;
111});
112​
113describe("environment theme", () => {
114 it.effect("follows the directory rather than the set read at start", () =>
115 withEnvironmentThemes(
116 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
117 Effect.gen(function* () {
118 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
119 const fs = yield* FileSystem.FileSystem;
120 const path = yield* Path.Path;
121​
122 yield* fs.writeFileString(
123 path.join(environmentThemesDir, "shared-light.json"),
124 encodeThemeFile(SHARED_THEME),
125 );
126 assert.equal((yield* currentThemes).length, 2);
127​
128 yield* fs.remove(path.join(environmentThemesDir, "nightfall.json"));
129 assert.deepEqual(
130 (yield* currentThemes).map((theme) => theme.id),
131 ["shared-light"],
132 );
133 }),
134 ),
135 );
136​
137 it.effect("never replays a set older than the snapshot it started from", () =>
138 withEnvironmentThemes(
139 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
140 Effect.gen(function* () {
141 const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
142 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
143 const fs = yield* FileSystem.FileSystem;
144 const path = yield* Path.Path;
145​
146 yield* fs.writeFileString(
147 path.join(environmentThemesDir, "shared-light.json"),
148 encodeThemeFile(SHARED_THEME),
149 );
150 const seen = yield* Queue.unbounded<ReadonlyArray<{ readonly id: string }>>();
151 yield* Stream.runForEach(environmentTheme.streamChanges, (themes) =>
152 Queue.offer(seen, themes),
153 ).pipe(Effect.forkScoped);
154 assert.deepEqual(
155 (yield* Queue.take(seen)).map((theme) => theme.id),
156 ["nightfall", "shared-light"],
157 );
158 yield* fs.remove(path.join(environmentThemesDir, "nightfall.json"));
159 yield* currentThemes;
160 assert.deepEqual(
161 (yield* Queue.take(seen)).map((theme) => theme.id),
162 ["shared-light"],
163 );
164 }),
165 ),
166 );
167​
168 it.live("publishes restored themes to subscribers that saw the directory disappear", () =>
169 withEnvironmentThemes(
170 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
171 Effect.gen(function* () {
172 const service = yield* EnvironmentTheme.EnvironmentThemeService;
173 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
174 const fs = yield* FileSystem.FileSystem;
175 const path = yield* Path.Path;
176 const restored = path.join(path.dirname(environmentThemesDir), "themes-restored");
177 yield* fs.makeDirectory(restored);
178 yield* fs.writeFileString(
179 path.join(restored, "shared-light.json"),
180 encodeThemeFile(SHARED_THEME),
181 );
182​
183 const snapshots = yield* service.streamChanges.pipe(
184 Stream.map((themes) => themes.map((theme) => theme.name)),
185 Stream.toQueue({ capacity: "unbounded" }),
186 );
187 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
188​
189 yield* fs.rename(
190 environmentThemesDir,
191 path.join(path.dirname(restored), "themes-previous"),
192 );
193 assert.deepEqual(yield* Queue.take(snapshots), []);
194​
195 yield* fs.rename(restored, environmentThemesDir);
196 assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]);
197​
198 yield* fs.writeFileString(
199 path.join(environmentThemesDir, "nightfall.json"),
200 encodeThemeFile(NIGHTFALL_THEME),
201 );
202 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
203 }),
204 ),
205 );
206​
207 it.live.skipIf(!symlinksSupported)(
208 "publishes edits after the target of a symlinked themes directory is restored",
209 () =>
210 withEnvironmentThemes(
211 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
212 Effect.gen(function* () {
213 const service = yield* EnvironmentTheme.EnvironmentThemeService;
214 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
215 const fs = yield* FileSystem.FileSystem;
216 const path = yield* Path.Path;
217 const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" });
218 const targetParent = path.join(outside, "active-parent");
219 const target = path.join(targetParent, "active");
220 const restored = path.join(outside, "restored");
221 yield* fs.makeDirectory(target, { recursive: true });
222 yield* fs.makeDirectory(restored);
223 let linkTarget = target;
224 if ((yield* HostProcess.Platform) !== "win32") {
225 const userdata = path.dirname(environmentThemesDir);
226 const anchor = path.join(targetParent, "anchor");
227 yield* fs.makeDirectory(anchor);
228 yield* fs.makeDirectory(path.join(userdata, "active"));
229 yield* fs.symlink(anchor, path.join(userdata, "alias"));
230 linkTarget = "alias/../active";
231 }
232 yield* fs.writeFileString(
233 path.join(target, "shared-light.json"),
234 encodeThemeFile(SHARED_THEME),
235 );
236 yield* fs.writeFileString(
237 path.join(restored, "nightfall.json"),
238 encodeThemeFile(NIGHTFALL_THEME),
239 );
240​
241 const snapshots = yield* service.streamChanges.pipe(
242 Stream.map((themes) => themes.map((theme) => theme.name)),
243 Stream.toQueue({ capacity: "unbounded" }),
244 );
245 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
246​
247 yield* fs.rename(environmentThemesDir, path.join(outside, "original"));
248 yield* fs.symlink(linkTarget, environmentThemesDir);
249 assert.deepEqual(
250 yield* Stream.fromQueue(snapshots).pipe(
251 Stream.filter((names) => names.length > 0),
252 Stream.runHead,
253 Effect.map((names) => names.valueOrUndefined),
254 ),
255 ["Shared Light"],
256 );
257​
258 yield* fs.writeFileString(
259 path.join(target, "nightfall.json"),
260 encodeThemeFile(NIGHTFALL_THEME),
261 );
262 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
263​
264 yield* fs.rename(target, path.join(outside, "previous"));
265 assert.deepEqual(yield* Queue.take(snapshots), []);
266 yield* fs.rename(restored, target);
267 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
268​
269 yield* fs.writeFileString(
270 path.join(target, "shared-light.json"),
271 encodeThemeFile(SHARED_THEME),
272 );
273 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
274​
275 const restoredParent = path.join(outside, "restored-parent");
276 const restoredTarget = path.join(restoredParent, "active");
277 yield* fs.makeDirectory(restoredTarget, { recursive: true });
278 yield* fs.makeDirectory(path.join(restoredParent, "anchor"));
279 yield* fs.writeFileString(
280 path.join(restoredTarget, "shared-light.json"),
281 encodeThemeFile(SHARED_THEME),
282 );
283​
284 yield* fs.rename(targetParent, path.join(outside, "previous-parent"));
285 assert.deepEqual(yield* Queue.take(snapshots), []);
286 yield* fs.rename(restoredParent, targetParent);
287 assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]);
288​
289 yield* fs.writeFileString(
290 path.join(target, "nightfall.json"),
291 encodeThemeFile(NIGHTFALL_THEME),
292 );
293 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
294 }),
295 ),
296 );
297​
298 it.live.skipIf(!symlinksSupported)(
299 "publishes later edits after a linked theme directory's grandparent is restored",
300 () =>
301 withEnvironmentThemes(
302 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
303 Effect.gen(function* () {
304 const service = yield* EnvironmentTheme.EnvironmentThemeService;
305 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
306 const fs = yield* FileSystem.FileSystem;
307 const path = yield* Path.Path;
308 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" });
309 const active = path.join(fixture, "active");
310 const restored = path.join(fixture, "restored");
311 const target = path.join(active, "shared", "themes");
312 const restoredTarget = path.join(restored, "shared", "themes");
313 for (const directory of [target, restoredTarget]) {
314 yield* fs.makeDirectory(directory, { recursive: true });
315 yield* fs.writeFileString(
316 path.join(directory, "shared-light.json"),
317 encodeThemeFile(SHARED_THEME),
318 );
319 }
320​
321 const snapshots = yield* service.streamChanges.pipe(
322 Stream.map((themes) => themes.map((theme) => theme.name)),
323 Stream.toQueue({ capacity: "unbounded" }),
324 );
325 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
326 yield* fs.rename(environmentThemesDir, path.join(fixture, "original"));
327 yield* fs.symlink(target, environmentThemesDir);
328 assert.deepEqual(
329 yield* Stream.fromQueue(snapshots).pipe(
330 Stream.filter((names) => names.length > 0),
331 Stream.runHead,
332 Effect.map((names) => names.valueOrUndefined),
333 ),
334 ["Shared Light"],
335 );
336​
337 yield* fs.rename(active, path.join(fixture, "active-previous"));
338 assert.deepEqual(yield* Queue.take(snapshots), []);
339 yield* fs.rename(restored, active);
340 assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]);
341​
342 yield* fs.writeFileString(
343 path.join(fixture, "active-previous", "shared", "themes", "nightfall.json"),
344 encodeThemeFile(NIGHTFALL_THEME),
345 );
346 yield* fs.writeFileString(
347 path.join(target, "shared-light.json"),
348 encodeThemeFile({ ...SHARED_THEME, name: "Edited Shared Light" }),
349 );
350 assert.deepEqual(yield* Queue.take(snapshots), ["Edited Shared Light"]);
351 }),
352 ),
353 );
354​
355 it.live.skipIf(!symlinksSupported)(
356 "publishes themes when a linked theme tree vanishes after listing and returns between probes",
357 () =>
358 Effect.gen(function* () {
359 const resumeProbes = yield* Deferred.make<void>();
360 let linkedEntry: string | undefined;
361 let moveAfterListing: Effect.Effect<void> | undefined;
362 let holdProbes = false;
363 yield* withEnvironmentThemes(
364 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
365 Effect.gen(function* () {
366 const service = yield* EnvironmentTheme.EnvironmentThemeService;
367 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
368 const fs = yield* FileSystem.FileSystem;
369 const path = yield* Path.Path;
370 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" });
371 const active = path.join(fixture, "active");
372 const previous = path.join(fixture, "previous");
373 const target = path.join(active, "shared", "themes");
374 yield* fs.makeDirectory(target, { recursive: true });
375 yield* fs.writeFileString(
376 path.join(target, "shared-light.json"),
377 encodeThemeFile(SHARED_THEME),
378 );
379​
380 const snapshots = yield* service.streamChanges.pipe(
381 Stream.map((themes) => themes.map((theme) => theme.name)),
382 Stream.toQueue({ capacity: "unbounded" }),
383 );
384 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
385 linkedEntry = environmentThemesDir;
386 yield* fs.rename(environmentThemesDir, path.join(fixture, "original"));
387 yield* fs.symlink(target, environmentThemesDir);
388 assert.deepEqual(
389 (yield* Stream.fromQueue(snapshots).pipe(
390 Stream.filter((names) => names.length > 0),
391 Stream.runHead,
392 )).valueOrUndefined,
393 ["Shared Light"],
394 );
395​
396 // The next listing succeeds, then the tree moves before its files are opened.
397 moveAfterListing = Effect.orDie(fs.rename(active, previous));
398 holdProbes = true;
399 yield* fs.writeFileString(
400 path.join(target, "nightfall.json"),
401 encodeThemeFile(NIGHTFALL_THEME),
402 );
403 assert.deepEqual(yield* Queue.take(snapshots), []);
404 yield* fs.rename(previous, active);
405 yield* Deferred.succeed(resumeProbes, undefined);
406 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
407 }),
408 {
409 wrapFileSystem: (fs) =>
410 FileSystem.FileSystem.of({
411 ...fs,
412 readDirectory: (directory, options) =>
413 fs.readDirectory(directory, options).pipe(
414 Effect.tap(() => {
415 const move = directory === linkedEntry ? moveAfterListing : undefined;
416 if (move === undefined) return Effect.void;
417 moveAfterListing = undefined;
418 return move;
419 }),
420 ),
421 stat: (entry) =>
422 Effect.suspend(() =>
423 entry === linkedEntry && holdProbes
424 ? Deferred.await(resumeProbes).pipe(Effect.andThen(fs.stat(entry)))
425 : fs.stat(entry),
426 ),
427 }),
428 },
429 );
430 }),
431 );
432​
433 it.live.skipIf(!symlinksSupported)(
434 "publishes themes when a linked theme directory's original grandparent is restored between probes",
435 () =>
436 Effect.gen(function* () {
437 const resumeProbes = yield* Deferred.make<void>();
438 let linkedEntry: string | undefined;
439 let holdProbes = false;
440 yield* withEnvironmentThemes(
441 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
442 Effect.gen(function* () {
443 const service = yield* EnvironmentTheme.EnvironmentThemeService;
444 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
445 const fs = yield* FileSystem.FileSystem;
446 const path = yield* Path.Path;
447 const fixture = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" });
448 const active = path.join(fixture, "active");
449 const previous = path.join(fixture, "previous");
450 const target = path.join(active, "shared", "themes");
451 yield* fs.makeDirectory(target, { recursive: true });
452 yield* fs.writeFileString(
453 path.join(target, "shared-light.json"),
454 encodeThemeFile(SHARED_THEME),
455 );
456​
457 const snapshots = yield* service.streamChanges.pipe(
458 Stream.map((themes) => themes.map((theme) => theme.name)),
459 Stream.toQueue({ capacity: "unbounded" }),
460 );
461 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
462 linkedEntry = environmentThemesDir;
463 yield* fs.rename(environmentThemesDir, path.join(fixture, "original"));
464 yield* fs.symlink(target, environmentThemesDir);
465 assert.deepEqual(
466 (yield* Stream.fromQueue(snapshots).pipe(
467 Stream.filter((names) => names.length > 0),
468 Stream.runHead,
469 )).valueOrUndefined,
470 ["Shared Light"],
471 );
472​
473 holdProbes = true;
474 yield* fs.rename(active, previous);
475 yield* fs.writeFileString(
476 path.join(previous, "shared", "themes", "nightfall.json"),
477 encodeThemeFile(NIGHTFALL_THEME),
478 );
479 assert.deepEqual(yield* Queue.take(snapshots), []);
480 yield* fs.rename(previous, active);
481 yield* Deferred.succeed(resumeProbes, undefined);
482 assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
483 }),
484 {
485 wrapFileSystem: (fs) =>
486 FileSystem.FileSystem.of({
487 ...fs,
488 stat: (entry) =>
489 Effect.suspend(() =>
490 entry === linkedEntry && holdProbes
491 ? Deferred.await(resumeProbes).pipe(Effect.andThen(fs.stat(entry)))
492 : fs.stat(entry),
493 ),
494 }),
495 },
496 );
497 }),
498 );
499​
500 it.effect("skips invalid files while keeping valid ones", () =>
501 withEnvironmentThemes(
502 {
503 "nightfall.json": encodeThemeFile(NIGHTFALL_THEME),
504 "notepad.json": `\uFEFF${encodeThemeFile(SHARED_THEME)}`,
505 "unresolved.json":
506 '{ "name": "X", "appearance": "dark", "canvas": "{{ background }}", "accent": "#7aa2f7" }',
507 "malformed.json": "{ not json",
508 "no-colors.json": '{ "name": "Empty", "appearance": "dark" }',
509 "Bad Name.json": encodeThemeFile(SHARED_THEME),
510 "ocean.json": encodeThemeFile(SHARED_THEME),
511 "dark.json": encodeThemeFile(SHARED_THEME),
512 "notes.txt": "not a theme",
513 },
514 Effect.gen(function* () {
515 assert.deepEqual(
516 (yield* currentThemes).map((theme) => theme.id),
517 ["nightfall", "notepad"],
518 );
519 }),
520 ),
521 );
522​
523 it.effect("puts the previous theme back when the new one cannot be selected", () =>
524 withEnvironmentThemes(
525 { [`${REFUSED_THEME_ID}.json`]: encodeThemeFile(NIGHTFALL_THEME) },
526 Effect.gen(function* () {
527 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
528 const refused = yield* themes
529 .apply({ themeId: REFUSED_THEME_ID, theme: { ...NIGHTFALL_THEME, name: "Changed" } })
530 .pipe(Effect.flip);
531 assert.strictEqual(refused._tag, "EnvironmentThemeNotSelectedError");
532 assert.deepEqual(yield* themes.current, [{ id: REFUSED_THEME_ID, ...NIGHTFALL_THEME }]);
533 }),
534 ),
535 );
536​
537 it.effect("does not replace a theme file it could not put back", () => {
538 const oversized = JSON.stringify({
539 ...NIGHTFALL_THEME,
540 padding: "x".repeat(EnvironmentTheme.MAX_THEME_FILE_BYTES),
541 });
542 return withEnvironmentThemes(
543 { [`${REFUSED_THEME_ID}.json`]: oversized },
544 Effect.gen(function* () {
545 const fs = yield* FileSystem.FileSystem;
546 const config = yield* ServerConfig.ServerConfig;
547 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
548 const refused = yield* themes
549 .apply({ themeId: REFUSED_THEME_ID, theme: NIGHTFALL_THEME })
550 .pipe(Effect.flip);
551 assert.match(refused.message, /could not be backed up/);
552 assert.strictEqual(
553 yield* fs.readFileString(`${config.environmentThemesDir}/${REFUSED_THEME_ID}.json`),
554 oversized,
555 );
556 }),
557 );
558 });
559​
560 it.effect.skipIf(!symlinksSupported)("does not write through a symlink at its staging path", () =>
561 withEnvironmentThemes(
562 {},
563 Effect.gen(function* () {
564 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
565 const fs = yield* FileSystem.FileSystem;
566 const path = yield* Path.Path;
567 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
568 const outside = path.join(environmentThemesDir, "..", "outside.txt");
569 yield* fs.writeFileString(outside, "keep");
570 yield* fs.symlink(
571 outside,
572 path.join(environmentThemesDir, `look.json.staging-${process.pid}`),
573 );
574​
575 yield* themes.apply({ themeId: "look", theme: NIGHTFALL_THEME });
576 assert.strictEqual(yield* fs.readFileString(outside), "keep");
577 assert.deepEqual(yield* themes.current, [{ id: "look", ...NIGHTFALL_THEME }]);
578 }),
579 ),
580 );
581​
582 it.effect.skipIf(!symlinksSupported)("ignores a symlinked theme file", () =>
583 withEnvironmentThemes(
584 {},
585 Effect.gen(function* () {
586 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
587 const fs = yield* FileSystem.FileSystem;
588 const path = yield* Path.Path;
589 const outside = path.join(environmentThemesDir, "..", "outside.json");
590 yield* fs.writeFileString(outside, encodeThemeFile(NIGHTFALL_THEME));
591 yield* fs.symlink(outside, path.join(environmentThemesDir, "nightfall.json"));
592 assert.deepEqual(yield* currentThemes, []);
593 }),
594 ),
595 );
596​
597 it.effect("publishes and selects a theme, and refuses unsafe CSS and unknown ids", () => {
598 const selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [];
599 return withEnvironmentThemes(
600 {},
601 Effect.gen(function* () {
602 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
603 // A comment may name an address. Only a rule that loads one is refused.
604 const css =
605 "/* from url(https://example.com/guide) */ [data-chat-header] { border-bottom: 1px solid red; }";
606 yield* themes.apply({ themeId: "agent-look", theme: { ...NIGHTFALL_THEME, css } });
607 assert.deepEqual(yield* themes.current, [{ id: "agent-look", ...NIGHTFALL_THEME, css }]);
608​
609 const leaky = yield* themes
610 .apply({
611 themeId: "leaky",
612 theme: {
613 ...NIGHTFALL_THEME,
614 css: 'input[value^="a"] { background: url(https://example.com/a); }',
615 },
616 })
617 .pipe(Effect.flip);
618 assert.match(leaky.message, /loads files/);
619 const reserved = yield* themes
620 .apply({ themeId: "dark", theme: NIGHTFALL_THEME })
621 .pipe(Effect.flip);
622 assert.match(reserved.message, /not a valid theme id/);
623 const unknown = yield* themes.apply({ themeId: "missing" }).pipe(Effect.flip);
624 assert.match(unknown.message, /not a built-in or published theme/);
625 yield* themes.apply({ themeId: "grove" });
626 yield* themes.apply({ themeId: "grove", appearance: "dark" });
627 yield* themes.apply({ appearance: "light" });
628​
629 assert.deepEqual(
630 (yield* themes.current).map((theme) => theme.id),
631 ["agent-look"],
632 );
633 // Only a theme that was published or already exists becomes the environment theme.
634 assert.deepEqual(selected, [
635 { theme: "agent-look" },
636 { theme: "grove" },
637 { theme: "grove", appearance: "dark" },
638 { appearance: "light" },
639 ]);
640 }),
641 { selected },
642 );
643 });
644​
645 it.effect("switches back to the stock theme after selecting another", () => {
646 const selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [];
647 return withEnvironmentThemes(
648 {},
649 Effect.gen(function* () {
650 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
651 yield* themes.apply({ themeId: "agent-look", theme: NIGHTFALL_THEME });
652 yield* themes.apply({ themeId: "t3-code" });
653 assert.deepEqual(selected, [{ theme: "agent-look" }, { theme: "" }]);
654 }),
655 { selected },
656 );
657 });
658​
659 it.effect(
660 "reports the image beside a theme as its background, with a new revision per file",
661 () =>
662 withEnvironmentThemes(
663 { "look.json": encodeThemeFile(NIGHTFALL_THEME), "look.png": "first" },
664 Effect.gen(function* () {
665 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
666 const fs = yield* FileSystem.FileSystem;
667 const path = yield* Path.Path;
668 const background = Effect.map(currentThemes, (themes) => themes[0]?.background);
669 const image = path.join(environmentThemesDir, "look.png");
670​
671 const first = yield* background;
672 assert.isDefined(first);
673 yield* fs.writeFileString(image, "a longer second image");
674 assert.notStrictEqual(yield* background, first);
675​
676 yield* fs.remove(image);
677 assert.isUndefined(yield* background);
678 if (symlinksSupported) {
679 const outside = path.join(environmentThemesDir, "..", "outside.png");
680 yield* fs.writeFileString(outside, "outside");
681 yield* fs.symlink(outside, image);
682 assert.isUndefined(yield* background);
683 }
684 }),
685 ),
686 );
687​
688 it.effect("keeps the served theme when an update does not fit the size limit", () => {
689 const large = (name: string): EnvironmentThemeFile => ({
690 ...NIGHTFALL_THEME,
691 name,
692 css: `/* ${"界".repeat(THEME_CSS_MAX_LENGTH - 6)} */`,
693 });
694 return withEnvironmentThemes(
695 {
696 ...Object.fromEntries(
697 Array.from({ length: 3 }, (_, index) => [
698 `aa-${index}.json`,
699 encodeThemeFileEscaped(large(`Large ${index}`)),
700 ]),
701 ),
702 "zz-look.json": encodeThemeFile(NIGHTFALL_THEME),
703 },
704 Effect.gen(function* () {
705 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
706 const served = Effect.map(themes.current, (all) =>
707 all.find((theme) => theme.id === "zz-look"),
708 );
709 assert.deepEqual(yield* served, { id: "zz-look", ...NIGHTFALL_THEME });
710​
711 const refused = yield* themes
712 .apply({ themeId: "zz-look", theme: large("Too much") })
713 .pipe(Effect.flip);
714 assert.match(refused.message, /could not be published/);
715 assert.deepEqual(yield* served, { id: "zz-look", ...NIGHTFALL_THEME });
716​
717 // A new theme that sorts first fits, and the last large one no longer does.
718 const before = (yield* themes.current).map((theme) => theme.id);
719 const displacing = yield* themes
720 .apply({ themeId: "a0-first", theme: large("Displacing") })
721 .pipe(Effect.flip);
722 assert.match(displacing.message, /could not be published/);
723 assert.deepEqual(
724 (yield* themes.current).map((theme) => theme.id),
725 before,
726 );
727 }),
728 );
729 });
730​
731 it.effect("does not charge skipped files against the total size limit", () =>
732 withEnvironmentThemes(
733 {
734 ...Object.fromEntries(
735 Array.from({ length: 7 }, (_, index) => [
736 `junk-${index}.json`,
737 "{".repeat(EnvironmentTheme.MAX_THEME_FILE_BYTES),
738 ]),
739 ),
740 "zz-valid.json": encodeThemeFile(NIGHTFALL_THEME),
741 },
742 Effect.gen(function* () {
743 assert.deepEqual(
744 (yield* currentThemes).map((theme) => theme.id),
745 ["zz-valid"],
746 );
747 }),
748 ),
749 );
750});