@devries-cameron20 / t3code Mirror · read-only / commits / 42057b82d0
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, 16:00 UTC

feat: agents can restyle T3 Code with theme colors and CSS (#35247)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>

Theo Browne committed Nov 13, 2026 at 16:59 UTC 42057b82d097156f56f9b487887226b99f018bcb
36 files changed +1231 -20
apps/server/src/environmentTheme.test.ts
+179 -1
@@ -1,4 +1,8 @@
1 -import { EnvironmentThemeFile } from "@t3tools/contracts";
1 +import {
2 + DEFAULT_SERVER_SETTINGS,
3 + EnvironmentThemeFile,
4 + ServerSettingsError,
5 +} from "@t3tools/contracts";
6 import * as NodeServices from "@effect/platform-node/NodeServices";
7 import { assert, it } from "@effect/vitest";
8 import * as Effect from "effect/Effect";
@@ -12,6 +16,7 @@ import * as Stream from "effect/Stream";
16
17 import * as ServerConfig from "./config.ts";
18 import * as EnvironmentTheme from "./environmentTheme.ts";
19 +import { ServerSettingsService } from "./serverSettings.ts";
20 import { symlinksSupported } from "@t3tools/shared/testing/symlinks";
21
22 const encodeThemeFile = Schema.encodeSync(Schema.fromJsonString(EnvironmentThemeFile));
@@ -30,6 +35,9 @@ const SHARED_THEME: EnvironmentThemeFile = {
35 colors: { canvas: "#eff1f5", accent: "#1e66f5" },
36 };
37
38 +/** The settings mock refuses to make this theme the default, as a managed policy can. */
39 +const REFUSED_THEME_ID = "refused";
40 +
41 const withEnvironmentThemes = <A, E>(
42 seeds: Readonly<Record<string, string>>,
43 body: Effect.Effect<
@@ -41,6 +49,8 @@ const withEnvironmentThemes = <A, E>(
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;
@@ -56,6 +66,27 @@ const withEnvironmentThemes = <A, E>(
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 );
@@ -144,6 +175,62 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
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 {},
@@ -159,6 +246,97 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
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 {
apps/server/src/environmentTheme.ts
+220 -1
@@ -3,20 +3,26 @@
3 import * as NodeFS from "node:fs";
4
5 import {
6 + type DefaultAppearancePreference,
7 EnvironmentTheme,
8 + type ServerSettingsError,
9 EnvironmentThemeFile,
10 EnvironmentThemeId,
11 environmentThemeFileHasColors,
12 } from "@t3tools/contracts";
11 -import { UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
13 +import { fromJsonStringPretty } from "@t3tools/shared/schemaJson";
14 +import { themeCssLoadsRemoteFiles } from "@t3tools/shared/themeCss";
15 +import { BUILT_IN_THEME_IDS, UNPUBLISHABLE_THEME_IDS } from "@t3tools/shared/themePalettes";
16 import * as Cause from "effect/Cause";
17 import * as Context from "effect/Context";
18 +import * as DateTime from "effect/DateTime";
19 import * as Duration from "effect/Duration";
20 import * as Effect from "effect/Effect";
21 import * as Equal from "effect/Equal";
22 import * as Exit from "effect/Exit";
23 import * as FileSystem from "effect/FileSystem";
24 import * as Layer from "effect/Layer";
25 +import * as Option from "effect/Option";
26 import * as PubSub from "effect/PubSub";
27 import * as Ref from "effect/Ref";
28 import * as Schema from "effect/Schema";
@@ -25,10 +31,14 @@ import * as Scope from "effect/Scope";
31 import * as Stream from "effect/Stream";
32
33 import * as ServerConfig from "./config.ts";
34 +import * as ServerSettings from "./serverSettings.ts";
35
36 const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
37 Schema.fromJsonString(EnvironmentThemeFile),
38 );
39 +const encodeEnvironmentThemeFileJson = Schema.encodeEffect(
40 + fromJsonStringPretty(EnvironmentThemeFile),
41 +);
42 const isEnvironmentThemeId = Schema.is(EnvironmentThemeId);
43
44 const THEME_FILE_SUFFIX = ".json";
@@ -43,16 +53,86 @@ interface PublishedThemes {
53 readonly themes: ReadonlyArray<EnvironmentTheme>;
54 }
55
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",
63 + {
64 + themeId: Schema.String,
65 + problem: Schema.String,
66 + known: Schema.optional(Schema.Array(Schema.String)),
67 + cause: Schema.optional(Schema.Defect()),
68 + },
69 +) {
70 + override get message(): string {
71 + 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 {
86 + const subject = this.themeId === undefined ? "The appearance" : `Theme "${this.themeId}"`;
87 + return `${subject} was not applied, because the settings could not be saved.`;
88 + }
89 +}
90 +
91 export class EnvironmentThemeService extends Context.Service<
92 EnvironmentThemeService,
93 {
94 readonly current: Effect.Effect<ReadonlyArray<EnvironmentTheme>>;
95
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 +
106 + /**
107 + * Makes `themeId` the environment theme and `appearance` its mode, so connected clients
108 + * switch to them. With `theme`, first publishes that file under the id, replacing one already
109 + * there.
110 + */
111 + readonly apply: (
112 + input:
113 + | {
114 + readonly themeId: string;
115 + readonly theme?: EnvironmentThemeFile | undefined;
116 + readonly appearance?: Exclude<DefaultAppearancePreference, ""> | undefined;
117 + }
118 + | { readonly appearance: Exclude<DefaultAppearancePreference, ""> },
119 + ) => Effect.Effect<void, EnvironmentThemeRefusedError | EnvironmentThemeNotSelectedError>;
120 +
121 /** Subscribes before reading to retain changes during connection. */
122 readonly streamChanges: Stream.Stream<ReadonlyArray<EnvironmentTheme>>;
123 }
124 >()("t3/environmentTheme/EnvironmentThemeService") {}
125
126 +/** True when anything, a dangling symlink included, is at the path. */
127 +const pathIsTaken = (filePath: string): boolean => {
128 + try {
129 + NodeFS.lstatSync(filePath);
130 + return true;
131 + } catch {
132 + return false;
133 + }
134 +};
135 +
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. */
138 export const readThemeFileGuarded = (filePath: string, maxBytes: number): string | null => {
@@ -156,6 +236,7 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) {
236 const make = Effect.gen(function* () {
237 const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
238 const fs = yield* FileSystem.FileSystem;
239 + const settings = yield* ServerSettings.ServerSettingsService;
240 // Sequence numbers let subscribers drop queued events older than their initial snapshot.
241 const changes = yield* PubSub.sliding<PublishedThemes>(1);
242 const published = yield* Ref.make<PublishedThemes>({ seq: 0, themes: [] });
@@ -197,8 +278,146 @@ const make = Effect.gen(function* () {
278 Effect.asVoid,
279 );
280
281 + // One publish at a time: they share a staging path, and each one checks what is served after it.
282 + const publishSemaphore = yield* Semaphore.make(1);
283 +
284 + /** Callers hold `publishSemaphore`. Succeeds with the effect that undoes this publish. */
285 +
286 + const publish = Effect.fnUntraced(function* (themeId: string, file: EnvironmentThemeFile) {
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 + }
296 + if (file.css !== undefined && themeCssLoadsRemoteFiles(file.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 + });
302 + }
303 + const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(
304 + Effect.mapError(
305 + (cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
306 + ),
307 + );
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 + }
314 +
315 + const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;
316 + // The watcher reads only .json names, so it never sees a half-written file.
317 + const staging = `${destination}.staging-${process.pid}`;
318 + // Exclusive create: a link left at the staging path is removed, never written through.
319 + const replace = (next: string) =>
320 + fs.remove(staging, { force: true }).pipe(
321 + Effect.andThen(fs.writeFileString(staging, next, { flag: "wx" })),
322 + Effect.andThen(fs.rename(staging, destination)),
323 + Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),
324 + );
325 +
326 + // The guarded reader does not block on a FIFO and does not follow a symlink.
327 + const previous = Option.fromNullOr(readThemeFileGuarded(destination, MAX_THEME_FILE_BYTES));
328 + // A file it cannot read back, such as one over the size limit, could not be restored.
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 + }
335 + const servedBefore = (yield* refresh).themes.map((theme) => theme.id);
336 + // Puts back what was there, so a failed apply does not take a working theme away.
337 + const revert = Option.match(previous, {
338 + onNone: () => fs.remove(destination, { force: true }),
339 + onSome: replace,
340 + }).pipe(Effect.ignore, Effect.andThen(refresh), Effect.asVoid);
341 +
342 + yield* fs.makeDirectory(environmentThemesDir, { recursive: true }).pipe(
343 + Effect.andThen(replace(contents)),
344 + Effect.mapError(
345 + (cause) => new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED, cause }),
346 + ),
347 + );
348 + // The reader stops at its count and size limits, so this file can go unserved, or it can
349 + // push another theme out. Both count as a failed publish.
350 + const served = new Set((yield* refresh).themes.map((theme) => theme.id));
351 + if (served.has(themeId) && servedBefore.every((id) => served.has(id))) return revert;
352 + yield* revert;
353 + return yield* new EnvironmentThemeRefusedError({ themeId, problem: NOT_PUBLISHED });
354 + });
355 +
356 + const apply: EnvironmentThemeService["Service"]["apply"] = Effect.fn(
357 + "EnvironmentThemeService.apply",
358 + )(function* (input) {
359 + const themeId = "themeId" in input ? input.themeId : undefined;
360 + const theme = "theme" in input ? input.theme : undefined;
361 + const { appearance } = input;
362 + if (themeId !== undefined && !isEnvironmentThemeId(themeId)) {
363 + return yield* new EnvironmentThemeRefusedError({ themeId, problem: INVALID_ID });
364 + }
365 + // Timestamps make clients apply a set again when its value did not change. Theme and
366 + // appearance have one each, so setting one does not undo a later local choice of the other.
367 + const select = Effect.gen(function* () {
368 + const setAt = DateTime.formatIso(yield* DateTime.now);
369 + yield* settings
370 + .updateSettings({
371 + ...(themeId === undefined ? {} : { defaultTheme: themeId, defaultThemeSetAt: setAt }),
372 + ...(appearance === undefined
373 + ? {}
374 + : { defaultAppearance: appearance, defaultAppearanceSetAt: setAt }),
375 + })
376 + .pipe(Effect.mapError((cause) => new EnvironmentThemeNotSelectedError({ themeId, cause })));
377 + });
378 + // One at a time, so a selection never sees a file that a failed publish then takes back.
379 + // If the theme cannot be selected, the file it replaced comes back.
380 + yield* publishSemaphore.withPermits(1)(
381 + Effect.gen(function* () {
382 + if (themeId === undefined) return yield* select;
383 + if (theme === undefined) {
384 + const known = [...BUILT_IN_THEME_IDS, ...(yield* refresh).themes.map(({ id }) => id)];
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 + }
392 + return yield* select;
393 + }
394 + const revert = yield* publish(themeId, theme);
395 + yield* select.pipe(Effect.tapError(() => revert));
396 + }),
397 + );
398 + });
399 +
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 +
417 return {
418 current: Effect.map(refresh, (state) => state.themes),
419 + read,
420 + apply,
421 get streamChanges() {
422 return Stream.unwrap(
423 Effect.gen(function* () {
apps/server/src/mcp/McpHttpServer.ts
+7
@@ -53,6 +53,8 @@ import { PreviewControlsToolkit } from "./toolkits/previewControls/tools.ts";
53 import * as PreviewControlsHandlers from "./toolkits/previewControls/handlers.ts";
54 import { EnvironmentToolkit } from "./toolkits/environment/tools.ts";
55 import * as EnvironmentHandlers from "./toolkits/environment/handlers.ts";
56 +import { ThemeToolkit } from "./toolkits/theme/tools.ts";
57 +import * as ThemeHandlers from "./toolkits/theme/handlers.ts";
58 import { ProjectToolkit } from "./toolkits/project/tools.ts";
59 import * as ProjectHandlers from "./toolkits/project/handlers.ts";
60 import { AttachmentToolkit } from "./toolkits/attachment/tools.ts";
@@ -1258,6 +1260,10 @@ const layerEnvironmentToolkit = toolkitRegistration(
1260 EnvironmentHandlers.layer,
1261 ).pipe(Layer.provide(ThreadCommandExecutor.layer));
1262
1263 +const layerThemeToolkit = toolkitRegistration(ThemeToolkit, ThemeHandlers.layer).pipe(
1264 + Layer.provide(ThreadCommandExecutor.layer),
1265 +);
1266 +
1267 export const layerProjectRegistration = toolkitRegistration(ProjectToolkit, ProjectHandlers.layer);
1268
1269 export const layerAttachmentToolkit = toolkitRegistration(
@@ -1323,6 +1329,7 @@ export const layerTools = Layer.mergeAll(
1329 layerAttachmentToolkit,
1330 layerProjectRegistration,
1331 layerEnvironmentToolkit,
1332 + layerThemeToolkit,
1333 layerPreviewControlsRegistration,
1334 layerWorktreeToolkitRegistration,
1335 layerPullRequestsToolkit,
apps/server/src/mcp/toolkits/theme/handlers.test.ts new
+97
@@ -0,0 +1,97 @@
1 +import { expect, it } from "@effect/vitest";
2 +import {
3 + EnvironmentId,
4 + type EnvironmentThemeFile,
5 + ProviderInstanceId,
6 + ThreadId,
7 +} from "@t3tools/contracts";
8 +import * as Effect from "effect/Effect";
9 +import * as Layer from "effect/Layer";
10 +import * as Stream from "effect/Stream";
11 +
12 +import {
13 + EnvironmentThemeRefusedError,
14 + EnvironmentThemeService,
15 +} from "../../../environmentTheme.ts";
16 +import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
17 +import * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
18 +import * as McpInvocationContext from "../../McpInvocationContext.ts";
19 +import * as McpToolAccess from "../../McpToolAccess.ts";
20 +import { liveThreadShell } from "../../McpToolAccess.testkit.ts";
21 +import * as ThemeHandlers from "./handlers.ts";
22 +import { ThemeToolkit } from "./tools.ts";
23 +
24 +const environmentId = EnvironmentId.make("environment:theme");
25 +const threadId = ThreadId.make("thread:theme");
26 +const AGENT_THEME = {
27 + name: "Agent Look",
28 + appearance: "dark",
29 + canvas: "#101010",
30 + accent: "#7aa2f7",
31 + css: "[data-chat-header] { border-bottom: 1px solid red; }",
32 +} satisfies EnvironmentThemeFile;
33 +
34 +it.effect("applies the theme through the service and reports a refusal as an invalid request", () =>
35 + Effect.gen(function* () {
36 + const layerDependencies = Layer.mergeAll(
37 + ThreadCommandExecutor.layer,
38 + Layer.succeed(McpInvocationContext.McpInvocationContext, {
39 + environmentId,
40 + requestNamespace: "provider:theme",
41 + thread: {
42 + threadId,
43 + providerSessionId: "provider:theme",
44 + providerInstanceId: ProviderInstanceId.make("codex"),
45 + },
46 + client: undefined,
47 + capabilities: new Set(["orchestration" as const]),
48 + issuedAt: 0,
49 + }),
50 + Layer.mock(ThreadManagement.ThreadManagementService)({
51 + getThreadShell: () => Effect.succeed(liveThreadShell(threadId)),
52 + }),
53 + Layer.mock(EnvironmentThemeService)({
54 + apply: (input) =>
55 + "themeId" in input && input.themeId === "missing"
56 + ? Effect.fail(
57 + new EnvironmentThemeRefusedError({
58 + themeId: input.themeId,
59 + problem: "is not a built-in or published theme.",
60 + }),
61 + )
62 + : Effect.void,
63 + }),
64 + );
65 + yield* Effect.gen(function* () {
66 + const toolkit = yield* ThemeToolkit;
67 + const call = (params: Parameters<typeof toolkit.handle<"t3_theme_set">>[1]) =>
68 + toolkit.handle("t3_theme_set", params).pipe(
69 + Stream.unwrap,
70 + Stream.runCollect,
71 + Effect.map((parts) => parts.at(-1)?.result),
72 + );
73 +
74 + expect(yield* call({ themeId: "agent-look", theme: AGENT_THEME })).toEqual({
75 + themeId: "agent-look",
76 + published: true,
77 + });
78 + expect(yield* call({ themeId: "grove" })).toEqual({ themeId: "grove", published: false });
79 + expect(yield* call({ appearance: "dark" })).toEqual({
80 + appearance: "dark",
81 + published: false,
82 + });
83 + expect(yield* call({ theme: AGENT_THEME })).toMatchObject({ code: "invalid_request" });
84 + expect(yield* call({})).toMatchObject({ code: "invalid_request" });
85 + expect(yield* call({ themeId: "missing" })).toMatchObject({
86 + code: "invalid_request",
87 + message: 'Theme "missing" is not a built-in or published theme.',
88 + });
89 + }).pipe(
90 + Effect.provide(
91 + McpToolAccess.HandlersLayer.layer(ThemeHandlers.layer).pipe(
92 + Layer.provideMerge(layerDependencies),
93 + ),
94 + ),
95 + );
96 + }),
97 +);
apps/server/src/mcp/toolkits/theme/handlers.ts new
+79
@@ -0,0 +1,79 @@
1 +import { OrchestratorMcpFailure } from "@t3tools/contracts";
2 +import { THEME_GUIDE } from "@t3tools/shared/themeCss";
3 +import { BUILT_IN_THEME_IDS } from "@t3tools/shared/themePalettes";
4 +import * as Effect from "effect/Effect";
5 +import * as Struct from "effect/Struct";
6 +import * as EnvironmentTheme from "../../../environmentTheme.ts";
7 +import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
8 +import * as McpInvocationContext from "../../McpInvocationContext.ts";
9 +import * as McpToolAccess from "../../McpToolAccess.ts";
10 +import { unavailable } from "../../threadAccess.ts";
11 +import { ThemeToolkit } from "./tools.ts";
12 +
13 +export const layer = McpToolAccess.toLayer(ThemeToolkit, {
14 + t3_theme_read: McpToolAccess.reads(({ themeId }) =>
15 + Effect.gen(function* () {
16 + const themes = yield* EnvironmentTheme.EnvironmentThemeService;
17 + const {
18 + current,
19 + themes: published,
20 + theme,
21 + } = yield* themes.read(themeId).pipe(
22 + Effect.catchTags({
23 + EnvironmentThemeRefusedError: (error) =>
24 + Effect.fail(
25 + new OrchestratorMcpFailure({ code: "invalid_request", message: error.message }),
26 + ),
27 + ServerSettingsError: () => Effect.fail(unavailable()),
28 + }),
29 + );
30 + return {
31 + current,
32 + builtIn: BUILT_IN_THEME_IDS,
33 + published: published.map(({ id, name, css }) => ({ id, name, hasCss: Boolean(css) })),
34 + ...(theme === undefined ? {} : { theme: Struct.omit(theme, ["id"]) }),
35 + guide: THEME_GUIDE,
36 + };
37 + }),
38 + ),
39 + t3_theme_set: McpToolAccess.writesEnvironment(({ themeId, theme, appearance }, check) =>
40 + Effect.gen(function* () {
41 + const input =
42 + themeId !== undefined
43 + ? { themeId, theme, appearance }
44 + : theme === undefined && appearance !== undefined
45 + ? { appearance }
46 + : undefined;
47 + if (input === undefined) {
48 + return yield* new OrchestratorMcpFailure({
49 + code: "invalid_request",
50 + message: "Give `themeId`, `appearance`, or both. `theme` needs a `themeId`.",
51 + });
52 + }
53 + const scope = yield* McpInvocationContext.McpInvocationContext;
54 + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
55 + const themes = yield* EnvironmentTheme.EnvironmentThemeService;
56 + const set = Effect.gen(function* () {
57 + // The turn may have ended, or the thread's modes changed, while this waited for the lock.
58 + yield* check;
59 + yield* themes.apply(input).pipe(
60 + Effect.catchTags({
61 + EnvironmentThemeRefusedError: (error) =>
62 + Effect.fail(
63 + new OrchestratorMcpFailure({ code: "invalid_request", message: error.message }),
64 + ),
65 + EnvironmentThemeNotSelectedError: () => Effect.fail(unavailable()),
66 + }),
67 + );
68 + return {
69 + ...(themeId === undefined ? {} : { themeId }),
70 + ...(appearance === undefined ? {} : { appearance }),
71 + published: theme !== undefined,
72 + };
73 + });
74 + return yield* scope.thread === undefined
75 + ? set
76 + : executor.withLock(scope.thread.threadId, set);
77 + }),
78 + ),
79 +});
apps/server/src/mcp/toolkits/theme/tools.ts new
+69
@@ -0,0 +1,69 @@
1 +import {
2 + DefaultThemePreference,
3 + EnvironmentThemeFile,
4 + EnvironmentThemeId,
5 + OrchestratorMcpFailure,
6 +} from "@t3tools/contracts";
7 +import * as Schema from "effect/Schema";
8 +import { Tool, Toolkit } from "effect/ai";
9 +import * as EnvironmentTheme from "../../../environmentTheme.ts";
10 +import * as McpInvocationContext from "../../McpInvocationContext.ts";
11 +import * as ThreadCommandExecutor from "../../../orchestration-v2/ThreadCommandExecutor.ts";
12 +import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
13 +
14 +const Appearance = Schema.Literals(["light", "dark", "system"]);
15 +
16 +const shared = {
17 + failure: OrchestratorMcpFailure,
18 + failureMode: "return" as const,
19 + dependencies: [
20 + McpInvocationContext.McpInvocationContext,
21 + ThreadManagementService.ThreadManagementService,
22 + EnvironmentTheme.EnvironmentThemeService,
23 + ThreadCommandExecutor.ThreadCommandExecutor,
24 + ],
25 +};
26 +
27 +const ThemeReadTool = Tool.make("t3_theme_read", {
28 + ...shared,
29 + description:
30 + "Read T3 Code's own themes and the guide to restyle it: color roles and CSS selectors. Call before `t3_theme_set`.",
31 + parameters: Schema.Struct({
32 + themeId: Schema.optionalKey(
33 + EnvironmentThemeId.annotate({ description: "Also return this published theme's file." }),
34 + ),
35 + }),
36 + success: Schema.Struct({
37 + current: DefaultThemePreference,
38 + builtIn: Schema.Array(Schema.String),
39 + published: Schema.Array(
40 + Schema.Struct({
41 + id: EnvironmentThemeId,
42 + name: Schema.String,
43 + hasCss: Schema.Boolean,
44 + }),
45 + ),
46 + theme: Schema.optionalKey(EnvironmentThemeFile),
47 + guide: Schema.String,
48 + }),
49 +})
50 + .annotate(Tool.Readonly, true)
51 + .annotate(Tool.Destructive, false);
52 +
53 +const ThemeSetTool = Tool.make("t3_theme_set", {
54 + ...shared,
55 + description:
56 + "Restyle T3 Code itself, only when the user asks. With `theme`, publish it as `themeId` (the same id updates it) and switch this machine's web and desktop clients to it. Without `theme`, switch to a built-in or published `themeId`. `appearance` switches them to light, dark, or system mode, with or without a theme. Live full-access or default caller thread only.",
57 + parameters: Schema.Struct({
58 + themeId: Schema.optionalKey(EnvironmentThemeId),
59 + theme: Schema.optionalKey(EnvironmentThemeFile),
60 + appearance: Schema.optionalKey(Appearance),
61 + }),
62 + success: Schema.Struct({
63 + themeId: Schema.optionalKey(EnvironmentThemeId),
64 + appearance: Schema.optionalKey(Appearance),
65 + published: Schema.Boolean,
66 + }),
67 +}).annotate(Tool.Destructive, true);
68 +
69 +export const ThemeToolkit = Toolkit.make(ThemeReadTool, ThemeSetTool);
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+2
@@ -92,6 +92,7 @@ import { PreviewControlsToolkit } from "../../mcp/toolkits/previewControls/tools
92 import { HtmlToolkit } from "../../mcp/toolkits/html/tools.ts";
93 import { MessageToolkit } from "../../mcp/toolkits/message/tools.ts";
94 import { EnvironmentToolkit } from "../../mcp/toolkits/environment/tools.ts";
95 +import { ThemeToolkit } from "../../mcp/toolkits/theme/tools.ts";
96 import { ProjectToolkit } from "../../mcp/toolkits/project/tools.ts";
97 import { WorktreeToolkit } from "../../mcp/toolkits/worktree/tools.ts";
98 import { ThreadToolkit } from "../../mcp/toolkits/thread/tools.ts";
@@ -662,6 +663,7 @@ describe("ClaudeAdapterV2 MCP query overrides", () => {
663 ...Object.values(WorktreeToolkit.tools),
664 ...Object.values(ProjectToolkit.tools),
665 ...Object.values(EnvironmentToolkit.tools),
666 + ...Object.values(ThemeToolkit.tools),
667 ...Object.values(PreviewControlsToolkit.tools),
668 ...Object.values(HtmlToolkit.tools),
669 ...Object.values(MessageToolkit.tools),
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+1
@@ -2275,6 +2275,7 @@ export const CLAUDE_READ_ONLY_T3_MCP_ALLOWED_TOOLS: ReadonlyArray<string> = [
2275 "mcp__t3-code__t3_preview_list",
2276 "mcp__t3-code__t3_environment_read",
2277 "mcp__t3-code__t3_environment_links",
2278 + "mcp__t3-code__t3_theme_read",
2279 "mcp__t3-code__html_preview",
2280 "mcp__t3-code__html_render",
2281 "mcp__t3-code__send_to_user",
apps/server/src/provider/AgentContextBudget.test.ts
+2
@@ -44,6 +44,7 @@ import { GitVcsDriver } from "../vcs/GitVcsDriver.ts";
44 import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts";
45 import { buildCodexAdditionalContext } from "./CodexDeveloperInstructions.ts";
46 import { DocumentText } from "./DocumentText.ts";
47 +import { EnvironmentThemeService } from "../environmentTheme.ts";
48 import { ProviderRegistry } from "./ProviderRegistry.ts";
49 import budget from "./agentContextBudget.json" with { type: "json" };
50
@@ -52,6 +53,7 @@ const toolHandlerServices = Layer.mergeAll(
53 Layer.mock(AssetSigner)({}),
54 Layer.mock(DeviceService)({}),
55 Layer.mock(DocumentText)({}),
56 + Layer.mock(EnvironmentThemeService)({}),
57 Layer.mock(GitVcsDriver)({}),
58 Layer.mock(GitWorkflowService)({}),
59 Layer.mock(ManagedProjectFolders)({ namedProjectsRoot: "" }),
apps/server/src/provider/agentContextBudget.json
+1 -1
@@ -1,5 +1,5 @@
1 {
2 "claudeSystemAppendBytes": 5930,
3 "codexAdditionalContextBytes": 7324,
4 - "mcpToolListJsonBytes": 48566
4 + "mcpToolListJsonBytes": 49806
5 }
apps/server/src/server.ts
+3 -3
@@ -707,15 +707,15 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
707 Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)),
708 Layer.provideMerge(SecretCheck.layer),
709 Layer.provideMerge(SecretResolver.layer),
710 + // Above the settings it writes when a theme is applied.
711 + Layer.provideMerge(EnvironmentTheme.layer),
712 Layer.provideMerge(layerServerSettings),
713 Layer.provideMerge(layerSourceControlProviderRegistry),
714 Layer.provideMerge(layerGit),
715 Layer.provideMerge(layerVcs),
716 Layer.provideMerge(Layer.mergeAll(layerTerminal, layerPreview, layerDevice)),
717 Layer.provideMerge(layerPersistence),
716 - Layer.provideMerge(
717 - Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer),
718 - ),
718 + Layer.provideMerge(Layer.mergeAll(Keybindings.layer, UsageLimitSources.layer)),
719 Layer.provideMerge(ProviderRegistry.layer),
720 Layer.provideMerge(
721 ProviderInstanceRegistryHydration.layer.pipe(Layer.provide(SqlitePersistence.layerConfig)),
apps/web/src/components/ProjectMonogram.tsx
+1
@@ -17,6 +17,7 @@ export function ProjectMonogram({
17 return (
18 <span
19 aria-hidden="true"
20 + data-slot="project-monogram"
21 className={cn("inline-flex size-4 shrink-0 items-center justify-center", className)}
22 >
23 <svg
apps/web/src/components/chat/TimelineUserMessageRow.tsx
+2
@@ -313,6 +313,7 @@ function AutomationMessageRow({ row }: { row: Extract<TimelineRow, { kind: "mess
313 BUBBLE_CHIP_CLASS_NAME,
314 expanded && "w-full",
315 )}
316 + data-user-message-bubble=""
317 >
318 <MessageAuthorHeading>Automation</MessageAuthorHeading>
319 <FoldedMessageHeader
@@ -888,6 +889,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
889 !folded && !mediaOnly && !fileCardsOnly && !audioOnly && "p-3",
890 folded && expanded && "w-full",
891 )}
892 + data-user-message-bubble=""
893 >
894 {/* Outside the fold so a collapsed message still has a heading to navigate to. */}
895 {mediaAboveText ? null : (
apps/web/src/components/settings/ThemeCssEditor.tsx new
+124
@@ -0,0 +1,124 @@
1 +import { useId, useState, type KeyboardEvent } from "react";
2 +
3 +import { Button } from "../ui/button";
4 +
5 +export function ThemeCssEditor({
6 + value,
7 + onChange,
8 +}: {
9 + value: string;
10 + onChange: (value: string) => void;
11 +}) {
12 + const hintId = useId();
13 + const [position, setPosition] = useState({ line: 1, column: 1 });
14 + const [tabIndents, setTabIndents] = useState(true);
15 +
16 + function updatePosition(editor: HTMLTextAreaElement) {
17 + const preceding = editor.value.slice(0, editor.selectionStart).split("\n");
18 + setPosition({ line: preceding.length, column: (preceding.at(-1)?.length ?? 0) + 1 });
19 + }
20 +
21 + function replaceSelection(editor: HTMLTextAreaElement, replacement: string) {
22 + // Native insertion preserves undo history for indentation as well as typing.
23 + if (!document.execCommand("insertText", false, replacement)) {
24 + editor.setRangeText(replacement, editor.selectionStart, editor.selectionEnd, "end");
25 + }
26 + onChange(editor.value);
27 + updatePosition(editor);
28 + }
29 +
30 + function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
31 + if (event.nativeEvent.isComposing || event.ctrlKey || event.metaKey || event.altKey) return;
32 + const editor = event.currentTarget;
33 + if (event.key === "Escape") {
34 + event.preventDefault();
35 + event.stopPropagation();
36 + setTabIndents(false);
37 + return;
38 + }
39 + if (event.key === "Tab" && tabIndents) {
40 + event.preventDefault();
41 + const start = editor.selectionStart;
42 + const end = editor.selectionEnd;
43 + const lineStart = start === 0 ? 0 : editor.value.lastIndexOf("\n", start - 1) + 1;
44 + if (start === end && !event.shiftKey) {
45 + replaceSelection(editor, " ");
46 + } else if (start === end) {
47 + const indent = editor.value.slice(lineStart).match(/^(?: {1,2}|\t)/)?.[0] ?? "";
48 + if (!indent) return;
49 + editor.setSelectionRange(lineStart, lineStart + indent.length);
50 + replaceSelection(editor, "");
51 + editor.setSelectionRange(
52 + Math.max(lineStart, start - indent.length),
53 + Math.max(lineStart, end - indent.length),
54 + );
55 + } else {
56 + // A selection ending at a line's start leaves that next line untouched.
57 + const blockEnd = end > start && editor.value[end - 1] === "\n" ? end - 1 : end;
58 + const selected = editor.value.slice(lineStart, blockEnd);
59 + const replacement = selected
60 + .split("\n")
61 + .map((line) => (event.shiftKey ? line.replace(/^(?: {1,2}|\t)/, "") : ` ${line}`))
62 + .join("\n");
63 + editor.setSelectionRange(lineStart, blockEnd);
64 + replaceSelection(editor, replacement);
65 + editor.setSelectionRange(lineStart, lineStart + replacement.length);
66 + }
67 + updatePosition(editor);
68 + } else if (event.key === "Enter" && editor.selectionStart === editor.selectionEnd) {
69 + const precedingLine = editor.value.slice(0, editor.selectionStart).split("\n").at(-1) ?? "";
70 + const indent = precedingLine.match(/^[\t ]*/)?.[0] ?? "";
71 + event.preventDefault();
72 + replaceSelection(editor, `\n${indent}${precedingLine.trimEnd().endsWith("{") ? " " : ""}`);
73 + }
74 + }
75 +
76 + return (
77 + <div className="space-y-2">
78 + <div className="overflow-hidden rounded-lg border border-input bg-code text-foreground focus-within:border-ring focus-within:ring-3 focus-within:ring-inset focus-within:ring-ring/24">
79 + <textarea
80 + aria-label="Custom CSS"
81 + aria-describedby={hintId}
82 + autoCapitalize="off"
83 + autoComplete="off"
84 + autoCorrect="off"
85 + spellCheck={false}
86 + wrap="off"
87 + className="block h-52 w-full resize-none bg-transparent p-3 font-mono text-xs leading-5 outline-none"
88 + value={value}
89 + onFocus={() => setTabIndents(true)}
90 + onChange={(event) => {
91 + onChange(event.currentTarget.value);
92 + updatePosition(event.currentTarget);
93 + }}
94 + onSelect={(event) => updatePosition(event.currentTarget)}
95 + onKeyDown={handleKeyDown}
96 + />
97 + <div className="flex items-center justify-between border-t border-input px-3 py-1 font-mono text-xs">
98 + <span>CSS</span>
99 + <span>
100 + Ln {position.line}, Col {position.column}
101 + </span>
102 + </div>
103 + </div>
104 + <div className="flex items-start justify-between gap-2">
105 + <p id={hintId} className="text-xs text-muted-foreground">
106 + {tabIndents
107 + ? "Tab indents. Shift+Tab unindents. Press Escape, then Tab to leave."
108 + : "Tab moves to the next control."}
109 + </p>
110 + <Button
111 + size="xs"
112 + variant="ghost"
113 + disabled={!value}
114 + onClick={() => {
115 + onChange("");
116 + setPosition({ line: 1, column: 1 });
117 + }}
118 + >
119 + Clear CSS
120 + </Button>
121 + </div>
122 + </div>
123 + );
124 +}
apps/web/src/components/settings/ThemeEditorPanel.tsx
+41 -2
@@ -4,6 +4,7 @@ import {
4 PlusIcon,
5 XIcon,
6 ChevronDownIcon,
7 + ChevronRightIcon,
8 ChevronUpIcon,
9 } from "lucide-react";
10 import { useEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from "react";
@@ -36,6 +37,7 @@ import { Switch } from "../ui/switch";
37 import { Toggle, ToggleGroup } from "../ui/toggle-group";
38 import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
39 import { getThemeRoleLabel, ThemeColorField } from "./ThemeColorPicker";
40 +import { ThemeCssEditor } from "./ThemeCssEditor";
41 import {
42 clearThemeInspectorHover,
43 clearThemeInspectorHighlights,
@@ -348,6 +350,8 @@ export function ThemeEditorPanel({
350 Record<ThemeAppearance, boolean>
351 >({ light: false, dark: false });
352 const [shouldRegenerateGuidedColors, setShouldRegenerateGuidedColors] = useState(false);
353 + const [css, setCss] = useState("");
354 + const [cssOpen, setCssOpen] = useState(false);
355 const [error, setError] = useState<string | null>(null);
356 const [isMinimized, setIsMinimized] = useState(false);
357 const [roleQuery, setRoleQuery] = useState("");
@@ -400,6 +404,8 @@ export function ThemeEditorPanel({
404 setSimpleColorsDirtyByAppearance({ light: false, dark: false });
405 setShouldRegenerateGuidedColors(sourceTheme !== null && sourceTheme.managed !== true);
406 setColorsByAppearance(nextColors);
407 + setCss(sourceTheme?.css ?? "");
408 + setCssOpen(Boolean(sourceTheme?.css));
409 setSelectedRole(null);
410 setUsageCount(null);
411 setIsInspecting(false);
@@ -418,6 +424,8 @@ export function ThemeEditorPanel({
424 (theme.id === nameTargetId || theme.label.trim().toLowerCase() === normalizedName),
425 ) ?? null);
426 const takenAppearances = mergeTarget ? getThemeModes(mergeTarget) : [];
427 + // A merge keeps the target's CSS when this draft has none.
428 + const cssForSave = css.trim() ? css : (mergeTarget?.css ?? "");
429 const editableAppearances = editingTheme ? getThemeModes(editingTheme) : null;
430
431 const appearanceLockReason = (appearance: ThemeAppearance): string | null => {
@@ -447,8 +455,8 @@ export function ThemeEditorPanel({
455 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- applies the edited colors to the document as a live theme preview while the editor is open
456 useEffect(() => {
457 if (!open) return;
450 - applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance);
451 - }, [activeAppearance, colorsByAppearance, open]);
458 + applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance, cssForSave);
459 + }, [activeAppearance, colorsByAppearance, cssForSave, open]);
460
461 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- restores the document theme when the editor closes or unmounts
462 useEffect(() => {
@@ -757,6 +765,13 @@ export function ThemeEditorPanel({
765 return;
766 }
767
768 + if (mergeTarget?.css && css.trim() && mergeTarget.css !== css) {
769 + setError(
770 + `“${mergeTarget.label}” has different custom CSS. Use the same CSS or pick another name.`,
771 + );
772 + return;
773 + }
774 +
775 try {
776 const colorsForSave = !isAdvanced
777 ? {
@@ -792,6 +807,7 @@ export function ThemeEditorPanel({
807 ...Object.fromEntries(editedModes.map((mode) => [mode, colorsForSave[mode]])),
808 },
809 ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
810 + ...(cssForSave ? { css: cssForSave } : {}),
811 }),
812 ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
813 });
@@ -811,6 +827,7 @@ export function ThemeEditorPanel({
827 ? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } }
828 : {}),
829 ...(isAdvanced ? {} : { managed: true }),
830 + ...(cssForSave ? { css: cssForSave } : {}),
831 }),
832 ...(editingTheme.collection ? { collection: editingTheme.collection } : {}),
833 });
@@ -834,6 +851,7 @@ export function ThemeEditorPanel({
851 [activeAppearance]: colorsForSave[activeAppearance],
852 },
853 ...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
854 + ...(cssForSave ? { css: cssForSave } : {}),
855 }),
856 ...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
857 });
@@ -845,6 +863,7 @@ export function ThemeEditorPanel({
863 appearance: activeAppearance,
864 colors: colorsForSave[activeAppearance],
865 ...(isAdvanced ? {} : { managed: true }),
866 + ...(cssForSave ? { css: cssForSave } : {}),
867 }),
868 );
869 }
@@ -1207,6 +1226,26 @@ export function ThemeEditorPanel({
1226 {renderColorsHeader()}
1227 {renderColorFields()}
1228 </div>
1229 + <div className="space-y-2">
1230 + <Button
1231 + aria-expanded={cssOpen}
1232 + size="xs"
1233 + variant="ghost"
1234 + onClick={() => setCssOpen(!cssOpen)}
1235 + >
1236 + {cssOpen ? <ChevronDownIcon /> : <ChevronRightIcon />}
1237 + Custom CSS
1238 + </Button>
1239 + {cssOpen ? (
1240 + <>
1241 + <p className="text-xs text-muted-foreground">
1242 + Saved with this theme and included when you export it. Web and desktop only.
1243 + Rules that load remote files are ignored.
1244 + </p>
1245 + <ThemeCssEditor value={css} onChange={setCss} />
1246 + </>
1247 + ) : null}
1248 + </div>
1249 </div>
1250 <div className="flex items-center justify-end gap-2 border-t border-border/70 px-3 py-2">
1251 <Button size="sm" variant="ghost" onClick={() => onOpenChange(false)}>
apps/web/src/hooks/useDefaultTheme.test.ts
+11 -1
@@ -1,6 +1,6 @@
1 import { describe, expect, it } from "vite-plus/test";
2
3 -import { defaultThemeGeneration, defaultThemeToApply } from "./useDefaultTheme";
3 +import { defaultThemeGeneration, defaultThemeToApply, themeSetsOwnMode } from "./useDefaultTheme";
4
5 const BASE = {
6 environmentId: "env-1",
@@ -27,3 +27,13 @@ describe("default theme adoption", () => {
27 expect(next).not.toBe(applied);
28 });
29 });
30 +
31 +it("lets a theme set its own mode only when no mode was set with it or after it", () => {
32 + const theme = "2026-11-13T10:00:00.000Z";
33 + const set = (defaultAppearance: string, defaultAppearanceSetAt: string) =>
34 + themeSetsOwnMode({ defaultThemeSetAt: theme, defaultAppearance, defaultAppearanceSetAt });
35 + expect(set("", "")).toBe(true);
36 + expect(set("dark", "2026-11-13T09:00:00.000Z")).toBe(true);
37 + expect(set("dark", theme)).toBe(false);
38 + expect(set("light", "2026-11-13T11:00:00.000Z")).toBe(false);
39 +});
apps/web/src/hooks/useDefaultTheme.ts
+41 -6
@@ -5,6 +5,7 @@ import { getThemeDefinition, singleAppearanceOf, subscribeToCustomThemes } from
5 import { setAppearanceMode, setTheme } from "./useTheme";
6
7 const APPLIED_DEFAULT_THEME_STORAGE_PREFIX = "t3code:default-theme-applied:v2:";
8 +const APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX = "t3code:default-appearance-applied:v1:";
9
10 /** Include set time so reasserting the same theme still applies. */
11 export function defaultThemeGeneration(theme: string, setAt: string): string {
@@ -28,6 +29,16 @@ export function defaultThemeToApply(input: {
29 return generation;
30 }
31
32 +/** A single-appearance theme sets its own mode unless a mode was set with it or after it. */
33 +export function themeSetsOwnMode(input: {
34 + readonly defaultThemeSetAt: string;
35 + readonly defaultAppearance: string;
36 + readonly defaultAppearanceSetAt: string;
37 +}): boolean {
38 + // ISO timestamps from one server compare correctly as strings.
39 + return input.defaultAppearance === "" || input.defaultAppearanceSetAt < input.defaultThemeSetAt;
40 +}
41 +
42 function readAppliedGeneration(storageKey: string): string | null {
43 if (typeof window === "undefined") return null;
44 try {
@@ -47,7 +58,8 @@ function adoptDefaultTheme(): void {
58 if (typeof window === "undefined") return;
59 const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom);
60 if (environmentId === null) return;
50 - const { defaultTheme, defaultThemeSetAt } = appAtomRegistry.get(themeServerSettingsAtom);
61 + const settings = appAtomRegistry.get(themeServerSettingsAtom);
62 + const { defaultTheme, defaultThemeSetAt } = settings;
63 const definition = getThemeDefinition(defaultTheme);
64 const storageKey = `${APPLIED_DEFAULT_THEME_STORAGE_PREFIX}${environmentId}`;
65 const generation = defaultThemeToApply({
@@ -63,10 +75,33 @@ function adoptDefaultTheme(): void {
75 if (!setTheme(defaultTheme)) return;
76 const half = singleAppearanceOf(definition);
77 // Only record adoption after both writes succeed, so an appearance failure remains retryable.
66 - if (half !== null && !setAppearanceMode(half)) return;
78 + if (half !== null && themeSetsOwnMode(settings) && !setAppearanceMode(half)) return;
79 writeAppliedGeneration(storageKey, generation);
80 }
81
82 +/** Like the theme, the environment's mode applies once per set, then local choices win. */
83 +function adoptDefaultAppearance(): void {
84 + if (typeof window === "undefined") return;
85 + const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom);
86 + const { defaultAppearance, defaultAppearanceSetAt } =
87 + appAtomRegistry.get(themeServerSettingsAtom);
88 + const storageKey = `${APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX}${environmentId}`;
89 + const generation = defaultThemeToApply({
90 + environmentId,
91 + defaultTheme: defaultAppearance,
92 + defaultThemeSetAt: defaultAppearanceSetAt,
93 + appliedGeneration: readAppliedGeneration(storageKey),
94 + resolves: true,
95 + });
96 + if (generation === null || defaultAppearance === "") return;
97 + if (setAppearanceMode(defaultAppearance)) writeAppliedGeneration(storageKey, generation);
98 +}
99 +
100 +function adoptDefaults(): void {
101 + adoptDefaultTheme();
102 + adoptDefaultAppearance();
103 +}
104 +
105 /**
106 * Applies the theme environment's default theme once per generation. Start it after the
107 * environment theme sync so a first-run client adopting the environment's own theme finds it
@@ -75,11 +110,11 @@ function adoptDefaultTheme(): void {
110 */
111 export function startDefaultThemeAdoption(): () => void {
112 const unsubscribes = [
78 - appAtomRegistry.subscribe(themeEnvironmentIdAtom, adoptDefaultTheme),
79 - appAtomRegistry.subscribe(themeServerSettingsAtom, adoptDefaultTheme),
80 - subscribeToCustomThemes(adoptDefaultTheme),
113 + appAtomRegistry.subscribe(themeEnvironmentIdAtom, adoptDefaults),
114 + appAtomRegistry.subscribe(themeServerSettingsAtom, adoptDefaults),
115 + subscribeToCustomThemes(adoptDefaults),
116 ];
82 - adoptDefaultTheme();
117 + adoptDefaults();
118 return () => {
119 for (const unsubscribe of unsubscribes) unsubscribe();
120 };
apps/web/src/themeCss.browser.test.ts new
+43
@@ -0,0 +1,43 @@
1 +import { expect, it } from "vite-plus/test";
2 +
3 +import { applyThemeCss } from "./themeCss";
4 +
5 +it("applies theme CSS and drops every rule that would load a remote file", () => {
6 + const probe = document.createElement("div");
7 + probe.dataset.themeCssProbe = "";
8 + document.body.append(probe);
9 + using _probe = { [Symbol.dispose]: () => probe.remove() };
10 + using _css = { [Symbol.dispose]: () => applyThemeCss(undefined) };
11 +
12 + applyThemeCss(`
13 + @import url(https://example.com/sheet.css);
14 + @namespace svg url(http://www.w3.org/2000/svg);
15 + @property --registered { syntax: "<url>"; inherits: false; initial-value: url(https://example.com/d); }
16 + @counter-style leak { system: cyclic; symbols: url(https://example.com/f); }
17 + @keyframes leak { to { background-image: url(https://example.com/g); } }
18 + :root { --leak: u\\72l(https://example.com/a); }
19 + [data-theme-css-probe] {
20 + color: rgb(1, 2, 3);
21 + background-image: u\\72l(https://example.com/b);
22 + list-style-image: var(--leak);
23 + border-image-source: var(--registered);
24 + mask-image: v\\61r(--none, u\\72l(https://example.com/e));
25 + @media (min-width: 0px) { cursor: url(https://example.com/c), auto; }
26 + }
27 + `);
28 +
29 + const style = getComputedStyle(probe);
30 + expect(style.color).toBe("rgb(1, 2, 3)");
31 + expect(style.backgroundImage).toBe("none");
32 + expect(style.listStyleImage).toBe("none");
33 + expect(style.borderImageSource).toBe("none");
34 + expect(style.maskImage).toBe("none");
35 + const kept = document.adoptedStyleSheets.flatMap((sheet) =>
36 + Array.from(sheet.cssRules, (rule) => rule.cssText),
37 + );
38 + expect(kept.join("\n")).not.toContain("example.com");
39 + expect(style.cursor).toBe("auto");
40 +
41 + applyThemeCss(undefined);
42 + expect(getComputedStyle(probe).color).not.toBe("rgb(1, 2, 3)");
43 +});
apps/web/src/themeCss.ts new
+64
@@ -0,0 +1,64 @@
1 +import { themeCssValueFetches } from "@t3tools/shared/themeCss";
2 +
3 +// Theme CSS comes from imported files and from agents, so it must not fetch: a
4 +// url() on an attribute selector can send what is on screen to another host.
5 +// The browser parses the text first, so the checks see normalized values and
6 +// CSS escapes in a function name cannot dodge them.
7 +
8 +let themeSheet: CSSStyleSheet | null = null;
9 +let appliedCss = "";
10 +
11 +type RuleParent = Pick<CSSStyleSheet, "cssRules" | "deleteRule">;
12 +
13 +// @keyframes also has both members, but its deleteRule takes a keyframe selector.
14 +const isRuleParent = (rule: CSSRule): rule is CSSRule & RuleParent =>
15 + "cssRules" in rule && "deleteRule" in rule && !(rule instanceof CSSKeyframesRule);
16 +
17 +function stripDeclarations(rule: CSSRule): boolean {
18 + if (!("style" in rule) || !(rule.style instanceof CSSStyleDeclaration)) return false;
19 + for (let item = rule.style.length - 1; item >= 0; item--) {
20 + const property = rule.style.item(item);
21 + if (themeCssValueFetches(rule.style.getPropertyValue(property))) {
22 + rule.style.removeProperty(property);
23 + }
24 + }
25 + return true;
26 +}
27 +
28 +/** Keeps only rule shapes it can check, so a new at-rule that fetches is dropped by default. */
29 +function stripFetches(parent: RuleParent): void {
30 + for (let index = parent.cssRules.length - 1; index >= 0; index--) {
31 + const rule = parent.cssRules[index];
32 + if (!rule) continue;
33 + const hasStyle = stripDeclarations(rule);
34 + if (rule instanceof CSSKeyframesRule) {
35 + for (const frame of rule.cssRules) stripDeclarations(frame);
36 + } else if (isRuleParent(rule)) {
37 + stripFetches(rule);
38 + } else if (rule instanceof CSSPropertyRule) {
39 + // A registered property's initial value is used wherever var() reads it.
40 + if (themeCssValueFetches(rule.initialValue ?? "")) parent.deleteRule(index);
41 + } else if (
42 + !hasStyle &&
43 + !(rule instanceof CSSLayerStatementRule) &&
44 + // Names a namespace without loading it. CSSOM refuses to delete one while style rules remain.
45 + !(rule instanceof CSSNamespaceRule)
46 + ) {
47 + parent.deleteRule(index);
48 + }
49 + }
50 +}
51 +
52 +export function applyThemeCss(css: string | undefined): void {
53 + if (typeof document === "undefined" || typeof CSSStyleSheet === "undefined") return;
54 + const next = css ?? "";
55 + if (next === appliedCss) return;
56 + appliedCss = next;
57 + if (!themeSheet) {
58 + // Adopted sheets order after the document's own, and they cannot hold @import.
59 + themeSheet = new CSSStyleSheet();
60 + document.adoptedStyleSheets = [...document.adoptedStyleSheets, themeSheet];
61 + }
62 + themeSheet.replaceSync(next);
63 + stripFetches(themeSheet);
64 +}
apps/web/src/themeCssHooks.test.ts new
+28
@@ -0,0 +1,28 @@
1 +// @effect-diagnostics nodeBuiltinImport:off - a plain test that scans the source tree once.
2 +import * as NodeFS from "node:fs";
3 +import * as NodePath from "node:path";
4 +
5 +import { THEME_CSS_HOOKS } from "@t3tools/shared/themeCss";
6 +import { expect, it } from "vite-plus/test";
7 +
8 +const sourceDirectory = import.meta.dirname;
9 +const source = NodeFS.readdirSync(sourceDirectory, { recursive: true, encoding: "utf8" })
10 + .filter((file) => /\.(tsx?|css)$/.test(file) && !file.includes(".test."))
11 + .map((file) => NodeFS.readFileSync(NodePath.join(sourceDirectory, file), "utf8"))
12 + .join("\n");
13 +
14 +/** How the selector's hook is written in source: an attribute, a slot value, or a class name. */
15 +function sourcePattern(selector: string): RegExp {
16 + const slot = /^\[data-slot="([a-z-]+)"\]$/.exec(selector)?.[1];
17 + if (slot) return new RegExp(`data-slot["']?\\s*[:=]\\s*["']${slot}["']`);
18 + const attribute = /^\[(data-[a-z-]+)/.exec(selector)?.[1];
19 + return new RegExp(`\\b${attribute ?? selector.slice(1)}\\b`);
20 +}
21 +
22 +// Theme CSS and the agent guide rely on these selectors. Rename one in the guide too.
23 +it.each(THEME_CSS_HOOKS.map((hook) => hook.selector))(
24 + "%s is still in the web source",
25 + (selector) => {
26 + expect(source).toMatch(sourcePattern(selector));
27 + },
28 +);
apps/web/src/themePalette.test.ts
+2
@@ -271,8 +271,10 @@ describe("theme files", () => {
271 variants: {
272 dark: { canvas: "#101827", text: "#eef5ff" },
273 },
274 + css: "[data-chat-header] { border-bottom: 1px solid red; }",
275 });
276
277 + expect(JSON.parse(serializeThemeFile(theme)).css).toBe(theme.css);
278 expect(getThemeModes(theme)).toEqual(["light", "dark"]);
279 expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
280 canvas: canonical("#101827"),
apps/web/src/themePalette.ts
+22 -2
@@ -1,5 +1,5 @@
1 import { pipe } from "effect/Function";
2 -import type { EnvironmentTheme } from "@t3tools/contracts";
2 +import { THEME_CSS_MAX_LENGTH, type EnvironmentTheme } from "@t3tools/contracts";
3 import * as Equal from "effect/Equal";
4 import * as Option from "effect/Option";
5 import * as Schema from "effect/Schema";
@@ -30,6 +30,7 @@ import {
30 } from "./lib/contextChipAccents";
31
32 import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry";
33 +import { applyThemeCss } from "./themeCss";
34 import { themeServerEnvironmentThemesAtom } from "./state/server";
35
36 export { EMBER_THEME, GROVE_THEME, IRIS_THEME, OCEAN_THEME, T3_CHAT_THEME, THEME_COLOR_ROLES };
@@ -65,6 +66,7 @@ export type ThemeFile = Readonly<{
66 variants?: ThemeVariantOverrides;
67 collection?: ThemeCollection;
68 managed?: boolean;
69 + css?: string;
70 }>;
71
72 const customThemeListeners = new Set<() => void>();
@@ -120,6 +122,10 @@ function isThemeLabel(value: unknown): value is string {
122 return typeof value === "string" && value.trim().length > 0 && value.trim().length <= 48;
123 }
124
125 +function isThemeCss(value: unknown): value is string {
126 + return typeof value === "string" && value.length <= THEME_CSS_MAX_LENGTH;
127 +}
128 +
129 function parseThemeCollection(value: unknown): ThemeCollection | undefined {
130 return isRecord(value) &&
131 typeof value.id === "string" &&
@@ -184,6 +190,7 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {
190 ...(variants ? { variants } : {}),
191 ...(collection ? { collection } : {}),
192 ...(value.managed === true ? { managed: true } : {}),
193 + ...(isThemeCss(value.css) && value.css.length > 0 ? { css: value.css } : {}),
194 };
195 }
196
@@ -287,6 +294,7 @@ function environmentThemeDefinition(theme: EnvironmentTheme): ThemeDefinition {
294 theme.variants === undefined
295 ? { managed: true }
296 : {}),
297 + ...(theme.css ? { css: theme.css } : {}),
298 };
299 }
300
@@ -1496,6 +1504,10 @@ export function parseThemeFile(value: unknown): ThemeDefinition {
1504 throw new Error("Theme collections need a valid id and label.");
1505 }
1506
1507 + if (value.css !== undefined && !isThemeCss(value.css)) {
1508 + throw new Error(`Theme CSS must be text of ${THEME_CSS_MAX_LENGTH} characters or fewer.`);
1509 + }
1510 +
1511 const fallback = getDefaultThemeColors(appearance);
1512 const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
1513 if (value.variants !== undefined) {
@@ -1523,6 +1535,7 @@ export function parseThemeFile(value: unknown): ThemeDefinition {
1535 ...(Object.keys(variants).length > 0 ? { variants } : {}),
1536 ...(collection ? { collection } : {}),
1537 ...(value.managed === true ? { managed: true } : {}),
1538 + ...(value.css ? { css: value.css } : {}),
1539 };
1540 }
1541
@@ -1537,6 +1550,7 @@ export function serializeThemeFile(theme: ThemeDefinition): string {
1550 ...(canonicalTheme.variants ? { variants: canonicalTheme.variants } : {}),
1551 ...(canonicalTheme.collection ? { collection: canonicalTheme.collection } : {}),
1552 ...(canonicalTheme.managed ? { managed: true } : {}),
1553 + ...(canonicalTheme.css ? { css: canonicalTheme.css } : {}),
1554 };
1555 return `${JSON.stringify(file, null, 2)}\n`;
1556 }
@@ -1612,7 +1626,11 @@ export function getThemeColorVariable(role: ThemeColorRole): string {
1626 export const THEME_PREVIEW_ID = "__preview";
1627
1628 /** Callers must restore the stored theme with refreshTheme when the draft closes. */
1615 -export function applyThemeColorPreview(colors: ThemeColors, appearance: ThemeAppearance): void {
1629 +export function applyThemeColorPreview(
1630 + colors: ThemeColors,
1631 + appearance: ThemeAppearance,
1632 + css?: string,
1633 +): void {
1634 if (typeof document === "undefined") return;
1635 const root = document.documentElement;
1636 if (!root?.style) return;
@@ -1623,6 +1641,7 @@ export function applyThemeColorPreview(colors: ThemeColors, appearance: ThemeApp
1641 if (isThemeColor(value)) root.style.setProperty(APP_THEME_VARIABLES[role], value);
1642 }
1643 applyContextChipVariables(root, colors);
1644 + applyThemeCss(css);
1645 setThemePreviewAppearance(appearance);
1646 }
1647
@@ -1634,6 +1653,7 @@ export function applyThemePalette(theme: ThemePreference, appearance?: ThemeAppe
1653
1654 setThemePreviewAppearance(null);
1655 const palette = getThemeDefinition(theme);
1656 + applyThemeCss(palette?.css);
1657
1658 if (palette) {
1659 root.dataset.themeId = palette.id;
docs/user/appearance.md
+26 -1
@@ -54,6 +54,31 @@ On web and desktop, choose **Create theme** to adjust a palette, or import a T3
54 theme. The theme editor's color picker lets you select an area of the app to find the color to
55 change. Export your theme as JSON to share it.
56
57 +### Custom CSS
58 +
59 +For a change that colors cannot make, open **Custom CSS** in the theme editor. The CSS is saved with
60 +the theme, applies after T3 Code's own styles on web and desktop, and is included in exports. Use
61 +`.dark` or `:root:not(.dark)` to target one appearance.
62 +
63 +Custom CSS cannot load files. `@import`, `image-set()`, and `url()` are ignored, except `url()`
64 +with a `data:` address or an `#id`. This keeps an imported theme from sending what is on your screen
65 +to another site.
66 +
67 +Class names in the app change between releases. For rules that keep working, target `data-slot`
68 +and other `data-` attributes, such as `[data-chat-header]` or `[data-slot="button"]`.
69 +
70 +If a rule hides something you need, run `t3 theme set t3-chat` on the server to switch to a
71 +built-in theme, or press **Cmd+Option+A** on macOS or **Ctrl+Alt+A** on Windows/Linux to pick
72 +another theme.
73 +
74 +### Ask an agent
75 +
76 +An agent on the same machine as the server can restyle T3 Code for you. Ask it to change the look,
77 +for example "make T3 Code's chat header taller" or "give T3 Code a solarized theme". It publishes
78 +an [environment theme](#environment-themes) with colors and CSS, and web and desktop clients of that
79 +server switch to it. It can also switch them to light, dark, or system mode. The thread must run
80 +in Full access. Ask the agent to set a built-in theme to undo it.
81 +
82 ## Environment themes
83
84 Environment themes and defaults come from the server serving your web app or the desktop app's
@@ -103,7 +128,7 @@ For an integration that generates a palette, this shorter format also works:
128
129 Set `appearance` to `light` or `dark` and supply hex colors for `canvas` and `accent`. T3 Code
130 generates the rest. The optional `colors` overrides use the names in the theme editor's advanced
106 -view.
131 +view. An optional `css` string adds [custom CSS](#custom-css).
132
133 Write updates to a temporary file and rename it into place so clients never read a partial theme.
134 Invalid files are not published.
evals/mcp-tool-use/cases/themes.ndjson new
+3
@@ -0,0 +1,3 @@
1 +{"id": "restyle-t3-code-uses-theme-set", "area": "themes", "kind": "guard", "pattern": "restyle T3 Code itself", "experience": "Asked to change how T3 Code itself looks, an agent reads the theme guide, then publishes a theme with t3_theme_set. It does not write theme files by hand or edit the project.", "rule": "t3_theme_set: Restyle T3 Code itself, only when the user asks.", "privacy": "commit-safe", "source": {"pullRequest": "https://github.com/pingdotgg/t3code/pull/29293", "note": "A user needed a look the app had no setting for."}, "setup": {"role": "top", "mocks": {"t3_theme_read": {"current": "", "builtIn": ["t3-chat", "grove", "ocean", "ember", "iris"], "published": [], "guide": "Themes restyle T3 Code on web and desktop. `canvas` and `accent` (hex) derive a full palette. `css` applies after the app's styles."}, "t3_theme_set": {"themeId": "night-terminal", "published": true}}}, "prompt": "Make T3 Code itself look like a late-night terminal: near-black background with a green accent.", "expect": {"calls": [{"tool": "t3_theme_set", "args": {"theme.appearance": "dark"}}], "order": ["t3_theme_read", "t3_theme_set"]}, "maxSteps": 6}
2 +{"id": "control-project-theme-edit-leaves-t3-code-alone", "area": "themes", "kind": "control", "pattern": "ordinary task: edit the project's own theme", "experience": "The user's project has a theme of its own. A request to change it is a file edit. T3 Code's look must not change.", "rule": "t3_theme_set: Restyle T3 Code itself, only when the user asks.", "privacy": "commit-safe", "setup": {"role": "top", "world": {"files": {"src/theme.css": ":root { --accent: #3b82f6; }\n.dark { --accent: #60a5fa; }\n"}}}, "prompt": "Change the dark theme accent to green.", "expect": {"notCalls": ["t3_theme_set", "t3_theme_read"], "textMust": ["theme\\.css"]}, "maxSteps": 6, "source": {"pullRequest": "https://github.com/pingdotgg/t3code/pull/35247", "note": "A real Haiku turn in the dev app during this work: asked to change a project's theme file, it edited the file and left T3 Code alone."}}
3 +{"id": "dark-mode-request-sets-appearance", "area": "themes", "kind": "guard", "pattern": "switch T3 Code to dark mode", "experience": "Asked to switch T3 Code to dark mode, an agent sets the appearance with t3_theme_set. It does not tell the user to do it by hand, and it does not publish a new theme.", "rule": "t3_theme_set: `appearance` switches them to light, dark, or system mode, with or without a theme.", "privacy": "commit-safe", "source": {"pullRequest": "https://github.com/pingdotgg/t3code/pull/35247", "note": "In the dev app, an agent asked to swap to dark mode said it could not and sent the user to Settings."}, "setup": {"role": "top", "mocks": {"t3_theme_read": {"current": "sumi", "builtIn": ["t3-chat", "grove", "ocean", "ember", "iris"], "published": [{"id": "sumi", "name": "Sumi", "hasCss": true}], "guide": "Themes restyle T3 Code on web and desktop."}, "t3_theme_set": {"appearance": "dark", "published": false}}}, "prompt": "swap me to dark mode", "expect": {"calls": [{"tool": "t3_theme_set", "args": {"appearance": "dark"}}]}, "maxSteps": 4}
evals/mcp-tool-use/run.ts
+2
@@ -65,6 +65,7 @@ import {
65 CHILD_PULL_REQUEST_REPORT_NEXT,
66 PullRequestsToolkit,
67 } from "../../apps/server/src/mcp/toolkits/pullRequests/tools.ts";
68 +import { ThemeToolkit } from "../../apps/server/src/mcp/toolkits/theme/tools.ts";
69 import { ThreadToolkit } from "../../apps/server/src/mcp/toolkits/thread/tools.ts";
70 import { WorktreeToolkit } from "../../apps/server/src/mcp/toolkits/worktree/tools.ts";
71 import {
@@ -451,6 +452,7 @@ const t3SourceTools: ReadonlyArray<Tool.Any> = [
452 AttachmentToolkit,
453 ProjectToolkit,
454 EnvironmentToolkit,
455 + ThemeToolkit,
456 PreviewControlsToolkit,
457 WorktreeToolkit,
458 PullRequestsToolkit,
packages/client-runtime/src/t3ToolSummary.ts
+6
@@ -355,6 +355,12 @@ export function summarizeT3ToolCalls(
355 case "environment-update":
356 label = phrase("Updated", "update", `environment preferences ${times}`);
357 break;
358 + case "theme-read":
359 + label = phrase("Checked", "check", `themes ${times}`);
360 + break;
361 + case "theme-set":
362 + label = phrase("Set", "set", `the theme ${times}`);
363 + break;
364 case "environment-links":
365 label = phrase("Listed", "list", `linked environments ${times}`);
366 break;
packages/client-runtime/src/work-log/presentation.ts
+1
@@ -550,6 +550,7 @@ function summaryActionPriority(action: ToolGroupAction | T3McpToolSummaryAction)
550 case "project-delete":
551 case "project-clone":
552 case "environment-update":
553 + case "theme-set":
554 case "attachment-prepare":
555 case "attachment-discard":
556 case "attachment-send":
packages/contracts/src/rpc.ts
+2 -2
@@ -363,7 +363,7 @@ import {
363 DatabaseStorageStatus,
364 ServerSettings,
365 ServerSettingsError,
366 - ServerSettingsPatch,
366 + ClientServerSettingsPatch,
367 ListTextGeneratorModelsInput,
368 ListTextGeneratorModelsResult,
369 TextGeneratorError,
@@ -866,7 +866,7 @@ const WsPeerLinksAnswerRequestRpc = Rpc.make(WS_METHODS.peerLinksAnswerRequest,
866
867 const WsServerUpdateSettingsRpc = Rpc.make(WS_METHODS.serverUpdateSettings, {
868 payload: Schema.Struct({
869 - patch: ServerSettingsPatch,
869 + patch: ClientServerSettingsPatch,
870 providerInstanceMutation: Schema.optionalKey(ProviderInstanceMutation),
871 }),
872 success: ServerSettings,
packages/contracts/src/server.ts
+4
@@ -622,6 +622,8 @@ const EnvironmentThemeColors = Schema.Record(
622 TrimmedNonEmptyString.check(Schema.isMaxLength(64)),
623 );
624
625 +export const THEME_CSS_MAX_LENGTH = 20_000;
626 +
627 const environmentThemeFields = {
628 version: Schema.optional(Schema.Literal(1)),
629 name: TrimmedNonEmptyString.check(Schema.isMaxLength(48)),
@@ -636,6 +638,8 @@ const environmentThemeFields = {
638 dark: Schema.optional(EnvironmentThemeColors),
639 }),
640 ),
641 + /** Custom styles for web and desktop clients. */
642 + css: Schema.optional(Schema.String.check(Schema.isMaxLength(THEME_CSS_MAX_LENGTH))),
643 };
644
645 export const EnvironmentThemeFile = Schema.Struct(environmentThemeFields);
packages/contracts/src/settings.test.ts
+14
@@ -10,6 +10,7 @@ import {
10 import {
11 ClientSettingsSchema,
12 ClientSettingsPatch,
13 + ClientServerSettingsPatch,
14 ClaudeSettings,
15 DEFAULT_SERVER_SETTINGS,
16 globalIdleCompaction,
@@ -37,10 +38,23 @@ const decodeStringOnlyEnvironment = Schema.decodeUnknownSync(
38 ),
39 );
40 const decodeServerSettingsPatch = Schema.decodeUnknownSync(ServerSettingsPatch);
41 +const decodeClientServerSettingsPatch = Schema.decodeUnknownSync(ClientServerSettingsPatch);
42 const encodeServerSettings = Schema.encodeSync(ServerSettings);
43 const encodeServerSettingsPatch = Schema.encodeSync(ServerSettingsPatch);
44 const decodeClaudeSettings = Schema.decodeUnknownSync(ClaudeSettings);
45
46 +it("drops theme defaults from a client's settings patch", () => {
47 + expect(
48 + decodeClientServerSettingsPatch({
49 + newWorktreesStartFromOrigin: false,
50 + defaultTheme: "grove",
51 + defaultThemeSetAt: "2026-11-13T00:00:00.000Z",
52 + defaultAppearance: "dark",
53 + defaultAppearanceSetAt: "2026-11-13T00:00:00.000Z",
54 + }),
55 + ).toEqual({ newWorktreesStartFromOrigin: false });
56 +});
57 +
58 describe("storage cleanup settings", () => {
59 it("keeps cleanup disabled for existing installations", () => {
60 expect(decodeServerSettings({}).worktreeCleanup).toBeNull();
packages/contracts/src/settings.ts
+20
@@ -9,6 +9,7 @@ import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Duration from "effect/Duration";
11 import * as Schema from "effect/Schema";
12 +import * as Struct from "effect/Struct";
13 import * as SchemaTransformation from "effect/SchemaTransformation";
14 import {
15 EnvironmentId,
@@ -299,6 +300,10 @@ export const DefaultThemePreference = Schema.String.check(Schema.isMaxLength(64)
300 // Excluded from RPC patches so t3 theme set can validate syntax and resolvability.
301 export type DefaultThemePreference = typeof DefaultThemePreference.Type;
302
303 +/** A mode clients apply once per set, like the default theme. Empty sets none. */
304 +export const DefaultAppearancePreference = Schema.Literals(["", "light", "dark", "system"]);
305 +export type DefaultAppearancePreference = typeof DefaultAppearancePreference.Type;
306 +
307 export const DEFAULT_BROWSER_VIEWPORT: PreviewViewportSetting = FILL_PREVIEW_VIEWPORT;
308 export const DEFAULT_BROWSER_AUTO_SHOW_FLOATING_PREVIEW = true;
309 export {
@@ -1491,6 +1496,12 @@ export const ServerSettings = Schema.Struct({
1496 defaultThemeSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
1497 Schema.withDecodingDefault(Effect.succeed("")),
1498 ),
1499 + defaultAppearance: DefaultAppearancePreference.pipe(
1500 + Schema.withDecodingDefault(Effect.succeed("" as const)),
1501 + ),
1502 + defaultAppearanceSetAt: Schema.String.check(Schema.isMaxLength(64)).pipe(
1503 + Schema.withDecodingDefault(Effect.succeed("")),
1504 + ),
1505 environmentIcon: ForwardCompatibleNullable(EnvironmentMachineKind).pipe(
1506 Schema.withDecodingDefault(Effect.succeed(null)),
1507 ),
@@ -1901,6 +1912,10 @@ export const ServerSettingsPatch = Schema.Struct({
1912 automaticGitFetchInterval: Schema.optionalKey(Schema.DurationFromMillis),
1913 providerHealthRefreshInterval: Schema.optionalKey(Schema.DurationFromMillis),
1914 backgroundActivityProfile: Schema.optionalKey(BackgroundActivityProfile),
1915 + defaultTheme: Schema.optionalKey(DefaultThemePreference),
1916 + defaultThemeSetAt: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(64))),
1917 + defaultAppearance: Schema.optionalKey(DefaultAppearancePreference),
1918 + defaultAppearanceSetAt: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(64))),
1919 environmentIcon: Schema.optionalKey(Schema.NullOr(EnvironmentMachineKind)),
1920 defaultThreadEnvMode: Schema.optionalKey(Schema.NullOr(ThreadEnvMode)),
1921 newWorktreesStartFromOrigin: Schema.optionalKey(Schema.Boolean),
@@ -1959,6 +1974,11 @@ export const ServerSettingsPatch = Schema.Struct({
1974 });
1975 export type ServerSettingsPatch = typeof ServerSettingsPatch.Type;
1976
1977 +/** The theme service sets theme defaults after it validates them, so clients cannot. */
1978 +export const ClientServerSettingsPatch = ServerSettingsPatch.mapFields(
1979 + Struct.omit(["defaultTheme", "defaultThemeSetAt", "defaultAppearance", "defaultAppearanceSetAt"]),
1980 +);
1981 +
1982 export function requiredScopesForServerSettingsPatch(
1983 patch: ServerSettingsPatch,
1984 ): ReadonlyArray<AuthEnvironmentScope> {
packages/shared/package.json
+4
@@ -35,6 +35,10 @@
35 "types": "./src/themePalettes.ts",
36 "import": "./src/themePalettes.ts"
37 },
38 + "./themeCss": {
39 + "types": "./src/themeCss.ts",
40 + "import": "./src/themeCss.ts"
41 + },
42 "./themePreview": {
43 "types": "./src/themePreview.ts",
44 "import": "./src/themePreview.ts"
packages/shared/src/t3McpToolPresentation.ts
+4
@@ -55,6 +55,8 @@ export type T3McpToolSummaryAction =
55 | "environment-link"
56 | "environment-unlink"
57 | "environment-update"
58 + | "theme-read"
59 + | "theme-set"
60 | "attachment-prepare"
61 | "attachment-discard"
62 | "attachment-send"
@@ -355,6 +357,8 @@ const T3_MCP_TOOLS: Readonly<Record<string, T3McpToolDefinition>> = {
357 ["Update", "Updating", "Updated", "environment preferences"],
358 "environment-update",
359 ),
360 + t3_theme_read: tool(["Read", "Reading", "Read", "themes"], "theme-read"),
361 + t3_theme_set: tool(["Set", "Setting", "Set", "the theme"], "theme-set"),
362 t3_thread_launch: tool(["Launch", "Launching", "Launched", "a project thread"], "thread-create"),
363 t3_project_list: tool(["List", "Listing", "Listed", "projects"], "project-list"),
364 t3_project_read: tool(["Read", "Reading", "Read", "a project"], "project-read"),
packages/shared/src/themeCss.test.ts new
+23
@@ -0,0 +1,23 @@
1 +import { describe, expect, it } from "vite-plus/test";
2 +
3 +import { themeCssValueFetches } from "./themeCss.ts";
4 +
5 +describe("themeCssValueFetches", () => {
6 + it.each([
7 + ["background-image", 'url("https://example.com/a")', true],
8 + ["background-image", 'url("/api/thing")', true],
9 + ["background-image", 'image-set("https://example.com/a" 1x)', true],
10 + // An unparsed value keeps its escapes, so an escaped function name hides in it.
11 + ["--leak", "u\\72l(https://example.com/a)", true],
12 + ["background-image", "im\\61ge-set(var(--leak) 1x)", true],
13 + ["background-image", "v\\61r(--none, u\\72l(https://example.com/a))", true],
14 + // A no-break space before the scheme makes this a path on the app's own origin.
15 + ["background-image", 'url("\u00a0data:/../../probe")', true],
16 + ["background-image", 'url("data:image/png;base64,AA")', false],
17 + ["filter", 'url("#blur")', false],
18 + ["background-image", "var(--pattern)", false],
19 + ["color", "red", false],
20 + ])("%s: %s", (_property, value, fetches) => {
21 + expect(themeCssValueFetches(value)).toBe(fetches);
22 + });
23 +});
packages/shared/src/themeCss.ts new
+81
@@ -0,0 +1,81 @@
1 +import { THEME_COLOR_ROLES } from "./themePalettes.ts";
2 +
3 +const FETCHES_BY_STRING = /image-set\(|\bsrc\(/i;
4 +// Only CSS whitespace may come first. \s also matches U+00A0, which makes the address relative.
5 +const URL_NOT_LOCAL = /url\((?![ \t\n\f\r]*["']?(?:data:|#))/i;
6 +
7 +/**
8 + * Whether one declaration value can load a remote file. Clients drop those declarations.
9 + * A value with var() stays unparsed until use, and an escape can spell `var` or `url` in it,
10 + * so every value that still has a backslash is refused.
11 + */
12 +export function themeCssValueFetches(value: string): boolean {
13 + return value.includes("\\") || FETCHES_BY_STRING.test(value) || URL_NOT_LOCAL.test(value);
14 +}
15 +
16 +/** A text check for early feedback. CSS escapes can dodge it; the client check is the guard. */
17 +export function themeCssLoadsRemoteFiles(css: string): boolean {
18 + const code = css.replace(/\/\*[\s\S]*?\*\//g, "");
19 + return /@import/i.test(code) || FETCHES_BY_STRING.test(code) || URL_NOT_LOCAL.test(code);
20 +}
21 +
22 +/**
23 + * Selectors that theme CSS may rely on. Other class names are Tailwind utilities and change
24 + * between releases. themeCss.test.ts in apps/web fails when one of these leaves the source.
25 + */
26 +export const THEME_CSS_HOOKS = [
27 + { selector: '[data-slot="sidebar"]', styles: "app sidebar" },
28 + { selector: '[data-slot="sidebar-inner"]', styles: "sidebar surface" },
29 + { selector: "[data-thread-item]", styles: "sidebar thread row" },
30 + {
31 + selector: '[data-slot="project-monogram"]',
32 + styles: "project icon with letters; its svg holds the tile",
33 + },
34 + { selector: "[data-chat-header]", styles: "chat header" },
35 + { selector: '[data-workspace-area="conversation"]', styles: "chat area, behind the messages" },
36 + { selector: ".messages-timeline-scroll", styles: "chat scroller" },
37 + { selector: "[data-timeline-row-kind]", styles: 'chat row, such as ="message" or ="work"' },
38 + { selector: '[data-message-role="user"]', styles: "user message row" },
39 + { selector: "[data-user-message-bubble]", styles: "user message bubble" },
40 + { selector: '[data-message-role="assistant"]', styles: "assistant message row" },
41 + { selector: ".chat-markdown", styles: "assistant text" },
42 + { selector: ".chat-markdown-codeblock", styles: "code block" },
43 + { selector: "[data-chat-composer-form]", styles: "composer" },
44 + { selector: '[data-slot="composer-host"]', styles: "composer card" },
45 + { selector: ".composer-tiptap", styles: "composer text" },
46 + { selector: "[data-thread-details-card]", styles: "thread details card" },
47 + { selector: "[data-thread-terminal-drawer]", styles: "terminal drawer" },
48 + { selector: "[data-settings-page-scroll]", styles: "settings page" },
49 + { selector: '[data-slot="button"]', styles: "button" },
50 + { selector: '[data-slot="input"]', styles: "text input" },
51 + { selector: '[data-slot="switch"]', styles: "switch" },
52 + { selector: '[data-slot="select-trigger"]', styles: "select" },
53 + { selector: '[data-slot="dialog-popup"]', styles: "dialog" },
54 + { selector: '[data-slot="popover-popup"]', styles: "popover" },
55 + { selector: '[data-slot="menu-popup"]', styles: "menu" },
56 + { selector: '[data-slot="tooltip-popup"]', styles: "tooltip" },
57 + { selector: '[data-slot="scroll-area-scrollbar"]', styles: "overlay scrollbar" },
58 + { selector: '[data-slot="scroll-area-thumb"]', styles: "overlay scrollbar thumb" },
59 +] as const;
60 +
61 +/** What an agent needs to restyle the app. `t3_theme_read` returns it. */
62 +export const THEME_GUIDE = [
63 + "Themes restyle T3 Code on web and desktop. Mobile does not use them.",
64 + "",
65 + "Colors: `canvas` and `accent` (hex) derive a full palette. `colors` overrides single roles, and `variants.light` or `variants.dark` does that for the other appearance. Prefer colors over CSS.",
66 + `Roles: ${THEME_COLOR_ROLES.join(", ")}.`,
67 + "",
68 + "CSS: `css` applies after the app's styles. Use `.dark` or `:root:not(.dark)` for one appearance.",
69 + "It cannot load files: no @import, no image-set(), and url() only with data: or #id.",
70 + "A background image must be embedded as a data: address. `css` holds 20,000 characters, so keep the image near 10 KB.",
71 + "The app's own rules can be more specific. If a rule has no effect, add !important.",
72 + "It cannot reach the terminal text, the file tree, or diff internals. Use color roles for those.",
73 + "Native scrollbars take `::-webkit-scrollbar` and `::-webkit-scrollbar-thumb`.",
74 + "Icons are `svg.lucide`. stroke-width, stroke-linecap, and stroke-linejoin restyle them.",
75 + "",
76 + "Stable selectors (other class names change between releases, so do not use them):",
77 + ...THEME_CSS_HOOKS.map((hook) => `- ${hook.selector}: ${hook.styles}`),
78 + "",
79 + "You cannot see the result. Make small changes, then ask the user how it looks.",
80 + "To undo, set a built-in theme: t3-chat, grove, ocean, ember, or iris.",
81 +].join("\n");
packages/shared/src/themePalettes.ts
+2
@@ -103,6 +103,8 @@ export type ThemeDefinition = Readonly<{
103 collection?: Readonly<{ id: string; label: string }>;
104 sidebarArtwork?: boolean;
105 managed?: boolean;
106 + /** Custom styles for web and desktop. */
107 + css?: string;
108 }>;
109
110 export const T3_CODE_LIGHT_THEME_COLORS: ThemeColors = {