feat: agents can restyle T3 Code with theme colors and CSS #35247
Mergedt3dotgg(GitHub profile, opens in a new tab)merged 22 commits into
main fromrefs/pull/35247/headmerged by t3dotgg(GitHub profile, opens in a new tab) View on GitHubt3dotgg(GitHub profile, opens in a new tab) added labelsagent-context-increase
github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/environmentTheme.ts line 273OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -199,0 +240,21 @@240+ const publish = Effect.fn("EnvironmentThemeService.publish")(function* (241+ themeId: string,242+ file: EnvironmentThemeFile,243+ ) {244+ const fail = (reason: EnvironmentThemePublishError["reason"], cause?: unknown) =>245+ new EnvironmentThemePublishError({ themeId, reason, cause });246+ if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {247+ return yield* fail("invalid-id");248+ }249+ if (!environmentThemeFileHasColors(file)) return yield* fail("no-colors");250+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {251+ return yield* fail("remote-css");252+ }253+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(254+ Effect.mapError((cause) => fail("not-published", cause)),255+ );256+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");257+258+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;259+ // The watcher reads only .json names, so it never sees a half-written file.260+ const staging = `${destination}.staging-${process.pid}`;apps/web/src/themeCss.ts line 13OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,13 @@1+import { themeCssValueFetches } from "@t3tools/shared/themeCss";2+3+// Theme CSS comes from imported files and from agents, so it must not fetch: a4+// 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 and6+// CSS escapes in a function name cannot dodge them.7+8+let themeSheet: CSSStyleSheet | null = null;9+let appliedCss = "";10+11+function stripFetches(rules: CSSRuleList): void {12+ for (const rule of rules) {13+ if ("style" in rule && rule.style instanceof CSSStyleDeclaration) {packages/shared/src/themeCss.ts line 12OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,12 @@1+import { THEME_COLOR_ROLES } from "./themePalettes.ts";2+3+const FETCHES_BY_STRING = /image-set\(|\bsrc\(/i;4+const URL_NOT_LOCAL = /url\((?!\s*["']?\s*(?:data:|#))/i;5+// Custom properties and var() values stay unparsed until use, so escapes survive in them.6+const UNPARSED_VALUE = /var\(|env\(|attr\(/i;7+8+/** Whether one parsed declaration can load a remote file. Clients drop those declarations. */9+export function themeCssValueFetches(property: string, value: string): boolean {10+ if (FETCHES_BY_STRING.test(value)) return true;11+ const unparsed = property.startsWith("--") || UNPARSED_VALUE.test(value);12+ if (unparsed && value.includes("\\")) return true;apps/server/src/environmentTheme.ts line 270OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -199,0 +250,21 @@250+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {251+ return yield* fail("remote-css");252+ }253+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(254+ Effect.mapError((cause) => fail("not-published", cause)),255+ );256+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");257+258+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;259+ // The watcher reads only .json names, so it never sees a half-written file.260+ const staging = `${destination}.staging-${process.pid}`;261+ yield* fs.makeDirectory(environmentThemesDir, { recursive: true }).pipe(262+ Effect.andThen(fs.writeFileString(staging, contents)),263+ Effect.andThen(fs.rename(staging, destination)),264+ Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),265+ Effect.mapError((cause) => fail("not-published", cause)),266+ );267+ // The reader skips files past its count and size limits, so confirm this one is served.268+ const { themes } = yield* refresh;269+ if (!themes.some((theme) => theme.id === themeId)) {270+ yield* fs.remove(destination, { force: true }).pipe(Effect.ignore);apps/server/src/mcp/toolkits/theme/handlers.ts line 36OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +16,21 @@16+export const layer = McpToolAccess.toLayer(ThemeToolkit, {17+ t3_theme_read: McpToolAccess.reads(({ themeId }) =>18+ Effect.gen(function* () {19+ const themes = yield* EnvironmentTheme.EnvironmentThemeService;20+ const settings = yield* Settings.ServerSettingsService;21+ const published = yield* themes.current;22+ const { defaultTheme } = yield* settings.getSettings.pipe(Effect.mapError(unavailable));23+ const requested = published.find((theme) => theme.id === themeId);24+ if (themeId !== undefined && requested === undefined) {25+ return yield* invalid(`No published theme is named "${themeId}".`);26+ }27+ return {28+ current: defaultTheme,29+ builtIn: BUILT_IN_THEME_IDS,30+ published: published.map(({ id, name, css }) => ({ id, name, hasCss: Boolean(css) })),31+ ...(requested === undefined ? {} : { theme: Struct.omit(requested, ["id"]) }),32+ guide: THEME_GUIDE,33+ };34+ }),35+ ),36+ t3_theme_set: McpToolAccess.writesEnvironment(({ themeId, theme }) =>
- packages/shared/src/themeCss.ts lines 4 to 4OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,4 @@1+import { THEME_COLOR_ROLES } from "./themePalettes.ts";2+3+const FETCHES_BY_STRING = /image-set\(|\bsrc\(/i;4+const URL_NOT_LOCAL = /url\((?!\s*["']?\s*(?:data:|#))/i;apps/server/src/environmentTheme.ts line 263OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -197,3 +238,17 @@197238 Effect.asVoid,198239 );199240241+ // One publish at a time: they share a staging path, and each one checks what is served after it.242+ const publishSemaphore = yield* Semaphore.make(1);243+244+ const publish = Effect.fn("EnvironmentThemeService.publish")(function* (245+ themeId: string,246+ file: EnvironmentThemeFile,247+ ) {248+ const fail = (reason: EnvironmentThemePublishError["reason"], cause?: unknown) =>249+ new EnvironmentThemePublishError({ themeId, reason, cause });250+ if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {251+ return yield* fail("invalid-id");252+ }253+ if (!environmentThemeFileHasColors(file)) return yield* fail("no-colors");254+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {apps/web/src/themeCss.ts lines 15 to 15OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,14 @@1+import { themeCssValueFetches } from "@t3tools/shared/themeCss";2+3+// Theme CSS comes from imported files and from agents, so it must not fetch: a4+// 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 and6+// 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+const isRuleParent = (rule: CSSRule): rule is CSSRule & RuleParent =>14+ "cssRules" in rule && "deleteRule" in rule && !(rule instanceof CSSKeyframesRule);
- apps/server/src/environmentTheme.ts line 273OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -199,0 +240,21 @@240+ const publish = Effect.fn("EnvironmentThemeService.publish")(function* (241+ themeId: string,242+ file: EnvironmentThemeFile,243+ ) {244+ const fail = (reason: EnvironmentThemePublishError["reason"], cause?: unknown) =>245+ new EnvironmentThemePublishError({ themeId, reason, cause });246+ if (!isEnvironmentThemeId(themeId) || UNPUBLISHABLE_THEME_IDS.has(themeId)) {247+ return yield* fail("invalid-id");248+ }249+ if (!environmentThemeFileHasColors(file)) return yield* fail("no-colors");250+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {251+ return yield* fail("remote-css");252+ }253+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(254+ Effect.mapError((cause) => fail("not-published", cause)),255+ );256+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");257+258+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;259+ // The watcher reads only .json names, so it never sees a half-written file.260+ const staging = `${destination}.staging-${process.pid}`;apps/server/src/environmentTheme.ts lines 269 to 270OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -199,0 +250,21 @@250+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {251+ return yield* fail("remote-css");252+ }253+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(254+ Effect.mapError((cause) => fail("not-published", cause)),255+ );256+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");257+258+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;259+ // The watcher reads only .json names, so it never sees a half-written file.260+ const staging = `${destination}.staging-${process.pid}`;261+ yield* fs.makeDirectory(environmentThemesDir, { recursive: true }).pipe(262+ Effect.andThen(fs.writeFileString(staging, contents)),263+ Effect.andThen(fs.rename(staging, destination)),264+ Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),265+ Effect.mapError((cause) => fail("not-published", cause)),266+ );267+ // The reader skips files past its count and size limits, so confirm this one is served.268+ const { themes } = yield* refresh;269+ if (!themes.some((theme) => theme.id === themeId)) {270+ yield* fs.remove(destination, { force: true }).pipe(Effect.ignore);apps/server/src/mcp/toolkits/theme/handlers.ts lines 40 to 56OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +36,21 @@36+ t3_theme_set: McpToolAccess.writesEnvironment(({ themeId, theme }) =>37+ Effect.gen(function* () {38+ const themes = yield* EnvironmentTheme.EnvironmentThemeService;39+ const settings = yield* Settings.ServerSettingsService;40+ if (theme !== undefined) {41+ yield* themes42+ .publish(themeId, theme)43+ .pipe(Effect.mapError((error) => invalid(error.message)));44+ } else {45+ const known = [...BUILT_IN_THEME_IDS, ...(yield* themes.current).map(({ id }) => id)];46+ if (!known.includes(themeId)) {47+ return yield* invalid(`No theme is named "${themeId}". Available: ${known.join(", ")}.`);48+ }49+ }50+ // The timestamp makes clients apply the theme again when its id did not change.51+ yield* settings52+ .updateSettings({53+ defaultTheme: themeId,54+ defaultThemeSetAt: DateTime.formatIso(yield* DateTime.now),55+ })56+ .pipe(Effect.mapError(unavailable));@@ -0,0 +1,13 @@1+import { themeCssValueFetches } from "@t3tools/shared/themeCss";2+3+// Theme CSS comes from imported files and from agents, so it must not fetch: a4+// 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 and6+// CSS escapes in a function name cannot dodge them.7+8+let themeSheet: CSSStyleSheet | null = null;9+let appliedCss = "";10+11+function stripFetches(rules: CSSRuleList): void {12+ for (const rule of rules) {13+ if ("style" in rule && rule.style instanceof CSSStyleDeclaration) {evals/mcp-tool-use/cases/themes.ndjson line 2OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -0,0 +1,2 @@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 ac2+{"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"]}, "maxSteps": 6}
- apps/server/src/environmentTheme.ts line 280OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -199,0 +260,21 @@260+ if (!environmentThemeFileHasColors(file)) return yield* fail("no-colors");261+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {262+ return yield* fail("remote-css");263+ }264+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(265+ Effect.mapError((cause) => fail("not-published", cause)),266+ );267+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");268+269+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;270+ // The watcher reads only .json names, so it never sees a half-written file.271+ const staging = `${destination}.staging-${process.pid}`;272+ const replace = (next: string) =>273+ fs.writeFileString(staging, next).pipe(274+ Effect.andThen(fs.rename(staging, destination)),275+ Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),276+ );277+278+ yield* publishSemaphore.withPermits(1)(279+ Effect.gen(function* () {280+ const previous = yield* fs.readFileString(destination).pipe(Effect.option);
- apps/server/src/environmentTheme.ts line 273OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -199,0 +253,21 @@253+ if (!environmentThemeFileHasColors(file)) return yield* fail("no-colors");254+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {255+ return yield* fail("remote-css");256+ }257+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(258+ Effect.mapError((cause) => fail("not-published", cause)),259+ );260+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");261+262+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;263+ // The watcher reads only .json names, so it never sees a half-written file.264+ const staging = `${destination}.staging-${process.pid}`;265+ const replace = (next: string) =>266+ fs.writeFileString(staging, next).pipe(267+ Effect.andThen(fs.rename(staging, destination)),268+ Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),269+ );270+271+ yield* publishSemaphore.withPermits(1)(272+ Effect.gen(function* () {273+ const previous = yield* fs.readFileString(destination).pipe(Effect.option);
- apps/server/src/environmentTheme.ts line 317OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -199,0 +297,21 @@297+ });298+299+ const apply: EnvironmentThemeService["Service"]["apply"] = Effect.fn(300+ "EnvironmentThemeService.apply",301+ )(function* ({ themeId, theme }) {302+ const fail = (reason: EnvironmentThemeApplyError["reason"], known?: ReadonlyArray<string>) =>303+ new EnvironmentThemeApplyError({ themeId, reason, known });304+ if (!isEnvironmentThemeId(themeId)) return yield* fail("invalid-id");305+ if (theme !== undefined) {306+ yield* publish(themeId, theme);307+ } else {308+ const known = [...BUILT_IN_THEME_IDS, ...(yield* refresh).themes.map(({ id }) => id)];309+ if (!known.includes(themeId)) return yield* fail("unknown-id", known);310+ }311+ // The timestamp makes clients apply the theme again when its id did not change.312+ yield* settings313+ .updateSettings({314+ defaultTheme: themeId,315+ defaultThemeSetAt: DateTime.formatIso(yield* DateTime.now),316+ })317+ .pipe(Effect.mapError(() => fail("not-selected")));evals/mcp-tool-use/cases/themes.ndjson line 2OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,2 @@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 ac2+{"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}
- apps/server/src/environmentTheme.ts line 273OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -199,0 +253,21 @@253+ // One publish at a time: they share a staging path, and each one checks what is served after it.254+ const publishSemaphore = yield* Semaphore.make(1);255+256+ const publish = Effect.fnUntraced(function* (themeId: string, file: EnvironmentThemeFile) {257+ const fail = (reason: EnvironmentThemeApplyError["reason"], cause?: unknown) =>258+ new EnvironmentThemeApplyError({ themeId, reason, cause });259+ if (UNPUBLISHABLE_THEME_IDS.has(themeId)) return yield* fail("invalid-id");260+ if (!environmentThemeFileHasColors(file)) return yield* fail("no-colors");261+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {262+ return yield* fail("remote-css");263+ }264+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(265+ Effect.mapError((cause) => fail("not-published", cause)),266+ );267+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");268+269+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;270+ // The watcher reads only .json names, so it never sees a half-written file.271+ const staging = `${destination}.staging-${process.pid}`;272+ const replace = (next: string) =>273+ fs.writeFileString(staging, next).pipe(
- apps/server/src/environmentTheme.ts line 313OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -199,0 +293,21 @@293+ // Put back what was there, so a rejected publish does not take a working theme away.294+ yield* Option.match(previous, {295+ onNone: () => fs.remove(destination, { force: true }),296+ onSome: replace,297+ }).pipe(Effect.ignore);298+ yield* refresh;299+ return yield* fail("not-published");300+ }),301+ );302+ });303+304+ const apply: EnvironmentThemeService["Service"]["apply"] = Effect.fn(305+ "EnvironmentThemeService.apply",306+ )(function* ({ themeId, theme }) {307+ const fail = (308+ reason: EnvironmentThemeApplyError["reason"],309+ detail?: { readonly known?: ReadonlyArray<string>; readonly cause?: unknown },310+ ) => new EnvironmentThemeApplyError({ themeId, reason, ...detail });311+ if (!isEnvironmentThemeId(themeId)) return yield* fail("invalid-id");312+ if (theme !== undefined) {313+ yield* publish(themeId, theme);evals/mcp-tool-use/cases/themes.ndjson line 1OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1 @@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 ac@@ -0,0 +1,2 @@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 ac2+{"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."}}
tanstack-source added labelsfeature
- @@ -199,0 +303,21 @@303+ const apply: EnvironmentThemeService["Service"]["apply"] = Effect.fn(304+ "EnvironmentThemeService.apply",305+ )(function* ({ themeId, theme }) {306+ const fail = (307+ reason: EnvironmentThemeApplyError["reason"],308+ detail?: { readonly known?: ReadonlyArray<string>; readonly cause?: unknown },309+ ) => new EnvironmentThemeApplyError({ themeId, reason, ...detail });310+ if (!isEnvironmentThemeId(themeId)) return yield* fail("invalid-id");311+ // The timestamp makes clients apply the theme again when its id did not change.312+ const select = Effect.gen(function* () {313+ yield* settings314+ .updateSettings({315+ defaultTheme: themeId,316+ defaultThemeSetAt: DateTime.formatIso(yield* DateTime.now),317+ })318+ .pipe(Effect.mapError((cause) => fail("not-selected", { cause })));319+ });320+ if (theme === undefined) {321+ const known = [...BUILT_IN_THEME_IDS, ...(yield* refresh).themes.map(({ id }) => id)];322+ if (!known.includes(themeId)) return yield* fail("unknown-id", { known });323+ return yield* select;@@ -0,0 +22,21 @@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 (!hasStyle && !(rule instanceof CSSLayerStatementRule)) {42+ parent.deleteRule(index);
- @@ -199,0 +263,21 @@263+ if (file.css !== undefined && themeCssLoadsRemoteFiles(file.css)) {264+ return yield* fail("remote-css");265+ }266+ const contents = yield* encodeEnvironmentThemeFileJson(file).pipe(267+ Effect.mapError((cause) => fail("not-published", cause)),268+ );269+ if (Buffer.byteLength(contents) > MAX_THEME_FILE_BYTES) return yield* fail("too-large");270+271+ const destination = `${environmentThemesDir}/${themeId}${THEME_FILE_SUFFIX}`;272+ // The watcher reads only .json names, so it never sees a half-written file.273+ const staging = `${destination}.staging-${process.pid}`;274+ // Exclusive create: a link left at the staging path is removed, never written through.275+ const replace = (next: string) =>276+ fs.remove(staging, { force: true }).pipe(277+ Effect.andThen(fs.writeFileString(staging, next, { flag: "wx" })),278+ Effect.andThen(fs.rename(staging, destination)),279+ Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),280+ );281+282+ // The guarded reader does not block on a FIFO and does not follow a symlink.283+ const previous = Option.fromNullOr(readThemeFileGuarded(destination, MAX_THEME_FILE_BYTES));
- @@ -67,3 +68,18 @@6768 writeAppliedGeneration(storageKey, generation);6869 }697071+/** Like the theme, the environment's mode applies once per set, then local choices win. */72+function adoptDefaultAppearance(): void {73+ if (typeof window === "undefined") return;74+ const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom);75+ const { defaultAppearance, defaultAppearanceSetAt } =76+ appAtomRegistry.get(themeServerSettingsAtom);77+ const storageKey = `${APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX}${environmentId}`;78+ const generation = defaultThemeToApply({79+ environmentId,80+ defaultTheme: defaultAppearance,81+ defaultThemeSetAt: defaultAppearanceSetAt,82+ appliedGeneration: readAppliedGeneration(storageKey),83+ resolves: true,84+ });85+ if (generation === null || defaultAppearance === "") return;
- @@ -0,0 +3,21 @@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))(
- @@ -0,0 +1,20 @@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 Settings from "../../../serverSettings.ts";9+import * as McpInvocationContext from "../../McpInvocationContext.ts";10+import * as McpToolAccess from "../../McpToolAccess.ts";11+import { unavailable } from "../../threadAccess.ts";12+import { ThemeToolkit } from "./tools.ts";13+14+const invalid = (message: string) =>15+ new OrchestratorMcpFailure({ code: "invalid_request", message });16+17+export const layer = McpToolAccess.toLayer(ThemeToolkit, {18+ t3_theme_read: McpToolAccess.reads(({ themeId }) =>19+ Effect.gen(function* () {20+ const themes = yield* EnvironmentTheme.EnvironmentThemeService;@@ -44,2 +53,21 @@4453 }455455+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",70+ {71+ /** Absent when only the appearance was set. */72+ themeId: Schema.optional(Schema.String),73+ reason: Schema.Literals([@@ -0,0 +1,15 @@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 Settings from "../../../serverSettings.ts";9+import * as McpInvocationContext from "../../McpInvocationContext.ts";10+import * as McpToolAccess from "../../McpToolAccess.ts";11+import { unavailable } from "../../threadAccess.ts";12+import { ThemeToolkit } from "./tools.ts";13+14+const invalid = (message: string) =>15+ new OrchestratorMcpFailure({ code: "invalid_request", message });@@ -25,3 +30,4 @@2530 import * as Stream from "effect/Stream";26312732 import * as ServerConfig from "./config.ts";33+import { ServerSettingsService } from "./serverSettings.ts";
- @@ -67,3 +68,20 @@6768 writeAppliedGeneration(storageKey, generation);6869 }697071+/** Like the theme, the environment's mode applies once per set, then local choices win. */72+function adoptDefaultAppearance(): void {73+ if (typeof window === "undefined") return;74+ const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom);75+ const { defaultAppearance, defaultAppearanceSetAt, defaultTheme } =76+ appAtomRegistry.get(themeServerSettingsAtom);77+ const storageKey = `${APPLIED_DEFAULT_APPEARANCE_STORAGE_PREFIX}${environmentId}`;78+ const generation = defaultThemeToApply({79+ environmentId,80+ defaultTheme: defaultAppearance,81+ defaultThemeSetAt: defaultAppearanceSetAt,82+ appliedGeneration: readAppliedGeneration(storageKey),83+ resolves: true,84+ });85+ if (generation === null || defaultAppearance === "") return;86+ // A theme that arrives later sets its own mode when it applies, so the set mode waits for it.87+ if (defaultTheme !== "" && getThemeDefinition(defaultTheme) === null) return;
Sign in to join this conversation.


This PR changes the test suite by +11 test cases (browser +1, unit +4, server +6).
New browser test files:
apps/web/src/themeCss.browser.test.ts. Each browser test file costs CI seconds of module loading before its first test runs; a unit test costs milliseconds.Keep tests that would fail for a real reason, and test logic below the UI where it can be. See Testing.