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

environmentTheme.test.ts

369 lines13.8 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 { assert, it } from "@effect/vitest";
9import * as Effect from "effect/Effect";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Queue from "effect/Queue";
14import * as Schema from "effect/Schema";
15import * as Scope from "effect/Scope";
16import * as Stream from "effect/Stream";
17​
18import * as ServerConfig from "./config.ts";
19import * as EnvironmentTheme from "./environmentTheme.ts";
20import { ServerSettingsService } from "./serverSettings.ts";
21import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
22​
23const encodeThemeFile = Schema.encodeSync(Schema.fromJsonString(EnvironmentThemeFile));
24/** Writes non-ASCII characters as `\uXXXX` escapes, as encoders such as Python's json.dumps do. */
25const encodeThemeFileEscaped = (theme: EnvironmentThemeFile) =>
26 encodeThemeFile(theme).replace(
27 /[\u0080-\uffff]/g,
28 (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`,
29 );
30​
31const NIGHTFALL_THEME: EnvironmentThemeFile = {
32 name: "Nightfall",
33 appearance: "dark",
34 canvas: "#1a1b26",
35 accent: "#7aa2f7",
36};
37​
38const SHARED_THEME: EnvironmentThemeFile = {
39 version: 1,
40 name: "Shared Light",
41 appearance: "light",
42 colors: { canvas: "#eff1f5", accent: "#1e66f5" },
43};
44​
45/** The settings mock refuses to make this theme the default, as a managed policy can. */
46const REFUSED_THEME_ID = "refused";
47​
48const withEnvironmentThemes = <A, E>(
49 seeds: Readonly<Record<string, string>>,
50 body: Effect.Effect<
51 A,
52 E,
53 | EnvironmentTheme.EnvironmentThemeService
54 | ServerConfig.ServerConfig
55 | FileSystem.FileSystem
56 | Path.Path
57 | Scope.Scope
58 >,
59 /** Receives each theme and appearance the service makes the environment default. */
60 selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [],
61) =>
62 Effect.gen(function* () {
63 const fs = yield* FileSystem.FileSystem;
64 const path = yield* Path.Path;
65 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-environment-theme-" });
66 const themesDir = path.join(baseDir, "userdata", "themes");
67 yield* fs.makeDirectory(themesDir, { recursive: true });
68 for (const [filename, contents] of Object.entries(seeds)) {
69 yield* fs.writeFileString(path.join(themesDir, filename), contents);
70 }
71​
72 return yield* body.pipe(
73 Effect.provide(
74 EnvironmentTheme.layer.pipe(
75 Layer.provideMerge(ServerConfig.layerTest(process.cwd(), baseDir)),
76 Layer.provideMerge(
77 Layer.mock(ServerSettingsService)({
78 updateSettings: (patch) =>
79 patch.defaultTheme === REFUSED_THEME_ID
80 ? Effect.fail(
81 new ServerSettingsError({
82 settingsPath: "settings.json",
83 operation: "write-managed-setting",
84 }),
85 )
86 : Effect.sync(() => {
87 selected.push({
88 ...(patch.defaultTheme === undefined ? {} : { theme: patch.defaultTheme }),
89 ...(patch.defaultAppearance === undefined
90 ? {}
91 : { appearance: patch.defaultAppearance }),
92 });
93 return DEFAULT_SERVER_SETTINGS;
94 }),
95 }),
96 ),
97 ),
98 ),
99 );
100 });
101​
102const currentThemes = Effect.gen(function* () {
103 const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
104 return yield* environmentTheme.current;
105});
106​
107it.layer(NodeServices.layer)("environment theme", (it) => {
108 it.effect("follows the directory rather than the set read at start", () =>
109 withEnvironmentThemes(
110 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
111 Effect.gen(function* () {
112 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
113 const fs = yield* FileSystem.FileSystem;
114 const path = yield* Path.Path;
115​
116 yield* fs.writeFileString(
117 path.join(environmentThemesDir, "shared-light.json"),
118 encodeThemeFile(SHARED_THEME),
119 );
120 assert.equal((yield* currentThemes).length, 2);
121​
122 yield* fs.remove(path.join(environmentThemesDir, "nightfall.json"));
123 assert.deepEqual(
124 (yield* currentThemes).map((theme) => theme.id),
125 ["shared-light"],
126 );
127 }),
128 ),
129 );
130​
131 it.effect("never replays a set older than the snapshot it started from", () =>
132 withEnvironmentThemes(
133 { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
134 Effect.gen(function* () {
135 const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
136 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
137 const fs = yield* FileSystem.FileSystem;
138 const path = yield* Path.Path;
139​
140 yield* fs.writeFileString(
141 path.join(environmentThemesDir, "shared-light.json"),
142 encodeThemeFile(SHARED_THEME),
143 );
144 const seen = yield* Queue.unbounded<ReadonlyArray<{ readonly id: string }>>();
145 yield* Stream.runForEach(environmentTheme.streamChanges, (themes) =>
146 Queue.offer(seen, themes),
147 ).pipe(Effect.forkScoped);
148 assert.deepEqual(
149 (yield* Queue.take(seen)).map((theme) => theme.id),
150 ["nightfall", "shared-light"],
151 );
152 yield* fs.remove(path.join(environmentThemesDir, "nightfall.json"));
153 yield* currentThemes;
154 assert.deepEqual(
155 (yield* Queue.take(seen)).map((theme) => theme.id),
156 ["shared-light"],
157 );
158 }),
159 ),
160 );
161​
162 it.effect("skips invalid files while keeping valid ones", () =>
163 withEnvironmentThemes(
164 {
165 "nightfall.json": encodeThemeFile(NIGHTFALL_THEME),
166 "notepad.json": `\uFEFF${encodeThemeFile(SHARED_THEME)}`,
167 "unresolved.json":
168 '{ "name": "X", "appearance": "dark", "canvas": "{{ background }}", "accent": "#7aa2f7" }',
169 "malformed.json": "{ not json",
170 "no-colors.json": '{ "name": "Empty", "appearance": "dark" }',
171 "Bad Name.json": encodeThemeFile(SHARED_THEME),
172 "ocean.json": encodeThemeFile(SHARED_THEME),
173 "dark.json": encodeThemeFile(SHARED_THEME),
174 "notes.txt": "not a theme",
175 },
176 Effect.gen(function* () {
177 assert.deepEqual(
178 (yield* currentThemes).map((theme) => theme.id),
179 ["nightfall", "notepad"],
180 );
181 }),
182 ),
183 );
184​
185 it.effect("puts the previous theme back when the new one cannot be selected", () =>
186 withEnvironmentThemes(
187 { [`${REFUSED_THEME_ID}.json`]: encodeThemeFile(NIGHTFALL_THEME) },
188 Effect.gen(function* () {
189 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
190 const refused = yield* themes
191 .apply({ themeId: REFUSED_THEME_ID, theme: { ...NIGHTFALL_THEME, name: "Changed" } })
192 .pipe(Effect.flip);
193 assert.strictEqual(refused._tag, "EnvironmentThemeNotSelectedError");
194 assert.deepEqual(yield* themes.current, [{ id: REFUSED_THEME_ID, ...NIGHTFALL_THEME }]);
195 }),
196 ),
197 );
198​
199 it.effect("does not replace a theme file it could not put back", () => {
200 const oversized = JSON.stringify({
201 ...NIGHTFALL_THEME,
202 padding: "x".repeat(EnvironmentTheme.MAX_THEME_FILE_BYTES),
203 });
204 return withEnvironmentThemes(
205 { [`${REFUSED_THEME_ID}.json`]: oversized },
206 Effect.gen(function* () {
207 const fs = yield* FileSystem.FileSystem;
208 const config = yield* ServerConfig.ServerConfig;
209 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
210 const refused = yield* themes
211 .apply({ themeId: REFUSED_THEME_ID, theme: NIGHTFALL_THEME })
212 .pipe(Effect.flip);
213 assert.match(refused.message, /could not be backed up/);
214 assert.strictEqual(
215 yield* fs.readFileString(`${config.environmentThemesDir}/${REFUSED_THEME_ID}.json`),
216 oversized,
217 );
218 }),
219 );
220 });
221​
222 it.effect.skipIf(!symlinksSupported)("does not write through a symlink at its staging path", () =>
223 withEnvironmentThemes(
224 {},
225 Effect.gen(function* () {
226 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
227 const fs = yield* FileSystem.FileSystem;
228 const path = yield* Path.Path;
229 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
230 const outside = path.join(environmentThemesDir, "..", "outside.txt");
231 yield* fs.writeFileString(outside, "keep");
232 yield* fs.symlink(
233 outside,
234 path.join(environmentThemesDir, `look.json.staging-${process.pid}`),
235 );
236​
237 yield* themes.apply({ themeId: "look", theme: NIGHTFALL_THEME });
238 assert.strictEqual(yield* fs.readFileString(outside), "keep");
239 assert.deepEqual(yield* themes.current, [{ id: "look", ...NIGHTFALL_THEME }]);
240 }),
241 ),
242 );
243​
244 it.effect.skipIf(!symlinksSupported)("ignores a symlinked theme file", () =>
245 withEnvironmentThemes(
246 {},
247 Effect.gen(function* () {
248 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
249 const fs = yield* FileSystem.FileSystem;
250 const path = yield* Path.Path;
251 const outside = path.join(environmentThemesDir, "..", "outside.json");
252 yield* fs.writeFileString(outside, encodeThemeFile(NIGHTFALL_THEME));
253 yield* fs.symlink(outside, path.join(environmentThemesDir, "nightfall.json"));
254 assert.deepEqual(yield* currentThemes, []);
255 }),
256 ),
257 );
258​
259 it.effect("publishes and selects a theme, and refuses unsafe CSS and unknown ids", () => {
260 const selected: Array<{ readonly theme?: string; readonly appearance?: string }> = [];
261 return withEnvironmentThemes(
262 {},
263 Effect.gen(function* () {
264 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
265 // A comment may name an address. Only a rule that loads one is refused.
266 const css =
267 "/* from url(https://example.com/guide) */ [data-chat-header] { border-bottom: 1px solid red; }";
268 yield* themes.apply({ themeId: "agent-look", theme: { ...NIGHTFALL_THEME, css } });
269 assert.deepEqual(yield* themes.current, [{ id: "agent-look", ...NIGHTFALL_THEME, css }]);
270​
271 const leaky = yield* themes
272 .apply({
273 themeId: "leaky",
274 theme: {
275 ...NIGHTFALL_THEME,
276 css: 'input[value^="a"] { background: url(https://example.com/a); }',
277 },
278 })
279 .pipe(Effect.flip);
280 assert.match(leaky.message, /loads files/);
281 const reserved = yield* themes
282 .apply({ themeId: "dark", theme: NIGHTFALL_THEME })
283 .pipe(Effect.flip);
284 assert.match(reserved.message, /not a valid theme id/);
285 const unknown = yield* themes.apply({ themeId: "missing" }).pipe(Effect.flip);
286 assert.match(unknown.message, /not a built-in or published theme/);
287 yield* themes.apply({ themeId: "grove" });
288 yield* themes.apply({ themeId: "grove", appearance: "dark" });
289 yield* themes.apply({ appearance: "light" });
290​
291 assert.deepEqual(
292 (yield* themes.current).map((theme) => theme.id),
293 ["agent-look"],
294 );
295 // Only a theme that was published or already exists becomes the environment theme.
296 assert.deepEqual(selected, [
297 { theme: "agent-look" },
298 { theme: "grove" },
299 { theme: "grove", appearance: "dark" },
300 { appearance: "light" },
301 ]);
302 }),
303 selected,
304 );
305 });
306​
307 it.effect("keeps the served theme when an update does not fit the size limit", () => {
308 const large = (name: string): EnvironmentThemeFile => ({
309 ...NIGHTFALL_THEME,
310 name,
311 css: `/* ${"界".repeat(THEME_CSS_MAX_LENGTH - 6)} */`,
312 });
313 return withEnvironmentThemes(
314 {
315 ...Object.fromEntries(
316 Array.from({ length: 6 }, (_, index) => [
317 `aa-${index}.json`,
318 encodeThemeFileEscaped(large(`Large ${index}`)),
319 ]),
320 ),
321 "zz-look.json": encodeThemeFile(NIGHTFALL_THEME),
322 },
323 Effect.gen(function* () {
324 const themes = yield* EnvironmentTheme.EnvironmentThemeService;
325 const served = Effect.map(themes.current, (all) =>
326 all.find((theme) => theme.id === "zz-look"),
327 );
328 assert.deepEqual(yield* served, { id: "zz-look", ...NIGHTFALL_THEME });
329​
330 const refused = yield* themes
331 .apply({ themeId: "zz-look", theme: large("Too much") })
332 .pipe(Effect.flip);
333 assert.match(refused.message, /could not be published/);
334 assert.deepEqual(yield* served, { id: "zz-look", ...NIGHTFALL_THEME });
335​
336 // A new theme that sorts first fits, and the last large one no longer does.
337 const before = (yield* themes.current).map((theme) => theme.id);
338 const displacing = yield* themes
339 .apply({ themeId: "a0-first", theme: large("Displacing") })
340 .pipe(Effect.flip);
341 assert.match(displacing.message, /could not be published/);
342 assert.deepEqual(
343 (yield* themes.current).map((theme) => theme.id),
344 before,
345 );
346 }),
347 );
348 });
349​
350 it.effect("does not charge skipped files against the total size limit", () =>
351 withEnvironmentThemes(
352 {
353 ...Object.fromEntries(
354 Array.from({ length: 7 }, (_, index) => [
355 `junk-${index}.json`,
356 "{".repeat(EnvironmentTheme.MAX_THEME_FILE_BYTES),
357 ]),
358 ),
359 "zz-valid.json": encodeThemeFile(NIGHTFALL_THEME),
360 },
361 Effect.gen(function* () {
362 assert.deepEqual(
363 (yield* currentThemes).map((theme) => theme.id),
364 ["zz-valid"],
365 );
366 }),
367 ),
368 );
369});