diff --git a/apps/server/src/assets/AssetAccess.test.ts b/apps/server/src/assets/AssetAccess.test.ts index d137305317327..8f2e133b2a6e3 100644 --- a/apps/server/src/assets/AssetAccess.test.ts +++ b/apps/server/src/assets/AssetAccess.test.ts @@ -215,6 +215,30 @@ describe("AssetAccess", () => { }).pipe(Effect.provide(layerTest)), ); + it.effect("serves the background image published beside an environment theme", () => + Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const { environmentThemesDir } = yield* ServerConfig.ServerConfig; + yield* fs.makeDirectory(environmentThemesDir, { recursive: true }); + const imagePath = `${environmentThemesDir}/frieren.png`; + yield* fs.writeFile(imagePath, screenshotPng); + const result = yield* issueAssetUrl({ + resource: { _tag: "environment-theme-background", themeId: "frieren" }, + }); + const suffix = result.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length); + const separator = suffix.indexOf("/"); + const token = suffix.slice(0, separator); + const asset = yield* resolveAsset(token, suffix.slice(separator + 1)); + expect(asset).toMatchObject({ kind: "file", path: yield* fs.realPath(imagePath) }); + if (asset?.kind !== "file") return; + const response = yield* assetFileResponse(asset); + expect(response.headers["content-type"]).toBe("image/png"); + + yield* fs.remove(imagePath); + expect(yield* resolveAsset(token, suffix.slice(separator + 1))).toBeNull(); + }).pipe(Effect.scoped, Effect.provide(layerTest)), + ); + it.effect("issues exact URLs for media and browser documents outside the workspace", () => Effect.gen(function* () { const fs = yield* FileSystem.FileSystem; diff --git a/apps/server/src/assets/AssetAccess.ts b/apps/server/src/assets/AssetAccess.ts index 5674372bee1a9..362d00fca9230 100644 --- a/apps/server/src/assets/AssetAccess.ts +++ b/apps/server/src/assets/AssetAccess.ts @@ -17,6 +17,7 @@ import { ThreadId, NativeAppIconReference, TurnItemId, + EnvironmentThemeId, } from "@t3tools/contracts"; import { hostPreviewMimeTypeFromExtension, @@ -52,6 +53,7 @@ import * as AssetSigner from "./AssetSigner.ts"; import { makeIsServerInternalPath } from "../auth/serverInternalPaths.ts"; import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts"; import * as ServerConfig from "../config.ts"; +import { findThemeBackground } from "../environmentTheme.ts"; import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion"; import * as ProjectFaviconResolver from "../project/ProjectFaviconResolver.ts"; @@ -168,6 +170,12 @@ const AssetClaimsSchema = Schema.Union([ app: NativeAppIconReference, expiresAt: Schema.Number, }), + Schema.Struct({ + version: Schema.Literal(1), + kind: Schema.Literal("environment-theme-background"), + themeId: EnvironmentThemeId, + expiresAt: Schema.Number, + }), Schema.Struct({ version: Schema.Literal(1), kind: Schema.Literal("tool-output-image"), @@ -834,6 +842,17 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i imageDimensions = readImageDimensions(image.bytes); break; } + case "environment-theme-background": { + // Published themes go to every client, so any client may read their backgrounds. + claims = { + version: 1, + kind: "environment-theme-background", + themeId: input.resource.themeId, + expiresAt, + }; + fileName = `${input.resource.themeId}-background`; + break; + } case "native-app-icon": { claims = { version: 1, @@ -982,6 +1001,24 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* ( return image ? ({ kind: "bytes", ...image } satisfies ResolvedAsset) : null; } + if (claims.kind === "environment-theme-background") { + const config = yield* ServerConfig.ServerConfig; + const fileSystem = yield* FileSystem.FileSystem; + // The themes directory may be a symlink; openMediaFile refuses any path that is not canonical. + const themesDir = yield* fileSystem + .realPath(config.environmentThemesDir) + .pipe(Effect.orElseSucceed(() => null)); + const background = themesDir === null ? null : findThemeBackground(themesDir, claims.themeId); + if (background === null) return null; + const file = yield* openMediaFile(background.path).pipe( + Effect.tapError((cause) => + Effect.logError("Failed to open theme background.", { path: background.path, cause }), + ), + Effect.orElseSucceed(() => null), + ); + return file ? ({ kind: "file", path: background.path, file } satisfies ResolvedAsset) : null; + } + if (claims.kind === "native-app-icon") { const nativeAppIconResolver = yield* NativeAppIconResolver.NativeAppIconResolver; const iconPath = yield* nativeAppIconResolver.resolve(claims.app); diff --git a/apps/server/src/environmentTheme.test.ts b/apps/server/src/environmentTheme.test.ts index 241c89546c228..a0bd921ad3f2e 100644 --- a/apps/server/src/environmentTheme.test.ts +++ b/apps/server/src/environmentTheme.test.ts @@ -304,6 +304,35 @@ it.layer(NodeServices.layer)("environment theme", (it) => { ); }); + it.effect( + "reports the image beside a theme as its background, with a new revision per file", + () => + withEnvironmentThemes( + { "look.json": encodeThemeFile(NIGHTFALL_THEME), "look.png": "first" }, + Effect.gen(function* () { + const { environmentThemesDir } = yield* ServerConfig.ServerConfig; + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const background = Effect.map(currentThemes, (themes) => themes[0]?.background); + const image = path.join(environmentThemesDir, "look.png"); + + const first = yield* background; + assert.isDefined(first); + yield* fs.writeFileString(image, "a longer second image"); + assert.notStrictEqual(yield* background, first); + + yield* fs.remove(image); + assert.isUndefined(yield* background); + if (symlinksSupported) { + const outside = path.join(environmentThemesDir, "..", "outside.png"); + yield* fs.writeFileString(outside, "outside"); + yield* fs.symlink(outside, image); + assert.isUndefined(yield* background); + } + }), + ), + ); + it.effect("keeps the served theme when an update does not fit the size limit", () => { const large = (name: string): EnvironmentThemeFile => ({ ...NIGHTFALL_THEME, diff --git a/apps/server/src/environmentTheme.ts b/apps/server/src/environmentTheme.ts index 1e7f4d3052301..0d45fd02de79d 100644 --- a/apps/server/src/environmentTheme.ts +++ b/apps/server/src/environmentTheme.ts @@ -1,6 +1,7 @@ // @effect-diagnostics nodeBuiltinImport:off - the guarded file read needs open // flags (O_NOFOLLOW, O_NONBLOCK) the FileSystem service does not expose. import * as NodeFS from "node:fs"; +import * as NodePath from "node:path"; import { type DefaultAppearancePreference, @@ -52,6 +53,10 @@ const MAX_THEME_FILES = 32; export const MAX_THEME_FILE_BYTES = 6 * THEME_CSS_MAX_LENGTH + 16 * 1024; const MAX_THEME_TOTAL_BYTES = 6 * MAX_THEME_FILE_BYTES; +/** A theme's background is `.` beside `.json`; earlier extensions win. */ +const THEME_BACKGROUND_EXTENSIONS = ["webp", "png", "jpg", "jpeg"] as const; +const MAX_THEME_BACKGROUND_BYTES = 16 * 1024 * 1024; + interface PublishedThemes { readonly seq: number; readonly themes: ReadonlyArray; @@ -101,6 +106,8 @@ export class EnvironmentThemeService extends Context.Service< readonly read: (themeId?: string) => Effect.Effect< { readonly current: string; + /** Where theme files and their background images live. */ + readonly themesDir: string; readonly themes: ReadonlyArray; readonly theme?: EnvironmentTheme; }, @@ -173,6 +180,35 @@ export const readThemeFileGuarded = (filePath: string, maxBytes: number): string } }; +/** + * The background image published beside `themeId`, if any. Symlinks and oversized files are + * skipped. `entries` lets a directory scan skip lookups for names it did not list. + */ +export function findThemeBackground( + themesDir: string, + themeId: string, + entries?: ReadonlySet, +): { readonly path: string; readonly revision: string } | null { + for (const extension of THEME_BACKGROUND_EXTENSIONS) { + const name = `${themeId}.${extension}`; + if (entries !== undefined && !entries.has(name)) continue; + // Native separators: the asset route refuses a path that differs from its canonical form. + const filePath = NodePath.join(themesDir, name); + let info: NodeFS.BigIntStats; + try { + info = NodeFS.lstatSync(filePath, { bigint: true }); + } catch { + continue; + } + if (!info.isFile() || info.size > MAX_THEME_BACKGROUND_BYTES) continue; + return { + path: filePath, + revision: [info.ino, info.size, info.mtimeNs].map((part) => part.toString(36)).join("-"), + }; + } + return null; +} + export const readPublishedThemes = Effect.fn(function* (themesDir: string) { const fs = yield* FileSystem.FileSystem; const entries = yield* fs @@ -180,6 +216,7 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) { .pipe(Effect.orElseSucceed((): Array => [])); const themes: Array = []; + const entryNames = new Set(entries); let examined = 0; let totalBytes = 0; for (const entry of entries.toSorted()) { @@ -232,7 +269,8 @@ export const readPublishedThemes = Effect.fn(function* (themesDir: string) { break; } - themes.push({ id, ...file }); + const background = findThemeBackground(themesDir, id, entryNames); + themes.push({ id, ...file, ...(background ? { background: background.revision } : {}) }); } return themes; }); @@ -406,7 +444,8 @@ const make = Effect.gen(function* () { )(function* (themeId) { const { themes } = yield* refresh; const { defaultTheme } = yield* settings.getSettings; - if (themeId === undefined) return { current: defaultTheme, themes }; + const themesDir = environmentThemesDir; + if (themeId === undefined) return { current: defaultTheme, themesDir, themes }; const theme = themes.find((candidate) => candidate.id === themeId); if (theme === undefined) { return yield* new EnvironmentThemeRefusedError({ @@ -415,7 +454,7 @@ const make = Effect.gen(function* () { known: themes.map(({ id }) => id), }); } - return { current: defaultTheme, themes, theme }; + return { current: defaultTheme, themesDir, themes, theme }; }); return { diff --git a/apps/server/src/mcp/toolkits/theme/handlers.ts b/apps/server/src/mcp/toolkits/theme/handlers.ts index ad469095b0e0d..1f8aede7f3996 100644 --- a/apps/server/src/mcp/toolkits/theme/handlers.ts +++ b/apps/server/src/mcp/toolkits/theme/handlers.ts @@ -16,6 +16,7 @@ export const layer = McpToolAccess.toLayer(ThemeToolkit, { const themes = yield* EnvironmentTheme.EnvironmentThemeService; const { current, + themesDir, themes: published, theme, } = yield* themes.read(themeId).pipe( @@ -30,8 +31,14 @@ export const layer = McpToolAccess.toLayer(ThemeToolkit, { return { current, builtIn: BUILT_IN_THEME_IDS, - published: published.map(({ id, name, css }) => ({ id, name, hasCss: Boolean(css) })), - ...(theme === undefined ? {} : { theme: Struct.omit(theme, ["id"]) }), + published: published.map(({ id, name, css, background }) => ({ + id, + name, + hasCss: Boolean(css), + hasBackground: background !== undefined, + })), + ...(theme === undefined ? {} : { theme: Struct.omit(theme, ["id", "background"]) }), + themesDir, guide: THEME_GUIDE, }; }), diff --git a/apps/server/src/mcp/toolkits/theme/tools.ts b/apps/server/src/mcp/toolkits/theme/tools.ts index f055e8776180f..716c540b2c41e 100644 --- a/apps/server/src/mcp/toolkits/theme/tools.ts +++ b/apps/server/src/mcp/toolkits/theme/tools.ts @@ -41,9 +41,11 @@ const ThemeReadTool = Tool.make("t3_theme_read", { id: EnvironmentThemeId, name: Schema.String, hasCss: Schema.Boolean, + hasBackground: Schema.Boolean, }), ), theme: Schema.optionalKey(EnvironmentThemeFile), + themesDir: Schema.String, guide: Schema.String, }), }) diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 8e8b30bab3270..6defac543eaac 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -3031,6 +3031,7 @@ export const layerWsRpc = ( if ( input.resource._tag === "attachment" || input.resource._tag === "native-app-icon" || + input.resource._tag === "environment-theme-background" || input.resource._tag === "tool-output-image" || input.resource._tag === SOURCE_CONTROL_MEDIA_ASSET || // A network path is served only from the thread's project, looked up below. diff --git a/apps/web/src/appInit.tsx b/apps/web/src/appInit.tsx index faa71137db049..d1873481ee510 100644 --- a/apps/web/src/appInit.tsx +++ b/apps/web/src/appInit.tsx @@ -37,6 +37,7 @@ import { } from "./composerDraftStore"; import { startDefaultThemeAdoption } from "./hooks/useDefaultTheme"; import { startEnvironmentThemeRepaint } from "./hooks/useEnvironmentTheme"; +import { startThemeBackground } from "./themeBackground"; import { readLocalStorageValue, subscribeLocalStorageKey } from "./hooks/useLocalStorage"; import { startHostEnvironmentLookup } from "./state/primaryEnvironment"; import { @@ -264,6 +265,7 @@ export function startAppServices(): AppRouter { startDocumentTitle(router); startHostEnvironmentLookup(); startEnvironmentThemeRepaint(); + startThemeBackground(); startBrowserChromeThemeSync(router); startDefaultThemeAdoption(); startModelPreferencesMigration(); diff --git a/apps/web/src/themeBackground.ts b/apps/web/src/themeBackground.ts new file mode 100644 index 0000000000000..c4bdd1bff5950 --- /dev/null +++ b/apps/web/src/themeBackground.ts @@ -0,0 +1,96 @@ +import { resolveAssetUrl } from "@t3tools/client-runtime/state/assets"; +import { executeAtomQuery } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentId } from "@t3tools/contracts"; + +import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry"; +import { assetEnvironment } from "./state/assets"; +import { themeEnvironmentIdAtom } from "./state/primaryEnvironment"; +import { themeServerEnvironmentThemesAtom } from "./state/server"; +import { environmentSession } from "./state/session"; + +const THEME_BACKGROUND_VARIABLE = "--theme-background-image"; + +let shownKey: string | null = null; +let loading: AbortController | null = null; +let objectUrl: string | null = null; + +function show(nextUrl: string | null): void { + const root = document.documentElement; + if (nextUrl === null) root.style.removeProperty(THEME_BACKGROUND_VARIABLE); + else root.style.setProperty(THEME_BACKGROUND_VARIABLE, `url("${nextUrl}")`); + if (objectUrl !== null) URL.revokeObjectURL(objectUrl); + objectUrl = nextUrl; +} + +async function loadBackground( + environmentId: EnvironmentId, + themeId: string, + signal: AbortSignal, +): Promise { + const minted = await executeAtomQuery( + appAtomRegistry, + assetEnvironment.createUrl({ + environmentId, + input: { resource: { _tag: "environment-theme-background", themeId } }, + }), + { label: "theme background", reportFailure: false, refresh: true, signal }, + ); + const connection = appAtomRegistry.get( + environmentSession.preparedConnectionValueAtom(environmentId), + ); + if (minted._tag !== "Success" || connection._tag === "None") return null; + const url = resolveAssetUrl(connection.value.httpBaseUrl, minted.value.relativeUrl); + if (url === null) return null; + const response = await fetch(url, { signal }); + if (!response.ok) return null; + const image = await response.blob(); + return image.type.startsWith("image/") ? URL.createObjectURL(image) : null; +} + +/** + * Sets `--theme-background-image` to the image published beside `themeId`, or clears it. + * The image is copied into a blob URL once per revision, so the signed URL may expire. + */ +export function applyThemeBackground(themeId: string | undefined): void { + if (typeof document === "undefined") return; + const environmentId = appAtomRegistry.get(themeEnvironmentIdAtom); + const revision = + themeId === undefined + ? undefined + : appAtomRegistry.get(themeServerEnvironmentThemesAtom)?.find((theme) => theme.id === themeId) + ?.background; + const key = + environmentId === null || themeId === undefined || revision === undefined + ? null + : JSON.stringify([environmentId, themeId, revision]); + if (key === shownKey) return; + shownKey = key; + loading?.abort(); + loading = null; + // The previous image must not show under the next theme while it loads. + show(null); + if (environmentId === null || themeId === undefined || key === null) return; + const controller = new AbortController(); + loading = controller; + const failed = () => { + if (controller.signal.aborted) return; + // Lets the next repaint try again. + shownKey = null; + }; + loadBackground(environmentId, themeId, controller.signal).then((url) => { + if (controller.signal.aborted) { + if (url !== null) URL.revokeObjectURL(url); + return; + } + loading = null; + if (url === null) failed(); + else show(url); + }, failed); +} + +/** A new image revision does not change the palette, so it does not repaint the theme. */ +export function startThemeBackground(): () => void { + return subscribeAtomChanges(themeServerEnvironmentThemesAtom, () => + applyThemeBackground(document.documentElement.dataset.themeId), + ); +} diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.ts index 1abd73b2cecb7..5e85922759ddb 100644 --- a/apps/web/src/themePalette.ts +++ b/apps/web/src/themePalette.ts @@ -30,6 +30,7 @@ import { } from "./lib/contextChipAccents"; import { appAtomRegistry, subscribeAtomChanges } from "./rpc/atomRegistry"; +import { applyThemeBackground } from "./themeBackground"; import { applyThemeCss } from "./themeCss"; import { themeServerEnvironmentThemesAtom } from "./state/server"; @@ -1681,6 +1682,7 @@ export function applyThemePalette(theme: ThemePreference, appearance?: ThemeAppe setThemePreviewAppearance(null); const palette = getThemeDefinition(theme); applyThemeCss(palette?.css); + applyThemeBackground(palette?.id); if (palette) { root.dataset.themeId = palette.id; diff --git a/docs/user/appearance.md b/docs/user/appearance.md index c37855fdf3c87..340e9e5ff5f1f 100644 --- a/docs/user/appearance.md +++ b/docs/user/appearance.md @@ -62,7 +62,7 @@ the theme, applies after T3 Code's own styles on web and desktop, and is include Custom CSS cannot load files. `@import`, `image-set()`, and `url()` are ignored, except `url()` with a `data:` address or an `#id`. This keeps an imported theme from sending what is on your screen -to another site. +to another site. For a full-size image, use a [background image](#background-image). Class names in the app change between releases. For rules that keep working, target `data-slot` and other `data-` attributes, such as `[data-chat-header]` or `[data-slot="button"]`. @@ -132,3 +132,18 @@ view. An optional `css` string adds [custom CSS](#custom-css). Write updates to a temporary file and rename it into place so clients never read a partial theme. Invalid files are not published. + +### Background image + +A published theme can have a full-size background image. Ask an agent, for example "use +~/Pictures/wallpaper.jpg as T3 Code's background", or save a JPEG, PNG, or WebP file of up to +16 MB beside the theme file: `nightfall.jpg` beside `nightfall.json`. The theme's CSS decides +where the image shows: + +```css +[data-workspace-area="conversation"] { + background: var(--theme-background-image) center / cover no-repeat; +} +``` + +Delete the image file to remove it. diff --git a/evals/mcp-tool-use/cases/themes.ndjson b/evals/mcp-tool-use/cases/themes.ndjson index 462086e6b7a48..93f2c76a99e4d 100644 --- a/evals/mcp-tool-use/cases/themes.ndjson +++ b/evals/mcp-tool-use/cases/themes.ndjson @@ -1,3 +1,4 @@ {"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} {"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."}} {"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` sets light, dark, or system mode.", "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} +{"id": "theme-background-uses-image-file", "area": "themes", "kind": "bad", "pattern": "put a full-size image behind T3 Code", "experience": "Asked to use a 2.3 MB wallpaper as T3 Code's background, an agent could only embed it as data: text in theme CSS, hit the 20,000 character limit, and told the user T3 Code could not do it.", "rule": "THEME_GUIDE: For a background image, copy a JPEG, PNG, or WebP file to `/.jpg`, beside the theme file. CSS shows it with `var(--theme-background-image)`.", "privacy": "commit-safe", "source": {"note": "A user on X shared an agent turn that shrank a wallpaper to fit theme CSS, then said a full-size image needed a T3 Code change."}, "setup": {"role": "top", "mocks": {"t3_theme_read": {"current": "sumi", "builtIn": ["t3-chat", "grove", "ocean", "ember", "iris"], "published": [{"id": "sumi", "name": "Sumi", "hasCss": true, "hasBackground": false}], "theme": {"name": "Sumi", "appearance": "dark", "canvas": "#16161d", "accent": "#c4746e", "css": "[data-chat-header] { border-bottom: 1px solid #2a2a37; }"}, "guide": "Themes restyle T3 Code on web and desktop. `canvas` and `accent` (hex) derive a full palette. `css` applies after the app's styles.", "themesDir": "/home/user/.t3/userdata/themes"}, "t3_theme_set": {"themeId": "sumi", "published": true}}}, "prompt": "Put /home/user/Downloads/frieren.jpeg behind T3 Code as the background of my Sumi theme. It's 2.3 MB and I want the full quality, not a shrunk copy.", "expect": {"shellMust": ["frieren\\.jpeg.*/home/user/\\.t3/userdata/themes/sumi\\.jpe?g"], "calls": [{"tool": "t3_theme_set", "args": {"themeId": "sumi", "theme.css": "~var(--theme-background-image)"}}]}, "maxSteps": 8} diff --git a/evals/mcp-tool-use/run.ts b/evals/mcp-tool-use/run.ts index 5786de748eaf1..b08cb8a490de3 100644 --- a/evals/mcp-tool-use/run.ts +++ b/evals/mcp-tool-use/run.ts @@ -48,6 +48,7 @@ import { ThreadId, } from "@t3tools/contracts"; import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; +import { THEME_GUIDE } from "@t3tools/shared/themeCss"; import { formatThreadLink } from "@t3tools/shared/threadLinks"; import { buildCodexAdditionalContext } from "../../apps/server/src/provider/CodexDeveloperInstructions.ts"; import { makeSideChatContext } from "../../apps/server/src/orchestration-v2/ContextHandoffService.ts"; @@ -1371,6 +1372,8 @@ const unsavedSecretNote = (Contracts as Record).SECRET_REQUEST_ /** Fields T3 adds to real thread and task results, applied to mocks and defaults alike. */ const withProductFields = (name: string, value: unknown, child: boolean): unknown => { if (!isRecord(value)) return value; + // The guide is the checkout's text, so a case's mock cannot go stale. + if (name === "t3_theme_read") return { ...value, guide: THEME_GUIDE }; const linked = (thread: unknown, idKey = "threadId") => { if (!isRecord(thread) || thread.link !== undefined) return thread; const id = thread[idKey] ?? thread.id; diff --git a/packages/contracts/src/assets.ts b/packages/contracts/src/assets.ts index 58b7ce1d18530..0a1e711c39227 100644 --- a/packages/contracts/src/assets.ts +++ b/packages/contracts/src/assets.ts @@ -8,6 +8,7 @@ import { } from "./chatAttachment.ts"; import { ProjectFaviconPath } from "./project.ts"; import { ToolActivityNativeAppReference } from "./providerRuntime.ts"; +import { EnvironmentThemeId } from "./server.ts"; const ASSET_PATH_MAX_LENGTH = 1024; @@ -66,6 +67,9 @@ export const AssetResource = Schema.Union([ // to a request that carries a credential, which the client has none of, so the server fetches // them with the credential the host's driver holds for the repository at `cwd`. `repository` // names the change request's repository, which can differ from the checkout at `cwd`. + Schema.TaggedStruct("environment-theme-background", { + themeId: EnvironmentThemeId, + }), Schema.TaggedStruct(SOURCE_CONTROL_MEDIA_ASSET, { cwd: TrimmedNonEmptyString.check(Schema.isMaxLength(ASSET_PATH_MAX_LENGTH)), url: TrimmedNonEmptyString.check(Schema.isMaxLength(2048)), diff --git a/packages/contracts/src/server.ts b/packages/contracts/src/server.ts index 144d2814b8804..f2e02c6b0a95e 100644 --- a/packages/contracts/src/server.ts +++ b/packages/contracts/src/server.ts @@ -653,6 +653,8 @@ export type EnvironmentThemeFile = typeof EnvironmentThemeFile.Type; export const EnvironmentTheme = Schema.Struct({ id: EnvironmentThemeId, ...environmentThemeFields, + /** Revision of the image file published beside the theme; absent without one. */ + background: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(64))), }); export type EnvironmentTheme = typeof EnvironmentTheme.Type; diff --git a/packages/shared/src/themeCss.ts b/packages/shared/src/themeCss.ts index 26a72b4117d99..910b18150fdea 100644 --- a/packages/shared/src/themeCss.ts +++ b/packages/shared/src/themeCss.ts @@ -79,7 +79,7 @@ export const THEME_GUIDE = [ "", "CSS: `css` applies after the app's styles. Use `.dark` or `:root:not(.dark)` for one appearance.", "It cannot load files: no @import, no image-set(), and url() only with data: or #id.", - "A background image must be embedded as a data: address. `css` holds 50,000 characters, so keep the image near 30 KB.", + 'For a background image, copy a JPEG, PNG, or WebP file of up to 16 MB to `/.jpg` (or .png, .webp), beside the theme file. CSS shows it with `var(--theme-background-image)`, such as `[data-workspace-area="conversation"] { background: var(--theme-background-image) center / cover no-repeat; }`. Delete the file to remove it. Do not embed images in `css`: it holds 50,000 characters.', "The app's own rules can be more specific. If a rule has no effect, add !important.", "It cannot reach the terminal text, the file tree, or diff internals. Use color roles for those.", "Native scrollbars take `::-webkit-scrollbar` and `::-webkit-scrollbar-thumb`.",