Multiplayer agent harness for work.
Synchronize app shell colors with the chat theme (#1512)
Regan Bell51a05cc2a990
diff --git a/plugins/web-ui/src/settings.ts b/plugins/web-ui/src/settings.tsindex 564003b50..7e6e69324 100644--- a/plugins/web-ui/src/settings.ts+++ b/plugins/web-ui/src/settings.ts@@ -56,6 +56,21 @@ function storeCustomTheme(palette: Palette | null): void {}}+let themeParentOrigin: string | null = null;++function publishTheme(): void {+ if (!themeParentOrigin) return;+ const root = document.documentElement;+ const style = getComputedStyle(root);+ const colors = Object.fromEntries(+ ["--background", "--foreground", "--secondary", "--muted-foreground", "--border", "--brand-accent"].map((key) => [+ key,+ style.getPropertyValue(key).trim(),+ ]),+ );+ window.parent.postMessage({ type: "qm:theme", dark: root.classList.contains("dark"), colors }, themeParentOrigin);+}+export function applyTheme(): void {const choice = storedTheme();const custom = choice === "custom" ? storedCustomTheme() : null;@@ -70,11 +85,13 @@ export function applyTheme(): void {}styleEl.textContent = themeCss(tokens);root.classList.toggle("dark", tokens.dark);+ publishTheme();return;}styleEl?.remove();const dark = choice === "system" ? window.matchMedia("(prefers-color-scheme: dark)").matches : choice === "dark";root.classList.toggle("dark", dark);+ publishTheme();}export function setTheme(choice: ThemeChoice): void {@@ -114,6 +131,15 @@ async function onThemeFileChosen(e: Event): Promise<void> {}export function watchSystemTheme(): void {+ window.addEventListener("message", (event) => {+ if (window.parent === window || event.source !== window.parent || event.origin === "null") return;+ if (event.data?.type !== "qm:theme-request") return;+ themeParentOrigin = event.origin;+ publishTheme();+ });+ window.addEventListener("storage", (event) => {+ if (event.key === null || event.key === THEME_KEY || event.key === CUSTOM_THEME_KEY) applyTheme();+ });window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {if (storedTheme() === "system") applyTheme();});diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.tsindex 19c3b4290..e77d78ace 100644--- a/plugins/web-ui/src/shell.ts+++ b/plugins/web-ui/src/shell.ts@@ -1001,6 +1001,7 @@ export async function bootSafely(): Promise<void> {}export async function boot(): Promise<void> {+ if (new URLSearchParams(location.search).get("themeOnly") === "1") return;captureConnectionReturn(location.href);captureSlackReturn(location.href);const params = new URLSearchParams(location.search);diff --git a/plugins/web-ui/test/app-shell-theme.test.ts b/plugins/web-ui/test/app-shell-theme.test.tsnew file mode 100644index 000000000..bb9ef19fc--- /dev/null+++ b/plugins/web-ui/test/app-shell-theme.test.ts@@ -0,0 +1,124 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { stripTypeScriptTypes } from "node:module";+import { runInNewContext } from "node:vm";+import { isPalette, themeCss, themeTokens } from "../src/theme-import.ts";+import { JSDOM, type DOMWindow } from "jsdom";+import { appShellHtml } from "../../../src/deploy/app-shell.ts";++const settings = readFileSync(new URL("../src/settings.ts", import.meta.url), "utf8");+const keys = ["--background", "--foreground", "--secondary", "--muted-foreground", "--border", "--brand-accent"];++test("the app bar accepts the chat palette only from its portal iframe, even while closed", () => {+ const dom = new JSDOM(appShellHtml({ slug: "demo", portalUrl: "https://portal.example.com", path: "/app" }), {+ url: "https://demo.apps.example.com",+ runScripts: "outside-only",+ });+ const win = dom.window;+ win.eval(+ "window.CSS = { supports: (_, value) => /^#[0-9a-f]{6}$/.test(value) }; window.fetch = async () => ({ ok: false });",+ );+ win.eval(win.document.querySelector("script")!.textContent!);+ const chat = win.document.querySelector<HTMLIFrameElement>("#chat")!;+ const root = win.document.documentElement;+ const colors = Object.fromEntries(keys.map((key) => [key, "#123456"]));+ const send = (origin: string, source: unknown, palette = colors, dark = true) =>+ win.dispatchEvent(+ new win.MessageEvent("message", {+ origin,+ source: source as Window,+ data: { type: "qm:theme", dark, colors: palette },+ }),+ );+ assert.match(chat.src, /app-edit\?slug=demo&embed=1&themeOnly=1$/);+ assert.equal(win.document.querySelector("#panel")!.classList.contains("open"), false);+ send("https://attacker.example.com", chat.contentWindow);+ send("https://portal.example.com", win.document.querySelector<HTMLIFrameElement>("#app")!.contentWindow);+ assert.equal(root.style.getPropertyValue("--background"), "");+ send("https://portal.example.com", chat.contentWindow);+ for (const key of keys) assert.equal(root.style.getPropertyValue(key), "#123456");+ assert.equal(root.style.colorScheme, "dark");+ send("https://portal.example.com", chat.contentWindow, { ...colors, "--border": "bad" });+ assert.equal(root.style.getPropertyValue("--border"), "#123456");+ send("https://portal.example.com", chat.contentWindow, colors, false);+ assert.equal(root.style.colorScheme, "light");+ win.document.querySelector<HTMLButtonElement>("#chat-toggle")!.click();+ assert.match(chat.src, /app-edit\?slug=demo&embed=1$/);+ win.document.querySelector<HTMLButtonElement>("#chat-toggle")!.click();+ assert.match(chat.src, /app-edit\?slug=demo&embed=1$/);+ dom.window.close();+});++test("embedded chat publishes active colors and tracks theme changes from other tabs", () => {+ const dom = new JSDOM("<iframe></iframe>", { url: "https://portal.example.com", runScripts: "outside-only" });+ const frame = dom.window.document.querySelector("iframe")!.contentWindow as unknown as DOMWindow;+ const messages: Array<{ data: { dark: boolean; colors: Record<string, string> }; origin: string }> = [];+ dom.window.postMessage = (data, origin) => messages.push({ data, origin: origin as string });+ Object.assign(frame, { isPalette, themeCss, themeTokens });+ frame.eval("window.matchMedia = () => ({ matches: false, addEventListener() {} });");+ const source =+ settings.slice(settings.indexOf("export function storedTheme"), settings.indexOf("let themeParentOrigin")) ++ settings.slice(settings.indexOf("let themeParentOrigin"), settings.indexOf("export function setTheme")) ++ settings.slice(settings.indexOf("export function watchSystemTheme"), settings.indexOf("function themeSwatches"));+ frame.eval(+ stripTypeScriptTypes(+ 'const THEME_KEY = "theme", CUSTOM_THEME_KEY = "theme:custom", CUSTOM_THEME_STYLE_ID = "custom-theme";\n' ++ source.replaceAll("export function", "function"),+ ),+ );+ const style = frame.document.createElement("style");+ style.textContent = `:root { ${keys.map((key) => `${key}: #abcdef;`).join(" ")} }`;+ frame.document.head.appendChild(style);+ frame.eval("applyTheme(); watchSystemTheme();");+ frame.dispatchEvent(+ new frame.MessageEvent("message", {+ source: dom.window as unknown as Window,+ origin: "https://demo.apps.example.com",+ data: { type: "qm:theme-request" },+ }),+ );+ assert.equal(messages.length, 1);+ assert.equal(messages[0].origin, "https://demo.apps.example.com");+ assert.equal(messages[0].data.colors["--background"], "#abcdef");+ assert.equal(messages[0].data.dark, false);+ frame.localStorage.setItem("theme", "dark");+ frame.dispatchEvent(new frame.StorageEvent("storage", { key: "theme" }));+ assert.equal(messages.at(-1)!.data.dark, true);+ const palette = {+ name: "Forest",+ source: "iterm2",+ background: { r: 16, g: 40, b: 32 },+ foreground: { r: 220, g: 252, b: 231 },+ ansi: Array(16).fill(null),+ };+ frame.localStorage.setItem("theme:custom", JSON.stringify(palette));+ frame.localStorage.setItem("theme", "custom");+ frame.dispatchEvent(new frame.StorageEvent("storage", { key: "theme" }));+ assert.equal(messages.at(-1)!.data.dark, true);+ assert.equal(messages.at(-1)!.data.colors["--background"], "#102820");+ frame.localStorage.clear();+ frame.dispatchEvent(new frame.StorageEvent("storage", { key: null }));+ assert.equal(messages.at(-1)!.data.dark, false);+ dom.window.close();+});++test("theme-only startup stops before authenticated chat boot", async () => {+ const shell = readFileSync(new URL("../src/shell.ts", import.meta.url), "utf8");+ const boot = stripTypeScriptTypes(shell.slice(shell.indexOf("export async function boot():")).replace("export ", ""));+ const location = { search: "?slug=demo&embed=1&themeOnly=1" };+ let started = false;+ const run = runInNewContext(boot + "; boot", {+ location,+ URLSearchParams,+ captureConnectionReturn: () => {+ started = true;+ throw new Error("chat boot");+ },+ }) as () => Promise<void>;+ await run();+ assert.equal(started, false);+ location.search = "?slug=demo&embed=1";+ await assert.rejects(run(), /chat boot/);+ assert.equal(started, true);+});diff --git a/src/deploy/app-shell.ts b/src/deploy/app-shell.tsindex 0a2252563..bdee2f79f 100644--- a/src/deploy/app-shell.ts+++ b/src/deploy/app-shell.ts@@ -99,8 +99,28 @@ export function appShellHtml(opts: { slug: string; name?: string; portalUrl: strconst drag = document.getElementById("drag");const openKey = "qmChat:" + slug;+ const portalOrigin = new URL(portal).origin;+ const themeColors = ["--background", "--foreground", "--secondary", "--muted-foreground", "--border", "--brand-accent"];+ window.addEventListener("message", (event) => {+ if (event.source !== chat.contentWindow || event.origin !== portalOrigin) return;+ const theme = event.data;+ if (theme?.type !== "qm:theme" || typeof theme.dark !== "boolean" || !theme.colors) return;+ if (!themeColors.every((key) => typeof theme.colors[key] === "string" && CSS.supports("color", theme.colors[key]))) return;+ for (const key of themeColors) document.documentElement.style.setProperty(key, theme.colors[key]);+ document.documentElement.style.colorScheme = theme.dark ? "dark" : "light";+ });+ chat.addEventListener("load", () => {+ chat.contentWindow.postMessage({ type: "qm:theme-request" }, portalOrigin);+ });+ const chatUrl = portal + "/app-edit?slug=" + encodeURIComponent(slug) + "&embed=1";+ chat.src = chatUrl + "&themeOnly=1";+ let chatLoaded = false;+const setOpen = (on) => {- if (on && !chat.src) chat.src = portal + "/app-edit?slug=" + encodeURIComponent(slug) + "&embed=1";+ if (on && !chatLoaded) {+ chatLoaded = true;+ chat.src = chatUrl;+ }panel.classList.toggle("open", on);toggle.dataset.on = on ? "1" : "0";toggle.setAttribute("aria-expanded", String(on));