Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf(frontend): slim eager boot payload and optimize polling timers (batches 7-8)
milind-soni2f8dffd9ba72
diff --git a/packages/phone-protocol/src/app-settings-ids.ts b/packages/phone-protocol/src/app-settings-ids.tsnew file mode 100644index 0000000000..ab770263fc--- /dev/null+++ b/packages/phone-protocol/src/app-settings-ids.ts@@ -0,0 +1,55 @@+// Pure identifiers and wire types for app_settings without zod schemas, so light boot entries can read SKIN_IDS / FONT_IDS+// without bundling zod.++export type SettingTier = "safe" | "secret" | "owner-only";++/** On a card: display values only, never a key. */+export interface AppSettingRequest {+ settingId: string;+ label: string;+ before?: string;+ after: string;+ tier: SettingTier;+}+export interface AppSettingCardField {+ /** A bot's change to one of the app's own settings, applied with Undo. */+ appSettingRequest?: AppSettingRequest;+}++/** Settings a bot can ask the app to show in chat as the real control. Adding one here, in the server's SETTINGS_CARDS+ * and in the window's card list is the whole registration. */+export const SETTINGS_CARD_IDS = ["other-computers", "ai-sign-in"] as const;+export type SettingsCardId = (typeof SETTINGS_CARD_IDS)[number];+export const isSettingsCardId = (id: unknown): id is SettingsCardId =>+ typeof id === "string" && (SETTINGS_CARD_IDS as readonly string[]).includes(id);++/** Security invariant: a settings card row names the setting only. What the control shows (a code, a link, an address)+ * is read by the window from the app itself and is never stored on the row or sent to a bot. */+export interface SettingsCardData {+ id: SettingsCardId;+}++export const SKIN_IDS = [+ "midnight",+ "atelier",+ "foundry",+ "lagoon",+ "graphite",+ "linen",+ "dusk",+ "daylight",+ "meadow",+ "pop",+ "halloween",+ "diwali",+ "aurora",+] as const;+export const FONT_IDS = ["skin", "system", "inter", "poppins", "serif"] as const;+export const CHAT_WIDTH_IDS = ["standard", "wide", "full"] as const;+/** The Enter-adds-a-line modes are for input methods that confirm a conversion with Enter (Japanese). */+export const SEND_KEYS = ["enter", "shift-enter", "mod-enter"] as const;+export const PLACE_SWATCHES = ["blue", "green", "amber", "rose", "violet", "slate"] as const;+export const TALK_KEYS = ["ctrl-opt-space", "ctrl-shift-space", "opt-shift-space"] as const;+/** The composer's end buttons, by name, in the order Advanced mode may draw them; today's order is the default. */+export const COMPOSER_BUTTONS = ["stop", "context", "mic", "call", "send"] as const;+export const USAGE_INDICATORS = ["bars", "ring"] as const;diff --git a/packages/phone-protocol/src/app-settings.ts b/packages/phone-protocol/src/app-settings.tsindex 16f27b2f54..e10c542727 100644--- a/packages/phone-protocol/src/app-settings.ts+++ b/packages/phone-protocol/src/app-settings.ts@@ -1,57 +1,35 @@// The app_settings tool's wire shapes: a setting's tier (the whole policy), the applied card a change rides on, and the// preferences that live in the window's localStorage, which the server reaches through an SSE frame.import { z } from "zod";+import {+ CHAT_WIDTH_IDS,+ COMPOSER_BUTTONS,+ FONT_IDS,+ PLACE_SWATCHES,+ SEND_KEYS,+ SKIN_IDS,+ TALK_KEYS,+ USAGE_INDICATORS,+} from "./app-settings-ids.ts";-export type SettingTier = "safe" | "secret" | "owner-only";+export {+ CHAT_WIDTH_IDS,+ COMPOSER_BUTTONS,+ FONT_IDS,+ isSettingsCardId,+ PLACE_SWATCHES,+ SEND_KEYS,+ SETTINGS_CARD_IDS,+ SKIN_IDS,+ TALK_KEYS,+ USAGE_INDICATORS,+ type AppSettingCardField,+ type AppSettingRequest,+ type SettingsCardData,+ type SettingsCardId,+ type SettingTier,+} from "./app-settings-ids.ts";-/** On a card: display values only, never a key. */-export interface AppSettingRequest {- settingId: string;- label: string;- before?: string;- after: string;- tier: SettingTier;-}-export interface AppSettingCardField {- /** A bot's change to one of the app's own settings, applied with Undo. */- appSettingRequest?: AppSettingRequest;-}--/** Settings a bot can ask the app to show in chat as the real control. Adding one here, in the server's SETTINGS_CARDS- * and in the window's card list is the whole registration. */-export const SETTINGS_CARD_IDS = ["other-computers", "ai-sign-in"] as const;-export type SettingsCardId = (typeof SETTINGS_CARD_IDS)[number];-export const isSettingsCardId = (id: unknown): id is SettingsCardId => typeof id === "string" && (SETTINGS_CARD_IDS as readonly string[]).includes(id);-/** Security invariant: a settings card row names the setting only. What the control shows (a code, a link, an address)- * is read by the window from the app itself and is never stored on the row or sent to a bot. */-export interface SettingsCardData {- id: SettingsCardId;-}--export const SKIN_IDS = [- "midnight",- "atelier",- "foundry",- "lagoon",- "graphite",- "linen",- "dusk",- "daylight",- "meadow",- "pop",- "halloween",- "diwali",- "aurora",-] as const;-export const FONT_IDS = ["skin", "system", "inter", "poppins", "serif"] as const;-export const CHAT_WIDTH_IDS = ["standard", "wide", "full"] as const;-/** The Enter-adds-a-line modes are for input methods that confirm a conversion with Enter (Japanese). */-export const SEND_KEYS = ["enter", "shift-enter", "mod-enter"] as const;-export const PLACE_SWATCHES = ["blue", "green", "amber", "rose", "violet", "slate"] as const;-export const TALK_KEYS = ["ctrl-opt-space", "ctrl-shift-space", "opt-shift-space"] as const;-/** The composer's end buttons, by name, in the order Advanced mode may draw them; today's order is the default. */-export const COMPOSER_BUTTONS = ["stop", "context", "mic", "call", "send"] as const;-export const USAGE_INDICATORS = ["bars", "ring"] as const;const pinnedPage = z.object({ name: z.string().trim().min(1).max(40), url: z.string().trim().max(2048).regex(/^https?:\/\/\S+$/, "an http(s) address") }).strict();/** Preferences kept in the window or behind the desktop app's own bridge, by setting id; the renderer applies a frame withdiff --git a/shared/app-settings-ids.ts b/shared/app-settings-ids.tsnew file mode 100644index 0000000000..9f920e549e--- /dev/null+++ b/shared/app-settings-ids.ts@@ -0,0 +1 @@+export * from "../packages/phone-protocol/src/app-settings-ids.ts";diff --git a/shared/theme-tokens.ts b/shared/theme-tokens.tsnew file mode 100644index 0000000000..5f18475ede--- /dev/null+++ b/shared/theme-tokens.ts@@ -0,0 +1,262 @@+// Zero-dependency theme tokens, types, URL safety checks, and lightweight ThemeFile validator for browser boot entries+// (main.tsx / rail.tsx) so booting the theme runtime does not pull zod into the initial bundle.+import { SKIN_IDS } from "./app-settings-ids.ts";++/** Where a theme's files are served, same origin, behind the server's sign-in: `<prefix><themeId>/<file>`. */+export const THEME_ASSET_PREFIX = "/api/theme-assets/";+/** Opening the app with this in its address starts it without the custom theme. */+export const SAFE_LOOK_PARAM = "safe-look";++export const THEME_LIMITS = {+ cssChars: 100_000,+ assetBytes: 10 * 1024 * 1024,+ themeBytes: 40 * 1024 * 1024,+ assetsPerTheme: 40,+ themesPerPerson: 50,+} as const;++export const THEME_ID = /^[a-z0-9][a-z0-9-]{0,47}$/;+export const THEME_ASSET_NAME = /^[a-z0-9][a-z0-9_-]{0,79}\.(png|jpe?g|webp|gif|avif|svg|woff2?|ttf|otf)$/;+const ASSET_URL = /^\/api\/theme-assets\/[a-z0-9][a-z0-9-]{0,47}\/[a-z0-9][a-z0-9_-]{0,79}\.[a-z0-9]{2,5}$/;++export const THEME_ASSET_TYPES: Readonly<Record<string, string>> = {+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", avif: "image/avif",+ svg: "image/svg+xml", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf",+};++/** The app's colour tokens a theme may set, as `--color-<role>`. */+export const THEME_COLOR_ROLES = [+ "app", "panel", "frame", "raised", "raised-hover", "card", "inset", "control", "composer", "composer-ring",+ "menu", "menu-hover", "menu-active", "hairline", "edge", "scrollbar",+ "ink", "ink-secondary", "ink-tertiary", "accent", "accent-border", "accent-text", "accent-ink", "focus",+ "bubble-user", "bubble-user-ink", "success", "success-ink", "danger", "danger-ink", "warning",+] as const;+export type ThemeColorRole = (typeof THEME_COLOR_ROLES)[number];++export const THEME_ROLE_HELP: Readonly<Record<ThemeColorRole, string>> = {+ app: "the window's ground behind the chat", panel: "the sidebar", frame: "the top bar and the rail around the app",+ raised: "content surfaces", "raised-hover": "a hovered row or button", card: "cards and the bot's bubble", inset: "sunken fields",+ control: "a control on a card", composer: "the message box", "composer-ring": "the message box's outline", menu: "menus and popovers",+ "menu-hover": "a hovered menu row", "menu-active": "a chosen menu row", hairline: "borders", edge: "the line where two panes meet",+ scrollbar: "scrollbar thumbs", ink: "main text", "ink-secondary": "quieter text", "ink-tertiary": "the quietest text: hints and times",+ accent: "buttons and highlights", "accent-border": "the accent's edge", "accent-text": "links and accent text", "accent-ink": "text on the accent",+ focus: "the keyboard focus ring", "bubble-user": "your own messages", "bubble-user-ink": "text in your own messages",+ success: "done and OK", "success-ink": "text on success", danger: "errors and delete", "danger-ink": "text on danger", warning: "warnings",+};++export interface ThemeVariant {+ canvas?: string;+ accent?: string;+ colors?: Partial<Record<ThemeColorRole, string>>;+}++export interface ThemeFile {+ name: string;+ skin?: (typeof SKIN_IDS)[number] | "system";+ canvas?: string;+ accent?: string;+ colors?: Partial<Record<ThemeColorRole, string>>;+ light?: ThemeVariant;+ dark?: ThemeVariant;+ font?: string;+ css?: string;+}++export interface ThemeSummary {+ id: string;+ name: string;+ hasCss: boolean;+ assets: string[];+}+/** GET /api/themes: this person's saved themes and the one their windows wear. */+export interface ThemeList {+ active: string | null;+ themes: ThemeSummary[];+}+/** GET /api/themes/active. */+export interface ActiveTheme {+ id: string | null;+ theme: ThemeFile | null;+}+/** How many of a person's look changes are kept to go back to. */+export const LOOK_HISTORY_LIMIT = 30;+/** What one look change did: a theme made, edited or deleted while worn, a theme or built-in skin worn, back to the+ * default look, or earlier changes gone back on. */+export const LOOK_CHANGE_KINDS = ["made", "edited", "deleted", "wore", "skin", "default", "undid"] as const;+export interface LookChange {+ kind: (typeof LOOK_CHANGE_KINDS)[number];+ /** The theme's name, or the built-in skin's id. */+ name?: string;+ /** undid: how many changes it went back on. */+ count?: number;+}+/** GET /api/themes/history, newest first; POST it `{ index }` to go back to how things looked right after that change. */+export interface ThemeHistoryItem extends LookChange {+ index: number;+ at: string;+}+export const THEME_EXPORT_VERSION = 1;++export const themeAssetUrl = (themeId: string, name: string) => `${THEME_ASSET_PREFIX}${themeId}/${name}`;+export const themeAssetType = (name: string): string | undefined => THEME_ASSET_TYPES[name.slice(name.lastIndexOf(".") + 1).toLowerCase()];++/** A url() target a theme may load: an inline data: address, a fragment, or one of the theme files on this server. */+export function themeUrlAllowed(target: string): boolean {+ return /^data:/i.test(target) || target.startsWith("#") || (ASSET_URL.test(target) && !target.includes(".."));+}++/** Every url() argument in `text`, or null when one cannot be read cleanly. */+export function urlTargets(text: string): string[] | null {+ const lower = text.toLowerCase();+ const found: string[] = [];+ for (let at = lower.indexOf("url("); at !== -1; at = lower.indexOf("url(", at + 4)) {+ let index = at + 4;+ while (/\s/.test(text[index] ?? "")) index++;+ const quote = text[index];+ let target: string;+ if (quote === '"' || quote === "'") {+ const close = text.indexOf(quote, index + 1);+ if (close === -1) return null;+ target = text.slice(index + 1, close);+ index = close + 1;+ while (/\s/.test(text[index] ?? "")) index++;+ if (text[index] !== ")") return null;+ } else {+ const close = text.indexOf(")", index);+ if (close === -1) return null;+ target = text.slice(index, close).trim();+ if (/[\s"'(]/.test(target)) return null;+ }+ found.push(target.trim());+ }+ return found;+}++export const LOADS_BY_NAME = /image-set\(|\bimage\(|\bsrc\(/i;++/**+ * Security: whether one parsed declaration value could load a file from anywhere but this server's theme files. The+ * window drops such declarations. A value that still holds a backslash is refused whole: an escape can spell `url` or+ * `var` where a check of the text would not see it.+ */+export function themeValueLoads(value: string): boolean {+ if (value.includes("\\") || LOADS_BY_NAME.test(value)) return true;+ const targets = urlTargets(value);+ return targets === null || targets.some((target) => !themeUrlAllowed(target));+}++const HEX_RE = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;+const COLOR_RE = /^[#a-z0-9(),.%\s/+-]+$/i;+const COLOR_LOAD_RE = /url|image|src|attr/i;+const FONT_RE = /^[\w\s"',.-]*$/;+const ROLE_SET = new Set<string>(THEME_COLOR_ROLES);+const SKIN_SET = new Set<string>([...SKIN_IDS, "system"]);+const THEME_KEYS = new Set(["name", "skin", "canvas", "accent", "colors", "light", "dark", "font", "css"]);+const VARIANT_KEYS = new Set(["canvas", "accent", "colors"]);++function isPlainRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function parseHex(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ return HEX_RE.test(trimmed) ? trimmed : null;+}++function parseColor(value: unknown): string | null {+ if (typeof value !== "string") return null;+ const trimmed = value.trim();+ if (trimmed.length < 1 || trimmed.length > 120) return null;+ if (!COLOR_RE.test(trimmed) || COLOR_LOAD_RE.test(trimmed)) return null;+ return trimmed;+}++function parseColors(value: unknown): Partial<Record<ThemeColorRole, string>> | null {+ if (!isPlainRecord(value)) return null;+ const out: Partial<Record<ThemeColorRole, string>> = {};+ for (const [key, raw] of Object.entries(value)) {+ if (!ROLE_SET.has(key)) return null;+ if (raw === undefined) continue;+ const parsed = parseColor(raw);+ if (parsed === null) return null;+ out[key as ThemeColorRole] = parsed;+ }+ return out;+}++function parseVariant(value: unknown): ThemeVariant | null {+ if (!isPlainRecord(value)) return null;+ for (const key of Object.keys(value)) {+ if (!VARIANT_KEYS.has(key)) return null;+ }+ const out: ThemeVariant = {};+ if (value.canvas !== undefined) {+ const canvas = parseHex(value.canvas);+ if (canvas === null) return null;+ out.canvas = canvas;+ }+ if (value.accent !== undefined) {+ const accent = parseHex(value.accent);+ if (accent === null) return null;+ out.accent = accent;+ }+ if (value.colors !== undefined) {+ const colors = parseColors(value.colors);+ if (colors === null) return null;+ out.colors = colors;+ }+ return out;+}++/** Zero-dependency strict validator matching `themeFileSchema` in `shared/theme.ts`. */+export function parseThemeFile(value: unknown): ThemeFile | null {+ if (!isPlainRecord(value)) return null;+ for (const key of Object.keys(value)) {+ if (!THEME_KEYS.has(key)) return null;+ }+ if (typeof value.name !== "string") return null;+ const name = value.name.trim();+ if (name.length < 1 || name.length > 60) return null;+ const out: ThemeFile = { name };+ if (value.skin !== undefined) {+ if (typeof value.skin !== "string" || !SKIN_SET.has(value.skin)) return null;+ out.skin = value.skin as ThemeFile["skin"];+ }+ if (value.canvas !== undefined) {+ const canvas = parseHex(value.canvas);+ if (canvas === null) return null;+ out.canvas = canvas;+ }+ if (value.accent !== undefined) {+ const accent = parseHex(value.accent);+ if (accent === null) return null;+ out.accent = accent;+ }+ if (value.colors !== undefined) {+ const colors = parseColors(value.colors);+ if (colors === null) return null;+ out.colors = colors;+ }+ if (value.light !== undefined) {+ const light = parseVariant(value.light);+ if (light === null) return null;+ out.light = light;+ }+ if (value.dark !== undefined) {+ const dark = parseVariant(value.dark);+ if (dark === null) return null;+ out.dark = dark;+ }+ if (value.font !== undefined) {+ if (typeof value.font !== "string") return null;+ const font = value.font.trim();+ if (font.length > 300 || !FONT_RE.test(font)) return null;+ out.font = font;+ }+ if (value.css !== undefined) {+ if (typeof value.css !== "string" || value.css.length > THEME_LIMITS.cssChars) return null;+ out.css = value.css;+ }+ return out;+}diff --git a/shared/theme.test.ts b/shared/theme.test.tsindex cd4dd6719f..4112f0a31d 100644--- a/shared/theme.test.ts+++ b/shared/theme.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { rehomeThemeCss, SAFE_LOOK_PARAM, themeCssProblem, themeFileSchema, themeGuide, THEME_HOOKS, themeValueLoads } from "./theme.ts";+import { parseThemeFile, rehomeThemeCss, SAFE_LOOK_PARAM, themeCssProblem, themeFileSchema, themeGuide, THEME_HOOKS, themeValueLoads } from "./theme.ts";describe("themeValueLoads", () => {it.each([@@ -78,3 +78,33 @@ it("tells a bot every hook, the rule against loading and both ways back", () =>expect(guide).toContain(`?${SAFE_LOOK_PARAM}`);expect(guide).toMatch(/cannot see the result/);});++it("parseThemeFile matches themeFileSchema across valid and invalid inputs", () => {+ const valid = [+ { name: " Minimal " },+ { name: "Dual", skin: "system", canvas: "#112233", accent: "#abc", colors: { app: "#101010", accent: "color-mix(in srgb, #fff 20%, #000)" }, light: { canvas: "#fafafa", colors: { ink: "#111" } }, dark: { accent: "#ff00aa" }, font: "\"Inter Variable\", serif", css: "[data-look=\"app\"] { color: red; }" },+ ];+ for (const input of valid) {+ const zod = themeFileSchema.safeParse(input);+ expect(zod.success).toBe(true);+ expect(parseThemeFile(input)).toEqual(zod.success ? zod.data : null);+ }+ const invalid: unknown[] = [+ null,+ {},+ { name: " " },+ { name: "X", extra: true },+ { name: "X", skin: "unknown-skin" },+ { name: "X", canvas: "red" },+ { name: "X", colors: { app: "url(https://example.com/a.png)" } },+ { name: "X", colors: { app: "image-set(a 1x)" } },+ { name: "X", colors: { bogus: "#111" } },+ { name: "X", light: { extra: "#111" } },+ { name: "X", font: "Inter; url(x)" },+ { name: "X", css: "a".repeat(100_001) },+ ];+ for (const input of invalid) {+ expect(themeFileSchema.safeParse(input).success).toBe(false);+ expect(parseThemeFile(input)).toBeNull();+ }+});diff --git a/shared/theme.ts b/shared/theme.tsindex ea99e18b59..e7838618c7 100644--- a/shared/theme.ts+++ b/shared/theme.ts@@ -3,49 +3,48 @@// edits, imports and exports them.import { z } from "zod";-import { SKIN_IDS } from "./app-settings.ts";--/** Where a theme's files are served, same origin, behind the server's sign-in: `<prefix><themeId>/<file>`. */-export const THEME_ASSET_PREFIX = "/api/theme-assets/";-/** Opening the app with this in its address starts it without the custom theme. */-export const SAFE_LOOK_PARAM = "safe-look";--export const THEME_LIMITS = {- cssChars: 100_000,- assetBytes: 10 * 1024 * 1024,- themeBytes: 40 * 1024 * 1024,- assetsPerTheme: 40,- themesPerPerson: 50,-} as const;--export const THEME_ID = /^[a-z0-9][a-z0-9-]{0,47}$/;-export const THEME_ASSET_NAME = /^[a-z0-9][a-z0-9_-]{0,79}\.(png|jpe?g|webp|gif|avif|svg|woff2?|ttf|otf)$/;-const ASSET_URL = /^\/api\/theme-assets\/[a-z0-9][a-z0-9-]{0,47}\/[a-z0-9][a-z0-9_-]{0,79}\.[a-z0-9]{2,5}$/;--export const THEME_ASSET_TYPES: Readonly<Record<string, string>> = {- png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", webp: "image/webp", gif: "image/gif", avif: "image/avif",- svg: "image/svg+xml", woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf",-};--/** The app's colour tokens a theme may set, as `--color-<role>`. */-export const THEME_COLOR_ROLES = [- "app", "panel", "frame", "raised", "raised-hover", "card", "inset", "control", "composer", "composer-ring",- "menu", "menu-hover", "menu-active", "hairline", "edge", "scrollbar",- "ink", "ink-secondary", "ink-tertiary", "accent", "accent-border", "accent-text", "accent-ink", "focus",- "bubble-user", "bubble-user-ink", "success", "success-ink", "danger", "danger-ink", "warning",-] as const;-export type ThemeColorRole = (typeof THEME_COLOR_ROLES)[number];--export const THEME_ROLE_HELP: Readonly<Record<ThemeColorRole, string>> = {- app: "the window's ground behind the chat", panel: "the sidebar", frame: "the top bar and the rail around the app",- raised: "content surfaces", "raised-hover": "a hovered row or button", card: "cards and the bot's bubble", inset: "sunken fields",- control: "a control on a card", composer: "the message box", "composer-ring": "the message box's outline", menu: "menus and popovers",- "menu-hover": "a hovered menu row", "menu-active": "a chosen menu row", hairline: "borders", edge: "the line where two panes meet",- scrollbar: "scrollbar thumbs", ink: "main text", "ink-secondary": "quieter text", "ink-tertiary": "the quietest text: hints and times",- accent: "buttons and highlights", "accent-border": "the accent's edge", "accent-text": "links and accent text", "accent-ink": "text on the accent",- focus: "the keyboard focus ring", "bubble-user": "your own messages", "bubble-user-ink": "text in your own messages",- success: "done and OK", "success-ink": "text on success", danger: "errors and delete", "danger-ink": "text on danger", warning: "warnings",-};+import { SKIN_IDS } from "./app-settings-ids.ts";+import {+ LOADS_BY_NAME,+ LOOK_HISTORY_LIMIT,+ SAFE_LOOK_PARAM,+ THEME_ASSET_NAME,+ THEME_ASSET_PREFIX,+ THEME_COLOR_ROLES,+ THEME_EXPORT_VERSION,+ THEME_ID,+ THEME_LIMITS,+ THEME_ROLE_HELP,+ themeUrlAllowed,+ urlTargets,+} from "./theme-tokens.ts";++export {+ LOOK_CHANGE_KINDS,+ LOOK_HISTORY_LIMIT,+ parseThemeFile,+ SAFE_LOOK_PARAM,+ THEME_ASSET_NAME,+ THEME_ASSET_PREFIX,+ THEME_ASSET_TYPES,+ THEME_COLOR_ROLES,+ THEME_EXPORT_VERSION,+ THEME_ID,+ THEME_LIMITS,+ THEME_ROLE_HELP,+ themeAssetType,+ themeAssetUrl,+ themeUrlAllowed,+ themeValueLoads,+ type ActiveTheme,+ type LookChange,+ type ThemeColorRole,+ type ThemeFile,+ type ThemeHistoryItem,+ type ThemeList,+ type ThemeSummary,+ type ThemeVariant,+} from "./theme-tokens.ts";const hex = z.string().trim().regex(/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i, "a hex colour such as #1a2b3c");/** Security: a colour lands in a custom property the app's own rules read, so it may never name a file. */@@ -72,42 +71,7 @@ export const themeFileSchema = z.object({font: z.string().trim().max(300).regex(/^[\w\s"',.-]*$/, "a font-family list such as \"Inter Variable\", serif").optional(),css: z.string().max(THEME_LIMITS.cssChars).optional(),}).strict();-export type ThemeFile = z.infer<typeof themeFileSchema>;-export interface ThemeSummary {- id: string;- name: string;- hasCss: boolean;- assets: string[];-}-/** GET /api/themes: this person's saved themes and the one their windows wear. */-export interface ThemeList {- active: string | null;- themes: ThemeSummary[];-}-/** GET /api/themes/active. */-export interface ActiveTheme {- id: string | null;- theme: ThemeFile | null;-}-/** How many of a person's look changes are kept to go back to. */-export const LOOK_HISTORY_LIMIT = 30;-/** What one look change did: a theme made, edited or deleted while worn, a theme or built-in skin worn, back to the- * default look, or earlier changes gone back on. */-export const LOOK_CHANGE_KINDS = ["made", "edited", "deleted", "wore", "skin", "default", "undid"] as const;-export interface LookChange {- kind: (typeof LOOK_CHANGE_KINDS)[number];- /** The theme's name, or the built-in skin's id. */- name?: string;- /** undid: how many changes it went back on. */- count?: number;-}-/** GET /api/themes/history, newest first; POST it `{ index }` to go back to how things looked right after that change. */-export interface ThemeHistoryItem extends LookChange {- index: number;- at: string;-}-export const THEME_EXPORT_VERSION = 1;/** One file: the theme with its files inlined as data: addresses. */export const themeExportSchema = z.object({mausbotTheme: z.literal(THEME_EXPORT_VERSION),@@ -117,54 +81,6 @@ export const themeExportSchema = z.object({}).strict();export type ThemeExport = z.infer<typeof themeExportSchema>;-export const themeAssetUrl = (themeId: string, name: string) => `${THEME_ASSET_PREFIX}${themeId}/${name}`;-export const themeAssetType = (name: string): string | undefined => THEME_ASSET_TYPES[name.slice(name.lastIndexOf(".") + 1).toLowerCase()];--/** A url() target a theme may load: an inline data: address, a fragment, or one of the theme files on this server. */-export function themeUrlAllowed(target: string): boolean {- return /^data:/i.test(target) || target.startsWith("#") || (ASSET_URL.test(target) && !target.includes(".."));-}--/** Every url() argument in `text`, or null when one cannot be read cleanly. */-function urlTargets(text: string): string[] | null {- const lower = text.toLowerCase();- const found: string[] = [];- for (let at = lower.indexOf("url("); at !== -1; at = lower.indexOf("url(", at + 4)) {- let index = at + 4;- while (/\s/.test(text[index] ?? "")) index++;- const quote = text[index];- let target: string;- if (quote === '"' || quote === "'") {- const close = text.indexOf(quote, index + 1);- if (close === -1) return null;- target = text.slice(index + 1, close);- index = close + 1;- while (/\s/.test(text[index] ?? "")) index++;- if (text[index] !== ")") return null;- } else {- const close = text.indexOf(")", index);- if (close === -1) return null;- target = text.slice(index, close).trim();- if (/[\s"'(]/.test(target)) return null;- }- found.push(target.trim());- }- return found;-}--const LOADS_BY_NAME = /image-set\(|\bimage\(|\bsrc\(/i;--/**- * Security: whether one parsed declaration value could load a file from anywhere but this server's theme files. The- * window drops such declarations. A value that still holds a backslash is refused whole: an escape can spell `url` or- * `var` where a check of the text would not see it.- */-export function themeValueLoads(value: string): boolean {- if (value.includes("\\") || LOADS_BY_NAME.test(value)) return true;- const targets = urlTargets(value);- return targets === null || targets.some((target) => !themeUrlAllowed(target));-}-/** The text with comments and quoted strings blanked, so a check of the code ignores what they say. */function codeOnly(css: string): string {let out = "";diff --git a/src/App.tsx b/src/App.tsxindex 8ed314dd80..7cafaa0099 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -6,7 +6,6 @@ import { useShowThreads } from "@/lib/thread-preferences";import { useWelcomeViewer, WelcomeGate } from "@/components/onboarding/WelcomeGate";import { MausBotWelcome } from "@/components/MausBotWelcome";import { NewBotNameHost } from "@/components/NewBotName";-import { MemberApps } from "@/components/MemberApps";import { CloudTimeZoneSync } from "@/components/CloudTimeZone";import { cloudSignInDue, noEnginesDue, spotlightsQuiet, workedEarlier, type WelcomeViewer } from "@/lib/onboarding";import { FirstConversationTour } from "@/components/onboarding/FirstConversationTour";@@ -21,9 +20,6 @@ import { viewerClosedRelease } from "@/components/computer-takeover";import { Sidebar } from "@/components/Sidebar";import { ChatView } from "@/components/ChatView";import { HandoffExchangeHost } from "@/components/HandoffExchange";-import { GroupView } from "@/components/GroupView";-import { ForkPanel } from "@/components/ForkPanel";-import { RoomFeedView } from "@/components/room-feed/RoomFeedView";import { useRoomFeed } from "@/components/room-feed/use-room-feed";import { useFeedThreadFull } from "@/components/room-feed/feed-fit";import { PHONE_LAYOUT, SIDEBAR_AND_BOT_PANEL_FIT, SIDEBAR_AND_NARROW_PANEL_FIT, SIDEBAR_AND_PANEL_FIT, SIDEBAR_INLINE, TWO_SIDE_PANELS_FIT, useMediaQuery } from "@/lib/use-media-query";@@ -33,6 +29,9 @@ import {ActivityPanel, AnnouncementsPage, BotSettingsDialog, CloudAddDialog, ComputerPanel, FilesView, InboxPanel, InspectorPanel, KeyboardShortcutsModal, LocalVmWorkspace,PluginsPanel, preloadScreens, PublishedAppsPage, RemoteAgentSettingsPanel, SkillBurgersPage, RemoteDesktopPanel, RoomPanel, SettingsModal, TeamFilesPage, TeamMapPage, TriggersPage,} from "@/components/lazy-screens";+import {+ CloudEngineSignIn, CloudIntent, CloudWelcome, ForkPanel, GroupView, MemberApps, NoEngines, RoomFeedView, TeamWelcome, WebPanelPage,+} from "@/components/lazy-views";import { useAdvancedMode } from "@/lib/interface-mode";import { closeRoomPanel, useRoomPanelShown } from "@/lib/room-panel";import { closeAppPreview, useAppPreview } from "@/lib/app-preview";@@ -61,13 +60,8 @@ import { DesktopCapabilitiesProvider, useCaptionChrome, useDesktopCapabilities,import { WindowCaptionButtons } from "@/components/WindowCaptionButtons";import { WindowFrameBar } from "@/components/WindowFrameBar";import { cn } from "@/lib/cn";-import { NoEngines } from "@/components/NoEngines";-import { CloudEngineSignIn } from "@/components/CloudEngineSignIn";-import { CloudIntent } from "@/components/CloudIntent";import { cloudIntentDue, cloudIntentShown, useCloudIntent } from "@/lib/cloud-intent";import { CloudSetup } from "@/components/CloudSetup";-import { CloudWelcome } from "@/components/cloud-welcome/CloudWelcome";-import { TeamWelcome } from "@/components/TeamWelcome";import { ConversationShareDialogs } from "@/components/conversation-share/ConversationShareDialogs";import { PublishTemplateHost } from "@/components/publish-template";import { invitedToTeam, teamWelcomeDue, useTeamWelcomeRecord } from "@/lib/team-welcome";@@ -83,7 +77,7 @@ import { useThreadCycleKeys } from "@/components/thread-cycle";import { effectiveLanguage, useLanguageChoice, usePageLanguage } from "@/lib/language-preference";import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";import { phonePairingSettingsAction, takePhonePairingRequest } from "@/lib/phone-pairing"; import { useConnectLink } from "@/lib/use-connect-link";-import { isSettingsPage } from "@/components/settings/settings-index";+import { isSettingsPage } from "@/components/settings/settings-pages";import { useBotListDrawer } from "@/hooks/use-bot-list-drawer";import { usePhoneBack } from "@/hooks/use-phone-back";import { useRememberedSidePanel } from "@/hooks/use-remembered-side-panel";@@ -99,7 +93,6 @@ import { useAiSwitchKeeper } from "@/lib/ai-switch";import { useChiefStepOpen } from "@/lib/default-bot";import { useSessionEnded } from "@/lib/session-ended";import { PairPage } from "./pair/PairPage";-import { WebPanelPage } from "@/components/WebPanelPage";import { AppPreviewPanel } from "@/components/published-apps/AppPreviewPanel";import { FilePreviewPanel } from "@/components/FilePreviewPanel";import { refreshPublishedApps } from "@/lib/own-published-apps";diff --git a/src/components/AccountMenu.tsx b/src/components/AccountMenu.tsxindex d94d1de197..5c2d23ba87 100644--- a/src/components/AccountMenu.tsx+++ b/src/components/AccountMenu.tsx@@ -104,8 +104,20 @@ function AddAccount({ start, onDone, onBack }: { start: string; onDone: (note: sconst [code, setCode] = useState("");const [busy, setBusy] = useState(false);const [browser, setBrowser] = useState(false);- const [now, setNow] = useState(Date.now());- useEffect(() => { const timer = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(timer); }, []);+ const resendAt = phase.step === "code" ? phase.resendAt : 0;+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!resendAt) return;+ const current = Date.now();+ setNow(current);+ if (current >= resendAt) return;+ const timer = setInterval(() => {+ const next = Date.now();+ setNow(next);+ if (next >= resendAt) clearInterval(timer);+ }, 1000);+ return () => clearInterval(timer);+ }, [resendAt]);useEffect(() => () => { void bridge?.addCancel().catch(() => {}); }, [bridge]);const send = () => {if (busy || !bridge) return;diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex 5778826484..8794897f09 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -63,7 +63,7 @@ import { VoiceNoteBubble, type VoiceNoteAttachment } from "./VoiceNoteBubble";import { RawMarkdownView, RawToggleAction } from "./RawMarkdownToggle";import { useTeammates } from "@/state/team-people";import { NewConversationInstead } from "./NewConversationInstead";-import { SkillBurgerSlot } from "./skill-burger/SkillBurgerSlot"; import { useFeature } from "@/lib/use-feature";+import { SkillBurgerSlot } from "./lazy-views"; import { useFeature } from "@/lib/use-feature";import { useColorUserBubbles } from "@/lib/user-bubble-preference";import { userBubbleStyle } from "@/lib/user-bubble-tone";import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { TemplateChatCard } from "./TemplateCard"; import { PublishedSiteCards } from "./published-apps/PublishedSiteCards";diff --git a/src/components/CloudTrialNotice.tsx b/src/components/CloudTrialNotice.tsxindex 63335c1f7d..f4f6bf0680 100644--- a/src/components/CloudTrialNotice.tsx+++ b/src/components/CloudTrialNotice.tsx@@ -18,7 +18,10 @@ export function useCloudPlanSnapshot(bridge: CloudPlanBridge | undefined): Cloudconst stop = () => { active = false; unsubscribe?.(); clearInterval(timer); window.removeEventListener?.("focus", read); window.removeEventListener?.(PLAN_CHANGED, read); };const read = () => { void bridge.state().then(next => { if (active) setPlan(next); }, () => { if (active) setPlan({ status: "none" }); stop(); }); };const unsubscribe = window.ogb?.cloudAccount?.onState(read);- const timer = setInterval(read, CLOUD_PLAN_REFRESH_MS);+ const timer = setInterval(() => {+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;+ read();+ }, CLOUD_PLAN_REFRESH_MS);window.addEventListener?.("focus", read);window.addEventListener?.(PLAN_CHANGED, read);read();diff --git a/src/components/ComputerPanel.tsx b/src/components/ComputerPanel.tsxindex fc7ef0b28a..2ab3337ccd 100644--- a/src/components/ComputerPanel.tsx+++ b/src/components/ComputerPanel.tsx@@ -1,3 +1,4 @@+import { createAdaptiveScheduler } from "@/lib/adaptive-poll";import { boatCapableEngine, cloudEngineOf } from "@/lib/remote-desktop";import { canWorkOnCloud } from "../../shared/cloud-computer";import { viewerTargetId } from "../../shared/desktop-viewer";@@ -604,8 +605,9 @@ export function ComputerPanel({threadPath,]);+ const pageVisible = usePageVisible();useEffect(() => {- if (phase !== "busy-boat") return;+ if (phase !== "busy-boat" || !pageVisible) return;let alive = true;const check = () => {if (!profileBot.busy && livePlace === "cloud") {@@ -622,11 +624,8 @@ export function ComputerPanel({.catch(() => {});};const timer = window.setInterval(check, 5_000);- return () => {- alive = false;- window.clearInterval(timer);- };- }, [phase, threadPath, profileBot.busy, livePlace]);+ return () => { alive = false; window.clearInterval(timer); };+ }, [phase, threadPath, profileBot.busy, livePlace, pageVisible]);const control = state.computerControl[bot.id] ?? { held: false, helpReason: null };const liveTarget = !computerStatusCurrent ? null@@ -653,10 +652,10 @@ export function ComputerPanel({const liveHere = takeover.here && Boolean(liveTarget);useEffect(() => { if (liveTarget) void loadLiveDesktop(); }, [liveTarget]);- const pageVisible = usePageVisible();const lastLiveAt = useRef(0);const previewBusy = useRef(bot.busy);- useEffect(() => { previewBusy.current = bot.busy; }, [bot.busy]);+ const previewReschedule = useRef<(() => void) | null>(null);+ useEffect(() => { previewBusy.current = bot.busy; previewReschedule.current?.(); }, [bot.busy]);useEffect(() => {lastLiveAt.current = 0;if (!cloudPreviewReady) return;@@ -680,10 +679,13 @@ export function ComputerPanel({const controller = new AbortController();setPreviewError(null);setPreviewRefreshing(true);+ const nextWait = () => Math.max(lastAttemptAt + (retryDelay ?? (previewBusy.current ? 4000 : 30_000)) - Date.now(), previewBusy.current ? lastLiveAt.current + 10_000 - Date.now() : 0);+ const scheduler = createAdaptiveScheduler(nextWait, () => void shoot());+ const schedule = () => { if (!controller.signal.aborted && !inFlight) scheduler.schedule(); };+ previewReschedule.current = schedule;const shoot = async () => {if (inFlight || controller.signal.aborted) return;- if (Date.now() - lastAttemptAt < (retryDelay ?? (previewBusy.current ? 4000 : 30_000))) return;- if (previewBusy.current && Date.now() - lastLiveAt.current < 10_000) return;+ if (nextWait() > 0) { schedule(); return; }inFlight = true;retryDelay = null;const startedAt = Date.now();@@ -718,14 +720,11 @@ export function ComputerPanel({} finally {inFlight = false;lastAttemptAt = Date.now();+ schedule();}};void shoot();- const timer = setInterval(shoot, 1000);- return () => {- controller.abort();- clearInterval(timer);- };+ return () => { if (previewReschedule.current === schedule) previewReschedule.current = null; controller.abort(); scheduler.cancel(); };}, [panelView, cloudPreviewReady, threadPath, cloudBackend, viewerOpen, liveHere, pageVisible, pending, controlPending, previewRetry]);useEffect(() => {diff --git a/src/components/ComputerSharingSettings.tsx b/src/components/ComputerSharingSettings.tsxindex e1ede443ed..069523a507 100644--- a/src/components/ComputerSharingSettings.tsx+++ b/src/components/ComputerSharingSettings.tsx@@ -30,13 +30,16 @@ export function ComputerSharingSettings({ workspace, own = false, onClose }: { wpanel.current?.scrollIntoView({ block: "start" });void bridge?.state(workspace.id).then(next => { if (mounted.current) apply(next); }).catch(() => { if (mounted.current) setError(t("computerSharing.loadFailed")); });+ void bridge?.activity?.(workspace.id).then(next => { if (mounted.current) setActivity(next); }).catch(() => {});const refresh = () => {+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;void bridge?.state(workspace.id).then(next => { if (mounted.current) setState(next); }).catch(() => {});void bridge?.activity?.(workspace.id).then(next => { if (mounted.current) setActivity(next); }).catch(() => {});};- refresh();const timer = setInterval(refresh, 3000);- return () => { mounted.current = false; clearInterval(timer); };+ const doc = typeof document === "undefined" ? undefined : document;+ doc?.addEventListener("visibilitychange", refresh);+ return () => { mounted.current = false; clearInterval(timer); doc?.removeEventListener("visibilitychange", refresh); };}, [bridge, workspace.id]);const perform = async (action: () => Promise<void>) => {if (pending.current) return;diff --git a/src/components/ConnectedWorkspacesSettings.tsx b/src/components/ConnectedWorkspacesSettings.tsxindex bebda8619c..d1b6a2b776 100644--- a/src/components/ConnectedWorkspacesSettings.tsx+++ b/src/components/ConnectedWorkspacesSettings.tsx@@ -43,10 +43,15 @@ export function ConnectedWorkspacesSettings({ label, description }: { label?: stuseEffect(() => {if (!sharing?.servers || !saved) return;let current = true;- const read = () => void sharing.servers!().then((next) => { if (current) setOwnServers(next); }).catch(() => {});+ const read = () => {+ if (typeof document !== "undefined" && document.visibilityState === "hidden") return;+ void sharing.servers!().then((next) => { if (current) setOwnServers(next); }).catch(() => {});+ };read();const timer = setInterval(read, 5000);- return () => { current = false; clearInterval(timer); };+ const doc = typeof document === "undefined" ? undefined : document;+ doc?.addEventListener("visibilitychange", read);+ return () => { current = false; clearInterval(timer); doc?.removeEventListener("visibilitychange", read); };}, [sharing, saved]);useEffect(() => {const consume = (id?: string | null) => {diff --git a/src/components/HtmlFilePreview.tsx b/src/components/HtmlFilePreview.tsxindex cf0f1edc92..28759790d1 100644--- a/src/components/HtmlFilePreview.tsx+++ b/src/components/HtmlFilePreview.tsx@@ -8,7 +8,7 @@ import { cn } from "@/lib/cn";import { useFileBesideChat, type FilePreview } from "@/lib/file-preview";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";-import { tableDelimiter } from "@/lib/table-data";+import { tableDelimiter } from "@/lib/table-helpers";import { PREVIEW_MAX_BYTES } from "../../shared/upload-limits";/** Security: the frame may draw what the file carries inline, and fetch nothing at all. */diff --git a/src/components/LocalVmWorkspace.tsx b/src/components/LocalVmWorkspace.tsxindex 9d5b80c4ce..e220314b7f 100644--- a/src/components/LocalVmWorkspace.tsx+++ b/src/components/LocalVmWorkspace.tsx@@ -284,10 +284,16 @@ function LocalVmPane({useEffect(() => {if (!botId) return;const controller = new AbortController();- const timer = window.setInterval(() => void refreshStatus(controller.signal), 30_000);+ const poll = () => {+ if (document.visibilityState === "hidden") return;+ void refreshStatus(controller.signal);+ };+ const timer = window.setInterval(poll, 30_000);+ document.addEventListener("visibilitychange", poll);return () => {controller.abort();window.clearInterval(timer);+ document.removeEventListener("visibilitychange", poll);};}, [botId, refreshStatus]);diff --git a/src/components/RichTable.tsx b/src/components/RichTable.tsxindex 638fed842f..fa32ad5911 100644--- a/src/components/RichTable.tsx+++ b/src/components/RichTable.tsx@@ -2,7 +2,7 @@ import { useDeferredValue, useEffect, useId, useMemo, useRef, useState, type Reaimport { createPortal } from "react-dom";import { useVirtualizer } from "@tanstack/react-virtual";import { ArrowDown, ArrowUp, Check, Copy, Download, Maximize2, Search, WrapText, X } from "lucide-react";-import { isTableAmount, tableCsv, tableRowOrder, type TableSort } from "@/lib/table-data";+import { isTableAmount, tableCsv, tableRowOrder, type TableSort } from "@/lib/table-helpers";import { intlLocale, t } from "@/lib/i18n";import { copyText } from "@/lib/copy-text";import { columnMinimums, fitsColumns } from "@/lib/table-fit";diff --git a/src/components/ServerUpdateRow.tsx b/src/components/ServerUpdateRow.tsxindex 6c3391a95d..20dcc6be3d 100644--- a/src/components/ServerUpdateRow.tsx+++ b/src/components/ServerUpdateRow.tsx@@ -1,3 +1,4 @@+import { useSharedClock } from "@/lib/shared-clock";import { useCallback, useEffect, useState } from "react";import { unlessRefused } from "@/lib/admin-scope";@@ -62,12 +63,10 @@ export function useServerUpdate() {const updating = pressed || !settled(status);const [waitingSince, setWaitingSince] = useState<number | null>(null);- const [now, setNow] = useState(() => Date.now());+ const now = useSharedClock(30_000, updating);useEffect(() => {if (!updating) return void setWaitingSince(null);setWaitingSince((since) => since ?? Date.now());- const timer = setInterval(() => setNow(Date.now()), 30_000);- return () => clearInterval(timer);}, [updating]);useEffect(() => {if (!updating || !connected) return;diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsxindex b5e643f222..4f2bc500b1 100644--- a/src/components/SidebarThreadRow.tsx+++ b/src/components/SidebarThreadRow.tsx@@ -1,3 +1,4 @@+import { useSharedClock } from "@/lib/shared-clock";import { memo, useEffect, useRef, useState, type Dispatch, type ReactNode, type RefObject, type SetStateAction } from "react";import { createPortal } from "react-dom";import { Archive, ArchiveRestore, BellOff, Brain, Check, ChevronRight, CircleCheck, CircleDashed, Clock, Clock3, FolderInput, Link2, Link2Off, Loader2, MoreHorizontal, Pencil, Pin, PinOff, RefreshCw, Star, Trash2 } from "lucide-react";@@ -223,44 +224,8 @@ export function useRevealedThreadRow(reveal: AppState["revealThread"], currentTh}, [reveal, currentThreadId]);}-type RelativeClock = {- win: Window & typeof globalThis;- doc: Document;- timer: number;- sync: () => void;- listeners: Set<(now: number) => void>;-};-let sharedRelativeClock: RelativeClock | null = null;-export function useRelativeNow(): number {- const [now, setNow] = useState(() => Date.now());- useEffect(() => {- if (sharedRelativeClock && (sharedRelativeClock.win !== window || sharedRelativeClock.doc !== document)) {- sharedRelativeClock = null;- }- if (!sharedRelativeClock) {- const listeners = new Set<(next: number) => void>();- const win = window, doc = document;- const sync = () => {- if (doc.visibilityState !== "visible") return;- const next = Date.now();- for (const notify of listeners) notify(next);- };- sharedRelativeClock = { win, doc, timer: win.setInterval(sync, 30_000), sync, listeners };- doc.addEventListener("visibilitychange", sync);- }- const clock = sharedRelativeClock;- clock.listeners.add(setNow);- return () => {- clock.listeners.delete(setNow);- if (clock.listeners.size === 0) {- clock.win.clearInterval(clock.timer);- clock.doc.removeEventListener("visibilitychange", clock.sync);- if (sharedRelativeClock === clock) sharedRelativeClock = null;- }- };- }, []);- return now;+ return useSharedClock(30_000);}const attentionRank = (task: ThreadRowTask, activeId: string): number => {if (task.activity === "waiting-on-you") return 0;diff --git a/src/components/TableFilePreview.tsx b/src/components/TableFilePreview.tsxindex 978670ab53..07196878ce 100644--- a/src/components/TableFilePreview.tsx+++ b/src/components/TableFilePreview.tsx@@ -4,7 +4,7 @@ import { requestMessageFile, type MessageAttachmentContext } from "./AttachmentPimport { OutsideWorkspacePreview, canOpenOutsideWorkspace, refusedAsOutsideWorkspace } from "./OutsideWorkspacePreview";import { RichTable, TableDialog } from "./RichTable";import { useFileBesideChat } from "@/lib/file-preview";-import { TABLE_FILE_MAX_BYTES, tableDelimiter, type TextTable } from "@/lib/table-data";+import { TABLE_FILE_MAX_BYTES, tableDelimiter, type TextTable } from "@/lib/table-helpers";import { t } from "@/lib/i18n";/** The whole body. A preview limit, not a download limit: chunked responses are bounded too. */diff --git a/src/components/TurnPresence.tsx b/src/components/TurnPresence.tsxindex 4c4a9477fe..d20667e057 100644--- a/src/components/TurnPresence.tsx+++ b/src/components/TurnPresence.tsx@@ -1,3 +1,4 @@+import { useSharedClock } from "@/lib/shared-clock";import { useEffect, useId, useRef, useState, type CSSProperties, type ReactNode } from "react";import { ChevronDown } from "lucide-react";import { cn } from "@/lib/cn";@@ -60,23 +61,13 @@ const Dot = () => <span aria-hidden="true" className="text-[12px] text-ink-terti/** "last output 2 min ago" counts on by itself; the other states change only with a new frame. */function QuietPart({ quiet }: { quiet: StepQuiet }) {- const [now, setNow] = useState(() => Date.now());- useEffect(() => {- if (quiet.kind !== "output") return;- setNow(Date.now());- const timer = setInterval(() => setNow(Date.now()), 15_000);- return () => clearInterval(timer);- }, [quiet]);+ const now = useSharedClock(15_000, quiet.kind === "output");return <><Dot /><span data-turn-quiet="" className="text-[12px] text-ink-tertiary">{quietText(quiet, now)}</span></>;}/** "nothing new for 5 min" when the whole turn has gone silent, counted from the last frame this window saw. */function SilencePart({ threadId }: { threadId: string }) {- const [now, setNow] = useState(() => Date.now());- useEffect(() => {- const timer = setInterval(() => setNow(Date.now()), 15_000);- return () => clearInterval(timer);- }, []);+ const now = useSharedClock(15_000);const text = silenceText(silentSince(threadId), now);return text ? <><Dot /><span data-turn-silent="" className="text-[12px] text-ink-tertiary">{text}</span></> : null;}diff --git a/src/components/inbox/InboxCard.tsx b/src/components/inbox/InboxCard.tsxindex 240a4c507e..b6880da86b 100644--- a/src/components/inbox/InboxCard.tsx+++ b/src/components/inbox/InboxCard.tsx@@ -1,8 +1,9 @@+import { useSharedClock } from "@/lib/shared-clock";// On a Team Cloud, in the person's inbox chat: one card that keeps what waits on them in view. It sits under the newest// line that needed them and updates in place: how many need them and how many are news, the newest few that need them// with their answers right there (the line it sits under answers on its own card), and the way into the whole inbox.// With nothing open it shrinks to one line.-import { useEffect, useState } from "react";+import { useState } from "react";import { Check, CornerUpLeft, Inbox } from "lucide-react";import type { InboxRow, InboxView } from "../../../shared/inbox";import { cn } from "@/lib/cn";@@ -62,11 +63,7 @@ function Answers({ row, view }: { row: InboxRow; view: InboxView }) {export function InboxCard({ view }: { view: InboxView }) {const { run } = useInboxActions(view);- const [now, setNow] = useState(() => Date.now());- useEffect(() => {- const timer = setInterval(() => setNow(Date.now()), 60_000);- return () => clearInterval(timer);- }, []);+ const now = useSharedClock(60_000);const counts = tabCounts(view);const rows = rowsIn(view, "needs-you").slice(0, CARD_ROWS);const openRow = (row: InboxRow) => openInbox({ reading: row.id });diff --git a/src/components/inbox/InboxPanel.tsx b/src/components/inbox/InboxPanel.tsxindex d13b76ef63..ef680489c0 100644--- a/src/components/inbox/InboxPanel.tsx+++ b/src/components/inbox/InboxPanel.tsx@@ -1,3 +1,4 @@+import { useSharedClock } from "@/lib/shared-clock";import { memo, useEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";import { createPortal } from "react-dom";import { Check, Inbox, Maximize2, Minimize2, Search, X } from "lucide-react";@@ -36,14 +37,10 @@ export const InboxPanel = memo(function InboxPanel() {const phone = useMediaQuery(PHONE_LAYOUT);const simple = !useAdvancedMode();const { run, openInChat } = useInboxActions(view), jump = useInboxJump();- const [now, setNow] = useState(() => Date.now());+ const now = useSharedClock(30_000);const [query, setQuery] = useState("");const [showDone, setShowDone] = useState(false);const [filter, setFilter] = useState<ThreadFilter>({});- useEffect(() => {- const timer = setInterval(() => setNow(Date.now()), 30_000);- return () => clearInterval(timer);- }, []);const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {if (event.key !== "Escape" || event.defaultPrevented) return;event.preventDefault();diff --git a/src/components/lazy-screens.test.ts b/src/components/lazy-screens.test.tsindex 003e6e785d..f8363ee5c1 100644--- a/src/components/lazy-screens.test.ts+++ b/src/components/lazy-screens.test.ts@@ -209,6 +209,20 @@ describe("preloadScreens", () => {expect(preloads.length).toBe(stubbed.length);});+ it("skips background screen preloading on save-data or 2g connections", () => {+ vi.useFakeTimers();+ const preloads = stubPreloads();+ const origNavigator = globalThis.navigator;+ vi.stubGlobal("navigator", { ...origNavigator, connection: { saveData: true } });+ preloadScreens("cloud.example");+ vi.runAllTimers();+ for (const preload of preloads) expect(preload).not.toHaveBeenCalled();+ vi.stubGlobal("navigator", { ...origNavigator, connection: { effectiveType: "2g" } });+ preloadScreens("cloud.example");+ vi.runAllTimers();+ for (const preload of preloads) expect(preload).not.toHaveBeenCalled();+ });+it("a window opened onto Settings fetches Settings at once, not when idle", async () => {let settingsFetched = false;vi.resetModules();@@ -268,11 +282,23 @@ describe("launch bundle", () => {"LocalVmWorkspace", "NewBotDialog", "PhoneAppDialog", "PhoneSetupFlow", "PluginsPanel", "published-apps/PublishedAppsPage", "skill-burger/SkillBurgersPage", "RemoteAgentSettingsPanel", "remote-desktop-panel", "RoutineCalendarPage","RoutinesPage", "SettingsModal", "ShareTemplateDialog", "ImportDialog", "TeamLibraryPanel", "TeamMapPage", "team-files/TeamFilesPage", "TriggersPage", "WebhookTrigger", "room-panel/RoomPanel","inbox/InboxPanel", "TeamDialog", "TeamSettingsDialog", "VoiceSetupDialog", "usage/TraceView", "bot-access/ShareBotDialog", "CommandAllowlistDialog", "WorkspaceBackupSettings",+ "GroupView", "room-feed/RoomFeedView", "ForkPanel", "WebPanelPage", "TeamWelcome", "cloud-welcome/CloudWelcome", "CloudIntent", "CloudEngineSignIn", "NoEngines", "MemberApps", "skill-burger/SkillBurgerSlot", "published-apps/SiteFrame",].map((name) => `components/${name}.tsx`);expect(deferred.filter((file) => reached.has(file))).toEqual([]);expect(reached.has("lib/template-details.ts"), "the team library brings the YAML parser in").toBe(false);expect(reached.has("../shared/browser-mates.ts")).toBe(true);expect(reached.has("../shared/logins.ts"), "saved logins bring the public-suffix list in").toBe(false);+ expect(reached.has("components/settings/settings-index.ts"), "settings metadata stays out of App boot").toBe(false);+ expect(reached.has("lib/table-data.ts"), "papaparse stays in the table worker").toBe(false);+ });++ it("keeps zod schema modules out of the main.tsx and rail.tsx boot entries", () => {+ for (const entry of ["main.tsx", "rail.tsx"]) {+ const reached = launchModules(entry);+ expect(reached.has("../shared/theme.ts"), `${entry} should use shared/theme-tokens.ts`).toBe(false);+ expect(reached.has("../shared/app-settings.ts"), `${entry} should use shared/app-settings-ids.ts`).toBe(false);+ expect(reached.has("../packages/phone-protocol/src/app-settings.ts"), `${entry} should not pull zod schemas`).toBe(false);+ }});it("the sign-in and home pages leave the app out", () => {diff --git a/src/components/lazy-screens.tsx b/src/components/lazy-screens.tsxindex e4d346979b..93d1f498de 100644--- a/src/components/lazy-screens.tsx+++ b/src/components/lazy-screens.tsx@@ -129,8 +129,13 @@ const REMOTE_PRELOAD_AFTER_MS = 5_000;// On this machine a first open costs 8-28 ms, and fetching every screen during launch held the first paint back by a// quarter, so a local page fetches each when it opens. Over a network a first open takes up to a second, so a Cloud page// still fetches them, once launch is over and one per idle moment.+function meteredOrSlowConnection(): boolean {+ const conn = (globalThis.navigator as { connection?: { saveData?: boolean; effectiveType?: string } } | undefined)?.connection;+ return Boolean(conn?.saveData || conn?.effectiveType === "slow-2g" || conn?.effectiveType === "2g");+}+export function preloadScreens(hostname = location.hostname): () => void {- if (LOCAL_HOSTS.has(hostname)) return () => {};+ if (LOCAL_HOSTS.has(hostname) || meteredOrSlowConnection()) return () => {};let stopped = false;let cancelWait = () => {};const whenIdle = (run: () => void) => {diff --git a/src/components/lazy-views.tsx b/src/components/lazy-views.tsxnew file mode 100644index 0000000000..3737523e51--- /dev/null+++ b/src/components/lazy-views.tsx@@ -0,0 +1,15 @@+import { lazyScreen } from "./lazy-screens";++// Mode-specific, onboarding, and preview views kept out of the initial App chunk and loaded on demand when shown.+export const GroupView = lazyScreen("GroupView", async () => (await import("./GroupView")).GroupView);+export const RoomFeedView = lazyScreen("RoomFeedView", async () => (await import("./room-feed/RoomFeedView")).RoomFeedView);+export const ForkPanel = lazyScreen("ForkPanel", async () => (await import("./ForkPanel")).ForkPanel);+export const WebPanelPage = lazyScreen("WebPanelPage", async () => (await import("./WebPanelPage")).WebPanelPage);+export const TeamWelcome = lazyScreen("TeamWelcome", async () => (await import("./TeamWelcome")).TeamWelcome);+export const CloudWelcome = lazyScreen("CloudWelcome", async () => (await import("./cloud-welcome/CloudWelcome")).CloudWelcome);+export const CloudIntent = lazyScreen("CloudIntent", async () => (await import("./CloudIntent")).CloudIntent);+export const CloudEngineSignIn = lazyScreen("CloudEngineSignIn", async () => (await import("./CloudEngineSignIn")).CloudEngineSignIn);+export const NoEngines = lazyScreen("NoEngines", async () => (await import("./NoEngines")).NoEngines);+export const MemberApps = lazyScreen("MemberApps", async () => (await import("./MemberApps")).MemberApps);+export const SkillBurgerSlot = lazyScreen("SkillBurgerSlot", async () => (await import("./skill-burger/SkillBurgerSlot")).SkillBurgerSlot);+export const SiteFrame = lazyScreen("SiteFrame", async () => (await import("./published-apps/SiteFrame")).SiteFrame);diff --git a/src/components/published-apps/AppPreviewPanel.tsx b/src/components/published-apps/AppPreviewPanel.tsxindex fa9af2f86f..f95d1533c4 100644--- a/src/components/published-apps/AppPreviewPanel.tsx+++ b/src/components/published-apps/AppPreviewPanel.tsx@@ -7,7 +7,7 @@ import { closeAppPreview, useAppPreview } from "@/lib/app-preview";import { t } from "@/lib/i18n";import { useStore } from "@/state/store";import { PANEL_MIN_WIDTH, useComputerPanelResize } from "../computer-panel-resize";-import { SiteFrame } from "./SiteFrame";+import { SiteFrame } from "../lazy-views";/** The published app a card's Preview or a link in a message opened, beside the conversation where the Computer panel* sits. One panel has that side at a time: it gives way when another one opens. */diff --git a/src/components/remote-desktop-panel.tsx b/src/components/remote-desktop-panel.tsxindex ea6d980f24..d99643be63 100644--- a/src/components/remote-desktop-panel.tsx+++ b/src/components/remote-desktop-panel.tsx@@ -1,3 +1,4 @@+import { createAdaptiveScheduler } from "@/lib/adaptive-poll";import { boatCapableEngine } from "@/lib/remote-desktop";import { useEffect, useRef, useState } from "react";import { CalendarClock, CalendarDays, Globe, ImageOff, Loader2, Monitor, Plus, X } from "lucide-react";@@ -75,7 +76,8 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {const [viewerOpen, setViewerOpen] = useState(false);const pageVisible = usePageVisible();const previewBusy = useRef(bot.busy);- useEffect(() => { previewBusy.current = bot.busy; }, [bot.busy]);+ const previewReschedule = useRef<(() => void) | null>(null);+ useEffect(() => { previewBusy.current = bot.busy; previewReschedule.current?.(); }, [bot.busy]);const [creatingRoutine, setCreatingRoutine] = useState(false);// The host runs this bot on its Local VM: preview, control and viewer all go to that desktop, not the cloud computer.const localVm = bot.computer === "vm";@@ -130,9 +132,13 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {let lastAttemptAt = -Infinity;let retryDelay: number | null = null;let contentionSince: number | null = null;+ const nextWait = () => lastAttemptAt + (retryDelay ?? (previewBusy.current ? 4000 : 30_000)) - Date.now();+ const scheduler = createAdaptiveScheduler(nextWait, () => void shoot());+ const schedule = () => { if (!controller.signal.aborted && !requestRunning) scheduler.schedule(); };+ previewReschedule.current = schedule;const shoot = async () => {if (requestRunning || controller.signal.aborted) return;- if (Date.now() - lastAttemptAt < (retryDelay ?? (previewBusy.current ? 4000 : 30_000))) return;+ if (nextWait() > 0) { schedule(); return; }requestRunning = true;retryDelay = null;try {@@ -166,13 +172,14 @@ export function RemoteDesktopPanel({ bot }: { bot: Bot }) {if (!controller.signal.aborted && retryDelay === null) setPreviewPending(false);requestRunning = false;lastAttemptAt = Date.now();+ schedule();}};void shoot();- const timer = window.setInterval(shoot, 1000);return () => {+ if (previewReschedule.current === schedule) previewReschedule.current = null;controller.abort();- window.clearInterval(timer);+ scheduler.cancel();};}, [bot.id, localVm, pageVisible, viewerOpen, pending, view]);diff --git a/src/components/settings/settings-index.ts b/src/components/settings/settings-index.tsindex 0d114d6141..cbe1fecf95 100644--- a/src/components/settings/settings-index.ts+++ b/src/components/settings/settings-index.ts@@ -1,3 +1,4 @@+import { isSettingsPage } from "./settings-pages";import {Archive, ArrowLeftRight, Bot, Coins, CreditCard, HardDrive, LockKeyhole, Monitor, Network, Palette, Server, SlidersHorizontal, Sparkles, ToggleRight, Users,type LucideIcon,@@ -138,7 +139,7 @@ export const LEGACY_SETTINGS: Record<Exclude<AppSettingsSection, SettingsPageId>updates: (ctx) => (ctx.desktop ? { page: "app", anchor: "updates" } : { page: "overview" }),};-export const isSettingsPage = (id: string | null | undefined): id is SettingsPageId => SETTINGS_PAGES.some((page) => page.id === id);+export { isSettingsPage };/** True when a row or section is one Advanced mode adds (on a page Simple shows, or on an Advanced-only page). */export function needsAdvanced(target: SettingsTarget, ctx: SettingsContext): boolean {diff --git a/src/components/settings/settings-pages.ts b/src/components/settings/settings-pages.tsnew file mode 100644index 0000000000..944b1d7af7--- /dev/null+++ b/src/components/settings/settings-pages.ts@@ -0,0 +1,27 @@+import type { SettingsPageId } from "@/state/store";++export const SETTINGS_PAGE_IDS = [+ "overview",+ "devices",+ "ai",+ "bots",+ "desktops",+ "vault",+ "usage",+ "transfer",+ "storage",+ "data",+ "people",+ "installations",+ "features",+ "account",+ "plan",+ "app",+ "general",+ "appearance",+] as const satisfies readonly SettingsPageId[];++const SETTINGS_PAGE_SET = new Set<string>(SETTINGS_PAGE_IDS);++export const isSettingsPage = (id: string | null | undefined): id is SettingsPageId =>+ typeof id === "string" && SETTINGS_PAGE_SET.has(id);diff --git a/src/lib/adaptive-poll.ts b/src/lib/adaptive-poll.tsnew file mode 100644index 0000000000..1b6d910f2e--- /dev/null+++ b/src/lib/adaptive-poll.ts@@ -0,0 +1,33 @@+/**+ * Schedules repeated callbacks with an adaptive delay computed at schedule time,+ * avoiding fixed 1-second polling loops when the active interval is much longer.+ */+export interface AdaptiveScheduler {+ schedule: () => void;+ cancel: () => void;+}++export function createAdaptiveScheduler(getDelayMs: () => number, run: () => void): AdaptiveScheduler {+ let timer: ReturnType<typeof setTimeout> | null = null;+ let cancelled = false;+ const clear = () => {+ if (timer !== null) {+ clearTimeout(timer);+ timer = null;+ }+ };+ return {+ schedule() {+ clear();+ if (cancelled) return;+ timer = setTimeout(() => {+ timer = null;+ if (!cancelled) run();+ }, Math.max(0, getDelayMs()));+ },+ cancel() {+ cancelled = true;+ clear();+ },+ };+}diff --git a/src/lib/chat-width.ts b/src/lib/chat-width.tsindex bb76a1c72d..7fefb7a6e3 100644--- a/src/lib/chat-width.ts+++ b/src/lib/chat-width.ts@@ -1,4 +1,4 @@-import { CHAT_WIDTH_IDS } from "../../shared/app-settings";+import { CHAT_WIDTH_IDS } from "../../shared/app-settings-ids";import { windowPrefChanged } from "./window-pref-changes";export { CHAT_WIDTH_IDS };diff --git a/src/lib/composer-layout.ts b/src/lib/composer-layout.tsindex 2b9a3df692..79d80333ab 100644--- a/src/lib/composer-layout.ts+++ b/src/lib/composer-layout.ts@@ -2,7 +2,7 @@// usage one: how a plan's usage shows beside the model (today's bars, or one ring), and the order of the composer's end// buttons. Both default to what the app always drew; only the usage row is shown, and only in Advanced mode.import { useSyncExternalStore, type CSSProperties } from "react";-import { COMPOSER_BUTTONS, USAGE_INDICATORS } from "../../shared/app-settings";+import { COMPOSER_BUTTONS, USAGE_INDICATORS } from "../../shared/app-settings-ids";import { windowPrefChanged } from "./window-pref-changes";export type UsageIndicator = (typeof USAGE_INDICATORS)[number];diff --git a/src/lib/fonts.ts b/src/lib/fonts.tsindex 1bb0ec1af2..86080b3d82 100644--- a/src/lib/fonts.ts+++ b/src/lib/fonts.ts@@ -1,4 +1,4 @@-import { FONT_IDS } from "../../shared/app-settings";+import { FONT_IDS } from "../../shared/app-settings-ids";import { windowPrefChanged } from "./window-pref-changes";export { FONT_IDS };diff --git a/src/lib/send-key.ts b/src/lib/send-key.tsindex 8a590d5531..5b0a8ffd56 100644--- a/src/lib/send-key.ts+++ b/src/lib/send-key.ts@@ -1,6 +1,6 @@import { useSyncExternalStore } from "react";-import { SEND_KEYS } from "../../shared/app-settings";+import { SEND_KEYS } from "../../shared/app-settings-ids";import { activeLocale } from "./i18n";import { isMacPlatform } from "./keyboard-shortcuts";import { windowPrefChanged } from "./window-pref-changes";diff --git a/src/lib/shared-clock.test.ts b/src/lib/shared-clock.test.tsnew file mode 100644index 0000000000..3267046b91--- /dev/null+++ b/src/lib/shared-clock.test.ts@@ -0,0 +1,108 @@+import { createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { act } from "react";+import { Window } from "happy-dom";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { useSharedClock } from "./shared-clock";++let win: Window;+let root: Root;++function setVisibility(state: "visible" | "hidden") {+ Object.defineProperty(document, "visibilityState", { value: state, configurable: true });+ document.dispatchEvent(new Event("visibilitychange"));+}++beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-06-01T12:00:00.000Z"));+ win = new Window();+ vi.stubGlobal("window", win);+ vi.stubGlobal("document", win.document);+ vi.stubGlobal("Event", win.Event);+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ setVisibility("visible");+ const host = win.document.createElement("div");+ win.document.body.appendChild(host);+ root = createRoot(host as unknown as Element);+});++afterEach(() => {+ act(() => root.unmount());+ vi.useRealTimers();+ vi.unstubAllGlobals();+ win.close();+});++function ClockReader({ id, intervalMs, enabled = true }: { id: string; intervalMs: number; enabled?: boolean }) {+ const now = useSharedClock(intervalMs, enabled);+ return createElement("span", { "data-clock": id }, String(now));+}++describe("useSharedClock", () => {+ it("coalesces subscribers at the same interval onto one timer and cleans up when the last unmounts", () => {+ const setIntervalSpy = vi.spyOn(globalThis, "setInterval");+ const clearIntervalSpy = vi.spyOn(globalThis, "clearInterval");++ act(() => {+ root.render(+ createElement("div", null,+ createElement(ClockReader, { id: "a", intervalMs: 15_000 }),+ createElement(ClockReader, { id: "b", intervalMs: 15_000 }),+ createElement(ClockReader, { id: "c", intervalMs: 15_000 }),+ ),+ );+ });++ expect(setIntervalSpy).toHaveBeenCalledTimes(1);+ const initial = Date.now();+ expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(String(initial));++ act(() => {+ vi.advanceTimersByTime(15_000);+ });+ const afterTick = String(initial + 15_000);+ expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(afterTick);+ expect(document.querySelector('[data-clock="b"]')?.textContent).toBe(afterTick);+ expect(document.querySelector('[data-clock="c"]')?.textContent).toBe(afterTick);++ // Unmounting two of three keeps the shared timer alive.+ act(() => {+ root.render(createElement("div", null, createElement(ClockReader, { id: "a", intervalMs: 15_000 })));+ });+ expect(clearIntervalSpy).not.toHaveBeenCalled();++ // Unmounting the last tears down the shared timer.+ act(() => {+ root.render(createElement("div", null));+ });+ expect(clearIntervalSpy).toHaveBeenCalledTimes(1);+ });++ it("pauses updates while hidden and syncs immediately when visible again", () => {+ act(() => {+ root.render(createElement(ClockReader, { id: "a", intervalMs: 30_000 }));+ });+ const initial = Date.now();++ act(() => {+ setVisibility("hidden");+ vi.advanceTimersByTime(90_000);+ });+ expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(String(initial));++ act(() => {+ setVisibility("visible");+ });+ expect(document.querySelector('[data-clock="a"]')?.textContent).toBe(String(initial + 90_000));+ });++ it("does not register a timer when disabled", () => {+ const setIntervalSpy = vi.spyOn(globalThis, "setInterval");+ act(() => {+ root.render(createElement(ClockReader, { id: "a", intervalMs: 15_000, enabled: false }));+ });+ expect(setIntervalSpy).not.toHaveBeenCalled();+ });+});diff --git a/src/lib/shared-clock.ts b/src/lib/shared-clock.tsnew file mode 100644index 0000000000..f77744a261--- /dev/null+++ b/src/lib/shared-clock.ts@@ -0,0 +1,56 @@+import { useEffect, useState } from "react";++type ClockListener = (now: number) => void;++interface ClockBucket {+ doc: Document | undefined;+ timer: ReturnType<typeof setInterval>;+ sync: () => void;+ listeners: Set<ClockListener>;+}++const buckets = new Map<number, ClockBucket>();++/**+ * Subscribes to a shared visibility-aware wall clock for the given `intervalMs`.+ * All mounted components requesting the same interval share a single `setInterval` and+ * `visibilitychange` listener, pausing ticks while the document is hidden and syncing+ * immediately when the tab becomes visible again.+ */+export function useSharedClock(intervalMs: number, enabled = true): number {+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!enabled) return;+ setNow(Date.now());+ const doc = typeof document === "undefined" ? undefined : document;+ let bucket = buckets.get(intervalMs);+ if (bucket && bucket.doc !== doc) {+ clearInterval(bucket.timer);+ bucket.doc?.removeEventListener("visibilitychange", bucket.sync);+ buckets.delete(intervalMs);+ bucket = undefined;+ }+ if (!bucket) {+ const listeners = new Set<ClockListener>();+ const sync = () => {+ if (doc && doc.visibilityState !== "visible") return;+ const next = Date.now();+ for (const notify of listeners) notify(next);+ };+ bucket = { doc, timer: setInterval(sync, intervalMs), sync, listeners };+ doc?.addEventListener("visibilitychange", sync);+ buckets.set(intervalMs, bucket);+ }+ const active = bucket;+ active.listeners.add(setNow);+ return () => {+ active.listeners.delete(setNow);+ if (active.listeners.size === 0) {+ clearInterval(active.timer);+ active.doc?.removeEventListener("visibilitychange", active.sync);+ if (buckets.get(intervalMs) === active) buckets.delete(intervalMs);+ }+ };+ }, [intervalMs, enabled]);+ return now;+}diff --git a/src/lib/sidebar-preferences.ts b/src/lib/sidebar-preferences.tsindex f9a764ba0b..c0d0ef99b9 100644--- a/src/lib/sidebar-preferences.ts+++ b/src/lib/sidebar-preferences.ts@@ -1,5 +1,4 @@import { useSyncExternalStore } from "react";-import { z } from "zod";/** The sidebar as it is, or "icons": the column of avatars the person dragged its edge down to. */export type SidebarDensity = "comfortable" | "icons";@@ -380,14 +379,14 @@ export function useUniversalPins(): boolean {}-const stringListSchema = z.array(z.string().min(1).max(240));-function parseStringList(raw: string | null): string[] {if (!raw) return [];try {const parsed: unknown = JSON.parse(raw);- const result = stringListSchema.safeParse(parsed);- return result.success ? [...new Set(result.data)].slice(0, 100) : [];+ if (!Array.isArray(parsed) || !parsed.every((item): item is string => typeof item === "string" && item.length >= 1 && item.length <= 240)) {+ return [];+ }+ return [...new Set(parsed)].slice(0, 100);} catch {return [];}diff --git a/src/lib/skins.ts b/src/lib/skins.tsindex 4f656d4d7e..15101de3ce 100644--- a/src/lib/skins.ts+++ b/src/lib/skins.ts@@ -1,4 +1,4 @@-import { SKIN_IDS } from "../../shared/app-settings";+import { SKIN_IDS } from "../../shared/app-settings-ids";import { paintAuroraField } from "./aurora-field";import { syncBrowserChrome } from "./browser-chrome";import { hasPriorRun } from "./prior-run";diff --git a/src/lib/table-data.ts b/src/lib/table-data.tsindex 87c1113374..925d48f3e6 100644--- a/src/lib/table-data.ts+++ b/src/lib/table-data.ts@@ -1,17 +1,21 @@import Papa from "papaparse";+import type { TextTable } from "./table-helpers";++export {+ isTableAmount,+ isTableNumber,+ TABLE_FILE_MAX_BYTES,+ tableCsv,+ tableDelimiter,+ tableRowOrder,+ type TableSort,+ type TextTable,+} from "./table-helpers";-export const TABLE_FILE_MAX_BYTES = 10 * 1024 * 1024;const MAX_ROWS = 100_000;const MAX_COLUMNS = 200;const MAX_CELLS = 500_000;-export interface TextTable { headers: string[]; rows: string[][] }-export type TableSort = { column: number; descending: boolean } | null;--export function tableDelimiter(name: string): "," | "\t" | null {- return /\.csv$/i.test(name) ? "," : /\.tsv$/i.test(name) ? "\t" : null;-}-/** Strings stay strings: leading zeroes and long IDs must never be coerced. */export function parseTableFile(text: string, delimiter: "," | "\t"): TextTable {if (text.includes("\0")) throw new Error("format");@@ -30,53 +34,3 @@ export function parseTableFile(text: string, delimiter: "," | "\t"): TextTable {}return { headers, rows };}--const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });-const NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;-export function isTableNumber(text: string): boolean { return NUMBER.test(text.trim()); }--const AMOUNT = /^[+-]?[$€£¥₹]?\d{1,3}(?:,?\d{3})*(?:\.\d+)?%?$/;-/** A cell that reads as a quantity (a plain number, a price, a percentage), so its column lines up on the right. */-export function isTableAmount(text: string): boolean { return isTableNumber(text) || AMOUNT.test(text.trim()); }--function decimalParts(text: string): { sign: number; order: bigint; digits: string } {- const negative = text.startsWith("-");- const [mantissa = "", exponent = "0"] = text.replace(/^[+-]/, "").toLowerCase().split("e");- const dot = mantissa.indexOf(".");- const decimals = dot < 0 ? 0 : mantissa.length - dot - 1;- const digits = mantissa.replace(".", "").replace(/^0+/, "");- if (!digits) return { sign: 0, order: 0n, digits: "" };- return { sign: negative ? -1 : 1, order: BigInt(exponent) + BigInt(digits.length - decimals), digits: digits.replace(/0+$/, "") };-}--/** Different floating-point values keep decimal order; equal rounded values need their original decimal digits. */-function compareTableNumbers(left: string, right: string): number {- const l = Number(left), r = Number(right);- if (l < r) return -1;- if (l > r) return 1;- const a = decimalParts(left.trim()), b = decimalParts(right.trim());- if (a.sign !== b.sign) return a.sign - b.sign;- if (!a.sign) return 0;- const magnitude = a.order < b.order ? -1 : a.order > b.order ? 1- : a.digits < b.digits ? -1 : a.digits > b.digits ? 1 : 0;- return a.sign * magnitude;-}--export function tableRowOrder(rows: readonly (readonly string[])[], query: string, sort: TableSort): number[] {- const needle = query.trim().toLocaleLowerCase();- const order = rows.flatMap((row, index) => !needle || row.some((cell) => cell.toLocaleLowerCase().includes(needle)) ? [index] : []);- if (sort) order.sort((a, b) => {- const left = rows[a]![sort.column] ?? "", right = rows[b]![sort.column] ?? "";- if (!left.trim() || !right.trim()) return Number(!left.trim()) - Number(!right.trim()) || a - b;- const difference = isTableNumber(left) && isTableNumber(right) ? compareTableNumbers(left, right) : collator.compare(left, right);- return difference * (sort.descending ? -1 : 1) || a - b;- });- return order;-}--/** A cell a spreadsheet would read as a formula; a plain number such as -12.50 is a number, not a formula. */-const FORMULA = /^(?![+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$)[=+\-@\t\r]/i;--export function tableCsv(headers: readonly string[], rows: readonly (readonly string[])[]): string {- return Papa.unparse([headers, ...rows], { newline: "\r\n", escapeFormulae: FORMULA });-}diff --git a/src/lib/table-helpers.ts b/src/lib/table-helpers.tsnew file mode 100644index 0000000000..d0c7f99286--- /dev/null+++ b/src/lib/table-helpers.ts@@ -0,0 +1,64 @@+export const TABLE_FILE_MAX_BYTES = 10 * 1024 * 1024;++export interface TextTable { headers: string[]; rows: string[][] }+export type TableSort = { column: number; descending: boolean } | null;++export function tableDelimiter(name: string): "," | "\t" | null {+ return /\.csv$/i.test(name) ? "," : /\.tsv$/i.test(name) ? "\t" : null;+}++const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });+const NUMBER = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i;+export function isTableNumber(text: string): boolean { return NUMBER.test(text.trim()); }++const AMOUNT = /^[+-]?[$€£¥₹]?\d{1,3}(?:,?\d{3})*(?:\.\d+)?%?$/;+/** A cell that reads as a quantity (a plain number, a price, a percentage), so its column lines up on the right. */+export function isTableAmount(text: string): boolean { return isTableNumber(text) || AMOUNT.test(text.trim()); }++function decimalParts(text: string): { sign: number; order: bigint; digits: string } {+ const negative = text.startsWith("-");+ const [mantissa = "", exponent = "0"] = text.replace(/^[+-]/, "").toLowerCase().split("e");+ const dot = mantissa.indexOf(".");+ const decimals = dot < 0 ? 0 : mantissa.length - dot - 1;+ const digits = mantissa.replace(".", "").replace(/^0+/, "");+ if (!digits) return { sign: 0, order: 0n, digits: "" };+ return { sign: negative ? -1 : 1, order: BigInt(exponent) + BigInt(digits.length - decimals), digits: digits.replace(/0+$/, "") };+}++/** Different floating-point values keep decimal order; equal rounded values need their original decimal digits. */+function compareTableNumbers(left: string, right: string): number {+ const l = Number(left), r = Number(right);+ if (l < r) return -1;+ if (l > r) return 1;+ const a = decimalParts(left.trim()), b = decimalParts(right.trim());+ if (a.sign !== b.sign) return a.sign - b.sign;+ if (!a.sign) return 0;+ const magnitude = a.order < b.order ? -1 : a.order > b.order ? 1+ : a.digits < b.digits ? -1 : a.digits > b.digits ? 1 : 0;+ return a.sign * magnitude;+}++export function tableRowOrder(rows: readonly (readonly string[])[], query: string, sort: TableSort): number[] {+ const needle = query.trim().toLocaleLowerCase();+ const order = rows.flatMap((row, index) => !needle || row.some((cell) => cell.toLocaleLowerCase().includes(needle)) ? [index] : []);+ if (sort) order.sort((a, b) => {+ const left = rows[a]![sort.column] ?? "", right = rows[b]![sort.column] ?? "";+ if (!left.trim() || !right.trim()) return Number(!left.trim()) - Number(!right.trim()) || a - b;+ const difference = isTableNumber(left) && isTableNumber(right) ? compareTableNumbers(left, right) : collator.compare(left, right);+ return difference * (sort.descending ? -1 : 1) || a - b;+ });+ return order;+}++/** A cell a spreadsheet would read as a formula; a plain number such as -12.50 is a number, not a formula. */+const FORMULA = /^(?![+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$)[=+\-@\t\r]/i;+const NEEDS_QUOTES = /[",\r\n]/;++function csvCell(value: string): string {+ const safe = FORMULA.test(value) ? `'${value}` : value;+ return NEEDS_QUOTES.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe;+}++export function tableCsv(headers: readonly string[], rows: readonly (readonly string[])[]): string {+ return [headers, ...rows].map((row) => row.map((cell) => csvCell(cell ?? "")).join(",")).join("\r\n");+}diff --git a/src/lib/theme/runtime.ts b/src/lib/theme/runtime.tsindex f2a590bf21..39411f4f55 100644--- a/src/lib/theme/runtime.ts+++ b/src/lib/theme/runtime.ts@@ -1,6 +1,6 @@// The window's custom theme: colours painted over the skin's tokens, the theme's CSS after the app's own, kept in step// with the server through `theme` frames. Every way back lives here, outside anything a theme's CSS can hide.-import { SAFE_LOOK_PARAM, THEME_COLOR_ROLES, themeFileSchema, type ActiveTheme, type ThemeFile } from "../../../shared/theme";+import { parseThemeFile, SAFE_LOOK_PARAM, THEME_COLOR_ROLES, type ActiveTheme, type ThemeFile } from "../../../shared/theme-tokens";import { readColorScheme } from "../color-scheme";import { DEFAULT_SKIN_CHOICE, SKIN_IDS, applySkinChoice, readSkin, resolveSkin, subscribeSkin, THEME_SKINS, wearSkin, type SkinChoice } from "../skins";import { accentPalette, canvasPalette, modeOf } from "./palette";@@ -115,8 +115,8 @@ export function wearTheme(next: WornTheme | null): void {function cachedTheme(): WornTheme | null {try {const raw = JSON.parse(storage("localStorage")?.getItem(CACHE_KEY) ?? "null") as { id?: unknown; theme?: unknown } | null;- const theme = themeFileSchema.safeParse(raw?.theme);- return typeof raw?.id === "string" && theme.success ? { id: raw.id, theme: theme.data } : null;+ const theme = parseThemeFile(raw?.theme);+ return typeof raw?.id === "string" && theme ? { id: raw.id, theme } : null;} catch {return null;}@@ -128,8 +128,8 @@ export async function loadTheme(): Promise<void> {const res = await serverFetch("/api/themes/active", { headers: { accept: "application/json" } });if (!res.ok) return;const active = (await res.json()) as ActiveTheme;- const theme = active.theme ? themeFileSchema.safeParse(active.theme) : null;- wearTheme(active.id && theme?.success ? { id: active.id, theme: theme.data } : null);+ const theme = active.theme ? parseThemeFile(active.theme) : null;+ wearTheme(active.id && theme ? { id: active.id, theme } : null);} catch {}}diff --git a/src/lib/theme/theme-css.ts b/src/lib/theme/theme-css.tsindex 9a58e94380..d9643a10ef 100644--- a/src/lib/theme/theme-css.ts+++ b/src/lib/theme/theme-css.ts@@ -2,7 +2,7 @@// site (an attribute selector plus a url()). The browser parses the text first, so every check below reads values the// way the browser will use them; then any declaration or rule that could load something other than this server's theme// files, a data: address or an #id is removed. A rule of a kind this file does not know is removed too.-import { themeValueLoads } from "../../../shared/theme";+import { themeValueLoads } from "../../../shared/theme-tokens";type RuleParent = { readonly cssRules: CSSRuleList; deleteRule(index: number): void };type Declarations = Pick<CSSStyleDeclaration, "length" | "item" | "getPropertyValue" | "removeProperty">;diff --git a/vite.config.ts b/vite.config.tsindex d42716d2df..62b3e11120 100644--- a/vite.config.ts+++ b/vite.config.ts@@ -51,6 +51,7 @@ export default defineConfig({input: { index: page("./index.html"), rail: page("./rail.html") },output: {manualChunks(id) {+ if (/[\\/]src[\\/]locales[\\/]en\.json$/.test(id)) return "locale-en";if (!id.includes("node_modules")) return undefined;if (/[\\/]node_modules[\\/](react|react-dom|scheduler)[\\/]/.test(id)) return "vendor-react";if (/[\\/]node_modules[\\/]lucide-react[\\/]/.test(id)) return "vendor-icons";