Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

9.6 KB
Raw Blame
import { describe, expect, it } from 'bun:test';
import { readdirSync, readFileSync } from 'fs';
import { join } from 'path';
import { VIEWER_THEME_PRE_PAINT_SCRIPT } from '../../src/ui/viewer/utils/theme-pre-paint';
import { THEME_PRE_PAINT_SCRIPT } from '../../src/ui/my-work/src/lib/theme-pre-paint';
import {
  APPEARANCE_WORDS, FONT_CHOICE_LABELS, PALETTE_THEMES, READING_CHOICE_LABELS, THEME_PRESET_LABELS, THEME_PRESETS,
} from '../../src/ui/theme-appearance';
import { LOCALES } from '../../src/ui/i18n/locale';

const template = readFileSync(join(import.meta.dir, '../../src/ui/viewer-template.html'), 'utf-8');
const myWorkCss = readFileSync(join(import.meta.dir, '../../src/ui/my-work/src/index.css'), 'utf-8');
const I18N_DIR = join(import.meta.dir, '../../src/ui/i18n');
const APPEARANCE_KEY = 'claude-mem-theme-appearance';

/** Custom properties declared in the first rule that opens with `ruleOpener` (same parser as theme-tokens.test.ts). */
function tokens(ruleOpener: string): Record<string, string> {
  const start = template.indexOf(ruleOpener);
  expect(start).toBeGreaterThan(-1);
  const body = template.slice(start + ruleOpener.length, template.indexOf('}', start));
  return Object.fromEntries([...body.matchAll(/(--[\w-]+):\s*([^;]+);/g)].map(match => [match[1], match[2].trim()]));
}

function luminance(hex: string): number {
  const channels = [0, 2, 4].map(offset => parseInt(hex.slice(1 + offset, 3 + offset), 16) / 255)
    .map(channel => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4));
  return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
}

function contrast(foreground: string, background: string): number {
  const [lighter, darker] = [luminance(foreground), luminance(background)].sort((a, b) => b - a);
  return (lighter + 0.05) / (darker + 0.05);
}

function runScript(source: string, saved: Record<string, string>, options: { systemDark?: boolean; search?: string } = {}) {
  const items = new Map(Object.entries(saved));
  const attributes = new Map<string, string>();
  const properties = new Map<string, string>();
  const classes = new Set<string>();
  const root = {
    setAttribute: (name: string, value: string) => { attributes.set(name, value); },
    getAttribute: (name: string) => attributes.get(name) ?? null,
    classList: { add: (name: string) => { classes.add(name); } },
    style: {
      setProperty: (name: string, value: string) => { properties.set(name, value); },
      removeProperty: (name: string) => { properties.delete(name); },
    },
  };
  const localStorage = { getItem: (key: string) => items.get(key) ?? null, setItem: (key: string, value: string) => { items.set(key, value); } };
  const document = { documentElement: root };
  const matchMedia = () => ({ matches: options.systemDark ?? false });
  const location = { search: options.search ?? '' };
  new Function('localStorage', 'document', 'matchMedia', 'location', 'console', source)(localStorage, document, matchMedia, location, console);
  return { attributes, properties, classes };
}

const readerLook = JSON.stringify({ preset: 'warm-cream', font: 'serif', reading: 'comfortable' });

describe('readable theme appearance', () => {
  it('offers warm cream, neutral light, warm tint and neutral dark palettes, with faces and reading sizes', () => {
    const warmCream = tokens('[data-theme="light"][data-palette="warm-cream"] {');
    expect(warmCream['--color-bg-primary']).toBe('#f5f2eb');
    expect(warmCream['--color-text-primary']).toBe('#202020');
    const neutralLight = tokens('[data-theme="light"][data-palette="neutral-light"] {');
    expect(neutralLight['--color-bg-primary']).toBe('#fafafa');
    expect(neutralLight['--color-text-primary']).toBe('#242424');
    const warmTint = tokens('[data-theme="light"][data-palette="warm-tint"] {');
    expect(warmTint['--color-bg-primary']).toBe('#edd1b0');
    const neutralDark = tokens('[data-theme="dark"][data-palette="neutral-dark"] {');
    expect(neutralDark['--color-bg-primary']).toBe('#22252a');
    expect(neutralDark['--color-text-primary']).toBe('#e0e0e0');
    // A palette is a complete token set, never a half-tinted page with the theme's old green behind it.
    const read = new Set([...template.matchAll(/var\(\s*(--(?:color|shadow|font)-[\w-]+)/g)].map(match => match[1]));
    expect(read.size).toBeGreaterThan(20);
    for (const [name, palette] of Object.entries({ warmCream, neutralLight, warmTint, neutralDark })) {
      expect({ name, missing: [...read].filter(token => !(token in palette)) }).toEqual({ name, missing: [] });
    }
    expect(tokens('[data-font="serif"] {')['--font-sans']).toContain('Georgia');
    expect(tokens('[data-reading="comfortable"] {')['--theme-line-height']).toBe('1.65');
    expect(myWorkCss).toContain('html[data-reading="comfortable"] { --theme-scale: 1.08;');
    expect(myWorkCss).toContain('html[data-reading] { font-size: calc(100% * var(--theme-scale, 1)); }');
    // A font-size scale, not zoom: zoom moves the coordinates popovers and menus are placed by.
    expect(template).not.toMatch(/\bzoom:/);
    expect(myWorkCss).not.toMatch(/\bzoom:/);
  });

  it('keeps body text readable in every curated palette', () => {
    for (const name of ['warm-cream', 'neutral-light', 'warm-tint', 'neutral-dark']) {
      const palette = tokens(`[data-theme="${PALETTE_THEMES[name as keyof typeof PALETTE_THEMES]}"][data-palette="${name}"] {`);
      expect({ name, ratio: contrast(palette['--color-text-primary'], palette['--color-bg-primary']) >= 4.5 })
        .toEqual({ name, ratio: true });
    }
  });

  it('puts a saved warm palette, face and reading size on <html> before the first paint', () => {
    const drawn = runScript(VIEWER_THEME_PRE_PAINT_SCRIPT, {
      'claude-mem-theme': 'light', [APPEARANCE_KEY]: readerLook,
    });
    expect({ theme: drawn.attributes.get('data-theme'), palette: drawn.attributes.get('data-palette'),
      font: drawn.attributes.get('data-font'), reading: drawn.attributes.get('data-reading') })
      .toEqual({ theme: 'light', palette: 'warm-cream', font: 'serif', reading: 'comfortable' });
    expect(drawn.properties.size).toBe(0);
  });

  it('follows the system and the default palette when the saved appearance is broken or unknown', () => {
    const broken = runScript(VIEWER_THEME_PRE_PAINT_SCRIPT, {
      'claude-mem-theme': 'system', [APPEARANCE_KEY]: '{not json',
    }, { systemDark: true });
    expect({ theme: broken.attributes.get('data-theme'), palette: broken.attributes.get('data-palette'),
      font: broken.attributes.get('data-font'), reading: broken.attributes.get('data-reading') })
      .toEqual({ theme: 'dark', palette: 'default', font: 'default', reading: 'default' });
    expect(broken.properties.size).toBe(0);

    const unknown = runScript(VIEWER_THEME_PRE_PAINT_SCRIPT, {
      [APPEARANCE_KEY]: JSON.stringify({ preset: 'sepia', background: '#123456', font: 'comic', reading: 'huge' }),
    });
    expect({ palette: unknown.attributes.get('data-palette'), font: unknown.attributes.get('data-font'),
      reading: unknown.attributes.get('data-reading') })
      .toEqual({ palette: 'default', font: 'default', reading: 'default' });
    // A background colour saved by an earlier build is ignored, not painted.
    expect(unknown.properties.size).toBe(0);
  });

  it('My Work puts the same saved appearance on <html> before its first paint', () => {
    const drawn = runScript(THEME_PRE_PAINT_SCRIPT, {
      'claude-mem-theme': 'dark', [APPEARANCE_KEY]: readerLook,
    });
    expect({ dark: drawn.classes.has('dark'), palette: drawn.attributes.get('data-palette'),
      font: drawn.attributes.get('data-font'), reading: drawn.attributes.get('data-reading') })
      .toEqual({ dark: true, palette: 'warm-cream', font: 'serif', reading: 'comfortable' });
  });

  it('applies a palette only under its own theme, so a light palette under the dark theme sets no palette tokens', () => {
    // Every rule that names a palette, in both stylesheets, with the theme condition it carries.
    const rules = (css: string) => [...css.matchAll(/^\s*([^{}\n]*data-palette[^{}\n]*)\{/gm)].map(match => match[1].trim());
    const viewerRules = rules(template), myWorkRules = rules(myWorkCss);
    const curated = THEME_PRESETS.filter(preset => PALETTE_THEMES[preset] !== null);
    expect(viewerRules).toHaveLength(curated.length);
    expect(myWorkRules).toHaveLength(curated.length);
    for (const preset of curated) {
      const theme = PALETTE_THEMES[preset]!;
      expect(viewerRules).toContain(`[data-theme="${theme}"][data-palette="${preset}"]`);
      expect(myWorkRules).toContain(`${theme === 'dark' ? 'html.dark' : 'html:not(.dark)'}[data-palette="${preset}"]`);
    }
    // So under data-theme="dark" (viewer) or .dark (My Work), the light palettes' rules match nothing.
    for (const rule of viewerRules) expect(rule).toMatch(/^\[data-theme="(light|dark)"\]\[data-palette="[\w-]+"\]$/);
  });

  it('every appearance word is in every language catalog', () => {
    // The words reach t() from tables, which tests/ui-i18n.test.ts's literal t('…') scan cannot see.
    const words = [...Object.values(APPEARANCE_WORDS), ...Object.values(THEME_PRESET_LABELS),
      ...Object.values(FONT_CHOICE_LABELS), ...Object.values(READING_CHOICE_LABELS)];
    for (const locale of LOCALES.filter(code => code !== 'en')) {
      const suffix = locale === 'zh-CN' ? 'zh' : locale;
      const catalog: Record<string, string> = Object.assign({}, ...readdirSync(I18N_DIR)
        .filter(file => file.endsWith(`-${suffix}.ts`))
        .map(file => Object.values(require(join(I18N_DIR, file)))[0] as Record<string, string>));
      expect({ locale, missing: words.filter(word => !(word in catalog)) }).toEqual({ locale, missing: [] });
    }
  });
});