Skip to content

Commit c1c34a5

Browse files
t3dotggclaude
andcommitted
refactor(server): theme failures are two tagged errors, and the service owns reads
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 2601ed7 commit c1c34a5

5 files changed

Lines changed: 145 additions & 84 deletions

File tree

‎apps/server/src/environmentTheme.test.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,7 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
183183
const refused = yield* themes
184184
.apply({ themeId: REFUSED_THEME_ID, theme: { ...NIGHTFALL_THEME, name: "Changed" } })
185185
.pipe(Effect.flip);
186-
assert.strictEqual(refused.reason, "not-selected");
186+
assert.strictEqual(refused._tag, "EnvironmentThemeNotSelectedError");
187187
assert.deepEqual(yield* themes.current, [{ id: REFUSED_THEME_ID, ...NIGHTFALL_THEME }]);
188188
}),
189189
),
@@ -200,7 +200,7 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
200200
const refused = yield* themes
201201
.apply({ themeId: REFUSED_THEME_ID, theme: NIGHTFALL_THEME })
202202
.pipe(Effect.flip);
203-
assert.strictEqual(refused.reason, "occupied");
203+
assert.match(refused.message, /could not be backed up/);
204204
assert.strictEqual(
205205
yield* fs.readFileString(`${config.environmentThemesDir}/${REFUSED_THEME_ID}.json`),
206206
oversized,
@@ -267,13 +267,13 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
267267
},
268268
})
269269
.pipe(Effect.flip);
270-
assert.strictEqual(leaky.reason, "remote-css");
270+
assert.match(leaky.message, /loads files/);
271271
const reserved = yield* themes
272272
.apply({ themeId: "dark", theme: NIGHTFALL_THEME })
273273
.pipe(Effect.flip);
274-
assert.strictEqual(reserved.reason, "invalid-id");
274+
assert.match(reserved.message, /not a valid theme id/);
275275
const unknown = yield* themes.apply({ themeId: "missing" }).pipe(Effect.flip);
276-
assert.strictEqual(unknown.reason, "unknown-id");
276+
assert.match(unknown.message, /not a built-in or published theme/);
277277
yield* themes.apply({ themeId: "grove" });
278278
yield* themes.apply({ themeId: "grove", appearance: "dark" });
279279
yield* themes.apply({ appearance: "light" });
@@ -320,15 +320,15 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
320320
const refused = yield* themes
321321
.apply({ themeId: "zz-look", theme: large("Too much") })
322322
.pipe(Effect.flip);
323-
assert.strictEqual(refused.reason, "not-published");
323+
assert.match(refused.message, /could not be published/);
324324
assert.deepEqual(yield* served, { id: "zz-look", ...NIGHTFALL_THEME });
325325

326326
// A new theme that sorts first fits, and the last large one no longer does.
327327
const before = (yield* themes.current).map((theme) => theme.id);
328328
const displacing = yield* themes
329329
.apply({ themeId: "a0-first", theme: large("Displacing") })
330330
.pipe(Effect.flip);
331-
assert.strictEqual(displacing.reason, "not-published");
331+
assert.match(displacing.message, /could not be published/);
332332
assert.deepEqual(
333333
(yield* themes.current).map((theme) => theme.id),
334334
before,

‎apps/server/src/environmentTheme.ts‎

Lines changed: 102 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import * as NodeFS from "node:fs";
55
import {
66
type DefaultAppearancePreference,
77
EnvironmentTheme,
8+
type ServerSettingsError,
89
EnvironmentThemeFile,
910
EnvironmentThemeId,
1011
environmentThemeFileHasColors,
@@ -30,7 +31,7 @@ import * as Scope from "effect/Scope";
3031
import * as Stream from "effect/Stream";
3132

3233
import * as ServerConfig from "./config.ts";
33-
import { ServerSettingsService } from "./serverSettings.ts";
34+
import * as ServerSettings from "./serverSettings.ts";
3435

3536
const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
3637
Schema.fromJsonString(EnvironmentThemeFile),
@@ -52,42 +53,38 @@ interface PublishedThemes {
5253
readonly themes: ReadonlyArray<EnvironmentTheme>;
5354
}
5455

55-
const APPLY_FAILURES = {
56-
"invalid-id":
57-
"is not a valid theme id. Use lowercase letters, digits, and hyphens, and not a built-in name.",
58-
"unknown-id": "is not a built-in or published theme.",
59-
"no-colors": "has no colors. Give canvas and accent, or at least one color role.",
60-
"remote-css":
61-
"has CSS that loads files. Remove @import, image-set(), and url() that is not data: or #id.",
62-
"too-large": `is larger than ${MAX_THEME_FILE_BYTES} bytes.`,
63-
"not-published": "could not be published. The themes directory may be full or not writable.",
64-
occupied: "would replace a file that could not be backed up. Use another theme id.",
65-
"not-selected": "was not applied, because the settings could not be saved.",
66-
} as const;
67-
68-
export class EnvironmentThemeApplyError extends Schema.TaggedError<EnvironmentThemeApplyError>()(
69-
"EnvironmentThemeApplyError",
56+
const INVALID_ID =
57+
"is not a valid theme id. Use lowercase letters, digits, and hyphens, and not a built-in name.";
58+
const NOT_PUBLISHED = "could not be published. The themes directory may be full or not writable.";
59+
60+
/** A theme the service will not publish or select. `problem` ends the sentence naming it. */
61+
export class EnvironmentThemeRefusedError extends Schema.TaggedError<EnvironmentThemeRefusedError>()(
62+
"EnvironmentThemeRefusedError",
7063
{
71-
/** Absent when only the appearance was set. */
72-
themeId: Schema.optional(Schema.String),
73-
reason: Schema.Literals([
74-
"invalid-id",
75-
"unknown-id",
76-
"no-colors",
77-
"remote-css",
78-
"too-large",
79-
"not-published",
80-
"occupied",
81-
"not-selected",
82-
]),
64+
themeId: Schema.String,
65+
problem: Schema.String,
8366
known: Schema.optional(Schema.Array(Schema.String)),
8467
cause: Schema.optional(Schema.Defect()),
8568
},
8669
) {
8770
override get message(): string {
8871
const known = this.known ? ` Available: ${this.known.join(", ")}.` : "";
72+
return `Theme "${this.themeId}" ${this.problem}${known}`;
73+
}
74+
}
75+
76+
/** The settings write that makes a theme or mode the default failed. */
77+
export class EnvironmentThemeNotSelectedError extends Schema.TaggedError<EnvironmentThemeNotSelectedError>()(
78+
"EnvironmentThemeNotSelectedError",
79+
{
80+
/** Absent when only the appearance was set. */
81+
themeId: Schema.optional(Schema.String),
82+
cause: Schema.Defect(),
83+
},
84+
) {
85+
override get message(): string {
8986
const subject = this.themeId === undefined ? "The appearance" : `Theme "${this.themeId}"`;
90-
return `${subject} ${APPLY_FAILURES[this.reason]}${known}`;
87+
return `${subject} was not applied, because the settings could not be saved.`;
9188
}
9289
}
9390

@@ -96,6 +93,16 @@ export class EnvironmentThemeService extends Context.Service<
9693
{
9794
readonly current: Effect.Effect<ReadonlyArray<EnvironmentTheme>>;
9895

96+
/** The default theme id and the published themes, plus the one named `themeId`. */
97+
readonly read: (themeId?: string) => Effect.Effect<
98+
{
99+
readonly current: string;
100+
readonly themes: ReadonlyArray<EnvironmentTheme>;
101+
readonly theme?: EnvironmentTheme;
102+
},
103+
EnvironmentThemeRefusedError | ServerSettingsError
104+
>;
105+
99106
/**
100107
* Makes `themeId` the environment theme and `appearance` its mode, so connected clients
101108
* switch to them. With `theme`, first publishes that file under the id, replacing one already
@@ -109,15 +116,13 @@ export class EnvironmentThemeService extends Context.Service<
109116
readonly appearance?: Exclude<DefaultAppearancePreference, ""> | undefined;
110117
}
111118
| { readonly appearance: Exclude<DefaultAppearancePreference, ""> },
112-
) => Effect.Effect<void, EnvironmentThemeApplyError>;
119+
) => Effect.Effect<void, EnvironmentThemeRefusedError | EnvironmentThemeNotSelectedError>;
113120

114121
/** Subscribes before reading to retain changes during connection. */
115122
readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
116123
}
117124
>()("t3/environmentTheme/EnvironmentThemeService") {}
118125

119-
/** Validates and reads one handle; rejects symlinked files, allows symlinked directories.
120-
* Uses non-blocking opens against FIFOs; Windows lacks these flags and checks symlinks with lstat. */
121126
/** True when anything, a dangling symlink included, is at the path. */
122127
const pathIsTaken = (filePath: string): boolean => {
123128
try {
@@ -128,6 +133,8 @@ const pathIsTaken = (filePath: string): boolean => {
128133
}
129134
};
130135

136+
/** Validates and reads one handle; rejects symlinked files, allows symlinked directories.
137+
* Uses non-blocking opens against FIFOs; Windows lacks these flags and checks symlinks with lstat. */
131138
export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => {
132139
let fd: number;
133140
try {
@@ -229,7 +236,7 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
229236
const make = Effect.gen(function* () {
230237
const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
231238
const fs = yield* FileSystem.FileSystem;
232-
const settings = yield* ServerSettingsService;
239+
const settings = yield* ServerSettings.ServerSettingsService;
233240
// Sequence numbers let subscribers drop queued events older than their initial snapshot.
234241
const changes = yield* PubSub.sliding<PublishedThemes>(1);
235242
const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
@@ -277,17 +284,33 @@ const make = Effect.gen(function* () {
277284
/** Callers hold `publishSemaphore`. Succeeds with the effect that undoes this publish. */
278285

279286
const publish = Effect.fnUntraced(function* (themeId: string, file: EnvironmentThemeFile) {
280-
const fail = (reason: EnvironmentThemeApplyError["reason"], cause?: unknown) =>
281-
new EnvironmentThemeApplyError({ themeId, reason, cause });
282-
if (UNPUBLISHABLE_THEME_IDS.has(themeId)) return yield* fail("invalid-id");
283-
if (!environmentThemeFileHasColors(file)) return yield* fail("no-colors");
287+
if (UNPUBLISHABLE_THEME_IDS.has(themeId)) {
288+
return yield* new EnvironmentThemeRefusedError({ themeId, problem: INVALID_ID });
289+
}
290+
if (!environmentThemeFileHasColors(file)) {
291+
return yield* new EnvironmentThemeRefusedError({
292+
themeId,
293+
problem: "has no colors. Give canvas and accent, or at least one color role.",
294+
});
295+
}
284296
if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {
285-
return yield* fail("remote-css");
297+
return yield* new EnvironmentThemeRefusedError({
298+
themeId,
299+
problem:
300+
"has CSS that loads files. Remove @import, image-set(), and url() that is not data: or #id.",
301+
});
286302
}
287303
const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(
288-
Effect.mapError((cause) => fail("not-published", cause)),
304+
Effect.mapError(
305+
(cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
306+
),
289307
);
290-
if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");
308+
if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) {
309+
return yield* new EnvironmentThemeRefusedError({
310+
themeId,
311+
problem: `is larger than ${MAX_THEME_FILE_BYTES} bytes.`,
312+
});
313+
}
291314

292315
const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;
293316
// The watcher reads only .json names, so it never sees a half-written file.
@@ -303,7 +326,12 @@ const make = Effect.gen(function* () {
303326
// The guarded reader does not block on a FIFO and does not follow a symlink.
304327
const previous = Option.fromNullOr(readThemeFileGuarded(destination, MAX_THEME_FILE_BYTES));
305328
// A file it cannot read back, such as one over the size limit, could not be restored.
306-
if (Option.isNone(previous) && pathIsTaken(destination)) return yield* fail("occupied");
329+
if (Option.isNone(previous) && pathIsTaken(destination)) {
330+
return yield* new EnvironmentThemeRefusedError({
331+
themeId,
332+
problem: "would replace a file that could not be backed up. Use another theme id.",
333+
});
334+
}
307335
const servedBefore = (yield* refresh).themes.map((theme) => theme.id);
308336
// Puts back what was there, so a failed apply does not take a working theme away.
309337
const revert = Option.match(previous, {
@@ -313,14 +341,16 @@ const make = Effect.gen(function* () {
313341

314342
yield* fs.makeDirectory(environmentThemesDir, { recursive: true }).pipe(
315343
Effect.andThen(replace(contents)),
316-
Effect.mapError((cause) => fail("not-published", cause)),
344+
Effect.mapError(
345+
(cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
346+
),
317347
);
318348
// The reader stops at its count and size limits, so this file can go unserved, or it can
319349
// push another theme out. Both count as a failed publish.
320350
const served = new Set((yield* refresh).themes.map((theme) => theme.id));
321351
if (served.has(themeId) && servedBefore.every((id) => served.has(id))) return revert;
322352
yield* revert;
323-
return yield* fail("not-published");
353+
return yield* new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED });
324354
});
325355

326356
const apply: EnvironmentThemeService["Service"]["apply"] = Effect.fn(
@@ -329,11 +359,9 @@ const make = Effect.gen(function* () {
329359
const themeId = "themeId" in input ? input.themeId : undefined;
330360
const theme = "theme" in input ? input.theme : undefined;
331361
const { appearance } = input;
332-
const fail = (
333-
reason: EnvironmentThemeApplyError["reason"],
334-
detail?: { readonly known?: ReadonlyArray<string>; readonly cause?: unknown },
335-
) => new EnvironmentThemeApplyError({ themeId, reason, ...detail });
336-
if (themeId !== undefined && !isEnvironmentThemeId(themeId)) return yield* fail("invalid-id");
362+
if (themeId !== undefined && !isEnvironmentThemeId(themeId)) {
363+
return yield* new EnvironmentThemeRefusedError({ themeId, problem: INVALID_ID });
364+
}
337365
// Timestamps make clients apply a set again when its value did not change. Theme and
338366
// appearance have one each, so setting one does not undo a later local choice of the other.
339367
const select = Effect.gen(function* () {
@@ -345,7 +373,7 @@ const make = Effect.gen(function* () {
345373
? {}
346374
: { defaultAppearance: appearance, defaultAppearanceSetAt: setAt }),
347375
})
348-
.pipe(Effect.mapError((cause) => fail("not-selected", { cause })));
376+
.pipe(Effect.mapError((cause) => new EnvironmentThemeNotSelectedError({ themeId, cause })));
349377
});
350378
// One at a time, so a selection never sees a file that a failed publish then takes back.
351379
// If the theme cannot be selected, the file it replaced comes back.
@@ -354,7 +382,13 @@ const make = Effect.gen(function* () {
354382
if (themeId === undefined) return yield* select;
355383
if (theme === undefined) {
356384
const known = [...BUILT_IN_THEME_IDS, ...(yield* refresh).themes.map(({ id }) => id)];
357-
if (!known.includes(themeId)) return yield* fail("unknown-id", { known });
385+
if (!known.includes(themeId)) {
386+
return yield* new EnvironmentThemeRefusedError({
387+
themeId,
388+
problem: "is not a built-in or published theme.",
389+
known,
390+
});
391+
}
358392
return yield* select;
359393
}
360394
const revert = yield* publish(themeId, theme);
@@ -363,8 +397,26 @@ const make = Effect.gen(function* () {
363397
);
364398
});
365399

400+
const read: EnvironmentThemeService["Service"]["read"] = Effect.fn(
401+
"EnvironmentThemeService.read",
402+
)(function* (themeId) {
403+
const { themes } = yield* refresh;
404+
const { defaultTheme } = yield* settings.getSettings;
405+
if (themeId === undefined) return { current: defaultTheme, themes };
406+
const theme = themes.find((candidate) => candidate.id === themeId);
407+
if (theme === undefined) {
408+
return yield* new EnvironmentThemeRefusedError({
409+
themeId,
410+
problem: "is not a published theme.",
411+
known: themes.map(({ id }) => id),
412+
});
413+
}
414+
return { current: defaultTheme, themes, theme };
415+
});
416+
366417
return {
367418
current: Effect.map(refresh, (state) => state.themes),
419+
read,
368420
apply,
369421
get streamChanges() {
370422
return Stream.unwrap(

‎apps/server/src/mcp/toolkits/theme/handlers.test.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,12 @@ import * as Effect from "effect/Effect";
99
import * as Layer from "effect/Layer";
1010
import * as Stream from "effect/Stream";
1111

12-
import { EnvironmentThemeApplyError, EnvironmentThemeService } from "../../../environmentTheme.ts";
12+
import {
13+
EnvironmentThemeRefusedError,
14+
EnvironmentThemeService,
15+
} from "../../../environmentTheme.ts";
1316
import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
1417
import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
15-
import * as Settings from "../../../serverSettings.ts";
1618
import * as McpInvocationContext from "../../McpInvocationContext.ts";
1719
import * as McpToolAccess from "../../McpToolAccess.ts";
1820
import { liveThreadShell } from "../../McpToolAccess.testkit.ts";
@@ -52,11 +54,13 @@ it.effect("applies the theme through the service and reports a refusal as an inv
5254
apply: (input) =>
5355
"themeId" in input && input.themeId === "missing"
5456
? Effect.fail(
55-
new EnvironmentThemeApplyError({ themeId: input.themeId, reason: "unknown-id" }),
57+
new EnvironmentThemeRefusedError({
58+
themeId: input.themeId,
59+
problem: "is not a built-in or published theme.",
60+
}),
5661
)
5762
: Effect.void,
5863
}),
59-
Layer.mock(Settings.ServerSettingsService)({}),
6064
);
6165
yield* Effect.gen(function* () {
6266
const toolkit = yield* ThemeToolkit;

0 commit comments

Comments
 (0)