Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

13.9 KB
Raw Blame
// A person's own look for the app: colours derived onto the app's colour tokens, a stylesheet applied after the app's
// own, and image or font files the stylesheet may use. Bots write themes through app_settings; Settings → Appearance
// edits, imports and exports them.
import { z } from "zod";

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. */
const color = z.string().trim().min(1).max(120)
  .regex(/^[#a-z0-9(),.%\s/+-]+$/i, "a CSS colour such as #1a2b3c, rgb(…) or color-mix(…)")
  .refine((value) => !/url|image|src|attr/i.test(value), "a colour, not a file");
const colors = z.partialRecord(z.enum(THEME_COLOR_ROLES), color);
const variant = z.object({ canvas: hex.optional(), accent: hex.optional(), colors: colors.optional() }).strict();

/** A theme as it is saved, exported and sent by a bot. */
export const themeFileSchema = z.object({
  name: z.string().trim().min(1).max(60),
  /** The built-in skin underneath: what any colour the theme leaves out comes from. Absent: the one matching the canvas. */
  skin: z.enum([...SKIN_IDS, "system"]).optional(),
  /** The base background; the app derives its surfaces, lines and text from it. */
  canvas: hex.optional(),
  accent: hex.optional(),
  /** Single colour roles, over what canvas and accent derive. */
  colors: colors.optional(),
  /** The same, used only while the app is light or dark. */
  light: variant.optional(),
  dark: variant.optional(),
  /** A font-family list: bundled fonts, fonts installed on the computer, or one the CSS loads with @font-face. */
  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();

/** One file: the theme with its files inlined as data: addresses. */
export const themeExportSchema = z.object({
  mausbotTheme: z.literal(THEME_EXPORT_VERSION),
  id: z.string().regex(THEME_ID).optional(),
  theme: themeFileSchema,
  assets: z.record(z.string().regex(THEME_ASSET_NAME), z.string().max(Math.ceil(THEME_LIMITS.assetBytes * 1.4)).regex(/^data:[\w/+.-]+;base64,[A-Za-z0-9+/=]+$/)).optional(),
}).strict();
export type ThemeExport = z.infer<typeof themeExportSchema>;

/** 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 = "";
  for (let index = 0; index < css.length; index++) {
    const char = css[index]!;
    if (char === "/" && css[index + 1] === "*") {
      const end = css.indexOf("*/", index + 2);
      index = end === -1 ? css.length : end + 1;
      out += " ";
    } else if (char === '"' || char === "'") {
      let end = index + 1;
      while (end < css.length && css[end] !== char && css[end] !== "\n") end += css[end] === "\\" ? 2 : 1;
      out += `${char}${" ".repeat(Math.max(0, end - index - 1))}${char}`;
      index = end;
    } else out += char;
  }
  return out;
}

/**
 * The server's early answer on a theme's CSS, in words a bot or person can act on; null when nothing in the text loads a
 * file. Escapes can hide from a text check, so the window's check of the parsed rules is the guard.
 */
export function themeCssProblem(css: string): string | null {
  const code = codeOnly(css);
  if (/@import/i.test(code)) return "@import is not allowed: themes cannot load other stylesheets.";
  if (code.includes("\\")) return "Backslash escapes are only allowed inside quoted strings.";
  if (LOADS_BY_NAME.test(code)) return "image-set(), image() and src() are not allowed: use url() with a theme file or a data: address.";
  const withoutComments = css.replace(/\/\*[\s\S]*?\*\//g, " ");
  const targets = urlTargets(withoutComments);
  if (targets === null) return "A url() could not be read. Write url(\"/api/theme-assets/<theme>/<file>\").";
  const remote = targets.find((target) => !themeUrlAllowed(target));
  if (remote !== undefined) return `url(${remote.slice(0, 80)}) is not allowed: themes load only their own files (${THEME_ASSET_PREFIX}<theme>/<file>), data: addresses or #ids, never the internet.`;
  return null;
}

/** The theme's url() targets under this server's theme files, for re-homing them on import or duplicate. */
export function rehomeThemeCss(css: string, fromId: string, toId: string): string {
  return css.split(`${THEME_ASSET_PREFIX}${fromId}/`).join(`${THEME_ASSET_PREFIX}${toId}/`);
}

/**
 * Selectors a theme can rely on across releases. The app's other class names are utilities that change; tests fail when
 * one of these leaves the app's source.
 */
export const THEME_HOOKS = [
  { selector: '[data-look="app"]', what: "the whole window, behind everything" },
  { selector: '[data-look="window"]', what: "the desktop app's rounded card holding the sidebar and chat (not in the web app)" },
  { selector: '[data-look="rail"]', what: "the rail of places down the side (desktop app)" },
  { selector: '[data-look="sidebar"]', what: "the sidebar" },
  { selector: '[data-look="sidebar-bot"]', what: "a bot's row in the sidebar" },
  { selector: '[data-look="sidebar-thread"]', what: "a conversation's row in the sidebar" },
  { selector: "[data-avatar]", what: 'every face: a bot\'s or a person\'s; [data-avatar="picture"|"mascot"|"initials"], [data-avatar-kind="bot"|"person"]' },
  { selector: '[data-look="chat-header"]', what: "the bar at the top of a chat" },
  { selector: '[data-look="chat"]', what: "the chat area, behind the messages" },
  { selector: '[data-look="chat-backdrop"]', what: "an empty layer filling the chat area under everything in it, never scrolling, never clicked: for backgrounds and animations (its ::before and ::after too)" },
  { selector: '[data-look="message-user"]', what: "a row with your own message" },
  { selector: '[data-look="message-bot"]', what: "a row with a bot's message" },
  { selector: '[data-look="user-bubble"]', what: "your own message's bubble" },
  { selector: '[data-look="bot-bubble"]', what: "a bot's message bubble" },
  { selector: '[data-look="bot-text"]', what: "a bot's message text" },
  { selector: '[data-look="code-block"]', what: "a code block" },
  { selector: '[data-look="composer"]', what: "the message box" },
  { selector: '[data-look="ask-card"]', what: "a question card a bot asks you" },
  { selector: '[data-look="approval-card"]', what: "a card asking you to allow something" },
  { selector: '[data-look="inbox"]', what: "the inbox panel" },
  { selector: '[data-look="settings"]', what: "the Settings page" },
  { selector: '[data-look="dialog"]', what: "a dialog box" },
  { selector: '[data-look="menu"]', what: "a menu" },
  { selector: '[data-look="popover"]', what: "a popover" },
  { selector: '[data-look="tooltip"]', what: "a tooltip" },
  { selector: '[data-look="switch"]', what: "an on/off switch" },
  { selector: '[data-look="select"]', what: "a drop-down list" },
  { selector: "button", what: "every button" },
  { selector: "input, textarea", what: "text fields" },
  { selector: '[role="dialog"]', what: "every dialog, including ones without a hook" },
  { selector: '[role="menu"]', what: "every menu" },
  { selector: "::-webkit-scrollbar, ::-webkit-scrollbar-thumb", what: "scrollbars and their thumbs" },
] as const;

const SHORTCUT = "Cmd+Option+Shift+R on a Mac, Ctrl+Alt+Shift+R elsewhere";

/** What a bot needs to restyle the app; app_settings `theme` returns it. */
export function themeGuide(): string {
  return [
    "A theme restyles MausBot's desktop app and web app for the person who asked, in every window they have open. Phones keep their own look.",
    "",
    "Colours first. `canvas` (hex) is the base background and `accent` (hex) the highlight; the app derives its surfaces, lines and text from them.",
    "`skin` picks the built-in skin underneath, so anything the theme leaves out comes from it. `colors` sets single roles; `light` and `dark` hold canvas, accent and colors used only in that mode. With both `light` and `dark`, and `skin` left out or set to \"system\", \"daylight\" or \"midnight\", the person's Light or dark choice in Settings picks the mode; otherwise `skin` or a top-level `canvas` fixes it.",
    `Roles: ${THEME_COLOR_ROLES.map((role) => `${role} (${THEME_ROLE_HELP[role]})`).join("; ")}.`,
    "`font` is a font-family list. Bundled: \"Geist Variable\", \"Inter Variable\", \"Geist Mono Variable\". A font installed on the computer works by name, and a font file can be a theme file loaded with @font-face.",
    "",
    `CSS: \`css\` (up to ${THEME_LIMITS.cssChars.toLocaleString("en")} characters) applies after the app's own styles. Anything goes: borders, roundness, spacing, bubble shapes, backgrounds, @keyframes animations, hover effects.`,
    "The app's own rules can be more specific; add !important when a rule has no effect. Respect @media (prefers-reduced-motion: reduce) for big animations.",
    "Never the internet: @import, image-set(), image(), src() and url() to any other address are removed, and so is any value with a backslash escape outside a string.",
    `url() may name a theme file (${THEME_ASSET_PREFIX}<theme id>/<file>), a data: address or an #id.`,
    "Theme files: add_theme_asset copies an image (png, jpg, webp, gif, avif, svg; animated is fine) or a font (woff2, woff, ttf, otf) from your workspace or this conversation's attachments into a theme, up to 10 MB each, and answers with the url() to use. path: a file of yours, or an attachment by its path or file name; left out, the latest picture attached here. id: left out, the theme the person wears, or with none worn a new theme over their built-in skin, worn once you set_theme it. HEIC photos and larger files are refused: if you have a shell, convert first (sips -s format jpeg -Z 2560 in.heic --out out.jpg on a Mac) and pass the new file. An SVG you write in your workspace is a theme file too; its own SMIL or CSS animation plays as a background, but repaints every frame and ignores reduced motion: prefer the recipes below.",
    "",
    "Backgrounds: style [data-look=\"chat-backdrop\"] and its ::before and ::after; it sits under the messages, stays put while they scroll, and never takes a click. Keep text readable: lay the canvas colour over a picture (62%, as below, keeps text readable over any picture in light and dark), and keep patterns and animations faint. Animate only transform and opacity, slowly; the app stops them when the person asks for reduced motion. Known-good, to adapt:",
    '- Picture: [data-look="chat-backdrop"] { background: linear-gradient(color-mix(in srgb, var(--color-app) 62%, transparent), color-mix(in srgb, var(--color-app) 62%, transparent)), url("/api/theme-assets/<id>/<file>") center / cover no-repeat; }',
    '- Moving gradient: [data-look="chat-backdrop"]::before { content: ""; position: absolute; inset: -50%; background: conic-gradient(from 0deg, #1d3557, #e63946, #f1faee, #1d3557); opacity: 0.25; animation: bg-turn 60s linear infinite; } @keyframes bg-turn { to { transform: rotate(1turn); } }',
    '- Drifting pattern: [data-look="chat-backdrop"]::after { content: ""; position: absolute; inset: -40px 0 0; background: url("data:image/svg+xml,<svg xmlns=\'http://www.w3.org/2000/svg\' width=\'40\' height=\'40\'><circle cx=\'20\' cy=\'20\' r=\'2\' fill=\'%23888\'/></svg>"); opacity: 0.35; animation: bg-drift 8s linear infinite; } @keyframes bg-drift { to { transform: translateY(40px); } }',
    '- The whole window instead: the same background on [data-look="app"] (with !important), then [data-look="window"], [data-look="chat"] { background: transparent !important; } [data-look="sidebar"], [data-look="rail"] { background: color-mix(in srgb, var(--color-panel) 80%, transparent) !important; }',
    "",
    "Stable selectors (other class names change between releases, so never rely on them):",
    ...THEME_HOOKS.map((hook) => `- ${hook.selector}: ${hook.what}`),
    "",
    "Calls: theme (optional id: also return that saved theme). set_theme with id and theme (the theme as JSON) saves and wears it; with only id it wears a saved theme, a built-in skin, or none. add_theme_asset with path and id (both optional).",
    `theme_history lists the person's last ${LOOK_HISTORY_LIMIT} look changes, newest first, each with its index and the look right after it. undo_theme goes back: steps (default 1) undoes that many changes; index returns to the look right after that entry, theme file and all. An undo is itself a change, so undoing it again is a redo.`,
    "",
    "You cannot see the result. Make one small change at a time, then ask the person how it looks.",
    "Going back: \"undo that\", \"go back\", \"go back two changes\", \"how it was before\" → undo_theme with steps. \"The purple one from earlier\", \"the one from this morning\" → theme_history, then undo_theme with that index.",
    "\"Revert\" or \"reset\" to the original, default or normal look → set_theme with id \"none\". Wear a built-in skin only when the person names one.",
    `If a theme hides what the person needs, tell them: ${SHORTCUT} resets to the default look, and opening the app with ?${SAFE_LOOK_PARAM} in its address starts it without the theme. The card in the conversation has Undo too.`,
  ].join("\n");
}