Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(webui): refine appearance and add custom reading sizes
Xubin Renef8271b2c050
diff --git a/docs/webui.md b/docs/webui.mdindex 4729d7fbe..c236e7f81 100644--- a/docs/webui.md+++ b/docs/webui.md@@ -258,7 +258,9 @@ Local triggers do not have a WebUI "Run now" action because each run needs a mesRuntime settings may require a gateway restart; the WebUI marks those controls.-**Appearance → Local preferences** applies immediately to the current browser without changing gateway configuration. **Reading text size** adjusts conversation text, Markdown, code and the input, but not navigation or toolbars; standard is the default.+**Appearance** preferences apply immediately in the current browser without changing gateway configuration. Choose **System**, **Light**, or **Dark** for the theme; **System** follows operating-system changes while the app is open. Existing explicit light/dark preferences are preserved.++Under **Reading**, choose a small, standard or large preset, or enter a custom size in the inline **Custom** field beside them. Select the field to edit the saved custom value, using whole pixels from 14 to 28. Hovering or focusing the field shows the supported range and how reading sizes apply. An out-of-range or fractional entry is marked invalid when you finish editing, with a hint showing the size still in use; it does not silently clamp or replace your last valid size. The size applies to both desktop and narrow screens. The input retains a 16px minimum on every screen. The live preview uses the same reading typography as conversations: messages, Markdown and code scale together, while navigation and toolbars stay unchanged. Standard remains the default; switching to a preset preserves your custom value for later use. **Activity display** controls how much process and file-edit detail appears, not what the agent executes.## LAN Accessdiff --git a/webui/COMPONENTS.md b/webui/COMPONENTS.mdindex ce2ab7790..86a02451f 100644--- a/webui/COMPONENTS.md+++ b/webui/COMPONENTS.md@@ -59,7 +59,7 @@ Prompt navigation retains at most three server pages. Static ready Blocks appearUse the text roles in `tailwind.config.js` for shared metrics: `text-ui` for navigation, `text-control-label` for controls, `text-ui-label` for compact labels, `text-caption` for auxiliary text, and `text-title` / `text-ui-heading` for interface headings. These roles stay independent of reading preferences. Register new size utilities in `src/lib/utils.ts` so `cn()` distinguishes them from text colors.-`text-reading` and `.markdown-content` own reading typography; Markdown headings retain relative sizes, and tables, inline code and fenced code preserve their own hierarchy. Browser preferences select small / standard / large body sizes of 16 / 18 / 20px on desktop and 15 / 16 / 18px below 640px. Latin body line height is 1.625; Chinese, Japanese and Korean retain 1.8. `text-code` and `text-code-dense` share the mono stack and scale to 0.875 and 0.75 of body size. Avoid local font-size or line-height overrides for these roles.+`text-reading` and `.markdown-content` own reading typography; Markdown headings retain relative sizes, and tables, inline code and fenced code preserve their own hierarchy. Browser preferences select small / standard / large body sizes of 16 / 18 / 20px on desktop and 15 / 16 / 18px below 640px. Custom reading sizes use a persisted integer from 14 to 28px on both viewport sizes; switching presets preserves the custom value. The `.reading-typography` scope lets the Appearance live preview use the same tokens with its caller-owned preferences. Latin body line height is 1.625; Chinese, Japanese and Korean retain 1.8. `text-code` and `text-code-dense` share the mono stack and scale to 0.875 and 0.75 of body size. Avoid local font-size or line-height overrides for these roles.The Composer shares `text-composer` between its textarea and mention overlay, with a 16px minimum and 1.5 line height. Preserve identical text metrics, padding and literal CJK/Latin spacing in both layers. Reading preferences are projected by `useReadingTypography` through document tokens, without changing the root font size, the rem spacing grid or browser zoom.diff --git a/webui/browser/appearance-fixture.tsx b/webui/browser/appearance-fixture.tsxnew file mode 100644index 000000000..b5facd41a--- /dev/null+++ b/webui/browser/appearance-fixture.tsx@@ -0,0 +1,34 @@+import type { Dispatch, SetStateAction } from "react";+import { useTranslation } from "react-i18next";++import { AppearanceSettingsView } from "@/components/settings/overview/AppearanceSettingsView";+import { useReadingTypography } from "@/hooks/useReadingTypography";+import { useLocalPreferences } from "@/hooks/useLocalPreferences";+import { ThemeProvider, useTheme } from "@/hooks/useTheme";+import { readLocalPreferences, writeLocalPreferences, type LocalPreferences } from "@/lib/local-preferences";++/** Actual appearance controls in a browser-local harness, without a gateway. */+export function AppearanceFixture() {+ const { t } = useTranslation();+ const { theme, preference, setTheme } = useTheme();+ const preferences = useLocalPreferences();+ const setPreferences: Dispatch<SetStateAction<LocalPreferences>> = (update) => {+ writeLocalPreferences(typeof update === "function" ? update(readLocalPreferences()) : update);+ };+ useReadingTypography();+ return <ThemeProvider theme={theme}>+ <main className="h-full overflow-y-auto bg-background" data-appearance-fixture>+ <header className="flex items-center gap-2 text-caption text-muted-foreground" style={{ maxWidth: 800, margin: "0 auto", padding: "28px 32px" }}>+ <img src="/brand/nanobot_mark.svg" className="h-5 w-5" alt="" />+ <span className="font-medium text-foreground">nanobot</span><span aria-hidden>/</span><span>{t("settings.nav.appearance")}</span>+ </header>+ <div style={{ containerType: "inline-size", maxWidth: 800, margin: "0 auto", padding: "0 16px 64px" }}>+ <div className="settings-grid" style={{ margin: 0, width: "100%", maxWidth: "none" }}>+ <h1 className="font-semibold tracking-tight" style={{ fontSize: 28, marginBottom: 20, paddingInline: "var(--settings-inset, 16px)" }}>{t("settings.nav.appearance")}</h1>+ <AppearanceSettingsView themePreference={preference} onChangeTheme={setTheme}+ localPrefs={preferences} onChangeLocalPrefs={setPreferences} />+ </div>+ </div>+ </main>+ </ThemeProvider>;+}diff --git a/webui/browser/appearance.spec.ts b/webui/browser/appearance.spec.tsnew file mode 100644index 000000000..126f249f1--- /dev/null+++ b/webui/browser/appearance.spec.ts@@ -0,0 +1,222 @@+import { expect, test } from "@playwright/test";++test.beforeEach(async ({ page }) => {+ await page.route("**/api/**", (route) => route.abort());+});++test("system theme stays live, explicit choices persist, and tabs agree", async ({ page, context }) => {+ await page.emulateMedia({ colorScheme: "light" });+ await page.goto("/browser/fixture.html?case=appearance");+ await expect(page.getByRole("radio", { name: "System", exact: true })).toBeChecked();+ await page.emulateMedia({ colorScheme: "dark" });+ await expect(page.locator("html")).toHaveClass(/dark/);+ await page.getByRole("radio", { name: "Light", exact: true }).check();+ await expect(page.locator("html")).not.toHaveClass(/dark/);+ await page.reload();+ await expect(page.getByRole("radio", { name: "Light", exact: true })).toBeChecked();+ await expect(page.locator("html")).not.toHaveClass(/dark/);+ await page.getByRole("radio", { name: "System", exact: true }).check();+ await expect(page.locator("html")).toHaveClass(/dark/);+ const other = await context.newPage();+ await other.goto("/browser/fixture.html?case=appearance");+ await expect(other.getByRole("radio", { name: "System", exact: true })).toBeChecked();+ await other.getByRole("radio", { name: "Light", exact: true }).check();+ await expect(page.getByRole("radio", { name: "Light", exact: true })).toBeChecked();+ await expect(page.locator("html")).not.toHaveClass(/dark/);+});++test("custom reading size previews, persists and survives preset changes", async ({ page }) => {+ await page.addInitScript(() => {+ if (!localStorage.getItem("nanobot-webui.settings-preferences")) {+ localStorage.setItem("nanobot-webui.settings-preferences", JSON.stringify({+ schemaVersion: 1, notificationSound: true, browserNotifications: true, brandLogos: false,+ }));+ }+ });+ await page.goto("/browser/fixture.html?case=appearance");+ const title = page.getByRole("heading", { name: "Appearance", exact: true });+ const titleSize = await title.evaluate((element) => getComputedStyle(element).fontSize);+ await page.getByRole("spinbutton", { name: "Custom text size", exact: true }).click();+ const input = page.getByRole("spinbutton", { name: "Custom text size" });+ await input.fill("23");+ const paragraph = page.locator("[data-reading-preview-content] .markdown-content p").first();+ await expect(paragraph).toHaveCSS("font-size", "23px");+ await expect(page.locator("[data-reading-preview-content] code")).toHaveCSS("font-size", "20.125px");+ await input.press("ArrowUp");+ await input.press("Enter");+ await expect(input).toHaveValue("24");+ await page.reload();+ await expect(input).toHaveValue("24");+ await page.getByRole("radio", { name: "Small reading text", exact: true }).click();+ await expect(paragraph).toHaveCSS("font-size", "16px");+ await page.getByRole("spinbutton", { name: "Custom text size", exact: true }).click();+ await expect(input).toHaveValue("24");+ await expect(paragraph).toHaveCSS("font-size", "24px");+ await expect(title).toHaveCSS("font-size", titleSize);+ expect(await page.evaluate(() => JSON.parse(localStorage.getItem("nanobot-webui.settings-preferences")!))).toMatchObject({+ readingTextSize: "custom", customReadingTextSize: 24, notificationSound: true, browserNotifications: true, brandLogos: false,+ });+});++for (const narrow of [false, true]) {+ test(`appearance remains usable at maximum size: ${narrow ? "narrow dark" : "desktop light"}`, async ({ page }, info) => {+ await page.setViewportSize(narrow ? { width: 390, height: 844 } : { width: 1280, height: 1000 });+ await page.addInitScript((dark) => {+ localStorage.setItem("nanobot.locale", "zh-CN");+ localStorage.setItem("nanobot-webui.theme", dark ? "dark" : "light");+ }, narrow);+ await page.goto("/browser/fixture.html?case=appearance");+ await page.getByRole("spinbutton", { name: "自定义字号", exact: true }).click();+ await page.getByRole("spinbutton", { name: "自定义字号" }).fill("28");+ await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "28px");+ expect(await page.locator("main").evaluate((element) => element.scrollWidth <= element.clientWidth)).toBe(true);+ const checkbox = page.getByRole("switch", { name: "品牌图标" });+ await checkbox.click();+ await expect(checkbox).toHaveAttribute("aria-checked", "false");+ await page.getByRole("button", { name: "折叠修改", exact: true }).click();+ await expect(page.getByText("默认收起代码差异,需要时点开。", { exact: true })).toBeVisible();+ await page.locator("main").evaluate((element) => element.scrollTo(0, 0));+ await page.screenshot({ path: info.outputPath("appearance.png") });+ });+}++test("changing a custom size reflows an existing composer and its mention layer", async ({ page }) => {+ await page.setViewportSize({ width: 390, height: 844 });+ await page.goto("/browser/fixture.html?case=typography");+ await page.getByRole("spinbutton", { name: "Custom text size", exact: true }).click();+ await page.getByRole("spinbutton", { name: "Custom text size" }).fill("14");+ const composer = page.getByRole("textbox", { name: "Message input", exact: true });+ await composer.fill("Hello @typography\nKeep reading\nAnother thought");+ await expect(composer).toHaveCSS("font-size", "16px");+ const before = (await composer.boundingBox())!.height;+ await page.getByRole("spinbutton", { name: "Custom text size" }).fill("28");+ await expect(composer).toHaveCSS("font-size", "28px");+ await expect.poll(async () => (await composer.boundingBox())!.height).toBeGreaterThan(before);+ expect(await composer.evaluate((element) => element.scrollHeight <= element.clientHeight + 1)).toBe(true);+ await expect(page.locator(".thread-composer-input > div[aria-hidden]")).toHaveCSS("font-size", "28px");+ await expect(composer).toHaveValue("Hello @typography\nKeep reading\nAnother thought");+});++test("long localized labels fit a small phone without hiding their meaning", async ({ browser, baseURL }) => {+ const context = await browser.newContext({ baseURL, viewport: { width: 320, height: 800 }, hasTouch: true, isMobile: true });+ try {+ const page = await context.newPage();+ await page.route("**/api/**", (route) => route.abort());+ await page.goto("/browser/fixture.html?case=appearance&lang=fr");+ const custom = page.locator(".appearance-size-options").getByRole("spinbutton");+ await page.locator(".appearance-custom-label").tap();+ await expect(custom).toBeFocused();+ await expect(custom).toHaveCSS("font-size", "16px");+ const hint = page.getByRole("tooltip");+ await expect(hint).toBeVisible();+ const hintSurface = page.locator("[data-radix-popper-content-wrapper]").filter({ has: hint });+ const hintBox = (await hintSurface.boundingBox())!;+ expect(hintBox.x).toBeGreaterThanOrEqual(0);+ expect(hintBox.x + hintBox.width).toBeLessThanOrEqual(320);+ expect(await page.locator(".appearance-theme-label, .appearance-size-options, .appearance-custom-label, .appearance-size-options button").evaluateAll(+ (elements) => elements.every((element) => element.scrollWidth <= element.clientWidth + 1 && element.scrollHeight <= element.clientHeight + 1),+ )).toBe(true);+ const labelBox = (await page.locator(".appearance-custom-label").boundingBox())!;+ const fieldBox = (await page.locator(".appearance-custom-option").boundingBox())!;+ expect(fieldBox.height).toBeGreaterThanOrEqual(44);+ expect(labelBox.y).toBeGreaterThan(fieldBox.y);+ expect(labelBox.y + labelBox.height).toBeLessThan((await custom.boundingBox())!.y + 1);+ } finally {+ await context.close();+ }+});++test("the inline custom field is keyboard-editable without moving the size control", async ({ page }) => {+ await page.goto("/browser/fixture.html?case=appearance");+ const preset = page.getByRole("radio", { name: "Large reading text", exact: true });+ await preset.click();+ const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });+ const before = (await input.boundingBox())!;+ await preset.press("Tab");+ await expect(input).toBeFocused();+ await input.pressSequentially("22");+ await expect(input).toHaveValue("22");+ await input.press("Enter");+ await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "22px");+ const after = (await input.boundingBox())!;+ expect(after.y).toBe(before.y);+ expect(after.height).toBe(before.height);+ const presetBox = (await preset.boundingBox())!;+ const groupBox = (await page.locator(".appearance-size-presets").boundingBox())!;+ const customBox = (await page.locator(".appearance-custom-option").boundingBox())!;+ expect(Math.abs((customBox.y + customBox.height / 2) - (presetBox.y + presetBox.height / 2))).toBeLessThan(1);+ expect(customBox.height).toBe(groupBox.height);+ expect(presetBox.width).toBe(presetBox.height);+ expect(customBox.x - (groupBox.x + groupBox.width)).toBeGreaterThanOrEqual(8);+ await input.fill("");+ await input.press("Enter");+ await expect(input).toHaveValue("22");+});++test("reading-size guidance opens on hover and focus, and invalid entries explain what stays saved", async ({ page }) => {+ await page.goto("/browser/fixture.html?case=appearance");+ const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });+ await input.hover();+ const hint = page.getByRole("tooltip");+ await expect(hint).toContainText("Enter a whole number from 14 to 28 px.");+ await expect(page.getByRole("radio", { name: "Standard reading text" })).toBeChecked();+ await input.click();+ await expect(hint).toContainText("the composer stays at least 16px");+ await input.fill("40");+ await input.press("Enter");+ await expect(input).toHaveValue("40");+ await expect(input).toHaveAttribute("aria-invalid", "true");+ await expect(hint).toContainText("Your text remains at 18 px.");+ await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "18px");+ await input.fill("22");+ await input.press("Enter");+ await expect(input).not.toHaveAttribute("aria-invalid", "true");+ await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "22px");+ await expect(hint).toBeHidden();+ await page.reload();+ await expect(input).toHaveValue("22");+});++test("the visible Custom label activates the same inline editor from a preset", async ({ page }) => {+ await page.goto("/browser/fixture.html?case=appearance");+ const label = page.locator(".appearance-custom-label");+ const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });+ await label.click();+ await expect(input).toBeFocused();+ await input.pressSequentially("23");+ await input.press("Enter");+ await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "23px");+ await page.getByRole("radio", { name: "Small reading text", exact: true }).click();+ await label.click();+ await expect(input).toBeFocused();+ await expect(input).toHaveValue("23");+ await expect(page.locator("[data-reading-preview-content] .markdown-content p").first()).toHaveCSS("font-size", "23px");+});+++test("unfinished numeric input reports an error instead of acting like a cleared field", async ({ page }) => {+ await page.goto("/browser/fixture.html?case=appearance");+ const input = page.getByRole("spinbutton", { name: "Custom text size", exact: true });+ const paragraph = page.locator("[data-reading-preview-content] .markdown-content p").first();+ for (const text of ["-", "1e"]) {+ await input.click();+ await input.pressSequentially(text);+ expect(await input.evaluate((element: HTMLInputElement) => element.validity.badInput)).toBe(true);+ await input.press("Enter");+ await expect(input).toHaveAttribute("aria-invalid", "true");+ await expect(page.getByRole("tooltip", { name: /Your text remains at 18 px\./ })).toBeVisible();+ await expect(paragraph).toHaveCSS("font-size", "18px");+ await input.click();+ await input.press("Escape");+ await expect(input).toHaveValue("18");+ await expect(input).not.toHaveAttribute("aria-invalid", "true");+ await input.press("Tab");+ }+ await input.fill("22");+ await input.press("Enter");+ await expect(paragraph).toHaveCSS("font-size", "22px");+ await input.fill("");+ await input.press("Enter");+ await expect(input).toHaveValue("22");+ await expect(input).not.toHaveAttribute("aria-invalid", "true");+});diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsxindex 46a2ab735..ea5835744 100644--- a/webui/browser/fixture.tsx+++ b/webui/browser/fixture.tsx@@ -15,7 +15,8 @@ import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle, Diaimport { TooltipProvider } from "@/components/ui/tooltip";import { Button } from "@/components/ui/button";import { SettingsIcon } from "@/components/icons/product-icons";-import { initializeI18n } from "@/i18n";+import { initializeI18n, setAppLanguage } from "@/i18n";+import { normalizeLocale } from "@/i18n/config";import type { McpPresetInfo, UIMessage } from "@/lib/types";import { SkeletonFixture } from "./skeleton-fixture";import { installSkeletonPreviewApi, SkeletonAdditionsFixture } from "./skeleton-additions-fixture";@@ -42,6 +43,7 @@ import { ThemeToggleFixture } from "./theme-toggle-fixture";import { DisplayMathFixture } from "./display-math-fixture";import { AttachmentLayoutFixture } from "./attachment-layout-fixture";import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture";+import { AppearanceFixture } from "./appearance-fixture";const history: UIMessage[] = [{ id: "question", role: "user", content: "Earlier question", createdAt: 1_700_000_000_000 },@@ -214,8 +216,13 @@ function AppsFixture() {if (parameters.get("case") === "skeleton-additions") installSkeletonPreviewApi();if (parameters.get("case") === "idle-compaction") installIdleCompactionApi();await initializeI18n();+if (parameters.get("case") === "appearance" && parameters.has("lang")) {+ await setAppLanguage(normalizeLocale(parameters.get("lang")));+}createRoot(document.getElementById("root")!).render(<TooltipProvider>- {parameters.get("case") === "loaded-session-search"+ {parameters.get("case") === "appearance"+ ? <AppearanceFixture />+ : parameters.get("case") === "loaded-session-search"? <LoadedSessionSearchFixture />: parameters.get("case") === "attachments"? <AttachmentLayoutFixture />diff --git a/webui/browser/idle-compaction-fixture.tsx b/webui/browser/idle-compaction-fixture.tsxindex fec66b1bc..16e12727b 100644--- a/webui/browser/idle-compaction-fixture.tsx+++ b/webui/browser/idle-compaction-fixture.tsx@@ -57,8 +57,8 @@ export function IdleCompactionFixture() {<button onClick={() => { failNext = true; }}>Fail next save</button><output aria-label="Persisted minutes">{String(snapshot.runtime_config?.[path])}</output></div>- <SettingsView theme="light" initialSection="runtime" initialSettings={initial}- onSettingsChange={setSnapshot} onToggleTheme={() => {}} onBackToChat={() => {}}+ <SettingsView themePreference="light" initialSection="runtime" initialSettings={initial}+ onSettingsChange={setSnapshot} onChangeTheme={() => {}} onBackToChat={() => {}}onModelNameChange={() => {}} onRestart={() => {}} /></div></ClientProvider>;diff --git a/webui/browser/skeleton-additions-fixture.tsx b/webui/browser/skeleton-additions-fixture.tsxindex 68f0bef6c..234f765c9 100644--- a/webui/browser/skeleton-additions-fixture.tsx+++ b/webui/browser/skeleton-additions-fixture.tsx@@ -129,7 +129,7 @@ function SkeletonSurface() {automationsError: state === "error" ? "Preview read failed" : null,},}}- theme={dark ? "dark" : "light"} showSidebar mainNavigationExpanded={false} onToggleTheme={noop} onBackToChat={noop}+ themePreference={dark ? "dark" : "light"} showSidebar mainNavigationExpanded={false} onChangeTheme={noop} onBackToChat={noop}skills={empty ? [] : [skill]} skillsLoading={loading && empty} skillsError={state === "error"} isRestarting={false} hostChromeInset={false} /></div>: <main className="settings-grid mx-auto w-full p-4" style={surface === "automations" ? { maxWidth: 960 } : undefined}>{surface === "chats" ? <div style={{ height: 440, width: 280, maxWidth: "100%" }} className="bg-sidebar"><ChatList sessions={empty ? [] : sessions} activeKey={null} loading={loading} density={density}diff --git a/webui/browser/typography-fixture.tsx b/webui/browser/typography-fixture.tsxindex 2374d983f..fae612633 100644--- a/webui/browser/typography-fixture.tsx+++ b/webui/browser/typography-fixture.tsx@@ -77,7 +77,7 @@ const messages: UIMessage[] = [export function TypographyFixture() {useReadingTypography();- const { theme, toggle } = useTheme();+ const { theme, preference, setTheme } = useTheme();const [preferences, setPreferences] = useState(readLocalPreferences);const [sent, setSent] = useState<UIMessage[]>([]);const previewMessages = new URLSearchParams(window.location.search).has("stress")@@ -87,7 +87,7 @@ export function TypographyFixture() {return <ThemeProvider theme={theme}><main className="h-full overflow-y-auto"><div className="settings-grid mx-auto py-6">- <AppearanceSettingsView theme={theme} onToggleTheme={toggle} localPrefs={preferences}+ <AppearanceSettingsView themePreference={preference} onChangeTheme={setTheme} localPrefs={preferences}onChangeLocalPrefs={setPreferences} /></div><section className="mx-auto max-w-[var(--content-column-width)] space-y-6 px-4 pb-8" aria-label="Reading preview">diff --git a/webui/browser/typography.spec.ts b/webui/browser/typography.spec.tsindex 95c4a0c9a..e707720f3 100644--- a/webui/browser/typography.spec.ts+++ b/webui/browser/typography.spec.ts@@ -32,18 +32,7 @@ for (const narrow of [false, true]) {await page.goto("/browser/fixture.html?case=typography");const group = page.getByRole("radiogroup", { name: "阅读字号", exact: true });await expect(group.getByRole("radio", { name: "阅读字号:标准", exact: true })).toBeChecked();- const heights = await group.evaluate((control) => {- const row = control.closest(".settings-row")!;- const nextRow = row.nextElementSibling!;- return {- readingRow: row.getBoundingClientRect().height,- otherRow: nextRow.getBoundingClientRect().height,- readingControl: control.getBoundingClientRect().height,- otherControl: nextRow.querySelector(".segmented-control")!.getBoundingClientRect().height,- };- });- expect(heights.readingRow).toBe(heights.otherRow);- expect(heights.readingControl).toBe(heights.otherControl);+ await expect(group.getByRole("radio")).toHaveCount(3);const stable = await metrics(page.locator(".settings-row").first().locator(".text-control-label"));const observations = [];for (const [size, label, bodySize] of [@@ -53,7 +42,7 @@ for (const narrow of [false, true]) {] as const) {await group.getByRole("radio", { name: label, exact: true }).click();await expect(page.locator("html")).toHaveAttribute("data-reading-text-size", size);- const paragraph = page.locator(".markdown-content p").first();+ const paragraph = page.locator('section[aria-label="Reading preview"] .markdown-content p').first();await expect(paragraph).toHaveCSS("font-size", `${bodySize}px`);const body = await metrics(paragraph);expect(body.size).toBe(bodySize);@@ -75,10 +64,17 @@ for (const narrow of [false, true]) {expect((await metrics(page.locator(".markdown-inline-code"))).size).toBeCloseTo(bodySize * 0.875);expect((await metrics(page.locator("textarea"))).size).toBe(Math.max(16, bodySize));expect(await metrics(page.locator(".settings-row").first().locator(".text-control-label"))).toEqual(stable);- const widths = await group.getByRole("radio").evaluateAll((nodes) => nodes.map(node => node.getBoundingClientRect().width));- expect(Math.max(...widths) - Math.min(...widths)).toBeLessThan(1);+ const targets = await group.getByRole("radio").evaluateAll((nodes) => nodes.map((node) => {+ const { width, height } = node.getBoundingClientRect();+ return { width, height };+ }));+ // Fine-pointer presets are circular; the separate touch test protects 44px hit targets.+ for (const target of targets) {+ expect(target.width).toBeGreaterThanOrEqual(36);+ expect(target.width).toBe(target.height);+ }expect(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)).toBe(true);- observations.push({ size, body, widths });+ observations.push({ size, body, targets });await page.locator(".markdown-content h1").evaluate(node => node.scrollIntoView({ block: "start" }));await page.screenshot({ path: info.outputPath(`${size}.png`) });}@@ -125,19 +121,13 @@ test("touch composer keeps literal mention metrics and a safe editable minimum",await page.goto("/browser/fixture.html?case=typography");const readingGroup = page.getByRole("radiogroup", { name: "Reading text size", exact: true });await expect(readingGroup.getByRole("radio")).toHaveCount(3);- const heights = await readingGroup.evaluate((control) => {- const row = control.closest(".settings-row")!;- const nextRow = row.nextElementSibling!;- return [row.getBoundingClientRect().height, nextRow.getBoundingClientRect().height];- });- expect(heights[0]).toBe(heights[1]);const radios = await readingGroup.getByRole("radio").all();for (const [index, radio] of radios.entries()) {await radio.scrollIntoViewIfNeeded();const target = await radio.boundingBox();expect(target!.width).toBeGreaterThanOrEqual(44);- // The shared switch pattern extends the hit area without growing the pill.- for (const edge of [-21, 21]) {+ expect(target!.height).toBeGreaterThanOrEqual(44);+ for (const edge of [-20, 20]) {await radios[(index + 1) % radios.length].tap();await page.touchscreen.tap(target!.x + target!.width / 2, target!.y + target!.height / 2 + edge);await expect(radio).toBeChecked();diff --git a/webui/src/App.tsx b/webui/src/App.tsxindex 3b48fda9f..a7e601d35 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -1177,7 +1177,7 @@ function Shell({const updateFlow = useUpdateFlow();const localActive = remoteConnections?.localActive !== false;const managingConnections = remoteConnections?.managing === true && !remoteConnections?.activeHostId;- const { theme, toggle } = useTheme();+ const { theme, preference: themePreference, toggle, setTheme } = useTheme();const managementMain = useRef<HTMLElement>(null);const reportManagementSurface = remoteConnections?.reportManagementSurface;useEffect(() => {@@ -3135,12 +3135,12 @@ function Shell({/> : <Suspense fallback={<StartupShell embedded surface={view} sidebarExpanded={hostSidebarOpen} />}><SettingsViewregisterExitGuard={registerSettingsExitGuard}- theme={theme}+ themePreference={themePreference}initialSection={settingsInitialSection}initialSettings={settingsSnapshot}showSidebar={view === "settings"}mainNavigationExpanded={showMainSidebar && hostSidebarOpen}- onToggleTheme={toggle}+ onChangeTheme={setTheme}onBackToChat={onBackToChat}onModelNameChange={onModelNameChange}onSettingsChange={setSettingsSnapshot}diff --git a/webui/src/components/settings/SettingsPage.tsx b/webui/src/components/settings/SettingsPage.tsxindex 0ac1cbad6..841e73956 100644--- a/webui/src/components/settings/SettingsPage.tsx+++ b/webui/src/components/settings/SettingsPage.tsx@@ -46,16 +46,17 @@ import { RuntimeConfigSettings } from "@/components/settings/system/RuntimeConfiimport { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";import type { SettingsController } from "@/components/settings/useSettingsController";import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";+import type { ThemePreference } from "@/hooks/useTheme";import type { ChatSummary, SessionAutomationJob, SkillSummary } from "@/lib/types";import { cn } from "@/lib/utils";interface SettingsPageProps {registerExitGuard?: (guard: SettingsExitGuard | null) => void;controller: SettingsController;- theme: "light" | "dark";+ themePreference: ThemePreference;showSidebar: boolean;mainNavigationExpanded: boolean;- onToggleTheme: () => void;+ onChangeTheme: (value: ThemePreference) => void;onBackToChat: () => void;skills: SkillSummary[];skillsLoading: boolean;@@ -76,10 +77,10 @@ interface SettingsPageProps {export function SettingsPage({registerExitGuard,controller,- theme,+ themePreference,showSidebar,mainNavigationExpanded,- onToggleTheme,+ onChangeTheme,onBackToChat,skills,skillsLoading,@@ -272,8 +273,8 @@ export function SettingsPage({case "appearance":return (<AppearanceSettings- theme={theme}- onToggleTheme={onToggleTheme}+ themePreference={themePreference}+ onChangeTheme={onChangeTheme}localPrefs={localPrefs}onChangeLocalPrefs={setLocalPrefs}/>diff --git a/webui/src/components/settings/SettingsView.tsx b/webui/src/components/settings/SettingsView.tsxindex 0b5e2f6b3..f9f72ec54 100644--- a/webui/src/components/settings/SettingsView.tsx+++ b/webui/src/components/settings/SettingsView.tsx@@ -2,18 +2,19 @@ import { SettingsPage } from "@/components/settings/SettingsPage";import type { SettingsExitGuard, SettingsSectionKey } from "@/components/settings/contracts";import { useSettingsController } from "@/components/settings/useSettingsController";import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream";+import type { ThemePreference } from "@/hooks/useTheme";import type { ChatSummary, SettingsPayload, SkillSummary } from "@/lib/types";export type { SettingsSectionKey } from "@/components/settings/contracts";interface SettingsViewProps {registerExitGuard?: (guard: SettingsExitGuard | null) => void;- theme: "light" | "dark";+ themePreference: ThemePreference;initialSection?: SettingsSectionKey;initialSettings?: SettingsPayload | null;showSidebar?: boolean;mainNavigationExpanded?: boolean;- onToggleTheme: () => void;+ onChangeTheme: (value: ThemePreference) => void;onBackToChat: () => void;onModelNameChange: (modelName: string | null) => void;onSettingsChange?: (payload: SettingsPayload) => void;@@ -38,12 +39,12 @@ interface SettingsViewProps {export function SettingsView({registerExitGuard,- theme,+ themePreference,initialSection = "overview",initialSettings = null,showSidebar = true,mainNavigationExpanded = false,- onToggleTheme,+ onChangeTheme,onBackToChat,onModelNameChange,onSettingsChange,@@ -74,10 +75,10 @@ export function SettingsView({<SettingsPageregisterExitGuard={registerExitGuard}controller={controller}- theme={theme}+ themePreference={themePreference}showSidebar={showSidebar}mainNavigationExpanded={mainNavigationExpanded}- onToggleTheme={onToggleTheme}+ onChangeTheme={onChangeTheme}onBackToChat={onBackToChat}skills={skills}skillsLoading={skillsLoading}diff --git a/webui/src/components/settings/overview/AppearanceSettingsView.tsx b/webui/src/components/settings/overview/AppearanceSettingsView.tsxindex de7fbb246..e0c905fec 100644--- a/webui/src/components/settings/overview/AppearanceSettingsView.tsx+++ b/webui/src/components/settings/overview/AppearanceSettingsView.tsx@@ -1,129 +1,108 @@-import type { Dispatch, SetStateAction } from "react";+import { useId, type Dispatch, type SetStateAction } from "react";+import { Check, Monitor, Moon, Sun } from "lucide-react";import { useTranslation } from "react-i18next";import { LanguageSwitcher } from "@/components/LanguageSwitcher";import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";import { ToggleButton } from "@/components/ui/toggle-button";import { SegmentedControl } from "@/components/ui/segmented-control";+import type { ThemePreference } from "@/hooks/useTheme";import type { FileEditDisplayMode, LocalActivityMode, LocalPreferences } from "@/lib/local-preferences";+import { ReadingSettings } from "./ReadingSettings";+import "./appearance-settings.css";-export function AppearanceSettingsView({- theme,- onToggleTheme,- localPrefs,- onChangeLocalPrefs,-}: {- theme: "light" | "dark";- onToggleTheme: () => void;+export function AppearanceSettingsView({ themePreference, onChangeTheme, localPrefs, onChangeLocalPrefs }: {+ themePreference: ThemePreference;+ onChangeTheme: (preference: ThemePreference) => void;localPrefs: LocalPreferences;onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;}) {const { t } = useTranslation();- const tx = (key: string, fallback: string) => t(key, { defaultValue: fallback });- return (- <div className="settings-stack">- <section>- <SettingsSectionTitle>{t("settings.sections.interface")}</SettingsSectionTitle>- <SettingsGroup>- <SettingsRow title={t("settings.rows.theme")}>- <SegmentedControl- value={theme}- ariaLabel={t("settings.rows.theme")}- className="bg-muted p-0.5"- itemClassName="px-3"- options={[- { value: "light", label: t("settings.values.light") },- { value: "dark", label: t("settings.values.dark") },- ]}- onChange={(nextTheme) => {- if (nextTheme !== theme) onToggleTheme();- }}- />- </SettingsRow>+ const themeId = useId();+ const themes = [+ { value: "system", label: t("settings.appearance.system"), icon: Monitor },+ { value: "light", label: t("settings.values.light"), icon: Sun },+ { value: "dark", label: t("settings.values.dark"), icon: Moon },+ ] as const;+ const editHelp = { summary: "summaryHelp", diff: "diffHelp", collapsed_diff: "collapsedHelp" } as const;- <SettingsRow title={t("settings.rows.language")}>- <LanguageSwitcher />- </SettingsRow>- </SettingsGroup>- </section>+ return <div className="settings-stack appearance-page">+ <section>+ <SettingsSectionTitle>{t("settings.rows.theme")}</SettingsSectionTitle>+ <fieldset>+ <legend className="sr-only">{t("settings.rows.theme")}</legend>+ <div className="appearance-theme-grid">+ {themes.map(({ value, label, icon: Icon }) => <label key={value} className="appearance-theme-option">+ <input className="appearance-theme-input" type="radio" name={themeId} value={value}+ checked={themePreference === value} onChange={() => onChangeTheme(value)} />+ <span className="appearance-theme-card">+ <span className="appearance-theme-miniature" data-mode={value} aria-hidden>+ <span className="appearance-mini-sidebar"><span /><span /><span /></span>+ <span className="appearance-mini-main"><span /><span /><span /><span /></span>+ </span>+ <span className="appearance-theme-label text-ui-label">+ <span className="flex min-w-0 items-center gap-1.5"><Icon className="h-3.5 w-3.5 shrink-0" aria-hidden /><span>{label}</span></span>+ <Check className="appearance-theme-check h-3.5 w-3.5 shrink-0" aria-hidden />+ </span>+ </span>+ </label>)}+ </div>+ </fieldset>+ </section>- <section>- <SettingsSectionTitle>{tx("settings.sections.localPreferences", "Local preferences")}</SettingsSectionTitle>+ <section>+ <SettingsSectionTitle>{t("settings.appearance.reading")}</SettingsSectionTitle>+ <ReadingSettings preferences={localPrefs} onChange={onChangeLocalPrefs} />+ <div className="mt-2"><SettingsGroup>- <SettingsRow title={t("settings.rows.readingTextSize")}>- <SegmentedControl- value={localPrefs.readingTextSize}- mode="radio"- ariaLabel={t("settings.rows.readingTextSize")}- className="w-36 [@media(pointer:coarse)]:w-40"- itemClassName="flex flex-1 basis-0 items-center justify-center !overflow-visible px-0 after:absolute after:inset-x-0 after:top-1/2 after:h-11 after:-translate-y-1/2 after:content-['']"- options={([- ["small", "text-[12px]"],- ["standard", "text-[16px]"],- ["large", "text-[20px]"],- ] as const).map(([value, size]) => ({- value,- label: <span aria-hidden className={size}>A</span>,- ariaLabel: t(`settings.readingTextSize.${value}`),- tooltip: t(`settings.readingTextSize.${value}`),- }))}- onChange={(readingTextSize) =>- onChangeLocalPrefs((prev) => ({ ...prev, readingTextSize }))- }- />+ <SettingsRow title={t("settings.rows.codeWrap")} description={t("settings.help.codeWrap")}>+ <ToggleButton checked={localPrefs.codeWrap}+ onChange={(codeWrap) => onChangeLocalPrefs((previous) => ({ ...previous, codeWrap }))}+ ariaLabel={t("settings.rows.codeWrap")}+ label={t(localPrefs.codeWrap ? "settings.values.on" : "settings.values.off")} /></SettingsRow>- <SettingsRow title={tx("settings.rows.activityMode", "Activity detail")}>- <SegmentedControl- value={localPrefs.activityMode}- options={[- { value: "auto", label: tx("settings.values.auto", "Auto") },- { value: "expanded", label: tx("settings.values.expanded", "Expanded") },- ]}- onChange={(activityMode) =>- onChangeLocalPrefs((prev) => ({ ...prev, activityMode: activityMode as LocalActivityMode }))- }- />- </SettingsRow>- <SettingsRow title={tx("settings.rows.fileEditDisplay", "File edit display")}>- <SegmentedControl- value={localPrefs.fileEditDisplayMode}+ </SettingsGroup>+ </div>+ </section>++ <section>+ <SettingsSectionTitle>{t("settings.appearance.process")}</SettingsSectionTitle>+ <p className="appearance-setting-help">{t("settings.appearance.processHelp")}</p>+ <SettingsGroup>+ <SettingsRow title={t("settings.rows.activityMode")}>+ <SegmentedControl<LocalActivityMode> value={localPrefs.activityMode}+ ariaLabel={t("settings.rows.activityMode")}+ options={[{ value: "auto", label: t("settings.values.auto") }, { value: "expanded", label: t("settings.values.expanded") }]}+ onChange={(activityMode) => onChangeLocalPrefs((previous) => ({ ...previous, activityMode }))} />+ </SettingsRow>+ <p className="appearance-setting-help">{t(`settings.appearance.${localPrefs.activityMode === "auto" ? "autoHelp" : "expandedHelp"}`)}</p>+ <div className="settings-group-divider">+ <SettingsRow title={t("settings.rows.fileEditDisplay")}>+ <SegmentedControl<FileEditDisplayMode> value={localPrefs.fileEditDisplayMode}+ ariaLabel={t("settings.rows.fileEditDisplay")}options={[- { value: "summary", label: tx("settings.values.summary", "Summary") },- { value: "diff", label: tx("settings.values.diff", "Diff") },- { value: "collapsed_diff", label: tx("settings.values.collapsedDiff", "Collapsed diff") },+ { value: "summary", label: t("settings.values.summary") },+ { value: "diff", label: t("settings.values.diff") },+ { value: "collapsed_diff", label: t("settings.values.collapsedDiff") },]}- onChange={(fileEditDisplayMode) =>- onChangeLocalPrefs((prev) => ({- ...prev,- fileEditDisplayMode: fileEditDisplayMode as FileEditDisplayMode,- }))- }- />- </SettingsRow>- <SettingsRow title={tx("settings.rows.codeWrap", "Code wrapping")}>- <ToggleButton- checked={localPrefs.codeWrap}- onChange={(codeWrap) => onChangeLocalPrefs((prev) => ({ ...prev, codeWrap }))}- ariaLabel={tx("settings.rows.codeWrap", "Code wrapping")}- label={localPrefs.codeWrap ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}- />+ onChange={(fileEditDisplayMode) => onChangeLocalPrefs((previous) => ({ ...previous, fileEditDisplayMode }))} /></SettingsRow>- <SettingsRow- title={tx("settings.rows.brandLogos", "Brand logos")}- description={tx(- "settings.legal.thirdPartyBrands",- "Product names, logos, and brands are property of their respective owners. Use is for identification only and does not imply endorsement.",- )}- >- <ToggleButton- checked={localPrefs.brandLogos}- onChange={(brandLogos) => onChangeLocalPrefs((prev) => ({ ...prev, brandLogos }))}- ariaLabel={tx("settings.rows.brandLogos", "Brand logos")}- label={localPrefs.brandLogos ? tx("settings.values.on", "On") : tx("settings.values.off", "Off")}- />- </SettingsRow>- </SettingsGroup>- </section>- </div>- );+ <p className="appearance-setting-help">{t(`settings.appearance.${editHelp[localPrefs.fileEditDisplayMode]}`)}</p>+ </div>+ </SettingsGroup>+ </section>++ <section>+ <SettingsSectionTitle>{t("settings.sections.interface")}</SettingsSectionTitle>+ <SettingsGroup>+ <SettingsRow title={t("settings.rows.language")}><LanguageSwitcher /></SettingsRow>+ <SettingsRow title={t("settings.rows.brandLogos")} description={t("settings.legal.thirdPartyBrands")}>+ <ToggleButton checked={localPrefs.brandLogos}+ onChange={(brandLogos) => onChangeLocalPrefs((previous) => ({ ...previous, brandLogos }))}+ ariaLabel={t("settings.rows.brandLogos")}+ label={t(localPrefs.brandLogos ? "settings.values.on" : "settings.values.off")} />+ </SettingsRow>+ </SettingsGroup>+ </section>+ </div>;}diff --git a/webui/src/components/settings/overview/OverviewSettings.tsx b/webui/src/components/settings/overview/OverviewSettings.tsxindex 545d500e4..1170fb821 100644--- a/webui/src/components/settings/overview/OverviewSettings.tsx+++ b/webui/src/components/settings/overview/OverviewSettings.tsx@@ -25,6 +25,7 @@ import {} from "@/components/settings/shared/SettingsControls";import { TokenUsageCard } from "@/components/settings/TokenUsageCard";import { useLogoFallback } from "@/hooks/useLogoFallback";+import type { ThemePreference } from "@/hooks/useTheme";import type {LocalPreferences,} from "@/lib/local-preferences";@@ -172,13 +173,13 @@ function VersionCheckRow({ currentVersion, currentCommit, onRequestUpdate, hasPechannelError={channelError} onChangeChannel={changeChannel} />;}-export function AppearanceSettings({ theme, onToggleTheme, localPrefs, onChangeLocalPrefs }: {- theme: "light" | "dark";- onToggleTheme: () => void;+export function AppearanceSettings({ themePreference, onChangeTheme, localPrefs, onChangeLocalPrefs }: {+ themePreference: ThemePreference;+ onChangeTheme: (value: ThemePreference) => void;localPrefs: LocalPreferences;onChangeLocalPrefs: Dispatch<SetStateAction<LocalPreferences>>;}) {- return <AppearanceSettingsView theme={theme} onToggleTheme={onToggleTheme}+ return <AppearanceSettingsView themePreference={themePreference} onChangeTheme={onChangeTheme}localPrefs={localPrefs} onChangeLocalPrefs={onChangeLocalPrefs} />;}diff --git a/webui/src/components/settings/overview/ReadingSettings.tsx b/webui/src/components/settings/overview/ReadingSettings.tsxnew file mode 100644index 000000000..d9eabb013--- /dev/null+++ b/webui/src/components/settings/overview/ReadingSettings.tsx@@ -0,0 +1,151 @@+import { useEffect, useId, useRef, useState, type CSSProperties, type Dispatch, type SetStateAction } from "react";+import { ArrowUp } from "lucide-react";+import { useTranslation } from "react-i18next";++import { MarkdownText } from "@/components/MarkdownText";+import { Input } from "@/components/ui/input";+import { SegmentedControl } from "@/components/ui/segmented-control";+import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";+import { MAX_READING_SIZE, MIN_READING_SIZE, type LocalPreferences, type ReadingTextSize } from "@/lib/local-preferences";++export function ReadingSettings({ preferences, onChange }: {+ preferences: LocalPreferences;+ onChange: Dispatch<SetStateAction<LocalPreferences>>;+}) {+ const { t } = useTranslation();+ const id = useId();+ const inputRef = useRef<HTMLInputElement>(null);+ const custom = preferences.readingTextSize === "custom";+ const [draft, setDraft] = useState(String(preferences.customReadingTextSize));+ const [hintOpen, setHintOpen] = useState(false);+ const [showError, setShowError] = useState(false);+ const hint = t(showError ? "settings.appearance.customInvalid" : "settings.appearance.customRange", {+ min: MIN_READING_SIZE, max: MAX_READING_SIZE, size: preferences.customReadingTextSize,+ });+ useEffect(() => {+ setDraft(String(preferences.customReadingTextSize));+ setShowError(false);+ // A preset selected in another tab ends an unfinished custom edit.+ if (!custom) {+ setHintOpen(false);+ if (document.activeElement === inputRef.current) inputRef.current?.blur();+ }+ }, [preferences.customReadingTextSize, custom]);++ const commitDraft = () => {+ if (!custom) return true;+ const value = draft.trim() ? Number(draft) : preferences.customReadingTextSize;+ // Native number inputs expose unfinished values such as "-" as an empty string.+ if (inputRef.current?.validity.badInput || !Number.isInteger(value) || value < MIN_READING_SIZE || value > MAX_READING_SIZE) {+ setShowError(true);+ setHintOpen(true);+ return false;+ }+ setDraft(String(value));+ setShowError(false);+ setHintOpen(false);+ onChange((previous) => ({ ...previous, customReadingTextSize: value }));+ return true;+ };++ return <div className="appearance-reading-card">+ <div className="appearance-reading-controls">+ <div className="flex flex-wrap items-center justify-between gap-3">+ <span className="text-control-label" id={`${id}-label`}>{t("settings.rows.readingTextSize")}</span>+ <div className="appearance-size-options">+ <SegmentedControl<ReadingTextSize>+ mode="radio"+ value={preferences.readingTextSize}+ ariaLabel={t("settings.rows.readingTextSize")}+ className="appearance-size-presets gap-0 p-0.5"+ itemClassName="flex items-center justify-center p-0"+ options={([+ ["small", "text-[12px]"], ["standard", "text-[16px]"], ["large", "text-[20px]"],+ ] as const).map(([value, size]) => ({+ value,+ label: <span aria-hidden className={size}>A</span>,+ ariaLabel: t(`settings.readingTextSize.${value}`),+ tooltip: t(`settings.readingTextSize.${value}`),+ }))}+ onChange={(readingTextSize) => onChange((previous) => ({ ...previous, readingTextSize }))}+ />+ <TooltipProvider>+ <Tooltip open={hintOpen} onOpenChange={(open) => {+ // Keep guidance visible while typing, including pointer/touch focus.+ if (open || document.activeElement !== inputRef.current) setHintOpen(open);+ }}>+ <TooltipTrigger asChild>+ <label className="appearance-custom-option" htmlFor={`${id}-custom`} data-selected={custom} data-invalid={showError}>+ <span className="appearance-custom-label">{t("settings.appearance.custom")}</span>+ <span className="appearance-custom-value">+ <Input ref={inputRef} id={`${id}-custom`} type="number" inputMode="numeric" min={MIN_READING_SIZE} max={MAX_READING_SIZE} step={1}+ className="appearance-size-input h-[calc(var(--appearance-preset-size)-16px)] w-[3ch] border-0 bg-transparent p-0 text-right text-ui-label tabular-nums focus-visible:ring-0"+ aria-label={t("settings.appearance.customSize")}+ aria-describedby={`${id}-range`}+ aria-invalid={showError || undefined}+ value={draft}+ onFocus={(event) => {+ event.currentTarget.select();+ setHintOpen(true);+ if (!custom) onChange((previous) => ({ ...previous, readingTextSize: "custom" }));+ }}+ onChange={(event) => {+ const next = event.currentTarget.value;+ setDraft(next);+ setShowError(false);+ const value = Number(next);+ if (next.trim() && Number.isInteger(value) && value >= MIN_READING_SIZE && value <= MAX_READING_SIZE) {+ onChange((previous) => ({ ...previous, readingTextSize: "custom", customReadingTextSize: value }));+ }+ }}+ onBlur={(event) => {+ if (!commitDraft()) event.preventDefault();+ }}+ onKeyDown={(event) => {+ if (event.key === "Enter") event.currentTarget.blur();+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ setDraft(String(preferences.customReadingTextSize));+ setShowError(false);+ setHintOpen(false);+ }+ }}+ />+ <span aria-hidden className="text-caption text-muted-foreground">px</span>+ </span>+ </label>+ </TooltipTrigger>+ <TooltipContent side="top" align="end" sideOffset={10}+ className={`max-w-[min(20rem,calc(100vw-2rem))] whitespace-pre-line leading-relaxed ${showError ? "text-destructive" : ""}`}>+ {hint}+ </TooltipContent>+ </Tooltip>+ </TooltipProvider>+ </div>+ </div>+ <p className="mt-2 text-caption text-muted-foreground">{t("settings.appearance.readingHelp")}</p>+ <span className="sr-only" id={`${id}-range`} aria-live="polite">{hint}</span>+ </div>+ <div className="reading-typography appearance-reading-preview"+ data-reading-text-size={preferences.readingTextSize}+ style={{ "--custom-reading-size": `${preferences.customReadingTextSize}px` } as CSSProperties}>+ <div className="mb-4 flex items-center justify-between gap-3 text-caption text-muted-foreground">+ <span className="inline-flex items-center gap-2 font-medium text-foreground">+ <img src="/brand/nanobot_mark.svg" className="h-5 w-5" alt="" />nanobot+ </span>+ <span className="inline-flex items-center gap-1.5"><span className="h-1.5 w-1.5 rounded-full bg-emerald-600/70 dark:bg-emerald-400/70" />{t("settings.appearance.preview")}</span>+ </div>+ <div data-reading-preview-content>+ <MarkdownText>{t("settings.appearance.previewText")}</MarkdownText>+ <div className="mt-4 overflow-x-auto rounded-control bg-muted/60 px-4 py-3">+ <code className={`block font-mono text-code ${preferences.codeWrap ? "whitespace-pre-wrap break-words" : "whitespace-pre"}`}><span className="text-[color:var(--code-keyword)]">const</span>{' idea = '}<span className="text-[color:var(--code-string)]">{'"Hello, nanobot."'}</span>;</code>+ </div>+ </div>+ <div className="mt-4 flex items-center gap-3 rounded-control border border-border/65 px-4 py-3 text-muted-foreground/80" aria-hidden>+ <span className="min-w-0 flex-1 text-composer">{t("settings.appearance.previewPlaceholder")}</span>+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full bg-foreground text-background"><ArrowUp className="h-4 w-4" /></span>+ </div>+ </div>+ </div>;+}diff --git a/webui/src/components/settings/overview/appearance-settings.css b/webui/src/components/settings/overview/appearance-settings.cssnew file mode 100644index 000000000..37c22ae62--- /dev/null+++ b/webui/src/components/settings/overview/appearance-settings.css@@ -0,0 +1,66 @@+.appearance-page { --settings-module-gap: 28px; --appearance-panel-inset: 8px; --appearance-preset-size: 36px; --appearance-control-height: calc(var(--appearance-preset-size) + 4px); container: appearance / inline-size; }+.appearance-page > section { min-width: 0; }+.appearance-theme-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; }+.appearance-theme-option { position: relative; min-width: 0; cursor: pointer; }+.appearance-theme-input { position: absolute; inset: 0; z-index: 1; width: 100%; height: 100%; margin: 0; opacity: 0; cursor: pointer; }+.appearance-theme-card { --appearance-theme-inset: 8px; display: block; padding: var(--appearance-theme-inset); border: 1px solid hsl(var(--border)); border-radius: var(--radius-panel); background: hsl(var(--settings-surface)); transition: border-color 160ms ease, box-shadow 160ms ease; }+.appearance-theme-option input:checked + .appearance-theme-card { border-color: hsl(var(--foreground) / 0.6); box-shadow: 0 0 0 1px hsl(var(--foreground) / 0.15); }+.appearance-theme-option input:focus-visible + .appearance-theme-card { outline: 2px solid hsl(var(--ring) / 0.65); outline-offset: 3px; }+.appearance-theme-check { opacity: 0; }+.appearance-theme-option input:checked + .appearance-theme-card .appearance-theme-check { opacity: 1; }+.appearance-theme-label { display: flex; align-items: center; justify-content: space-between; gap: 4px; padding: 8px 4px 2px; min-height: 36px; }+/* Nested surfaces follow the outer curve minus their actual inset, including the border. */+.appearance-theme-miniature { --mini-paper: #fff; --mini-sidebar: #f1f0ec; --mini-line: #dad9d5; display: flex; height: 84px; overflow: hidden; border-radius: calc(var(--radius-panel) - var(--appearance-theme-inset) - 1px); background: var(--mini-paper); box-shadow: inset 0 0 0 1px rgb(0 0 0 / 0.04); }+.appearance-theme-miniature[data-mode="dark"] { --mini-paper: #303030; --mini-sidebar: #383838; --mini-line: #656565; }+.appearance-theme-miniature[data-mode="system"] { --mini-paper: linear-gradient(110deg, #fff 50%, #303030 50%); --mini-sidebar: #f1f0ec; --mini-line: #969590; }+.appearance-mini-sidebar { width: 24%; display: flex; flex-direction: column; gap: 6px; padding: 11px 7px; background: var(--mini-sidebar); }+.appearance-mini-sidebar::before { content: ""; width: 8px; height: 8px; border-radius: 3px; background: #d7834c; margin-bottom: 6px; }+.appearance-mini-sidebar span { height: 3px; border-radius: 3px; background: var(--mini-line); }+.appearance-mini-main { display: flex; min-width: 0; flex: 1; flex-direction: column; align-items: flex-start; gap: 5px; padding: 16px 12px 10px; }+.appearance-mini-main span { height: 3px; width: 80%; border-radius: 3px; background: var(--mini-line); }+.appearance-mini-main span:first-child { width: 46%; height: 5px; margin-bottom: 4px; }+.appearance-mini-main span:last-child { width: 100%; height: 13px; margin-top: auto; border: 1px solid var(--mini-line); background: transparent; border-radius: 5px; }+.appearance-reading-card { overflow: hidden; border-radius: var(--radius-panel); background: hsl(var(--settings-surface)); }+.appearance-reading-controls { padding: 20px var(--settings-inset, 16px); }+.appearance-size-options { display: flex; align-items: center; gap: 12px; max-width: 100%; }+.appearance-size-presets { flex: 0 0 auto; }+.appearance-size-presets button { width: var(--appearance-preset-size); height: var(--appearance-preset-size); flex: 0 0 var(--appearance-preset-size); }+.appearance-custom-option { position: relative; display: flex; flex: 0 1 auto; align-items: center; justify-content: center; gap: 8px; min-width: 0; height: var(--appearance-control-height); padding: 0 14px; border: 1px solid hsl(var(--border)); border-radius: var(--radius-pill); corner-shape: round; color: hsl(var(--muted-foreground)); background: hsl(var(--background) / 0.55); cursor: text; transition: border-color 160ms ease, background-color 160ms ease; }+.appearance-custom-option[data-selected="true"] { color: hsl(var(--foreground)); border-color: hsl(var(--foreground) / 0.6); background: hsl(var(--background)); }+.appearance-custom-option:has(input:focus-visible) { outline: 2px solid hsl(var(--ring) / 0.65); outline-offset: 3px; }+.appearance-custom-option[data-invalid="true"] { border-color: hsl(var(--destructive)); outline-color: hsl(var(--destructive)); }+.appearance-custom-label { display: block; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; line-height: 16px; }+.appearance-custom-value { display: flex; flex-shrink: 0; align-items: baseline; gap: 1px; min-width: 0; }+@media (pointer: coarse) {+ .appearance-page { --appearance-preset-size: 44px; }+}+@media (hover: hover) {+ .appearance-theme-option:hover .appearance-theme-card { border-color: hsl(var(--foreground) / 0.6); }+ .appearance-custom-option:hover:not([data-selected="true"]):not([data-invalid="true"]) { border-color: hsl(var(--muted-foreground) / 0.55); background: hsl(var(--background) / 0.85); }+}+.appearance-size-input { appearance: textfield; -moz-appearance: textfield; }+.appearance-size-input::-webkit-inner-spin-button, .appearance-size-input::-webkit-outer-spin-button { appearance: none; margin: 0; }+.appearance-reading-preview { margin: 0 var(--appearance-panel-inset) var(--appearance-panel-inset); padding: 20px 16px; border: 1px solid hsl(var(--border) / 0.65); border-radius: calc(var(--radius-panel) - var(--appearance-panel-inset)); background: hsl(var(--background)); }+.appearance-reading-preview .markdown-content > :first-child { margin-top: 0; }+.appearance-reading-preview .markdown-content > :last-child { margin-bottom: 0; }+.appearance-setting-help { padding: 0 var(--settings-inset, 16px) 12px; font-size: 12px; line-height: 1.6; color: hsl(var(--muted-foreground)); }+.appearance-page .settings-section-title { margin-bottom: 12px; }+.appearance-page .settings-row { border-radius: 0; }+.appearance-page .settings-group-divider { border-top: 1px solid hsl(var(--border) / 0.65); }+@container appearance (max-width: 420px) {+ .appearance-theme-grid { gap: 8px; }+ .appearance-theme-card { --appearance-theme-inset: 6px; }+ .appearance-theme-miniature { height: 70px; }+ .appearance-theme-label { padding-inline: 0; font-size: 12px; }+ .appearance-mini-main { padding-inline: 8px; }+ .appearance-size-options { width: 100%; flex-wrap: wrap; justify-content: space-between; gap: 8px; }+ .appearance-custom-option { flex: 0 0 auto; flex-direction: column; gap: 0; min-width: 80px; padding: 2px 10px; }+ .appearance-custom-label { flex-shrink: 0; font-size: 11px; line-height: 12px; }+ .appearance-reading-controls { padding-top: 16px; }+}+@container appearance (max-width: 360px) {+ .appearance-theme-label > span > svg { display: none; }+}+@media (prefers-reduced-motion: reduce) {+ .appearance-theme-card, .appearance-custom-option { transition: none; }+}diff --git a/webui/src/components/thread/ThreadComposer.tsx b/webui/src/components/thread/ThreadComposer.tsxindex 4f00e18ec..c167cdc5b 100644--- a/webui/src/components/thread/ThreadComposer.tsx+++ b/webui/src/components/thread/ThreadComposer.tsx@@ -1160,7 +1160,7 @@ export function ThreadComposer({// keyboard still get the newline-on-Enter behavior.const hasCoarsePointer = useMediaQuery("(pointer: coarse)");const mobileWorkspaceControls = useMediaQuery("(max-width: 639px)");- const { readingTextSize } = useLocalPreferences();+ const { readingTextSize, customReadingTextSize } = useLocalPreferences();const textareaRef = useRef<HTMLTextAreaElement>(null);const mentionOverlayRef = useRef<HTMLDivElement>(null);const formRef = useRef<HTMLFormElement>(null);@@ -1846,7 +1846,7 @@ export function ThreadComposer({// The parent projects typography tokens in its layout effect; measure after it.const input = textareaRef.current;if (input) autosizeTextarea(input);- }, [readingTextSize]);+ }, [readingTextSize, customReadingTextSize]);// Runs before paint so switching sessions never flashes stale draft text.useLayoutEffect(() => {diff --git a/webui/src/dev/gallery/runtime-settings.tsx b/webui/src/dev/gallery/runtime-settings.tsxindex 9032f8648..505cfa24e 100644--- a/webui/src/dev/gallery/runtime-settings.tsx+++ b/webui/src/dev/gallery/runtime-settings.tsx@@ -9,6 +9,7 @@ import { AutomationRunDialogView, type AutomationRunResult } from "@/components/import { Button } from "@/components/ui/button";import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";import { DEFAULT_LOCAL_PREFS } from "@/lib/local-preferences";+import type { ThemePreference } from "@/hooks/useTheme";import type { UpdateChannel } from "@/lib/api";import type { AutomationChatsPayload, SessionAutomationJob } from "@/lib/types";import { StatePicker, type ComponentExample } from "./example";@@ -91,9 +92,9 @@ function AboutPreview() {}function AppearancePreview() {- const [theme, setTheme] = useState<"light" | "dark">("light");+ const [theme, setTheme] = useState<ThemePreference>("system");const [preferences, setPreferences] = useState(DEFAULT_LOCAL_PREFS);- return <><AppearanceSettingsView theme={theme} onToggleTheme={() => setTheme((current) => current === "light" ? "dark" : "light")}+ return <><AppearanceSettingsView themePreference={theme} onChangeTheme={setTheme}localPrefs={preferences} onChangeLocalPrefs={setPreferences} /><pre role="status" className="mt-4 overflow-auto rounded-control bg-muted p-4 text-xs">{JSON.stringify({ theme, ...preferences }, null, 2)}</pre></>;}@@ -127,7 +128,7 @@ export const runtimeSettingsExamples: ComponentExample[] = [{ title: "controls.appearance.title", files: ["webui/src/components/settings/overview/AppearanceSettingsView.tsx"], Preview: AppearancePreview,description: "controls.appearance.description",options: "controls.appearance.options",- code: '<AppearanceSettingsView theme={theme} onToggleTheme={toggleTheme} localPrefs={preferences} onChangeLocalPrefs={setPreferences} onChangeBrowserNotifications={changeNotifications} />' },+ code: '<AppearanceSettingsView themePreference={preference} onChangeTheme={setTheme} localPrefs={preferences} onChangeLocalPrefs={setPreferences} />' },{ title: "controls.starInvitation.title", files: ["webui/src/components/StarPromptView.tsx"], Preview: StarInvitationPreview,description: "controls.starInvitation.description",options: "controls.starInvitation.options",diff --git a/webui/src/globals.css b/webui/src/globals.cssindex 71d807460..a56719aa4 100644--- a/webui/src/globals.css+++ b/webui/src/globals.css@@ -81,11 +81,6 @@--radius-pill: 9999px;--corner-shape: superellipse(1.5);--content-column-width: 49.5rem;- --reading-size-wide: 18px;- --reading-size-narrow: 16px;- --text-reading-size: var(--reading-size-wide);- --text-code-size: calc(var(--text-reading-size) * 0.875);- --text-code-dense-size: calc(var(--text-reading-size) * 0.75);--sidebar: 40 8% 96.8%;--sidebar-foreground: 0 0% 3.9%;--sidebar-content: 240 3% 30%;@@ -101,18 +96,31 @@--scrollbar-thumb-hover: hsl(var(--muted-foreground) / 0.42);}- :root[data-reading-text-size="small"] {+ :root, .reading-typography {+ --reading-size-wide: 18px;+ --reading-size-narrow: 16px;+ --text-reading-size: var(--reading-size-wide);+ --text-code-size: calc(var(--text-reading-size) * 0.875);+ --text-code-dense-size: calc(var(--text-reading-size) * 0.75);+ }++ :root[data-reading-text-size="small"], .reading-typography[data-reading-text-size="small"] {--reading-size-wide: 16px;--reading-size-narrow: 15px;}- :root[data-reading-text-size="large"] {+ :root[data-reading-text-size="large"], .reading-typography[data-reading-text-size="large"] {--reading-size-wide: 20px;--reading-size-narrow: 18px;}+ :root[data-reading-text-size="custom"], .reading-typography[data-reading-text-size="custom"] {+ --reading-size-wide: var(--custom-reading-size, 18px);+ --reading-size-narrow: var(--custom-reading-size, 18px);+ }+@media (max-width: 639px) {- :root {+ :root, .reading-typography {--text-reading-size: var(--reading-size-narrow);}}diff --git a/webui/src/hooks/useReadingTypography.ts b/webui/src/hooks/useReadingTypography.tsindex 65cc88d52..d3a4b800c 100644--- a/webui/src/hooks/useReadingTypography.ts+++ b/webui/src/hooks/useReadingTypography.ts@@ -4,8 +4,9 @@ import { useLocalPreferences } from "@/hooks/useLocalPreferences";/** Project browser preferences onto text tokens, without scaling the UI or rem. */export function useReadingTypography(): void {- const { readingTextSize } = useLocalPreferences();+ const { readingTextSize, customReadingTextSize } = useLocalPreferences();useLayoutEffect(() => {document.documentElement.dataset.readingTextSize = readingTextSize;- }, [readingTextSize]);+ document.documentElement.style.setProperty("--custom-reading-size", `${customReadingTextSize}px`);+ }, [readingTextSize, customReadingTextSize]);}diff --git a/webui/src/hooks/useTheme.ts b/webui/src/hooks/useTheme.tsindex f1d1557f4..0213c70ca 100644--- a/webui/src/hooks/useTheme.ts+++ b/webui/src/hooks/useTheme.ts@@ -10,16 +10,19 @@ import {} from "react";import "./theme-transition.css";+import { useMediaQuery } from "@/hooks/useMediaQuery";++export type ThemePreference = "system" | "light" | "dark";type Theme = "light" | "dark";const STORAGE_KEY = "nanobot-webui.theme";const ThemeContext = createContext<Theme>("light");-function readStored(): Theme | null {+function readStored(): ThemePreference {try {- const v = localStorage.getItem(STORAGE_KEY);- return v === "light" || v === "dark" ? v : null;+ const value = localStorage.getItem(STORAGE_KEY);+ return value === "light" || value === "dark" ? value : "system";} catch {- return null;+ return "system";}}@@ -38,19 +41,13 @@ function applyTheme(theme: Theme): void {export function useTheme(): {theme: Theme;+ preference: ThemePreference;toggle: () => void;- setTheme: (t: Theme) => void;+ setTheme: (value: ThemePreference) => void;} {- const [theme, setThemeState] = useState<Theme>(() => {- const stored = readStored();- if (stored) return stored;- if (typeof window !== "undefined" && window.matchMedia) {- return window.matchMedia("(prefers-color-scheme: dark)").matches- ? "dark"- : "light";- }- return "light";- });+ const [preference, setPreference] = useState(readStored);+ const systemDark = useMediaQuery("(prefers-color-scheme: dark)");+ const theme: Theme = preference === "system" ? (systemDark ? "dark" : "light") : preference;const switchTimer = useRef<ReturnType<typeof setTimeout> | null>(null);useEffect(() => () => {@@ -63,27 +60,43 @@ export function useTheme(): {useEffect(() => {applyTheme(theme);+ }, [theme]);++ useEffect(() => {+ const refresh = (event: StorageEvent) => {+ if (event.key !== null && event.key !== STORAGE_KEY) return;+ if (event.storageArea && event.storageArea !== window.localStorage) return;+ setPreference(readStored());+ };+ window.addEventListener("storage", refresh);+ return () => window.removeEventListener("storage", refresh);+ }, []);++ const setTheme = useCallback((value: ThemePreference) => {+ if (value === preference) return;+ const next = value === "system" ? (systemDark ? "dark" : "light") : value;+ // Changing preference without changing the palette must not start or block a transition.+ if (next !== theme) {+ if (switchTimer.current !== null) return;+ document.documentElement.dataset.themeTransition = next;+ switchTimer.current = setTimeout(() => {+ delete document.documentElement.dataset.themeTransition;+ switchTimer.current = null;+ }, 600);+ }+ setPreference(value);+ // Only user choices persist. Resolved system changes and other tabs never write back.try {- localStorage.setItem(STORAGE_KEY, theme);+ localStorage.setItem(STORAGE_KEY, value);} catch {- // ignore+ // Browser-only preferences should never block the interface.}- }, [theme]);-- const setTheme = useCallback((next: Theme) => {- if (next === theme || switchTimer.current !== null) return;- document.documentElement.dataset.themeTransition = next;- setThemeState(next);- switchTimer.current = setTimeout(() => {- delete document.documentElement.dataset.themeTransition;- switchTimer.current = null;- }, 600);- }, [theme]);+ }, [preference, systemDark, theme]);const toggle = useCallback(() => setTheme(theme === "dark" ? "light" : "dark"),[setTheme, theme],);- return { theme, toggle, setTheme };+ return { theme, preference, toggle, setTheme };}export function ThemeProvider({ theme, children }: { theme: Theme; children: ReactNode }) {diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex f2b03e51d..bab60586e 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -905,6 +905,28 @@"failed": "Task failed. Click for details.","interrupted": "Task needs attention. Click to continue."},+ "appearance": {+ "system": "System",+ "reading": "Reading",+ "readingHelp": "Adjust messages, code and the composer—not navigation.",+ "custom": "Custom",+ "customSize": "Custom text size",+ "customRange": "Enter a whole number from {{min}} to {{max}} px.\nCode scales with the text; the composer stays at least 16px.",+ "customInvalid": "Use a whole number from {{min}} to {{max}} px.\nYour text remains at {{size}} px.",+ "small": "Small",+ "standard": "Standard",+ "large": "Large",+ "preview": "Live preview",+ "previewText": "**A little room to think.**\n\nClear words, comfortable reading. Make this space your own.",+ "previewPlaceholder": "Where should we begin?",+ "process": "Activity display",+ "processHelp": "Choose how much detail appears as nanobot works.",+ "autoHelp": "Show progress while working; keep finished work compact.",+ "expandedHelp": "Keep activity details expanded by default.",+ "summaryHelp": "Show changed files and line counts.",+ "diffHelp": "Show code changes directly in the conversation.",+ "collapsedHelp": "Keep code changes folded until you open them."+ },"readingTextSize": {"small": "Small reading text","standard": "Standard reading text",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 68143c2db..41ba3c10d 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -644,6 +644,28 @@"failed": "La tarea falló. Haz clic para ver los detalles.","interrupted": "La tarea necesita atención. Haz clic para continuar."},+ "appearance": {+ "system": "Sistema",+ "reading": "Lectura",+ "readingHelp": "Ajusta los mensajes, el código y el campo de escritura, sin cambiar la navegación.",+ "custom": "Personalizado",+ "customSize": "Tamaño de texto personalizado",+ "customRange": "Introduce un número entero entre {{min}} y {{max}} px.\nEl código se escala con el texto; el campo de entrada mantiene un mínimo de 16px.",+ "customInvalid": "Usa un número entero entre {{min}} y {{max}} px.\nEl texto sigue en {{size}} px.",+ "small": "Pequeño",+ "standard": "Estándar",+ "large": "Grande",+ "preview": "Vista previa en vivo",+ "previewText": "**Un poco de espacio para pensar.**\n\nPalabras claras, lectura cómoda. Haz tuyo este espacio.",+ "previewPlaceholder": "¿Por dónde empezamos?",+ "process": "Visualización de actividad",+ "processHelp": "Elige cuánto detalle se muestra mientras nanobot trabaja.",+ "autoHelp": "Muestra el progreso durante el trabajo y una vista compacta al terminar.",+ "expandedHelp": "Mantén los detalles de actividad expandidos por defecto.",+ "summaryHelp": "Muestra los archivos modificados y el número de líneas.",+ "diffHelp": "Muestra los cambios de código directamente en la conversación.",+ "collapsedHelp": "Mantén los cambios de código contraídos hasta que los abras."+ },"readingTextSize": {"small": "Texto de lectura pequeño","standard": "Texto de lectura estándar",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex 5fc3a7581..edb5ed0ba 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -644,6 +644,28 @@"failed": "La tâche a échoué. Cliquez pour les détails.","interrupted": "La tâche demande votre attention. Cliquez pour continuer."},+ "appearance": {+ "system": "Système",+ "reading": "Lecture",+ "readingHelp": "Ajustez les messages, le code et la zone de saisie, sans changer la navigation.",+ "custom": "Personnalisé",+ "customSize": "Taille du texte personnalisée",+ "customRange": "Saisissez un nombre entier entre {{min}} et {{max}} px.\nLe code suit la taille du texte ; le champ de saisie reste à 16px minimum.",+ "customInvalid": "Utilisez un nombre entier entre {{min}} et {{max}} px.\nLe texte reste à {{size}} px.",+ "small": "Petit",+ "standard": "Standard",+ "large": "Grand",+ "preview": "Aperçu en direct",+ "previewText": "**Un peu d’espace pour réfléchir.**\n\nDes mots clairs, une lecture agréable. Faites de cet espace le vôtre.",+ "previewPlaceholder": "Par où commencer ?",+ "process": "Affichage de l’activité",+ "processHelp": "Choisissez le niveau de détail affiché pendant que nanobot travaille.",+ "autoHelp": "Affichez la progression en cours et gardez les activités terminées compactes.",+ "expandedHelp": "Gardez les détails de l’activité développés par défaut.",+ "summaryHelp": "Affichez les fichiers modifiés et le nombre de lignes.",+ "diffHelp": "Affichez les changements de code directement dans la conversation.",+ "collapsedHelp": "Gardez les changements de code repliés jusqu’à leur ouverture."+ },"readingTextSize": {"small": "Texte de lecture : petit","standard": "Texte de lecture : standard",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 22457511c..6740d8717 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -644,6 +644,28 @@"failed": "Tugas gagal. Klik untuk melihat detailnya.","interrupted": "Tugas perlu perhatian. Klik untuk melanjutkan."},+ "appearance": {+ "system": "Ikuti sistem",+ "reading": "Membaca",+ "readingHelp": "Sesuaikan pesan, kode, dan kolom pesan, tanpa mengubah navigasi.",+ "custom": "Kustom",+ "customSize": "Ukuran teks kustom",+ "customRange": "Masukkan bilangan bulat dari {{min}} hingga {{max}} px.\nKode mengikuti ukuran teks; kolom input tetap minimal 16px.",+ "customInvalid": "Gunakan bilangan bulat dari {{min}} hingga {{max}} px.\nTeks tetap berukuran {{size}} px.",+ "small": "Kecil",+ "standard": "Standar",+ "large": "Besar",+ "preview": "Pratinjau langsung",+ "previewText": "**Sedikit ruang untuk berpikir.**\n\nKata-kata yang jelas, nyaman dibaca. Jadikan ruang ini milik Anda.",+ "previewPlaceholder": "Dari mana kita mulai?",+ "process": "Tampilan aktivitas",+ "processHelp": "Pilih seberapa banyak detail yang ditampilkan saat nanobot bekerja.",+ "autoHelp": "Tampilkan progres saat bekerja dan tampilan ringkas setelah selesai.",+ "expandedHelp": "Perluas detail aktivitas secara default.",+ "summaryHelp": "Tampilkan berkas yang diubah dan jumlah baris.",+ "diffHelp": "Tampilkan perubahan kode langsung dalam percakapan.",+ "collapsedHelp": "Lipat perubahan kode hingga Anda membukanya."+ },"readingTextSize": {"small": "Teks bacaan kecil","standard": "Teks bacaan standar",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex f302e1acd..b82ef5e3a 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -644,6 +644,28 @@"failed": "タスクが失敗しました。クリックして詳細を確認。","interrupted": "対応が必要です。クリックして続行。"},+ "appearance": {+ "system": "システムに合わせる",+ "reading": "読みやすさ",+ "readingHelp": "メッセージ、コード、入力欄の文字サイズを調整します。ナビゲーションは変わりません。",+ "custom": "カスタム",+ "customSize": "文字サイズを指定",+ "customRange": "{{min}}~{{max}} px の整数を入力してください。\nコードは本文に合わせて拡大縮小され、入力欄は最低 16px を保ちます。",+ "customInvalid": "{{min}}~{{max}} px の整数を指定してください。\n現在の文字サイズは {{size}} px のままです。",+ "small": "小",+ "standard": "標準",+ "large": "大",+ "preview": "ライブプレビュー",+ "previewText": "**考えるための、少しの余白。**\n\n明快な言葉と、心地よい読みやすさ。この空間を、あなたらしく。",+ "previewPlaceholder": "何から始めましょうか?",+ "process": "処理状況の表示",+ "processHelp": "nanobot の作業中に表示する詳細の量を選びます。",+ "autoHelp": "作業中は進捗を表示し、完了後はコンパクトにまとめます。",+ "expandedHelp": "処理の詳細を既定で展開します。",+ "summaryHelp": "変更されたファイルと行数を表示します。",+ "diffHelp": "コードの変更を会話内に直接表示します。",+ "collapsedHelp": "コードの変更は、開くまで折りたたんでおきます。"+ },"readingTextSize": {"small": "本文の文字サイズ:小","standard": "本文の文字サイズ:標準",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex 8ffda3546..37293e4c9 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -644,6 +644,28 @@"failed": "작업이 실패했습니다. 눌러서 자세히 확인하세요.","interrupted": "확인이 필요합니다. 눌러서 계속하세요."},+ "appearance": {+ "system": "시스템 설정",+ "reading": "읽기",+ "readingHelp": "메시지, 코드, 입력창의 글자 크기를 조절합니다. 탐색 메뉴는 바뀌지 않습니다.",+ "custom": "사용자 지정",+ "customSize": "사용자 지정 글자 크기",+ "customRange": "{{min}}~{{max}} px 사이의 정수를 입력하세요.\n코드는 본문에 맞춰 조절되며, 입력란은 최소 16px을 유지합니다.",+ "customInvalid": "{{min}}~{{max}} px 사이의 정수를 사용하세요.\n본문은 현재 {{size}} px로 유지됩니다.",+ "small": "작게",+ "standard": "표준",+ "large": "크게",+ "preview": "실시간 미리보기",+ "previewText": "**생각을 위한 작은 여유.**\n\n명확한 글과 편안한 읽기. 이 공간을 나에게 맞게 꾸며 보세요.",+ "previewPlaceholder": "어디서부터 시작할까요?",+ "process": "활동 표시",+ "processHelp": "nanobot이 작업하는 동안 표시할 세부 정보의 양을 선택하세요.",+ "autoHelp": "작업 중에는 진행 상황을 표시하고, 완료 후에는 간결하게 표시합니다.",+ "expandedHelp": "활동 세부 정보를 기본으로 펼쳐 둡니다.",+ "summaryHelp": "변경된 파일과 줄 수를 표시합니다.",+ "diffHelp": "코드 변경 내용을 대화에 바로 표시합니다.",+ "collapsedHelp": "코드 변경 내용은 직접 열 때까지 접어 둡니다."+ },"readingTextSize": {"small": "읽기 글자 크기: 작게","standard": "읽기 글자 크기: 표준",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 8e4d57223..cd2ab47a4 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -713,6 +713,28 @@"failed": "A tarefa falhou. Clique para ver os detalhes.","interrupted": "A tarefa precisa de atenção. Clique para continuar."},+ "appearance": {+ "system": "Sistema",+ "reading": "Leitura",+ "readingHelp": "Ajuste as mensagens, o código e o campo de escrita, sem alterar a navegação.",+ "custom": "Personalizado",+ "customSize": "Tamanho de texto personalizado",+ "customRange": "Digite um número inteiro entre {{min}} e {{max}} px.\nO código acompanha o tamanho do texto; o campo de entrada mantém no mínimo 16px.",+ "customInvalid": "Use um número inteiro entre {{min}} e {{max}} px.\nO texto permanece em {{size}} px.",+ "small": "Pequeno",+ "standard": "Padrão",+ "large": "Grande",+ "preview": "Prévia em tempo real",+ "previewText": "**Um pouco de espaço para pensar.**\n\nPalavras claras, leitura confortável. Deixe este espaço com a sua cara.",+ "previewPlaceholder": "Por onde começamos?",+ "process": "Exibição de atividade",+ "processHelp": "Escolha o nível de detalhe exibido enquanto o nanobot trabalha.",+ "autoHelp": "Mostre o progresso durante o trabalho e uma visão compacta ao terminar.",+ "expandedHelp": "Mantenha os detalhes de atividade expandidos por padrão.",+ "summaryHelp": "Mostre os arquivos alterados e a contagem de linhas.",+ "diffHelp": "Mostre as alterações de código diretamente na conversa.",+ "collapsedHelp": "Mantenha as alterações de código recolhidas até você abri-las."+ },"readingTextSize": {"small": "Texto de leitura pequeno","standard": "Texto de leitura padrão",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex e4aece2f1..039a2d154 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -644,6 +644,28 @@"failed": "Tác vụ thất bại. Nhấp để xem chi tiết.","interrupted": "Tác vụ cần chú ý. Nhấp để tiếp tục."},+ "appearance": {+ "system": "Theo hệ thống",+ "reading": "Đọc",+ "readingHelp": "Điều chỉnh tin nhắn, mã và ô soạn thảo, không thay đổi phần điều hướng.",+ "custom": "Tùy chỉnh",+ "customSize": "Cỡ chữ tùy chỉnh",+ "customRange": "Nhập số nguyên từ {{min}} đến {{max}} px.\nMã thay đổi theo cỡ chữ; ô nhập liệu luôn giữ tối thiểu 16px.",+ "customInvalid": "Hãy dùng số nguyên từ {{min}} đến {{max}} px.\nCỡ chữ vẫn giữ ở {{size}} px.",+ "small": "Nhỏ",+ "standard": "Tiêu chuẩn",+ "large": "Lớn",+ "preview": "Xem trước trực tiếp",+ "previewText": "**Một chút không gian để suy nghĩ.**\n\nCâu chữ rõ ràng, đọc thật thoải mái. Biến không gian này thành của riêng bạn.",+ "previewPlaceholder": "Chúng ta nên bắt đầu từ đâu?",+ "process": "Hiển thị hoạt động",+ "processHelp": "Chọn mức độ chi tiết hiển thị khi nanobot làm việc.",+ "autoHelp": "Hiển thị tiến độ khi đang làm việc và thu gọn khi hoàn tất.",+ "expandedHelp": "Mặc định mở rộng chi tiết hoạt động.",+ "summaryHelp": "Hiển thị các tệp đã thay đổi và số dòng.",+ "diffHelp": "Hiển thị thay đổi mã ngay trong cuộc trò chuyện.",+ "collapsedHelp": "Thu gọn thay đổi mã cho đến khi bạn mở ra."+ },"readingTextSize": {"small": "Cỡ chữ đọc nhỏ","standard": "Cỡ chữ đọc tiêu chuẩn",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex 3ad522b71..19cae03a1 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -905,6 +905,28 @@"failed": "任务失败,点击查看详情。","interrupted": "任务需要处理,点击继续。"},+ "appearance": {+ "system": "跟随系统",+ "reading": "阅读",+ "readingHelp": "调整消息、代码和输入框,不改变导航大小。",+ "custom": "自定义",+ "customSize": "自定义字号",+ "customRange": "支持 {{min}}–{{max}} px 整数。\n代码随正文缩放,输入框最小 16px。",+ "customInvalid": "请输入 {{min}}–{{max}} px 的整数。\n当前仍使用 {{size}} px。",+ "small": "小",+ "standard": "标准",+ "large": "大",+ "preview": "实时预览",+ "previewText": "**给思考留一点空间。**\n\n清晰的文字,舒服的节奏。让每一个想法,都有自在展开的空间。",+ "previewPlaceholder": "接下来,想聊点什么?",+ "process": "过程展示",+ "processHelp": "选择 nanobot 工作时展示多少细节。",+ "autoHelp": "工作时显示进度,结束后保持简洁。",+ "expandedHelp": "默认展开工具活动与子任务详情。",+ "summaryHelp": "显示修改文件和增删行数。",+ "diffHelp": "在对话中直接展示代码差异。",+ "collapsedHelp": "默认收起代码差异,需要时点开。"+ },"readingTextSize": {"small": "阅读字号:小","standard": "阅读字号:标准",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 511c10f9f..af88de9fb 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -644,6 +644,28 @@"failed": "任務失敗,點選查看詳情。","interrupted": "任務需要處理,點選繼續。"},+ "appearance": {+ "system": "跟隨系統",+ "reading": "閱讀",+ "readingHelp": "調整訊息、程式碼和輸入框,不改變導覽大小。",+ "custom": "自訂",+ "customSize": "自訂字級",+ "customRange": "支援 {{min}}–{{max}} px 整數。\n程式碼隨內文縮放,輸入框最小 16px。",+ "customInvalid": "請輸入 {{min}}–{{max}} px 的整數。\n目前仍使用 {{size}} px。",+ "small": "小",+ "standard": "標準",+ "large": "大",+ "preview": "即時預覽",+ "previewText": "**給思考留一點空間。**\n\n清晰的文字,舒服的節奏。讓每一個想法,都有自在展開的空間。",+ "previewPlaceholder": "接下來,想聊點什麼?",+ "process": "過程展示",+ "processHelp": "選擇 nanobot 工作時展示多少細節。",+ "autoHelp": "工作時顯示進度,結束後保持簡潔。",+ "expandedHelp": "預設展開工具活動與子任務詳情。",+ "summaryHelp": "顯示修改檔案和增刪行數。",+ "diffHelp": "在對話中直接展示程式碼差異。",+ "collapsedHelp": "預設收合程式碼差異,需要時點開。"+ },"readingTextSize": {"small": "閱讀字級:小","standard": "閱讀字級:標準",diff --git a/webui/src/lib/local-preferences.ts b/webui/src/lib/local-preferences.tsindex 60c09ec1a..87b3b844a 100644--- a/webui/src/lib/local-preferences.ts+++ b/webui/src/lib/local-preferences.ts@@ -1,10 +1,13 @@export type LocalActivityMode = "auto" | "expanded";-export type ReadingTextSize = "small" | "standard" | "large";+export type ReadingTextSize = "small" | "standard" | "large" | "custom";+export const MIN_READING_SIZE = 14;+export const MAX_READING_SIZE = 28;export type FileEditDisplayMode = "summary" | "diff" | "collapsed_diff";export interface LocalPreferences {activityMode: LocalActivityMode;readingTextSize: ReadingTextSize;+ customReadingTextSize: number;codeWrap: boolean;brandLogos: boolean;browserNotifications: boolean;@@ -23,6 +26,7 @@ type PersistedLocalPreferences = Partial<LocalPreferences> & {export const DEFAULT_LOCAL_PREFS: LocalPreferences = {activityMode: "auto",readingTextSize: "standard",+ customReadingTextSize: 18,codeWrap: true,brandLogos: true,browserNotifications: false,@@ -41,8 +45,11 @@ export function readLocalPreferences(): LocalPreferences {const parsed = JSON.parse(raw) as PersistedLocalPreferences;return {activityMode: parsed.activityMode === "expanded" ? "expanded" : "auto",- readingTextSize: parsed.readingTextSize === "small" || parsed.readingTextSize === "large"+ readingTextSize: parsed.readingTextSize === "small" || parsed.readingTextSize === "large" || parsed.readingTextSize === "custom"? parsed.readingTextSize : "standard",+ customReadingTextSize: typeof parsed.customReadingTextSize === "number" && Number.isFinite(parsed.customReadingTextSize)+ ? Math.min(MAX_READING_SIZE, Math.max(MIN_READING_SIZE, Math.round(parsed.customReadingTextSize)))+ : DEFAULT_LOCAL_PREFS.customReadingTextSize,codeWrap: parsed.codeWrap !== false,brandLogos: parsed.schemaVersion === LOCAL_PREFS_SCHEMA_VERSION? parsed.brandLogos !== falsediff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsxindex 635962c11..ba287f3c8 100644--- a/webui/src/tests/app-layout.test.tsx+++ b/webui/src/tests/app-layout.test.tsx@@ -224,6 +224,8 @@ vi.mock("@/hooks/useTheme", async () => {React.createElement(React.Fragment, null, children),useTheme: () => ({theme: "light" as const,+ preference: "light" as const,+ setTheme: vi.fn(),toggle: toggleThemeSpy,}),useThemeValue: () => "light" as const,diff --git a/webui/src/tests/local-preferences.test.ts b/webui/src/tests/local-preferences.test.tsindex e59b7a22b..5adc54967 100644--- a/webui/src/tests/local-preferences.test.ts+++ b/webui/src/tests/local-preferences.test.ts@@ -47,6 +47,22 @@ describe("local preferences", () => {});});+ it("round-trips a custom reading size without resetting other preferences", () => {+ const preferences = { ...DEFAULT_LOCAL_PREFS, readingTextSize: "custom" as const,+ customReadingTextSize: 24, notificationSound: true, codeWrap: false };+ writeLocalPreferences(preferences);+ expect(readLocalPreferences()).toEqual(preferences);+ });++ it.each([[40, 28], [8, 14], [19.6, 20], ["22", 18], [null, 18]])(+ "normalizes persisted custom size %j to %s", (stored, expected) => {+ localStorage.setItem(LOCAL_PREFS_STORAGE_KEY, JSON.stringify({+ schemaVersion: 1, readingTextSize: "custom", customReadingTextSize: stored, codeWrap: false,+ }));+ expect(readLocalPreferences()).toMatchObject({ readingTextSize: "custom", customReadingTextSize: expected, codeWrap: false });+ },+ );+it("keeps browser notifications opt-in", () => {expect(DEFAULT_LOCAL_PREFS.browserNotifications).toBe(false);expect(readLocalPreferences().browserNotifications).toBe(false);diff --git a/webui/src/tests/settings-capabilities.test.tsx b/webui/src/tests/settings-capabilities.test.tsxindex ceb71cac7..e869e5bf1 100644--- a/webui/src/tests/settings-capabilities.test.tsx+++ b/webui/src/tests/settings-capabilities.test.tsx@@ -531,9 +531,9 @@ describe("Settings capabilities", () => {return <ClientProvider client={{ requestMutation: requestMutationMock, status: "open",onStatus: (handler: (status: "open") => void) => { handler("open"); return () => {}; },} as never} token="tok">- <SettingsView theme="light" initialSection="voice" initialSettings={snapshot}+ <SettingsView themePreference="light" initialSection="voice" initialSettings={snapshot}onSettingsChange={setSnapshot} onNativeEngineRestart={restart}- onToggleTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} />+ onChangeTheme={() => {}} onBackToChat={() => {}} onModelNameChange={() => {}} /></ClientProvider>;}render(<Parent />);diff --git a/webui/src/tests/settings-overview.test.tsx b/webui/src/tests/settings-overview.test.tsxindex 6fb44a1b1..9d18d66a8 100644--- a/webui/src/tests/settings-overview.test.tsx+++ b/webui/src/tests/settings-overview.test.tsx@@ -182,6 +182,47 @@ describe("Settings overview and appearance", () => {expect(screen.getByRole("radio", { name: "Large reading text" })).toBeChecked();});+ it("edits and remembers a custom reading size without committing an empty input", async () => {+ writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true, codeWrap: false });+ renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload() });+ fireEvent.focus(screen.getByRole("spinbutton", { name: "Custom text size" }));+ const input = screen.getByRole("spinbutton", { name: "Custom text size" });+ fireEvent.change(input, { target: { value: "" } });+ expect(readLocalPreferences().customReadingTextSize).toBe(18);+ fireEvent.change(input, { target: { value: "24" } });+ await waitFor(() => expect(readLocalPreferences()).toMatchObject({+ readingTextSize: "custom", customReadingTextSize: 24, notificationSound: true, codeWrap: false,+ }));+ fireEvent.click(screen.getByRole("radio", { name: "Standard reading text" }));+ fireEvent.focus(screen.getByRole("spinbutton", { name: "Custom text size" }));+ expect(screen.getByRole("spinbutton", { name: "Custom text size" })).toHaveValue(24);+ const currentInput = screen.getByRole("spinbutton", { name: "Custom text size" });+ fireEvent.change(currentInput, { target: { value: "21" } });+ expect(readLocalPreferences().customReadingTextSize).toBe(21);+ fireEvent.change(currentInput, { target: { value: "40" } });+ fireEvent.blur(currentInput);+ expect(currentInput).toHaveValue(40);+ expect(currentInput).toHaveAttribute("aria-invalid", "true");+ expect(readLocalPreferences().customReadingTextSize).toBe(21);+ expect(await screen.findByRole("tooltip")).toHaveTextContent("Your text remains at 21 px.");+ fireEvent.change(currentInput, { target: { value: "22" } });+ expect(currentInput).not.toHaveAttribute("aria-invalid", "true");+ expect(readLocalPreferences().customReadingTextSize).toBe(22);+ });++ it.each(["", "40"])("restores the saved custom size after another tab interrupts draft %j", async (draft) => {+ writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, readingTextSize: "custom", customReadingTextSize: 24 });+ renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload() });+ fireEvent.change(screen.getByRole("spinbutton", { name: "Custom text size" }), { target: { value: draft } });+ act(() => {+ localStorage.setItem(LOCAL_PREFS_STORAGE_KEY, JSON.stringify({ ...readLocalPreferences(), schemaVersion: 1, readingTextSize: "small" }));+ window.dispatchEvent(new StorageEvent("storage", { key: LOCAL_PREFS_STORAGE_KEY }));+ });+ await waitFor(() => expect(screen.getByRole("radio", { name: "Small reading text" })).toBeChecked());+ fireEvent.focus(screen.getByRole("spinbutton", { name: "Custom text size" }));+ expect(screen.getByRole("spinbutton", { name: "Custom text size" })).toHaveValue(24);+ });+it("persists the file edit display local preference", async () => {renderSettingsView({initialSection: "appearance",diff --git a/webui/src/tests/settings-test-utils.tsx b/webui/src/tests/settings-test-utils.tsxindex 9400c042d..dfd093b18 100644--- a/webui/src/tests/settings-test-utils.tsx+++ b/webui/src/tests/settings-test-utils.tsx@@ -129,6 +129,8 @@ type SettingsViewTestOptions = Partial<Pick<React.ComponentProps<typeof SettingsView>,| "initialSection"| "initialSettings"+ | "themePreference"+ | "onChangeTheme"| "skills"| "skillsLoading"| "showSidebar"@@ -151,14 +153,14 @@ export function renderSettingsView(options: SettingsViewTestOptions = {}) {},} as never} token="tok"><SettingsView- theme="light"+ themePreference={options.themePreference ?? "light"}initialSection={options.initialSection ?? "apps"}initialSettings={options.initialSettings}skills={options.skills}skillsLoading={options.skillsLoading}showSidebar={options.showSidebar}mainNavigationExpanded={options.mainNavigationExpanded}- onToggleTheme={() => {}}+ onChangeTheme={options.onChangeTheme ?? (() => {})}onBackToChat={options.onBackToChat ?? (() => {})}onModelNameChange={() => {}}onSettingsChange={options.onSettingsChange}diff --git a/webui/src/tests/useTheme.test.tsx b/webui/src/tests/useTheme.test.tsxindex 76010340a..325d3b0d8 100644--- a/webui/src/tests/useTheme.test.tsx+++ b/webui/src/tests/useTheme.test.tsx@@ -1,11 +1,32 @@-import { act, renderHook } from "@testing-library/react";+import { act, cleanup, renderHook } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useTheme } from "@/hooks/useTheme";describe("useTheme", () => {+ let systemDark = false;+ let mediaEvents: EventTarget;++ function changeSystemTheme(dark: boolean) {+ act(() => {+ systemDark = dark;+ mediaEvents.dispatchEvent(new Event("change"));+ });+ }++ function notifyStorageChange(key: string | null = "nanobot-webui.theme") {+ act(() => window.dispatchEvent(new StorageEvent("storage", { key })));+ }+beforeEach(() => {vi.useFakeTimers();+ systemDark = false;+ mediaEvents = new EventTarget();+ vi.stubGlobal("matchMedia", vi.fn(() => ({+ get matches() { return systemDark; },+ addEventListener: mediaEvents.addEventListener.bind(mediaEvents),+ removeEventListener: mediaEvents.removeEventListener.bind(mediaEvents),+ })));localStorage.removeItem("nanobot-webui.theme");document.documentElement.classList.remove("dark");@@ -18,8 +39,11 @@ describe("useTheme", () => {});afterEach(() => {+ cleanup();vi.clearAllTimers();vi.useRealTimers();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();delete document.documentElement.dataset.themeTransition;document.querySelector('meta[name="theme-color"]')?.remove();document.documentElement.classList.remove("dark");@@ -39,6 +63,152 @@ describe("useTheme", () => {expect(document.documentElement).not.toHaveClass("dark");expect(themeColor?.content).toBe("#ffffff");expect(localStorage.getItem("nanobot-webui.theme")).toBe("light");+ expect(result.current.preference).toBe("light");+ });++ it.each(["light", "dark"] as const)("preserves a previously saved %s choice", (saved) => {+ systemDark = saved === "light";+ localStorage.setItem("nanobot-webui.theme", saved);+ const { result } = renderHook(useTheme);++ expect(result.current.preference).toBe(saved);+ expect(result.current.theme).toBe(saved);+ expect(localStorage.getItem("nanobot-webui.theme")).toBe(saved);+ });++ it("defaults to system and follows live changes without persisting the resolved theme", () => {+ const { result } = renderHook(useTheme);+ const themeColor = document.querySelector<HTMLMetaElement>('meta[name="theme-color"]');+ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("light");++ changeSystemTheme(true);+ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("dark");+ expect(document.documentElement).toHaveClass("dark");+ expect(themeColor?.content).toBe("#303030");++ changeSystemTheme(false);+ expect(result.current.theme).toBe("light");+ expect(document.documentElement).not.toHaveClass("dark");+ expect(themeColor?.content).toBe("#ffffff");+ expect(localStorage.getItem("nanobot-webui.theme")).toBeNull();+ });++ it("restores system preference against the current system theme", () => {+ localStorage.setItem("nanobot-webui.theme", "system");+ systemDark = true;+ const { result } = renderHook(useTheme);++ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("dark");+ changeSystemTheme(false);+ expect(result.current.theme).toBe("light");+ expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");+ });++ it("ignores system changes in explicit mode and resumes the latest system theme", () => {+ const { result } = renderHook(useTheme);+ act(() => result.current.setTheme("light"));+ changeSystemTheme(true);++ expect(result.current.preference).toBe("light");+ expect(result.current.theme).toBe("light");+ expect(document.documentElement).not.toHaveClass("dark");++ act(() => result.current.setTheme("system"));+ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("dark");+ expect(document.documentElement).toHaveClass("dark");+ expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");+ });++ it.each([false, true])("toggles the resolved system theme into an explicit choice: dark=%s", (dark) => {+ systemDark = dark;+ const { result } = renderHook(useTheme);+ const selected = dark ? "light" : "dark";++ act(() => result.current.toggle());+ expect(result.current.preference).toBe(selected);+ expect(result.current.theme).toBe(selected);+ expect(localStorage.getItem("nanobot-webui.theme")).toBe(selected);++ changeSystemTheme(!dark);+ changeSystemTheme(dark);+ expect(result.current.theme).toBe(selected);++ act(() => vi.advanceTimersByTime(600));+ act(() => result.current.toggle());+ expect(result.current.preference).toBe(dark ? "dark" : "light");+ expect(result.current.theme).toBe(dark ? "dark" : "light");+ });++ it("synchronizes other tabs and storage removal without writing back", () => {+ const { result } = renderHook(useTheme);+ const write = vi.spyOn(Storage.prototype, "setItem");+ localStorage.setItem("nanobot-webui.theme", "dark");+ write.mockClear();++ notifyStorageChange("nanobot.locale");+ expect(result.current.preference).toBe("system");+ notifyStorageChange();+ expect(result.current.preference).toBe("dark");+ expect(result.current.theme).toBe("dark");+ expect(document.documentElement).toHaveClass("dark");+ expect(write).not.toHaveBeenCalled();++ localStorage.removeItem("nanobot-webui.theme");+ notifyStorageChange();+ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("light");++ localStorage.setItem("nanobot-webui.theme", "dark");+ notifyStorageChange();+ localStorage.clear();+ write.mockClear();+ notifyStorageChange(null);+ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("light");+ expect(write).not.toHaveBeenCalled();+ });++ it("uses system for unrecognized stored preferences", () => {+ systemDark = true;+ localStorage.setItem("nanobot-webui.theme", "invalid");+ const { result } = renderHook(useTheme);++ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("dark");+ });++ it("keeps theme controls usable when browser storage is unavailable", () => {+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => { throw new Error("Storage blocked"); });+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => { throw new Error("Storage blocked"); });+ const { result } = renderHook(useTheme);++ expect(result.current.preference).toBe("system");+ act(() => result.current.setTheme("dark"));+ expect(result.current.preference).toBe("dark");+ expect(result.current.theme).toBe("dark");+ expect(document.documentElement).toHaveClass("dark");+ });++ it("can select system during a same-palette transition and still follows OS changes", () => {+ systemDark = true;+ localStorage.setItem("nanobot-webui.theme", "light");+ const { result } = renderHook(useTheme);+ act(() => result.current.setTheme("dark"));+ expect(document.documentElement).toHaveAttribute("data-theme-transition", "dark");+ act(() => result.current.setTheme("system"));+ expect(result.current.preference).toBe("system");+ expect(result.current.theme).toBe("dark");+ expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");+ changeSystemTheme(false);+ expect(result.current.theme).toBe("light");+ expect(localStorage.getItem("nanobot-webui.theme")).toBe("system");+ act(() => vi.advanceTimersByTime(600));+ expect(document.documentElement).not.toHaveAttribute("data-theme-transition");+ expect(result.current.theme).toBe("light");});it("ignores rapid reversals for 600ms without replaying them later", () => {