Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Themes: a bot can use a picture from the chat, or draw and animate the chat background itself (#7056)
Milind Soni6b961d084055
diff --git a/apps/docs/content/docs/features/themes.mdx b/apps/docs/content/docs/features/themes.mdxindex 9eb21104d3..18f2d9386d 100644--- a/apps/docs/content/docs/features/themes.mdx+++ b/apps/docs/content/docs/features/themes.mdx@@ -17,6 +17,16 @@ A theme only changes the look for you. On a team, your teammates keep theirs.The bot cannot see the result. It makes small changes and asks you how it looks. Every change has **Undo** on the card in the chat.+## Chat backgrounds++Attach a picture and say "make this my chat background", or describe one: "a slow moving gradient", "faint drifting dots", "a starry night". The bot writes the background itself, behind the messages, and it stays put while the conversation scrolls. It can also cover the whole window, sidebar included.++- **Your own picture.** Attach it in this message or an earlier one; the bot can also use a picture from its own folder. PNG, JPEG, WebP, GIF, AVIF and SVG work, up to 10 MB. iPhone HEIC photos do not: send the photo as a JPEG (on an iPhone, share it and choose **Options → Most Compatible**), or ask a bot that can run commands to convert it first.+- **Readable text.** The bot is guided to lay a veil of the theme's own background colour over a picture so messages stay readable in light and dark. If text is hard to read, ask it to dim the background.+- **Animation.** Moving chat backgrounds stand still when your computer is set to reduce motion.++A theme that changes the background also lives in **Your themes**, with Undo on its card like any other change.+## Going backMausBot keeps your last 30 look changes, from a bot or from Settings. Say what you want in the chat:diff --git a/server/drivers/agents-app-settings-tool.ts b/server/drivers/agents-app-settings-tool.tsindex bdde9dcd6b..98d1d771d6 100644--- a/server/drivers/agents-app-settings-tool.ts+++ b/server/drivers/agents-app-settings-tool.ts@@ -18,7 +18,7 @@ export const APP_SETTINGS_TOOL_DEFINITION = {reason: { type: "string", maxLength: 240, description: "set on a secret: why, for the card." },card: { type: "string", enum: [...SETTINGS_CARD_IDS], description: `show_card: ${SETTINGS_CARD_IDS.map((id) => `${id} ${SETTINGS_CARDS[id].when}`).join("; ")}.` },theme: { type: "string", maxLength: 120000, description: "set_theme: theme JSON." },- path: { type: "string", maxLength: 1024, description: "add_theme_asset: a file of yours." },+ path: { type: "string", maxLength: 1024, description: "add_theme_asset: a file of yours or an attachment; left out: the latest picture." },steps: { type: "integer", description: "undo_theme: changes back, default 1." },index: { type: "integer", description: "undo_theme: the theme_history entry to return to." },},diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex 922d32ac5f..b35bfe11ff 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -2441,7 +2441,7 @@},"path": {"type": "string",- "description": "add_theme_asset: a file of yours."+ "description": "add_theme_asset: a file of yours or an attachment; left out: the latest picture."},"steps": {"type": "integer",diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.jsonindex e015857394..31cb09628a 100644--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@ -1,7 +1,7 @@{"default": {- "bytes": 59734,- "sha256": "ab7715b5e771b4429c81a91aacb35ca407f5a4445cbcc1d5584570395b2892a2",+ "bytes": 59781,+ "sha256": "d5b6d82d67ef3f13240b2e238f0bc1cf68d347a701f5b6f6159df204434fb456","tools": ["tool_result_read","list_room_targets",@@ -59,8 +59,8 @@]},"voice": {- "bytes": 60515,- "sha256": "1b0007f2268a96a4148056ec77b9e24c853fdfb52be962164a717e0ce263d251",+ "bytes": 60562,+ "sha256": "ff8f8468cbd6cb5c1c80985646acc61a2da7a232dce67619f38c437246e0f1b0","tools": ["tool_result_read","list_room_targets",@@ -119,8 +119,8 @@]},"shared": {- "bytes": 61999,- "sha256": "6ca0151be77a27940068d82008da96d490d216677174ab3f03914bc0c30c20be",+ "bytes": 62046,+ "sha256": "f42b6a84ba8a972c7e778cc9be7f1a2bfe8128d62d5bf86a9db6698a2b9dd4c3","tools": ["tool_result_read","list_shared_computers",@@ -180,8 +180,8 @@]},"shared+voice": {- "bytes": 62780,- "sha256": "37dbaf2126ccf32f9eced54d525386857545900c46d2f0b06a37ef3838ee0d54",+ "bytes": 62827,+ "sha256": "370f4f4818b01f351db407c54e7e37d0d29936622441ff99281814598c1943c3","tools": ["tool_result_read","list_shared_computers",@@ -242,8 +242,8 @@]},"skills": {- "bytes": 62055,- "sha256": "11ca1c08523afd14190bc745b0c3440a6c09116e1d31044f077df56b125a7afc",+ "bytes": 62102,+ "sha256": "dd0fefa5e976b549e2c06206ef1d901b167876cb8c89fb66840eebfbee97986c","tools": ["tool_result_read","list_room_targets",@@ -303,8 +303,8 @@]},"skills+voice": {- "bytes": 62836,- "sha256": "42b02908d7c6d8042a879b08098453a33aa25dcebe894c208aa4c44bace7a535",+ "bytes": 62883,+ "sha256": "b6a1e813fa66dfb14ae7ba178a9c9e4e368077498d2b9c554fce8205dbdf5164","tools": ["tool_result_read","list_room_targets",@@ -365,8 +365,8 @@]},"skills+shared": {- "bytes": 64320,- "sha256": "98c1e1ca42e84b0cd764c2bc06e5e906b3010ebd7768116af716c0f05b0101e9",+ "bytes": 64367,+ "sha256": "838ab5d5573baed2c18b0a087d5c241180339302e210c3a984aa9049de5f6832","tools": ["tool_result_read","list_shared_computers",@@ -428,8 +428,8 @@]},"skills+shared+voice": {- "bytes": 65101,- "sha256": "ebc2f2dddbd8ceb4bbe2fae41bf37e294516b9dfda8d79c5f6fd3a1a9972d374",+ "bytes": 65148,+ "sha256": "efc8d9e633c5b70dad8df0e001d25e89ae236067921d6661532235f5e403cc4c","tools": ["tool_result_read","list_shared_computers",@@ -492,8 +492,8 @@]},"non-chief": {- "bytes": 51186,- "sha256": "e0536a58e2e50fb52d5f4bdf8036f75ca754e6bcb8d68d09bb671d38464973cf",+ "bytes": 51233,+ "sha256": "4e4e9dd8f78d4f376b4d38b09321665fc2af00ee164beb33c1adbc82fcb697d3","tools": ["tool_result_read","list_room_targets",@@ -544,8 +544,8 @@]},"voice+non-chief": {- "bytes": 51967,- "sha256": "fcd75cc868772ae03e79aeb2f4f047d9d6bf937b978846e03ff9d240f4aa3b9c",+ "bytes": 52014,+ "sha256": "67b88beff485fa04e36bf3708f5ed0e72b6ed5e62e778db5689109d7a119300a","tools": ["tool_result_read","list_room_targets",@@ -597,8 +597,8 @@]},"shared+non-chief": {- "bytes": 53451,- "sha256": "6713223d61530510777bef76a4f97cf6a93327d2c1249cff2ffcbe7687e170c6",+ "bytes": 53498,+ "sha256": "2239748bd26b3f3a70d89ce92cb19ad0fd84c380cf7cf7d3ca4d762acac1dcd4","tools": ["tool_result_read","list_shared_computers",@@ -651,8 +651,8 @@]},"shared+voice+non-chief": {- "bytes": 54232,- "sha256": "8ba15856271d3220e47edf85ae9aba22546f5c8321af68baa756921c8d73e616",+ "bytes": 54279,+ "sha256": "713f98bd12577c98307702dc8faae499bb67728bd0ae0bc46022eee7bcd81856","tools": ["tool_result_read","list_shared_computers",@@ -706,8 +706,8 @@]},"skills+non-chief": {- "bytes": 53507,- "sha256": "602e863e1e0df3b07a79c395bca9028e58af35b9e58d30bc44862dca9bf88a81",+ "bytes": 53554,+ "sha256": "c04ce2477fce548948d5b4718e440e07d340787cf43ab4fac7a2791d7bb035a4","tools": ["tool_result_read","list_room_targets",@@ -760,8 +760,8 @@]},"skills+voice+non-chief": {- "bytes": 54288,- "sha256": "55e0cf57441df1a1befd7a59e20e16b124cca94e8d91487c738122452e8eb63e",+ "bytes": 54335,+ "sha256": "04e38760fd3598a965cb6a4f4961812dfb868b732b2967de9a399a5022a36d5e","tools": ["tool_result_read","list_room_targets",@@ -815,8 +815,8 @@]},"skills+shared+non-chief": {- "bytes": 55772,- "sha256": "b8998eae7e64b7f28aa80d87f574342a478f3c1b522a0cf05f058b47c768fa72",+ "bytes": 55819,+ "sha256": "1ce4a9430aea2b5e80a4a8e8efa496a3163c40a456dbcbbaa849011af90b63d8","tools": ["tool_result_read","list_shared_computers",@@ -871,8 +871,8 @@]},"skills+shared+voice+non-chief": {- "bytes": 56553,- "sha256": "eee3b129143bb7fd50efc648673b0d8dda76bc55b70d5d648cab89b14c289490",+ "bytes": 56600,+ "sha256": "87734ce9302b2c5dc2aff938078eabc88b4ee27f6f6906d3cda48dfb5700e553","tools": ["tool_result_read","list_shared_computers",@@ -928,8 +928,8 @@]},"skills+shared+voice+cloud-home": {- "bytes": 64857,- "sha256": "7f3c5bb01d67071a8134b4a21eed660b302edf44e37e710570bb4afba1069bbe",+ "bytes": 64904,+ "sha256": "e8c97eb6c47c8a416a79aafb80a7bcc0b4e260dd032096f467aee071762dc19b","tools": ["tool_result_read","list_shared_computers",@@ -992,8 +992,8 @@]},"skills+shared+voice+non-chief+cloud-home": {- "bytes": 56309,- "sha256": "e6907bfddf551aae9ad781f2677ca8e2a4b48bd126f1272f5ee759fe749faa58",+ "bytes": 56356,+ "sha256": "f5fda05c097c0d483b032d76937f5cf5c411c202ed1227b7cb50c23cfe43efe2","tools": ["tool_result_read","list_shared_computers",@@ -1049,8 +1049,8 @@]},"skills+shared+voice+x": {- "bytes": 68940,- "sha256": "5de4ea6186bf5925cfc472f9b254b7f2c099faf2dd3fbfc8b97470da1efa5f3a",+ "bytes": 68987,+ "sha256": "968f7bf4f3c99a8905643f9604341e9fe8a99322e72ad105dfbdb1c5830e8f9d","tools": ["tool_result_read","list_shared_computers",@@ -1117,8 +1117,8 @@]},"skills+shared+voice+x+team": {- "bytes": 68940,- "sha256": "5de4ea6186bf5925cfc472f9b254b7f2c099faf2dd3fbfc8b97470da1efa5f3a",+ "bytes": 68987,+ "sha256": "968f7bf4f3c99a8905643f9604341e9fe8a99322e72ad105dfbdb1c5830e8f9d","tools": ["tool_result_read","list_shared_computers",@@ -1185,8 +1185,8 @@]},"skills+shared+voice+x+team+images": {- "bytes": 70887,- "sha256": "395eb54ac14e3ed16c7150c467af7898066a0ceb5ee2f70efcf4a0428c0ba307",+ "bytes": 70934,+ "sha256": "1e4663ae71a931773a914e2dcef19e03ce666613b0e40d709d5b899eb40d00aa","tools": ["tool_result_read","list_shared_computers",@@ -1255,8 +1255,8 @@]},"default+legacy-switches": {- "bytes": 59734,- "sha256": "ab7715b5e771b4429c81a91aacb35ca407f5a4445cbcc1d5584570395b2892a2",+ "bytes": 59781,+ "sha256": "d5b6d82d67ef3f13240b2e238f0bc1cf68d347a701f5b6f6159df204434fb456","tools": ["tool_result_read","list_room_targets",@@ -1314,8 +1314,8 @@]},"default+mausbot": {- "bytes": 60385,- "sha256": "b8efdfde9d452feccc29ae85832f3df68b2c42895895195a30978ccceedf6a10",+ "bytes": 60432,+ "sha256": "0016bdef250fa6d096bb799e0f2995b58e2f4ec0176b5ba943a40173ad5321ea","tools": ["tool_result_read","list_room_targets",@@ -1375,8 +1375,8 @@]},"skills+shared+voice+mausbot": {- "bytes": 65752,- "sha256": "8996d348f4cbf75bbd1baa452aa4c9592f97a9f33afce23414bdad09c8ba04e2",+ "bytes": 65799,+ "sha256": "2ad9a3acb4b772002ecfb6f1ad3191c5fcdec62a5bdaf421dd62db576c58f850","tools": ["tool_result_read","list_shared_computers",@@ -1441,8 +1441,8 @@]},"default+no-computer-pick": {- "bytes": 58522,- "sha256": "6a9a3bee15ee7977a4ad8b2df5b5355ff7935ca2da94c649c8c5b4e9af2f5e61",+ "bytes": 58569,+ "sha256": "32d65fcfeed2d56d2c3294b133fd7c3a4a82e521a5b2b52b22e6796c6f08fef6","tools": ["tool_result_read","list_room_targets",@@ -1499,8 +1499,8 @@]},"default+room": {- "bytes": 55082,- "sha256": "01f62d2d457b59de9505b51f6485c25bd02834d4e824f693360cd5ec1b2cf279",+ "bytes": 55129,+ "sha256": "c0dec68a54416632b212edd8ba9d447917a69e884724e05a609b043da14bf4fd","tools": ["tool_result_read","list_room_targets",@@ -1551,8 +1551,8 @@]},"non-chief+room": {- "bytes": 46534,- "sha256": "f31f21e0a6bd6045049672590eb3461066b4910339985075cba5f250119f5a13",+ "bytes": 46581,+ "sha256": "e6c5d362c70f6f079db883342f2316134591c952b87767b020c461feb7b7663b","tools": ["tool_result_read","list_room_targets",@@ -1596,8 +1596,8 @@]},"default+images": {- "bytes": 61681,- "sha256": "7752ed2dc2ab859b5111595f8a321c51af3eef4317aeb5afe5fd0951bb619a1c",+ "bytes": 61728,+ "sha256": "9d95bacb1400dc4ea42387db515726508b11c836c718bafa03bdbb0483c67dce","tools": ["tool_result_read","list_room_targets",@@ -1657,8 +1657,8 @@]},"skills+shared+voice+x+team+images+hosting": {- "bytes": 72750,- "sha256": "8673f4f1e3f63d834b308efee2b18b648e89bf2dbacfe9cba3ac8ff0684c0a48",+ "bytes": 72797,+ "sha256": "8a4338606662e70b50c805bf0cab16cad083a0844dc8dee06b53ae16224f799b","tools": ["tool_result_read","list_shared_computers",@@ -1729,8 +1729,8 @@]},"default+hosting": {- "bytes": 61597,- "sha256": "741b2ef654f2e629c321851e378a90c822342f460c966f0a33eeb51794e2ec8b",+ "bytes": 61644,+ "sha256": "ac3691f17ef86ea085bd19ffa4c6b53857ed1103ee3d45a4f165a80a8c450bcc","tools": ["tool_result_read","list_room_targets",@@ -1790,8 +1790,8 @@]},"default+tools-off": {- "bytes": 55416,- "sha256": "e57164617eea48bcd5d40c0d10e28c198cfe5e24f253a1d41a04b75f6b3c7d44",+ "bytes": 55463,+ "sha256": "539dabc1ed227c205e201fa1fed13fd4bea92b37acc54d6ec2f6ab3c5ae562af","tools": ["tool_result_read","list_room_targets",diff --git a/server/index.ts b/server/index.tsindex 7c5597f775..9b8819b85f 100644--- a/server/index.ts+++ b/server/index.ts@@ -12246,7 +12246,7 @@ const instanceRoutes = createInstanceRoutes({providerConfigBusy: { get: () => providerConfigBusy, set: (busy) => { providerConfigBusy = busy; } },providerInstancesChanging, describeInstances, persistProviderInstance, configStatus, broadcast, testCliBinary,cliProbeEnvironment, threadBusy, botForThread, activeGroupTurnForBot, checkInstance: testedAi.check,-}); ROUTES.push(createCustomDomainRoutes({ desktopManaged: DESKTOP_MANAGED, status: customDomainStatus, verify: (domain) => customDomainVerifier.verify(domain), save: (origin) => { saveConfig({ customDomain: origin }); cfg.customDomain = origin; }, sessionEnded: (auth) => auth.kind === "session" && !sessions.isLive(auth.session.id) })); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const themeStore = createThemeStore({ dataDir: DATA_DIR }); const themeChanged = (person: string, skin?: string) => broadcast({ kind: "theme", ...(skin ? { skin } : {}) }, CLOUD_TEAM ? { person } : { adminOnly: true }); ROUTES.push(createThemeRoutes({ store: themeStore, changed: themeChanged, person: (auth) => (CLOUD_TEAM ? (auth.kind === "session" ? personKey(auth.session) : null) : ownerOrAdmin(auth) ? "owner" : null) })); const themeTool = createThemeTool({ store: themeStore, changed: themeChanged, person: (turn) => (CLOUD_TEAM ? actingPeople.requester(turn.threadId, turn.generation) : phones.turnOwner(turn) ? "owner" : null), sources: (turn) => ({ roots: messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), attachments: store.messagesFor(turn.threadId).flatMap((message) => (message.attachments ?? []).flatMap((file) => (file.kind === "audio" ? [] : [file.path]))) }) }); const appSettings = createAppSettings({ themes: themeTool, cards: { here: (id) => id === "ai-sign-in" || DESKTOP_MANAGED, on: () => (tailnetShare.origin() !== null ? true : null) }, store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, botPatch: botPatchRoutes, sections: sidebarRoutes, instances: instanceRoutes, starterAwake: starterAwakeRoutes, skills: skillsRoutes }, providers: registry, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs, paused: () => starterAwake.paused() }), turnOwner: (turn) => phones.turnOwner(turn), ownerRefusal: (turn) => phones.turnOwnerRefusal(turn), guestDriven: cloudGuestDriven, automated: (turn) => { const request = directRequestOwners.get(turn.threadId); return Boolean(request?.automation) && (request!.generation === turn.generation || request!.generations.has(turn.generation)); }, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, language: threadLanguage, pictures: createPictureFiles({ attachmentsDir: ATTACHMENTS_DIR, ownFolders: (turn) => messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), inConversation: (turn, name) => threadsReferencing(name).includes(turn.threadId), save: (bytes, mime) => saveImage(bytes, mime).path, remove: deleteAttachment }) }); ROUTES.push(instanceRoutes, windowPrefs.routes);+}); ROUTES.push(createCustomDomainRoutes({ desktopManaged: DESKTOP_MANAGED, status: customDomainStatus, verify: (domain) => customDomainVerifier.verify(domain), save: (origin) => { saveConfig({ customDomain: origin }); cfg.customDomain = origin; }, sessionEnded: (auth) => auth.kind === "session" && !sessions.isLive(auth.session.id) })); const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.appWindow) }); const themeStore = createThemeStore({ dataDir: DATA_DIR }); const themeChanged = (person: string, skin?: string) => broadcast({ kind: "theme", ...(skin ? { skin } : {}) }, CLOUD_TEAM ? { person } : { adminOnly: true }); ROUTES.push(createThemeRoutes({ store: themeStore, changed: themeChanged, person: (auth) => (CLOUD_TEAM ? (auth.kind === "session" ? personKey(auth.session) : null) : ownerOrAdmin(auth) ? "owner" : null) })); const themeTool = createThemeTool({ store: themeStore, changed: themeChanged, person: (turn) => (CLOUD_TEAM ? actingPeople.requester(turn.threadId, turn.generation) : phones.turnOwner(turn) ? "owner" : null), sources: (turn) => ({ roots: messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), attachmentsDir: ATTACHMENTS_DIR, attachments: conversationAttachments(store.messagesFor(turn.threadId)) }) }); const appSettings = createAppSettings({ themes: themeTool, cards: { here: (id) => id === "ai-sign-in" || DESKTOP_MANAGED, on: () => (tailnetShare.origin() !== null ? true : null) }, store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, botPatch: botPatchRoutes, sections: sidebarRoutes, instances: instanceRoutes, starterAwake: starterAwakeRoutes, skills: skillsRoutes }, providers: registry, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs, paused: () => starterAwake.paused() }), turnOwner: (turn) => phones.turnOwner(turn), ownerRefusal: (turn) => phones.turnOwnerRefusal(turn), guestDriven: cloudGuestDriven, automated: (turn) => { const request = directRequestOwners.get(turn.threadId); return Boolean(request?.automation) && (request!.generation === turn.generation || request!.generations.has(turn.generation)); }, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, language: threadLanguage, pictures: createPictureFiles({ attachmentsDir: ATTACHMENTS_DIR, ownFolders: (turn) => messageFileRootsForThread(turn.botId, turn.threadId).filter((root) => root !== ATTACHMENTS_DIR), inConversation: (turn, name) => threadsReferencing(name).includes(turn.threadId), save: (bytes, mime) => saveImage(bytes, mime).path, remove: deleteAttachment }) }); ROUTES.push(instanceRoutes, windowPrefs.routes);ROUTES.push(createMcpServerRoutes({cfg, bot: (id) => store.bot(id), sessions, mcpOAuth, teamConnections,cloudHome: CLOUD_HOME,diff --git a/server/themes.tool.e2e.test.ts b/server/themes.tool.e2e.test.tsnew file mode 100644index 0000000000..2c47a15c4e--- /dev/null+++ b/server/themes.tool.e2e.test.ts@@ -0,0 +1,123 @@+// "Make this picture my chat background" through the real server and the real injected agents proxy, with only the+// provider's planning scripted (room-handoff-agent): the picture the person attached reaches the engine as a path,+// add_theme_asset takes it (this turn, an earlier turn by name, or with no path at all) with no theme worn yet, and one+// set_theme wears it with the card and Undo. A HEIC photo and a tag naming a file outside the store are refused.+import { spawn, type ChildProcess } from "node:child_process";+import { closeSync, existsSync, openSync, readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { afterAll, beforeAll, expect, it } from "vitest";++import { launchVerificationServer, verificationServerArgs, verificationServerEnvironment, type VerificationServer } from "../scripts/control-omb.ts";+import { waitForExit } from "./testing/cleanup.ts";+import { readRegistry, writeRegistry } from "./testing/registry.ts";++const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64");+const HEIC = Buffer.concat([Buffer.from([0, 0, 0, 24]), Buffer.from("ftypheic"), Buffer.from([0, 0, 0, 0]), Buffer.from("mif1heic"), Buffer.alloc(64)]);++let fixture: VerificationServer;+let child: ChildProcess | undefined;+let url: string;+let dataDir: string;+let planPath: string;+let bot: { id: string; threadId: string };+const plans: Record<string, { script: unknown[] }> = {};++const api = async (method: string, path: string, body?: unknown, raw?: { bytes: Buffer; type: string }) => {+ const response = await fetch(url + path, {+ method, headers: { "content-type": raw?.type ?? "application/json", origin: url },+ ...(raw ? { body: raw.bytes } : body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(15_000),+ });+ return { status: response.status, body: await response.json().catch(() => ({})) as any };+};+const providerTurns = (): any[] => existsSync(`${planPath}.evidence.jsonl`)+ ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];+const step = (args: Record<string, unknown>, extra: Record<string, unknown> = {}) => ({ tool: "app_settings", arguments: args, ...extra });+const results = (turn: any) => turn.evidence.filter((entry: any) => entry.step).map((entry: any) => ({+ isError: Boolean(entry.response.error || entry.response.result?.isError),+ text: (entry.response.result?.content ?? []).map((part: any) => part.text).join("\n") || JSON.stringify(entry.response.error ?? null),+}));+const promptOf = (turn: any) => JSON.stringify(turn.prompt);+const run = async (key: string, text: string, steps: unknown[]) => {+ plans[bot.id]!.script.push({ key, match: [key], steps, reply: `Done: ${key}`, timeoutMs: 20_000 });+ writeFileSync(planPath, JSON.stringify(plans));+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { threadId: bot.threadId, text: `${key}: ${text}` })).status).toBe(202);+ let turn: any;+ await expect.poll(() => (turn = providerTurns().find((candidate) => candidate.planKey === key)) !== undefined, { timeout: 30_000 }).toBe(true);+ await expect.poll(async () => (await api("GET", "/api/bots")).body.bots.every((one: any) => !one.busy), { timeout: 20_000 }).toBe(true);+ return turn;+};++beforeAll(async () => {+ fixture = await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true });+ ({ url, dataDir } = fixture.info);+ planPath = join(dataDir, "room-plan.json");+ const created = (await api("POST", "/api/bots", { name: "Painter" })).body.bot;+ bot = { id: created.id, threadId: created.threadId };+ plans[bot.id] = { script: [] };+ writeFileSync(planPath, JSON.stringify(plans));+ // Fixture setup, not a production grant: the stopped fixture's own bot is put on Full access on disk.+ await waitForExit(fixture.child, { signal: "SIGTERM" });+ const saved = readRegistry(dataDir).bots;+ const painter = saved.find((one: any) => one.id === bot.id);+ painter.approvalMode = "full"; painter.autoApprove = false;+ for (const task of painter.tasks) { task.approvalMode = "full"; task.autoApprove = false; }+ writeRegistry(dataDir, { bots: saved });+ const env = verificationServerEnvironment({}, dataDir, Number(new URL(url).port));+ const log = openSync(fixture.info.logPath, "a", 0o600);+ child = spawn(process.execPath, verificationServerArgs(env), { cwd: join(import.meta.dirname, ".."), env, stdio: ["ignore", log, log] });+ closeSync(log);+ for (const deadline = Date.now() + 20_000; ;) {+ if (child.exitCode !== null) throw new Error(`restarted server exited; see ${fixture.info.logPath}`);+ try { if ((await fetch(`${url}/api/health`, { signal: AbortSignal.timeout(1000) })).ok) break; } catch {}+ if (Date.now() > deadline) throw new Error(`restarted server did not start; see ${fixture.info.logPath}`);+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+}, 90_000);++afterAll(async () => {+ await waitForExit(child, { signal: "SIGTERM" });+ await fixture?.close();+});++it("a picture attached in the chat becomes the chat background in two calls, with the card and Undo", async () => {+ const uploaded = await api("POST", "/api/attachments", undefined, { bytes: PNG, type: "image/png" });+ expect(uploaded.status).toBe(201);+ const path: string = uploaded.body.path;++ const first = await run("BG-1", `make this my chat background\n\n<attached-image path="${path}" name="Beach Day.png" />`, [+ step({ action: "add_theme_asset" }, { capture: { file: 'url\\("([^"]+)"\\)' } }),+ step({ action: "set_theme", id: "background", theme: JSON.stringify({ name: "Background", css: '[data-look="chat-backdrop"] { background: url("{{file}}") center / cover; }' }) }),+ ]);+ expect(promptOf(first), "the engine is told the attachment's path").toContain(`<attached-file path=\\"${path}\\"`);+ const [added, worn] = results(first);+ expect(added).toMatchObject({ isError: false, text: expect.stringContaining('url("/api/theme-assets/background/beach-day.png")') });+ expect(worn.isError).toBe(false);+ const active = (await api("GET", "/api/themes/active")).body;+ expect(active).toMatchObject({ id: "background", theme: { css: expect.stringContaining("/api/theme-assets/background/beach-day.png") } });+ expect((await fetch(`${url}/api/theme-assets/background/beach-day.png`, { headers: { origin: url } })).status).toBe(200);++ const card = (await api("GET", `/api/threads/${bot.threadId}/messages?limit=200`)).body.messages.filter((message: any) => message.card?.appSettingRequest).at(-1);+ expect(card.card.appSettingRequest).toMatchObject({ settingId: "appearance.theme", after: "Update the theme Background and wear it" });+ expect((await api("POST", `/api/threads/${bot.threadId}/undo`, { requestId: card.card.requestId })).body).toMatchObject({ ok: true, undone: true });+ expect((await api("GET", "/api/themes/active")).body.id).toBeNull();++ // A later turn names the earlier picture by the name it was attached under.+ const later = await run("BG-2", "use the beach picture I sent before", [step({ action: "add_theme_asset", id: "background", path: "Beach Day.png" })]);+ expect(results(later)[0]).toMatchObject({ isError: false, text: expect.stringContaining("Added to the theme Background") });+}, 120_000);++it("refuses a HEIC photo by name and a tag naming a file outside the attachment store", async () => {+ const heic = await api("POST", "/api/files?name=IMG_0042.HEIC", undefined, { bytes: HEIC, type: "image/heic" });+ expect(heic.status).toBe(201);+ const turn = await run("BG-3", `make this my background\n\n<attached-file path="${heic.body.path}" name="IMG_0042.HEIC" />`, [+ step({ action: "add_theme_asset" }, { expectError: true }),+ ]);+ expect(results(turn)[0].text).toMatch(/^That is a HEIC photo/);++ const secret = join(dataDir, "config.json");+ const forged = await run("BG-4", `use this\n\n<attached-image path="${secret}" name="config.png" />`, [+ step({ action: "add_theme_asset", path: secret }, { expectError: true }),+ step({ action: "add_theme_asset", path: "config.png" }, { expectError: true }),+ ]);+ expect(results(forged).map((result: any) => result.text)).toEqual([expect.stringContaining("not in your workspace"), expect.stringContaining("not in your workspace")]);+}, 120_000);diff --git a/server/themes.ui.e2e.test.ts b/server/themes.ui.e2e.test.tsindex 76774690ec..1f7dd85a49 100644--- a/server/themes.ui.e2e.test.ts+++ b/server/themes.ui.e2e.test.ts@@ -1,5 +1,6 @@// A person's theme in a real browser against a real server (temporary home): it paints the window live, Settings lists-// it, the reset keys and ?safe-look both get back to the default look. Runs where a Chromium and playwright-core are named:+// it, the reset keys and ?safe-look both get back to the default look; a picture and an animation on the chat's backdrop+// paint under the messages. Runs where a Chromium and playwright-core are named:// OMB_UI_CHROMIUM=<chrome or headless shell> OMB_UI_PLAYWRIGHT_CORE=<playwright-core dir> OMB_UI_DIST=<vite build dir>// [OMB_UI_SHOTS=<folder for screenshots>] vitest run server/themes.ui.e2e.test.tsimport { createRequire } from "node:module";@@ -20,7 +21,7 @@ beforeAll(async () => {vi.spyOn(console, "log").mockImplementation(() => {});fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true }, [], undefined, dist);const { chromium } = createRequire(join(playwrightPath!, "package.json"))("playwright-core");- browser = await chromium.launch({ executablePath: chromiumPath, headless: true, args: ["--use-mock-keychain"] });+ browser = await chromium.launch({ executablePath: chromiumPath, headless: true, args: ["--use-mock-keychain", "--password-store=basic"] });if (shots) mkdirSync(shots, { recursive: true });}, 90_000);@@ -75,5 +76,75 @@ it.skipIf(!ready)("paints a theme live, lists it in Settings, and the reset keysexpect(await safe.evaluate("document.documentElement.dataset.theme ?? null")).toBeNull();await safe.close();- expect(remote).toEqual([]);+ expect(remote, remote.join("\n")).toEqual([]);+}, 120_000);++const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==";++it.skipIf(!ready)("paints a theme's picture and animation on the chat's backdrop: behind the messages, never over them", async () => {+ const url = fixture.info.url;+ const api = async (method: string, path: string, body?: unknown) => {+ const res = await fetch(`${url}${path}`, { method, headers: { "content-type": "application/json", origin: url }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });+ return { status: res.status, body: await res.json().catch(() => ({})) as any };+ };+ await api("PUT", "/api/config", { onboarding: { completedAt: new Date().toISOString(), version: WELCOME_VERSION } });+ if (!(await api("GET", "/api/bots")).body.bots.some((one: { name: string }) => one.name === "Scout")) await runControlOmb(["new-bot", "--name", "Scout", "--url", url]);+ expect((await api("PUT", "/api/themes/active", { id: null })).status).toBe(200);+ const css = [+ '[data-look="chat-backdrop"] { background: linear-gradient(rgb(255 0 0 / 0.5), rgb(255 0 0 / 0.5)), url("/api/theme-assets/sky/sky.png") center / cover no-repeat; }',+ '[data-look="chat-backdrop"]::before { content: ""; position: absolute; inset: -50%; background: conic-gradient(red, blue, red); opacity: 0.2; animation: bg-turn 60s linear infinite; }',+ "@keyframes bg-turn { to { transform: rotate(1turn); } }",+ ].join("\n");+ const imported = await api("POST", "/api/themes/import", { mausbotTheme: 1, id: "sky", theme: { name: "Sky", css }, assets: { "sky.png": `data:image/png;base64,${PNG}` } });+ expect(imported.status).toBeLessThan(300);+ const page = await browser.newPage({ viewport: { width: 1280, height: 820 }, reducedMotion: "no-preference" });+ const pictures: number[] = [];+ page.on("response", (response: any) => { if (response.url().endsWith("/api/theme-assets/sky/sky.png")) pictures.push(response.status()); });+ await page.goto(url);+ const greeting = page.locator('[data-look="chat"] [data-look="bot-bubble"]').getByText("Hi, I'm Scout", { exact: false }).first();+ await greeting.waitFor();+ const skipTour = page.getByRole("button", { name: "Skip tour" });+ if (await skipTour.isVisible().catch(() => false)) await skipTour.click();+ for (let n = 0; n < 5 && await page.locator("[data-mausbot-welcome]").isVisible().catch(() => false); n++) {+ await page.keyboard.press("Escape");+ await page.waitForTimeout(500);+ }+ const notNow = page.getByRole("button", { name: "Not now" });+ if (await notNow.isVisible().catch(() => false)) await notNow.click();+ await page.waitForTimeout(500);++ // Pixels, not the DOM: elementsFromPoint skips the click-through backdrop, so only a picture shows what it covers.+ const chat = (await page.locator('[data-look="chat"]').first().boundingBox())!;+ const text = (await greeting.boundingBox())!;+ const inBubble = { x: Math.round(text.x + 2), y: Math.round(text.y + 2), width: Math.round(Math.min(120, text.width - 4)), height: Math.round(text.height - 4) };+ const blank = { x: Math.round(chat.x + chat.width - 90), y: Math.round(chat.y + chat.height * 0.62), width: 60, height: 40 };+ const pixels = async () => ({ bubble: await page.screenshot({ clip: inBubble }), blank: await page.screenshot({ clip: blank }) });+ const plain = await pixels();++ expect((await api("PUT", "/api/themes/active", { id: imported.body.id })).status).toBe(200);+ const probe = () => page.evaluate(`(() => {+ const chat = document.querySelector('[data-look="chat"]'), back = document.querySelector('[data-look="chat-backdrop"]');+ const box = chat.getBoundingClientRect(), b = back.getBoundingClientRect();+ return { first: chat.firstElementChild === back, box: [b.top - box.top, b.height - box.height, b.width - box.width].map(Math.round), image: getComputedStyle(back).backgroundImage,+ animations: back.getAnimations({ subtree: true }).length, clickThrough: document.elementFromPoint(box.right - 60, box.top + box.height * 0.62) !== back };+ })()`);+ await expect.poll(probe, { timeout: 15_000 }).toMatchObject({ first: true, box: [0, 0, 0], image: expect.stringContaining("/api/theme-assets/sky/sky.png"), animations: 1, clickThrough: true });+ await expect.poll(() => pictures.includes(200), { timeout: 10_000 }).toBe(true);+ await page.waitForTimeout(500);+ const themed = await pixels();+ expect(themed.blank.equals(plain.blank), "the backdrop shows where no message is").toBe(false);+ expect(themed.bubble.equals(plain.bubble), "a message bubble paints over the backdrop, unchanged").toBe(true);+ if (shots) await page.screenshot({ path: join(shots, "theme-backdrop.png") });++ // Reduced motion stops what a theme animates there, whatever its CSS says.+ await page.emulateMedia({ reducedMotion: "reduce" });+ await expect.poll(probe, { timeout: 5_000 }).toMatchObject({ animations: 0 });+ await page.emulateMedia({ reducedMotion: "no-preference" });++ // Taken off, the backdrop is empty again and the chat looks as it did.+ expect((await api("PUT", "/api/themes/active", { id: null })).status).toBe(200);+ await expect.poll(probe, { timeout: 10_000 }).toMatchObject({ image: "none", animations: 0 });+ await page.waitForTimeout(500);+ expect((await pixels()).blank.equals(plain.blank)).toBe(true);+ await page.close();}, 120_000);diff --git a/server/themes/store.ts b/server/themes/store.tsindex 05aba052de..cd22c72248 100644--- a/server/themes/store.ts+++ b/server/themes/store.ts@@ -36,6 +36,32 @@ export type LookHistoryItem = ThemeHistoryItem & { seq: number; look: Look; fileexport const slugFor = (name: string) => name.toLowerCase().normalize("NFKD").replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40) || "theme";+export type PictureKind = "png" | "jpg" | "webp" | "gif" | "avif" | "svg";+const HEIF_BRANDS = new Set(["heic", "heix", "hevc", "hevx", "heim", "heis", "hevm", "hevs", "mif1", "msf1"]);++/** The brands an ISO media file's ftyp box names (AVIF and HEIC both are such files), or null when it is not one. */+function ftypBrands(bytes: Buffer): string[] | null {+ if (bytes.length < 16 || bytes.subarray(4, 8).toString("latin1") !== "ftyp") return null;+ const end = Math.min(bytes.length, Math.max(16, bytes.readUInt32BE(0)));+ const brands = [bytes.subarray(8, 12).toString("latin1")];+ for (let at = 16; at + 4 <= end; at += 4) brands.push(bytes.subarray(at, at + 4).toString("latin1"));+ return brands;+}++/** What picture the bytes are, by their first bytes: one a window can show, "heic" for a phone photo it cannot, or null. */+export function pictureKind(bytes: Buffer): PictureKind | "heic" | null {+ const starts = (...values: number[]) => values.every((value, index) => bytes[index] === value);+ const ascii = (at: number, text: string) => bytes.subarray(at, at + text.length).toString("latin1") === text;+ if (starts(0x89, 0x50, 0x4e, 0x47)) return "png";+ if (starts(0xff, 0xd8, 0xff)) return "jpg";+ if (ascii(0, "GIF8")) return "gif";+ if (ascii(0, "RIFF") && ascii(8, "WEBP")) return "webp";+ const brands = ftypBrands(bytes);+ if (brands) return brands.some((brand) => brand === "avif" || brand === "avis") ? "avif" : brands.some((brand) => HEIF_BRANDS.has(brand)) ? "heic" : null;+ const head = bytes.subarray(0, 4096).toString("utf8").replace(/^\uFEFF/, "").trimStart();+ return /^(<\?xml[^>]*>\s*)?(<!--[\s\S]*?-->\s*)*(<!DOCTYPE svg[^>]*>\s*)?<svg[\s>]/i.test(head) ? "svg" : null;+}+/** Security: a file's first bytes must match its extension, so a theme file is only ever the image or font it claims. */function looksLike(name: string, bytes: Buffer): boolean {const ext = name.slice(name.lastIndexOf(".") + 1);@@ -46,7 +72,7 @@ function looksLike(name: string, bytes: Buffer): boolean {case "jpg": case "jpeg": return starts(0xff, 0xd8, 0xff);case "gif": return ascii(0, "GIF8");case "webp": return ascii(0, "RIFF") && ascii(8, "WEBP");- case "avif": return ascii(4, "ftyp");+ case "avif": return pictureKind(bytes) === "avif";case "woff": return ascii(0, "wOFF");case "woff2": return ascii(0, "wOF2");case "ttf": return starts(0x00, 0x01, 0x00, 0x00) || ascii(0, "true");diff --git a/server/themes/tool.test.ts b/server/themes/tool.test.tsindex 51c8143e61..80c1e408ff 100644--- a/server/themes/tool.test.ts+++ b/server/themes/tool.test.ts@@ -1,14 +1,17 @@import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { basename, join } from "node:path";import { afterEach, describe, expect, it } from "vitest";import { createAppSettings } from "../app-settings/host.ts";+import { themeGuide } from "../../shared/theme.ts";+import { pictureKind } from "./store.ts";import type { BotRecord } from "../store.ts";import { createThemeStore } from "./store.ts";import { createThemeTool } from "./tool.ts";const PNG = Buffer.from("89504e470d0a1a0a0000000d49484452", "hex");+const JPG = (n: number) => Buffer.from([0xff, 0xd8, 0xff, 0xe0, n]);const dirs: string[] = [];afterEach(() => {for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });@@ -25,6 +28,7 @@ function fixture(options: { person?: string | null; guest?: boolean } = {}) {const attached = join(attachments, "upload-1.png");writeFileSync(attached, PNG);writeFileSync(join(attachments, "someone-elses.png"), PNG);+ const attachedList = [{ path: attached, name: "upload-1.png" }];const messages: Array<Record<string, any>> = [];const bots = [{ id: "kiwi", name: "Kiwi", color: "green", threadId: "t-kiwi" } as unknown as BotRecord];const store = {@@ -49,13 +53,20 @@ function fixture(options: { person?: string | null; guest?: boolean } = {}) {requestCredential: async () => ({ status: 500, body: {} }), connectorThread: () => null, language: () => undefined,themes: createThemeTool({store: themes, person: () => person, changed: (who, skin) => changed.push({ person: who, ...(skin ? { skin } : {}) }),- sources: () => ({ roots: [workspace], attachments: [attached] }),+ sources: () => ({ roots: [workspace], attachmentsDir: attachments, attachments: attachedList }),}),});const turn = { botId: "kiwi", threadId: "t-kiwi", generation: "gen-1" };const call = (body: Record<string, unknown>) => host.handle(body, turn);const undo = () => host.undo({ threadId: turn.threadId, requestId: String(messages.filter((m) => m.card?.appSettingRequest).at(-1)!.card.requestId) });- return { host, themes, changed, call, undo, messages, workspace, outside, attachments, attached };+ /** Attaches a file to this conversation as the composer does: stored under an id, listed with the name it came with. */+ const attach = (bytes: Buffer, name: string, stored = `${attachedList.length}-${name.toLowerCase().replace(/[^a-z0-9.]/g, "")}`) => {+ const path = join(attachments, stored);+ writeFileSync(path, bytes);+ attachedList.push({ path, name });+ return path;+ };+ return { host, themes, changed, call, undo, messages, workspace, outside, attachments, attached, attach, attachedList, dataDir };}const NEON = { name: "Neon", canvas: "#0b1020", accent: "#ff2bd6", css: '[data-look="app"] { animation: glow 4s infinite; } @keyframes glow { to { filter: hue-rotate(40deg); } }' };@@ -128,8 +139,8 @@ describe("app_settings theme actions", () => {expect((await call({ action: "add_theme_asset", id: "neon", path: join(workspace, "..", "outside", "secret.png") })).status).toBeGreaterThanOrEqual(400);expect((await call({ action: "add_theme_asset", id: "neon", path: join(attachments, "someone-elses.png") })).status).toBeGreaterThanOrEqual(400);expect((await call({ action: "add_theme_asset", id: "neon", path: join(workspace, "notes.png") })).status).toBe(400);- expect((await call({ action: "add_theme_asset", id: "missing", path: join(workspace, "Stars Big.png") })).status).toBe(404);expect(themes.list("owner").themes[0]!.assets).toEqual(["stars-big.png", "upload-1.png"]);+ expect((await call({ action: "add_theme_asset", id: "midnight", path: join(workspace, "Stars Big.png") })).status).toBe(400);});it("lists the look changes and goes back by steps, by index and on its own undo, each with a card that has Undo", async () => {@@ -185,4 +196,81 @@ describe("app_settings theme actions", () => {expect((await call({ action: "undo_theme" })).status).toBe(200);expect(themes.list("owner").active).toBe("neon");});-});++ it("takes a picture attached on this turn or earlier, by path, stored name or file name, or the latest one with no path", async () => {+ const { call, themes, workspace, attach, attachedList, messages, changed, undo } = fixture();+ const earlier = attach(JPG(1), "beach.jpg");+ attach(Buffer.from("%PDF-1.4"), "notes.pdf");++ // No custom theme worn and no id: one call makes a theme over the person's skin for the file, not worn yet.+ const first = await call({ action: "add_theme_asset" });+ expect(first).toMatchObject({ status: 200, body: { text: expect.stringContaining('url("/api/theme-assets/background/beach.jpg")') } });+ expect(first.body.text).toContain("Made the theme Background (id background)");+ expect(themes.list("owner")).toEqual({ active: null, themes: [{ id: "background", name: "Background", hasCss: false, assets: ["beach.jpg"] }] });+ expect(changed).toEqual([]);+ expect(messages.filter((m) => m.card)).toEqual([]);++ expect(first.body.text, "the reply carries the guide's picture recipe, so no guide read is needed").toContain(`url("/api/theme-assets/background/beach.jpg") center / cover no-repeat; }`);+ const veil = "color-mix(in srgb, var(--color-app) 62%, transparent)";+ expect(first.body.text).toContain(`linear-gradient(${veil}, ${veil})`);+ expect(themeGuide(), "the same veil as the guide's (palette.test.ts holds it readable)").toContain(`linear-gradient(${veil}, ${veil})`);+ // Asked again with nothing worn, the same unworn theme takes the file: no Background 2.+ expect((await call({ action: "add_theme_asset", path: "none" })).body.text).toContain("Added to the theme Background (id background)");+ expect(themes.list("owner").themes.map((theme) => theme.id)).toEqual(["background"]);++ // set_theme wears it, with the card and Undo.+ const css = '[data-look="chat-backdrop"] { background: url("/api/theme-assets/background/beach.jpg") center / cover; }';+ expect((await call({ action: "set_theme", id: "background", theme: JSON.stringify({ name: "Background", css }) })).status).toBe(200);+ expect(themes.list("owner").active).toBe("background");+ expect(messages.at(-1)!.card.appSettingRequest).toMatchObject({ settingId: "appearance.theme" });++ // Worn: no id means that theme. A bot box shows the upload under another folder: its stored name finds it; so does+ // the name it was attached under.+ const boxed = join(workspace, "..", "box-uploads", "kiwi", "t-kiwi", basename(earlier));+ expect((await call({ action: "add_theme_asset", path: boxed })).body.text).toContain("Added to the theme Background (id background)");+ const sunset = attach(PNG, "Sunset.PNG");+ expect((await call({ action: "add_theme_asset", path: "sunset.png" })).body.text).toContain("/background/sunset.png");+ expect((await call({ action: "add_theme_asset", path: earlier })).status).toBe(200);+ expect(themes.list("owner").themes[0]!.assets).toEqual(["beach.jpg", "sunset.png"]);+ expect(attachedList.map((one) => one.path)).toContain(sunset);++ // A second picture under a name the theme already has keeps its own name, so undo to the earlier look still shows+ // the earlier picture.+ attach(JPG(2), "beach.jpg");+ expect((await call({ action: "add_theme_asset" })).body.text).toMatch(/\/background\/beach-[0-9a-f]{6}\.jpg/);+ expect(themes.read("owner", "background")?.css).toBe(css);+ expect(await undo()).toEqual({ claimed: true, state: "undone" });+ expect(themes.list("owner").active).toBeNull();+ });++ it("opens an attachment only inside the attachment store and only from this conversation", async () => {+ const { call, themes, outside, attachments, attachedList } = fixture();+ themes.save("owner", "neon", { name: "Neon" });+ writeFileSync(join(outside, "secret.png"), PNG);+ // A tag in the person's own message is text: one naming a file outside the store opens nothing.+ attachedList.push({ path: join(outside, "secret.png"), name: "secret.png" });+ expect((await call({ action: "add_theme_asset", id: "neon", path: join(outside, "secret.png") })).status).toBeGreaterThanOrEqual(400);+ expect((await call({ action: "add_theme_asset", id: "neon", path: "secret.png" })).status).toBeGreaterThanOrEqual(400);+ writeFileSync(join(attachments, "other-chat.png"), PNG);+ expect((await call({ action: "add_theme_asset", id: "neon", path: "other-chat.png" })).status).toBeGreaterThanOrEqual(400);+ // With no path, the newest picture that opens: the forged one is skipped.+ expect((await call({ action: "add_theme_asset", id: "neon" })).body.text).toContain("/neon/upload-1.png");+ expect(themes.list("owner").themes[0]!.assets).toEqual(["upload-1.png"]);+ });++ it("names a HEIC photo and a file over the limit, and never uses an older picture in a HEIC's place", async () => {+ const { call, themes, workspace, attach } = fixture();+ const heic = Buffer.concat([Buffer.from([0, 0, 0, 24]), Buffer.from("ftypheic"), Buffer.from([0, 0, 0, 0]), Buffer.from("mif1heic"), Buffer.alloc(32)]);+ const avif = Buffer.concat([Buffer.from([0, 0, 0, 28]), Buffer.from("ftypavif"), Buffer.from([0, 0, 0, 0]), Buffer.from("avifmif1miaf"), Buffer.alloc(32)]);+ expect([pictureKind(heic), pictureKind(avif), pictureKind(PNG), pictureKind(JPG(1)), pictureKind(Buffer.from("<svg xmlns='http://www.w3.org/2000/svg'/>"))]).toEqual(["heic", "avif", "png", "jpg", "svg"]);+ attach(heic, "IMG_0042.HEIC", "1-img.bin");+ expect((await call({ action: "add_theme_asset" })).body.error).toMatch(/^That is a HEIC photo.*sips -s format jpeg/);+ expect((await call({ action: "add_theme_asset", path: "IMG_0042.HEIC" })).body.error).toMatch(/HEIC/);+ // Named .avif but HEIC inside: refused by its bytes.+ writeFileSync(join(workspace, "fake.avif"), heic);+ expect((await call({ action: "add_theme_asset", path: join(workspace, "fake.avif") })).status).toBe(400);+ writeFileSync(join(workspace, "huge.png"), Buffer.concat([PNG, Buffer.alloc(10 * 1024 * 1024)]));+ expect(await call({ action: "add_theme_asset", path: join(workspace, "huge.png") })).toMatchObject({ status: 413, body: { error: expect.stringMatching(/^A theme file may be up to 10 MB\..*sips/) } });+ expect(themes.list("owner").themes).toEqual([]);+ });+});\ No newline at end of filediff --git a/server/themes/tool.ts b/server/themes/tool.tsindex 7a0adfb854..bb45227345 100644--- a/server/themes/tool.ts+++ b/server/themes/tool.ts@@ -1,7 +1,9 @@// app_settings' theme actions: read the person's themes with the guide, save and wear one, copy a file from the bot's own// folders into a theme, and list or go back on their look changes. A theme is the person's who started the turn, so it// reaches their windows and no one else's.-import { basename, dirname, extname } from "node:path";+import { createHash } from "node:crypto";+import { readFileSync } from "node:fs";+import { basename, dirname, extname, resolve } from "node:path";import { z } from "zod";import { SKIN_IDS } from "../../shared/app-settings.ts";@@ -9,7 +11,7 @@ import { THEME_ID, THEME_LIMITS, themeCssProblem, themeFileSchema, themeGuide, timport { openMessageFile } from "../message-file.ts";import type { WritableEntry } from "../app-settings/registry.ts";import type { Skin } from "./history.ts";-import { isRefusal, slugFor, type ThemeStore } from "./store.ts";+import { isRefusal, pictureKind, slugFor, type ThemeStore } from "./store.ts";type Turn = { botId: string; threadId: string; generation: string };type Reply = { status: number; body: Record<string, unknown> };@@ -23,10 +25,27 @@ export interface ThemeToolDeps {/** The person whose own message began this turn's work; null when no one person's did. */person(turn: Turn): string | null;changed(person: string, skin?: string): void;- /** Folders the bot may copy a theme file from, and this conversation's attached files. */- sources(turn: Turn): { roots: string[]; attachments: string[] };+ /** Folders the bot may copy a theme file from; the attachment store; and this conversation's attached files, oldest+ * first, with the names they were attached under (server/conversation-attachments.ts). */+ sources(turn: Turn): { roots: string[]; attachmentsDir: string; attachments: ReadonlyArray<{ path: string; name: string }> };}+type Opened = Awaited<ReturnType<typeof openMessageFile>>;+/** An opened file, the name it goes by, its size and what its first bytes say it is. */+type Picked = { file: Opened; name: string; size: number; kind: ReturnType<typeof pictureKind> };+const OPEN_ANY_SIZE = Number.MAX_SAFE_INTEGER;++async function picked(file: Opened, name: string): Promise<Picked> {+ const head = Buffer.alloc(4096);+ const [{ bytesRead }, stat] = await Promise.all([file.handle.read(head, 0, head.length, 0), file.handle.stat()]);+ return { file, name, size: stat.size, kind: pictureKind(head.subarray(0, bytesRead)) };+}+const HEIC = "That is a HEIC photo, which the app cannot show. Ask the person to send it as a JPEG or PNG (on an iPhone: share it, Options, Most Compatible), or, if you have a shell, convert it (on a Mac: sips -s format jpeg -Z 2560 in.heic --out out.jpg) and pass the new file.";+const TOO_BIG = `A theme file may be up to ${THEME_LIMITS.assetBytes / 1024 / 1024} MB. Ask the person for a smaller one, or, if you have a shell, shrink it (on a Mac: sips -s format jpeg -Z 2560 in.jpg --out out.jpg) and pass the new file.`;+/** The guide's veil over a picture background (shared/theme.ts; src/lib/theme/palette.test.ts holds it readable). */+const VEIL = "color-mix(in srgb, var(--color-app) 62%, transparent)";+const NOT_FOUND = "That file is not in your workspace or this conversation's attachments, or it cannot be read.";+const BUILT_IN: readonly string[] = [...SKIN_IDS, "system"];const reply = (status: number, body: Record<string, unknown>): Reply => ({ status, body });@@ -137,26 +156,104 @@ export function createThemeTool(deps: ThemeToolDeps) {return { wear: { undoTo }, change: `${back}${missing.length ? `; files no longer there: ${missing.join(", ")}` : ""}` };}- async function addAsset(turn: Turn, person: string, body: Record<string, unknown>): Promise<Reply> {- const id = typeof body.id === "string" ? body.id : "";- if (!THEME_ID.test(id) || !store.read(person, id)) return refuse(404, "Name a saved theme in id: save it with set_theme first.");- const path = typeof body.path === "string" ? body.path.trim() : "";- if (!path) return refuse(400, "path is the file in your workspace or this conversation's attachments.");+ /**+ * The file a bot names: an attachment of this conversation by its exact path, by the stored file's name (a bot box+ * shows uploads under another folder) or by the name it was attached under, else a file in the bot's own folders.+ * Security: an attachment opens only directly inside the attachment store, and only one this conversation carries; a+ * tag naming any other file on disk opens nothing. The latest match wins. Opened at any size: the caller reads the+ * first bytes, so a large HEIC photo is named as one, and reads the rest only within the limit.+ */+ async function openNamed(turn: Turn, path: string): Promise<Picked | { error: string; status: number }> {const sources = deps.sources(turn);- const attached = sources.attachments.includes(path);- let file: Awaited<ReturnType<typeof openMessageFile>>;+ const wanted = basename(path.replaceAll("\\", "/"));+ const lower = wanted.toLowerCase();+ const newest = [...sources.attachments].reverse();+ const exact = newest.find((one) => one.path === path);+ const byName = newest.find((one) => basename(one.path) === wanted) ?? newest.find((one) => one.name.toLowerCase() === lower);+ const attached = async (one: { path: string; name: string }) => picked(await openAttachment(sources.attachmentsDir, one.path), one.name);try {- file = await openMessageFile(path, attached ? [dirname(path)] : sources.roots, THEME_LIMITS.assetBytes);+ if (exact) return await attached(exact);+ const file = await openMessageFile(path, sources.roots, OPEN_ANY_SIZE);+ return await picked(file, file.name);} catch (error) {- const status = (error as { status?: number }).status ?? 400;- return refuse(status, status === 413 ? `A theme file may be up to ${THEME_LIMITS.assetBytes / 1024 / 1024} MB.` : "That file is not in your workspace or this conversation's attachments, or it cannot be read.");+ try {+ if (byName) return await attached(byName);+ } catch {+ // Reported as the path the bot named.+ }+ return { status: (error as { status?: number }).status ?? 400, error: NOT_FOUND };}+ }++ async function openAttachment(store: string, path: string): Promise<Opened> {+ if (resolve(dirname(path)) !== resolve(store)) throw Object.assign(new Error("outside the attachment store"), { status: 403 });+ return openMessageFile(path, [store], OPEN_ANY_SIZE);+ }++ /** The newest file attached in this conversation that is a picture (or a HEIC photo, so it is refused by name rather+ * than an older picture used in its place), judged by its bytes. */+ async function latestPicture(turn: Turn): Promise<Picked | null> {+ const sources = deps.sources(turn);+ for (const one of [...sources.attachments].reverse()) {+ let found: Picked;+ try {+ found = await picked(await openAttachment(sources.attachmentsDir, one.path), one.name);+ } catch {+ continue;+ }+ if (found.kind) return found;+ await found.file.handle.close().catch(() => undefined);+ }+ return null;+ }++ /**+ * Copies a file into a theme. `id` left out means the theme the person wears; with none worn, or an id no theme has+ * yet, a theme is made for it (saved, not worn, over the person's built-in skin) so the bot never needs a set_theme+ * first. `path` left out means the latest picture attached in this conversation. Wearing the theme with the file in+ * its CSS is set_theme's, which posts the card with Undo.+ */+ async function addAsset(turn: Turn, person: string, body: Record<string, unknown>): Promise<Reply> {+ const asked = typeof body.id === "string" ? body.id.trim() : "";+ if (asked && (BUILT_IN.includes(asked) || !THEME_ID.test(asked) || asked === "none")) return refuse(400, `${asked} cannot be a saved theme's id. Use lowercase letters, digits and dashes, not a built-in skin's name.`);+ const given = typeof body.path === "string" ? body.path.trim() : "";+ // "none" and "latest" read as left out: models send a word where the schema says to leave a field out.+ const path = /^(none|latest|null)$/i.test(given) ? "" : given;+ const opened = path ? await openNamed(turn, path) : await latestPicture(turn);+ if (!opened) return refuse(404, "No picture is attached in this conversation. Ask the person to attach one, or pass path.");+ if ("error" in opened) return refuse(opened.status, opened.error);+ const { file, kind } = opened;try {- const ext = (extname(file.name).slice(1) || "").toLowerCase();- const stem = slugFor(basename(file.name, extname(file.name))).slice(0, 60);- const added = store.addAsset(person, id, `${stem}.${ext}`, await file.handle.readFile());- if (isRefusal(added)) return refuse(400, added.refusal);- return reply(200, { text: `Added. In the theme's css write url("${added.url}"). Then call set_theme with the theme to use it.` });+ if (kind === "heic") return refuse(400, HEIC);+ if (opened.size > THEME_LIMITS.assetBytes) return refuse(413, TOO_BIG);+ // With nothing worn, the theme an earlier call made here and never wore (it has no CSS yet) takes the file, so+ // trying again, or after Undo, does not leave Background, Background 2, ... behind.+ const unworn = store.read(person, "background");+ const id = asked || store.active(person) || (unworn && !unworn.css ? "background" : store.freeId(person, "Background"));+ const made = !store.read(person, id);+ if (made) {+ const saved = store.save(person, id, { name: asked || "Background" });+ if (saved) return refuse(400, saved.refusal);+ }+ // A stored attachment's own name is an id with a store extension; the bytes say what a picture is.+ const ext = kind ?? (extname(opened.name).slice(1) || "").toLowerCase();+ const stem = slugFor(basename(opened.name, extname(opened.name))).slice(0, 52);+ const bytes = await file.handle.readFile();+ // Another file under the same name (every pasted screenshot is image.png) gets its own, so going back to an+ // earlier look still shows that look's picture.+ const taken = store.asset(person, id, `${stem}.${ext}`);+ const name = taken && !readFileSync(taken.path).equals(bytes) ? `${stem}-${createHash("sha256").update(bytes).digest("hex").slice(0, 6)}.${ext}` : `${stem}.${ext}`;+ const added = store.addAsset(person, id, name, bytes);+ if (isRefusal(added)) {+ if (made) store.remove(person, id);+ return refuse(400, added.refusal);+ }+ const theme = store.read(person, id)!;+ return reply(200, { text: [+ made ? `Made the theme ${theme.name} (id ${id}) for this file over the person's built-in skin; it is not worn yet.` : `Added to the theme ${theme.name} (id ${id}).`,+ `In its css write url("${added.url}")${kind ? `; as the chat background: [data-look="chat-backdrop"] { background: linear-gradient(${VEIL}, ${VEIL}), url("${added.url}") center / cover no-repeat; } (the veil of the theme's ground colour keeps text readable)` : ""}.`,+ `Then call set_theme with id ${id} and the whole theme to wear it${made ? "" : ", keeping its other fields (theme with this id returns them)"}.`,+ ].join(" ") });} finally {await file.handle.close().catch(() => undefined);}diff --git a/shared/theme.ts b/shared/theme.tsindex cd2c4668a3..ea99e18b59 100644--- a/shared/theme.ts+++ b/shared/theme.ts@@ -212,6 +212,7 @@ export function rehomeThemeCss(css: string, fromId: string, toId: string): strin*/export const THEME_HOOKS = [{ selector: '[data-look="app"]', what: "the whole window, behind everything" },+ { selector: '[data-look="window"]', what: "the desktop app's rounded card holding the sidebar and chat (not in the web app)" },{ selector: '[data-look="rail"]', what: "the rail of places down the side (desktop app)" },{ selector: '[data-look="sidebar"]', what: "the sidebar" },{ selector: '[data-look="sidebar-bot"]', what: "a bot's row in the sidebar" },@@ -219,6 +220,7 @@ export const THEME_HOOKS = [{ selector: "[data-avatar]", what: 'every face: a bot\'s or a person\'s; [data-avatar="picture"|"mascot"|"initials"], [data-avatar-kind="bot"|"person"]' },{ selector: '[data-look="chat-header"]', what: "the bar at the top of a chat" },{ selector: '[data-look="chat"]', what: "the chat area, behind the messages" },+ { selector: '[data-look="chat-backdrop"]', what: "an empty layer filling the chat area under everything in it, never scrolling, never clicked: for backgrounds and animations (its ::before and ::after too)" },{ selector: '[data-look="message-user"]', what: "a row with your own message" },{ selector: '[data-look="message-bot"]', what: "a row with a bot's message" },{ selector: '[data-look="user-bubble"]', what: "your own message's bubble" },@@ -259,12 +261,18 @@ export function themeGuide(): string {"The app's own rules can be more specific; add !important when a rule has no effect. Respect @media (prefers-reduced-motion: reduce) for big animations.","Never the internet: @import, image-set(), image(), src() and url() to any other address are removed, and so is any value with a backslash escape outside a string.",`url() may name a theme file (${THEME_ASSET_PREFIX}<theme id>/<file>), a data: address or an #id.`,- "Theme files: add_theme_asset copies an image (png, jpg, webp, gif, avif, svg; animated is fine) or a font (woff2, woff, ttf, otf) from your workspace or this conversation's attachments into a theme, up to 10 MB each. It answers with the url() to use.",+ "Theme files: add_theme_asset copies an image (png, jpg, webp, gif, avif, svg; animated is fine) or a font (woff2, woff, ttf, otf) from your workspace or this conversation's attachments into a theme, up to 10 MB each, and answers with the url() to use. path: a file of yours, or an attachment by its path or file name; left out, the latest picture attached here. id: left out, the theme the person wears, or with none worn a new theme over their built-in skin, worn once you set_theme it. HEIC photos and larger files are refused: if you have a shell, convert first (sips -s format jpeg -Z 2560 in.heic --out out.jpg on a Mac) and pass the new file. An SVG you write in your workspace is a theme file too; its own SMIL or CSS animation plays as a background, but repaints every frame and ignores reduced motion: prefer the recipes below.",+ "",+ "Backgrounds: style [data-look=\"chat-backdrop\"] and its ::before and ::after; it sits under the messages, stays put while they scroll, and never takes a click. Keep text readable: lay the canvas colour over a picture (62%, as below, keeps text readable over any picture in light and dark), and keep patterns and animations faint. Animate only transform and opacity, slowly; the app stops them when the person asks for reduced motion. Known-good, to adapt:",+ '- Picture: [data-look="chat-backdrop"] { background: linear-gradient(color-mix(in srgb, var(--color-app) 62%, transparent), color-mix(in srgb, var(--color-app) 62%, transparent)), url("/api/theme-assets/<id>/<file>") center / cover no-repeat; }',+ '- Moving gradient: [data-look="chat-backdrop"]::before { content: ""; position: absolute; inset: -50%; background: conic-gradient(from 0deg, #1d3557, #e63946, #f1faee, #1d3557); opacity: 0.25; animation: bg-turn 60s linear infinite; } @keyframes bg-turn { to { transform: rotate(1turn); } }',+ '- Drifting pattern: [data-look="chat-backdrop"]::after { content: ""; position: absolute; inset: -40px 0 0; background: url("data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'40\' height=\'40\'><circle cx=\'20\' cy=\'20\' r=\'2\' fill=\'%23888\'/></svg>"); opacity: 0.35; animation: bg-drift 8s linear infinite; } @keyframes bg-drift { to { transform: translateY(40px); } }',+ '- The whole window instead: the same background on [data-look="app"] (with !important), then [data-look="window"], [data-look="chat"] { background: transparent !important; } [data-look="sidebar"], [data-look="rail"] { background: color-mix(in srgb, var(--color-panel) 80%, transparent) !important; }',"","Stable selectors (other class names change between releases, so never rely on them):",...THEME_HOOKS.map((hook) => `- ${hook.selector}: ${hook.what}`),"",- "Calls: theme (optional id: also return that saved theme). set_theme with id and theme (the theme as JSON) saves and wears it; with only id it wears a saved theme, a built-in skin, or none. add_theme_asset with id and path.",+ "Calls: theme (optional id: also return that saved theme). set_theme with id and theme (the theme as JSON) saves and wears it; with only id it wears a saved theme, a built-in skin, or none. add_theme_asset with path and id (both optional).",`theme_history lists the person's last ${LOOK_HISTORY_LIMIT} look changes, newest first, each with its index and the look right after it. undo_theme goes back: steps (default 1) undoes that many changes; index returns to the look right after that entry, theme file and all. An undo is itself a change, so undoing it again is a redo.`,"","You cannot see the result. Make one small change at a time, then ask the person how it looks.",diff --git a/src/App.tsx b/src/App.tsxindex 06b48b1349..d0800a0f9f 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -395,7 +395,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {the window's rail: its top corners and its bottom-left corner are round, and it runs to the window's right andbottom edges. */}<div data-window-card={framed ? "" : undefined}- className={framed ? "relative flex min-w-0 flex-1 flex-col overflow-hidden rounded-t-[12px] rounded-bl-[12px] bg-app" : "contents"}>+ data-look={framed ? "window" : undefined} className={framed ? "relative flex min-w-0 flex-1 flex-col overflow-hidden rounded-t-[12px] rounded-bl-[12px] bg-app" : "contents"}>{framed && strips}<div className={framed ? "relative flex min-h-0 flex-1 overflow-x-clip" : "contents"}>{!calendarFocus && <Sidebardiff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 038e77c248..f6ff2a9c95 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -112,7 +112,7 @@ import { ReplyBlocks } from "./ReplyBlocks";import { webhookMessageView } from "@/lib/webhook-message";import { splitTranscriptAttachments } from "@/lib/composer-attachments";import { useComposerDockPad } from "@/lib/composer-dock";-import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";+import { ChatBackdrop, GlassBar, GlassScrollFrame } from "./GlassScrollFrame";import { PagePaneContext } from "./app/PageTools";import { useTranscriptViewport } from "@/hooks/use-transcript-viewport"; import { staysInView } from "../../shared/person-wait";import { useUnreadDivider } from "@/hooks/use-unread-divider";@@ -930,7 +930,7 @@ export const ChatView = memo(function ChatView({ bot: profile, inForkPanel = falreturn (<ThreadLinkContext value={threadLink}><main data-look="chat" className="relative flex h-full min-w-0 flex-1 flex-col bg-app">- <CallOverlay bot={bot} />+ <ChatBackdrop /><CallOverlay bot={bot} /><GlassScrollFrame className="flex-1 [--glass-tint:var(--color-app)]">{/* z-[25]: above the room set-up card (z-20), below the CallOverlay (z-30). */}<GlassBar edge="top" fade={!remoteClient} data-chathead-float={simpleHead ? "" : undefined} className="z-[25]">diff --git a/src/components/GlassScrollFrame.tsx b/src/components/GlassScrollFrame.tsxindex 06ccda096c..12c3a65ce0 100644--- a/src/components/GlassScrollFrame.tsx+++ b/src/components/GlassScrollFrame.tsx@@ -127,3 +127,10 @@ export function GlassScroller({ className, children, ...rest }: HTMLAttributes<H</div>);}++/** The chat background's own layer: empty and see-through, so nothing changes until a theme styles it (with its+ * ::before and ::after). First in the chat area and positioned, so it paints under everything else there; it never takes+ * a click, and what a theme animates in it stays inside the chat area. */+export function ChatBackdrop() {+ return <div aria-hidden="true" data-look="chat-backdrop" className="pointer-events-none absolute inset-0 overflow-hidden" />;+}diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsxindex d8b8691016..2b90621d8c 100644--- a/src/components/GroupView.tsx+++ b/src/components/GroupView.tsx@@ -64,7 +64,7 @@ import { useMenuMotion } from "./MenuMotion";import { useLiveToolIds } from "@/hooks/use-live-tool-ids";import { roomNeedsSetup, setupResponderMode, type RoomResponderMode } from "@/lib/room-setup";import { useComposerDockPad } from "@/lib/composer-dock";-import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";+import { ChatBackdrop, GlassBar, GlassScrollFrame } from "./GlassScrollFrame";import { awaitedMemberId, showWorkingDots } from "@/lib/turn-tail";import { turnNowPhrases } from "@/lib/live-activity"; import { useTurnLive } from "@/state/turn-status"; import { isLiveReply, roomLiveSpeaker, StreamingReplyContext, useLiveRow, useLiveTranscriptLayout } from "@/state/live-reply";import { useTranscriptViewport } from "@/hooks/use-transcript-viewport"; import { staysInView } from "../../shared/person-wait";@@ -796,7 +796,7 @@ export function GroupView({ group, inForkPanel = false }: { group: Group; inForkreturn (<main data-look="chat" className="relative flex h-full min-w-0 flex-1 flex-col bg-app">- <GroupCallOverlay group={group} members={members} />+ <ChatBackdrop /><GroupCallOverlay group={group} members={members} />{membersOpen && !remoteClient && !group.dm && (<ManageMembersPanel group={group} onClose={closeMembers} triggerRef={membersTriggerRef} />)}diff --git a/src/components/HandoffExchange.tsx b/src/components/HandoffExchange.tsxindex 01eca85727..918a8b6932 100644--- a/src/components/HandoffExchange.tsx+++ b/src/components/HandoffExchange.tsx@@ -5,7 +5,7 @@ import { BotAvatar, InitialsAvatar } from "./Avatar";import { ChatMarkdown } from "./ChatMarkdown";import { DaySeparator } from "./DaySeparator";import { ClusterLabel } from "./RoomClusterLabel";-import { GlassBar, GlassScrollFrame } from "./GlassScrollFrame";+import { ChatBackdrop, GlassBar, GlassScrollFrame } from "./GlassScrollFrame";import { ELEVATED_FLOAT, ELEVATED_HOVER, ELEVATED_TINT } from "./elevated";import { joinedCorners, SIMPLE_BOT_BUBBLE, SIMPLE_BUBBLE_MAX, SIMPLE_STACKED, SIMPLE_USER_BUBBLE } from "./chat-bubble";import { useCaptionChrome } from "@/components/DesktopCapabilities";@@ -91,6 +91,7 @@ export function HandoffExchangeView({ exchange: { asker, helper, threadId }, onBreturn (<main data-look="chat" data-handoff-exchange={threadId} className="relative flex h-full min-w-0 flex-1 flex-col bg-app">+ <ChatBackdrop /><GlassScrollFrame className="flex-1 [--glass-tint:var(--color-app)]"><GlassBar edge="top" fade={!remoteClient} className="z-[25]"><div {...dragProps} data-look="chat-header" className="px-5 pb-2.5 pt-2.5 max-md:pl-14 max-md:pr-3">diff --git a/src/lib/theme/palette.test.ts b/src/lib/theme/palette.test.tsindex 0d829cdc07..03d4c1ead0 100644--- a/src/lib/theme/palette.test.ts+++ b/src/lib/theme/palette.test.ts@@ -20,3 +20,17 @@ it("gives an accent a readable text tone and ink", () => {expect(palette["accent-ink"]).toBe("#111111");expect(accentPalette("#5b21b6", "dark", "#0b1020")["accent-ink"]).toBe("#ffffff");});++describe("the guide's picture background", () => {+ it("lays enough of the canvas over a picture that main text stays at 4.5:1 over a black or white pixel, light and dark", async () => {+ const { themeGuide } = await import("../../../shared/theme");+ const veil = Number(/color-mix\(in srgb, var\(--color-app\) (\d+)%, transparent\)/.exec(themeGuide())![1]) / 100;+ // The default light and dark skins' ground and main text (src/styles.css, daylight and midnight).+ for (const [app, ink] of [["#fcfcfc", "#1c1c1c"], ["#121212", "#f5f5f5"]] as const) {+ for (const pixel of [[0, 0, 0], [255, 255, 255]] as const) {+ const seen = parseHex(app).map((channel, index) => veil * channel + (1 - veil) * pixel[index]!) as [number, number, number];+ expect(contrast(parseHex(ink), seen), `${ink} on ${app} over ${pixel}`).toBeGreaterThanOrEqual(4.5);+ }+ }+ });+});diff --git a/src/styles.css b/src/styles.cssindex 29fd45b1bd..98f742eae4 100644--- a/src/styles.css+++ b/src/styles.css@@ -3809,3 +3809,14 @@ button:disabled.bg-danger {from { opacity: 0; transform: translateX(-0.375rem); }to { opacity: 1; transform: translateX(0); }}++/* The chat backdrop (GlassScrollFrame's ChatBackdrop) is a theme's to paint and animate; with reduced motion asked for,+ whatever a theme animates there stands still, whether or not its CSS says so. */+@media (prefers-reduced-motion: reduce) {+ [data-look="chat-backdrop"],+ [data-look="chat-backdrop"]::before,+ [data-look="chat-backdrop"]::after {+ animation: none !important;+ transition: none !important;+ }+}