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

environmentTheme.test.ts

356 lines13.4 KB

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