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

21.9 KB
Raw Blame
import { expect, it } from 'bun:test';
import {
  chromeExecutablePath, compileBrowserFixture, connectToPage, failOnCiWithoutChrome, htmlResponse, launchChrome,
  readViewerTemplateHtml, scriptResponse, UNTHROTTLED_TIMER_FLAGS, withTimeout, type DevToolsPage, type OwnedChrome,
} from '../../helpers/chrome-devtools';
import { SUMMARY_SECTIONS } from '../../../src/ui/viewer/components/RecordRow';

/** The summary's sections; notes is left empty, so an opened summary shows the other four. */
const SUMMARY_FIELDS = { investigated: 'Looked at the cards', learned: 'Rows read faster', completed: 'Rows are in', next_steps: 'Check the phone', notes: null };

failOnCiWithoutChrome('CI requires Chrome for the timeline rows, All types, the welcome panel and #/?find=.');

// Design pass Phase 11, Codex D17 / Claude D18: a record is one row that opens in place (one at a time, by pointer,
// Enter or Space), the kinds are an "All types" menu instead of a chip row, the welcome is a panel above the toolbar
// that can be dismissed and brought back, and `#/?find=<words>` opens the timeline with those words in its find box.

const PROJECT = 'acme-project';
const WELCOME_KEY = 'claude-mem-welcome-dismissed-v3';

const bundle = () => compileBrowserFixture(`
  import React from 'react';
  import { createRoot } from 'react-dom/client';
  import { App } from './src/ui/viewer/App';
  import { ErrorBoundary } from './src/ui/viewer/components/ErrorBoundary';
  window.__errors = [];
  window.addEventListener('error', event => window.__errors.push(String(event.message)));
  window.confirm = () => { throw new Error('The viewer must not use the browser confirm box'); };
  // The test decides the welcome flag before the page draws: ?welcome=dismissed sets it, anything else clears it.
  if (new URLSearchParams(location.search).get('welcome') === 'dismissed') localStorage.setItem('${WELCOME_KEY}', 'true');
  else localStorage.removeItem('${WELCOME_KEY}');
  createRoot(document.getElementById('root')).render(<ErrorBoundary withHeader><App /></ErrorBoundary>);
  fetch('/ready');
`);

function serve(script: string) {
  let markReady!: () => void;
  const ready = new Promise<void>(resolve => { markReady = resolve; });
  const base = Date.UTC(2026, 10, 15, 20, 0, 0);
  const common = (id: number) => ({ id, project: PROJECT, platform_source: 'claude', content_session_id: 'session-1',
    memory_session_id: 'memory', created_at_epoch: base - id * 60_000, created_at: new Date(base - id * 60_000).toISOString() });
  const server = Bun.serve({ hostname: '127.0.0.1', port: 0, idleTimeout: 0, fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === '/') return htmlResponse(readViewerTemplateHtml());
    if (url.pathname === '/viewer-bundle.js') return scriptResponse(script);
    if (url.pathname === '/ready') { markReady(); return new Response('ready'); }
    if (url.pathname === '/stream') return new Response(new ReadableStream({ start(controller) {
      controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ type: 'initial_load', projects: [PROJECT] })}\n\n`));
    } }), { headers: { 'Content-Type': 'text/event-stream' } });
    // Six discoveries, two bugfixes and one feature: the All types menu lists them most rows first.
    if (url.pathname === '/api/observations') return Response.json({ items: Array.from({ length: 9 }, (_, i) => ({ ...common(i + 1),
      type: i < 6 ? 'discovery' : i < 8 ? 'bugfix' : 'feature', title: `Observation ${i + 1}`, subtitle: `Subtitle ${i + 1}`,
      narrative: `Narrative ${i + 1}`, text: null, facts: '["First fact","Second fact"]', concepts: '["how-it-works"]',
      files_read: '["/repo/src/a.ts"]', files_modified: '[]', prompt_number: 1 })), hasMore: false });
    if (url.pathname === '/api/summaries') return Response.json({ items: [{ ...common(20), session_id: 'session-1', request: 'Ship the timeline rows',
      ...SUMMARY_FIELDS }], hasMore: false });
    if (url.pathname === '/api/prompts') return Response.json({ items: [{ ...common(30), prompt_number: 1,
      prompt_text: 'make each record one row\nand open it in place' }], hasMore: false });
    if (url.pathname === '/api/projects') return Response.json({ projects: [PROJECT], sources: ['claude'], projectsBySource: { claude: [PROJECT] } });
    return Response.json({});
  } });
  return { server, ready };
}

interface Opened { server: ReturnType<typeof Bun.serve>; chrome: OwnedChrome; page: DevToolsPage }

async function openApp({ width = 1440, height = 900, welcome = 'dismissed', hash = '', rows = 11 }: { width?: number; height?: number; welcome?: 'dismissed' | 'shown'; hash?: string; rows?: number }, profile: string): Promise<Opened> {
  const { server, ready } = serve(bundle());
  const pageUrl = `${server.url.href}?welcome=${welcome}${hash}`;
  const chrome = launchChrome(pageUrl, { remoteDebugging: true, profilePrefix: profile,
    extraFlags: [...UNTHROTTLED_TIMER_FLAGS, `--window-size=${Math.max(width, 500)},${height}`] });
  try {
    // The fixture bundle and Chrome's start take about a second here; 30s is for a cold Chrome on a shared CI runner.
    await withTimeout(ready, 30_000, 'Viewer did not become ready');
    const page = await connectToPage(chrome, pageUrl);
    await page.send('Emulation.setFocusEmulationEnabled', { enabled: true });
    await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'reduce' }] });
    if (width < 500) await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: true });
    await until(page, `document.querySelectorAll('.mem-record').length === ${rows}`, 'the rows');
    return { server, chrome, page };
  } catch (error) { await chrome.close(); server.stop(true); throw error; }
}

async function close(opened: Opened | undefined) {
  opened?.page.close();
  await opened?.chrome.close();
  opened?.server.stop(true);
}

async function until(page: DevToolsPage, expression: string, what: string): Promise<void> {
  // Each wait here is one state change and a frame or a fake-worker read, under 100ms here; 15s for a loaded runner.
  const deadline = Date.now() + 15_000;
  while (!await page.evaluate(expression)) {
    if (Date.now() > deadline) throw new Error(`Timed out waiting for ${what}`);
    await Bun.sleep(25);
  }
}

async function key(page: DevToolsPage, name: 'Enter' | ' ' | 'Escape' | 'ArrowDown') {
  const codes = { Enter: ['Enter', 13], ' ': ['Space', 32], Escape: ['Escape', 27], ArrowDown: ['ArrowDown', 40] } as const;
  const [code, keyCode] = codes[name];
  await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: name, code, windowsVirtualKeyCode: keyCode, text: name === 'Enter' ? '\r' : name === ' ' ? ' ' : undefined });
  await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: name, code, windowsVirtualKeyCode: keyCode });
  await page.settle();
}

const row = (title: string) => `[...document.querySelectorAll('.mem-record')].find(record => record.querySelector('.mem-row-title').textContent === ${JSON.stringify(title)})`;
const openRows = `[...document.querySelectorAll('.mem-record-row[aria-expanded="true"]')].map(button => button.querySelector('.mem-row-title').textContent)`;

(chromeExecutablePath ? it : it.skip)('each record is one row that opens in place, one at a time, by pointer, Enter or Space', async () => {
  let opened: Opened | undefined;
  try {
    opened = await openApp({}, 'claude-mem-timeline-rows-');
    const { page } = opened;
    // A row: its time, its kind's mark, its title, then its kind and project; a summary is titled by its request and
    // a prompt by its words. The first day's heading says how many memories are loaded.
    const rows = await page.evaluate(`[...document.querySelectorAll('.mem-record')].map(record => ({
      title: record.querySelector('.mem-row-title').textContent, meta: record.querySelector('.mem-row-meta').textContent,
      time: !!record.querySelector('time.mem-time'), mark: !!record.querySelector('.mem-mark svg'), open: record.querySelector('.mem-record-row').getAttribute('aria-expanded') }))`);
    expect(rows[0]).toEqual({ title: 'Observation 1', meta: `Discovery·${PROJECT}`, time: true, mark: true, open: 'false' });
    expect(rows.find((item: { title: string }) => item.title === 'Ship the timeline rows')?.meta).toBe(`Summary·${PROJECT}`);
    expect(rows.find((item: { title: string }) => item.title.startsWith('make each record'))?.meta).toBe(`Prompt·${PROJECT}`);
    expect(await page.evaluate(`({ heading: document.querySelector('.mem-record-day h2').tagName, legend: document.querySelector('.mem-record-day .mem-legend').textContent })`))
      .toEqual({ heading: 'H2', legend: '11 memories loaded' });
    // No per-row Facts, Narrative or "…" buttons on a closed row: the row is one button.
    expect(await page.evaluate(`[...document.querySelectorAll('.mem-record')].every(record => record.querySelectorAll('button').length === 1)`)).toBe(true);

    // Pressing a row opens it under itself: the region the button names holds the subtitle, facts, narrative, concepts,
    // files, its id and the actions.
    await page.evaluate(`${row('Observation 2')}.querySelector('.mem-record-row').click()`);
    await page.settle();
    const details = await page.evaluate(`(() => {
      const button = ${row('Observation 2')}.querySelector('.mem-record-row');
      const region = document.getElementById(button.getAttribute('aria-controls'));
      return { expanded: button.getAttribute('aria-expanded'), role: region.getAttribute('role'), named: region.getAttribute('aria-labelledby') === button.querySelector('.mem-row-title').id,
        text: region.innerText, headings: [...region.querySelectorAll('h3')].map(h => h.textContent),
        actions: [...region.querySelectorAll('.mem-record-actions button')].filter(b => b.getClientRects().length).map(b => b.textContent.trim()) };
    })()`);
    expect(details).toMatchObject({ expanded: 'true', role: 'region', named: true, headings: ['Facts', 'Narrative', 'Concepts', 'Files'], actions: ['Copy text', 'Record actions'] });
    for (const words of ['Subtitle 2', 'First fact', 'Narrative 2', 'how-it-works', 'src/a.ts', '#2']) expect(details.text).toContain(words);

    // Record actions holds Copy id and Delete (the in-page question; no browser confirm box).
    await page.evaluate(`${row('Observation 2')}.querySelector('.mem-record-menu').click()`);
    await page.settle();
    expect(await page.evaluate(`[...${row('Observation 2')}.querySelectorAll('[role="menuitem"]')].map(item => item.textContent.trim())`))
      .toEqual(['Copy id #2', 'Delete observation…']);
    await key(page, 'Escape');

    // One row open at a time: opening the summary closes the observation; the summary shows its sections.
    await page.evaluate(`${row('Ship the timeline rows')}.querySelector('.mem-record-row').click()`);
    await page.settle();
    expect(await page.evaluate(openRows)).toEqual(['Ship the timeline rows']);
    expect(await page.evaluate(`[...${row('Ship the timeline rows')}.querySelectorAll('.mem-record-details h3')].map(h => h.textContent)`))
      .toEqual(SUMMARY_SECTIONS.filter(section => SUMMARY_FIELDS[section.key]).map(section => section.label));

    // The keyboard: Enter opens the focused row (closing the other), Space closes it again.
    await page.evaluate(`${row('Observation 3')}.querySelector('.mem-record-row').focus()`);
    await key(page, 'Enter');
    expect(await page.evaluate(openRows)).toEqual(['Observation 3']);
    await key(page, ' ');
    expect(await page.evaluate(openRows)).toEqual([]);
    expect(await page.evaluate(`document.activeElement === ${row('Observation 3')}.querySelector('.mem-record-row')`)).toBe(true);

    // A prompt's opened row has all its words, line breaks kept.
    await page.evaluate(`${row('make each record one row\nand open it in place')}.querySelector('.mem-record-row').click()`);
    await page.settle();
    expect(await page.evaluate(`document.querySelector('.mem-record-prompt').textContent`)).toBe('make each record one row\nand open it in place');
    expect(await page.evaluate(`window.__errors`)).toEqual([]);
  } finally { await close(opened); }
  // About 1s here (2026-11-29; the file's 5 tests take 5.0–5.3s); 90s for a slow CI runner.
}, 90_000);

(chromeExecutablePath ? it : it.skip)('All types replaces the chip row: kinds with counts, several at once, and back to All types', async () => {
  let opened: Opened | undefined;
  try {
    opened = await openApp({}, 'claude-mem-timeline-types-');
    const { page } = opened;
    expect(await page.evaluate(`!!document.querySelector('.kind-chip')`)).toBe(false);
    const trigger = `document.querySelector('.mem-types-trigger')`;
    expect(await page.evaluate(`({ words: ${trigger}.textContent, name: ${trigger}.getAttribute('aria-label'), popup: ${trigger}.getAttribute('aria-haspopup'), height: ${trigger}.getBoundingClientRect().height })`))
      .toEqual({ words: 'All types', name: 'All types', popup: 'menu', height: 44 });
    await page.evaluate(`${trigger}.click()`);
    await page.settle();
    const menu = `[...document.querySelectorAll('.mem-types-menu [role="menuitemcheckbox"]')].map(item => item.querySelector('.menu-item-label').textContent + ' ' + item.querySelector('.menu-item-hint').textContent + (item.getAttribute('aria-checked') === 'true' ? ' ✓' : ''))`;
    // Most rows first; "All types" (checked while none is chosen) clears.
    expect(await page.evaluate(menu)).toEqual(['All types 11 ✓', 'Discovery 6', 'Bugfix 2', 'Prompt 1', 'Summary 1', 'Feature 1']);
    // Focus is in the menu; Arrow keys move and Space chooses, and the menu stays open for another.
    expect(await page.evaluate(`document.activeElement.getAttribute('role')`)).toBe('menuitemcheckbox');
    await key(page, 'ArrowDown');
    await key(page, 'ArrowDown');
    await key(page, ' ');
    expect(await page.evaluate(`document.querySelectorAll('.mem-feed .mem-record').length`)).toBe(2);
    await page.evaluate(`[...document.querySelectorAll('.mem-types-menu [role="menuitemcheckbox"]')].find(item => item.textContent.startsWith('Feature')).click()`);
    await page.settle();
    expect(await page.evaluate(menu)).toEqual(['All types 11', 'Discovery 6', 'Bugfix 2 ✓', 'Prompt 1', 'Summary 1', 'Feature 1 ✓']);
    expect(await page.evaluate(`({ rows: [...document.querySelectorAll('.mem-feed .mem-record .mem-row-title')].map(t => t.textContent),
      button: document.querySelector('.mem-types-value').textContent, note: document.querySelector('.mem-find-note').textContent, open: ${trigger}.getAttribute('aria-expanded') })`))
      .toEqual({ rows: ['Observation 7', 'Observation 8', 'Observation 9'], button: '2 types', open: 'true',
        note: '3 of the 11 loaded memories match. Older memories are not searched until they load.' });
    // Escape closes it with focus back on the button; "All types" clears every chosen kind.
    await key(page, 'Escape');
    expect(await page.evaluate(`({ open: ${trigger}.getAttribute('aria-expanded'), focus: document.activeElement === ${trigger} })`)).toEqual({ open: 'false', focus: true });
    await page.evaluate(`${trigger}.click()`);
    await page.settle();
    await page.evaluate(`[...document.querySelectorAll('.mem-types-menu [role="menuitemcheckbox"]')].find(item => item.textContent.startsWith('All types')).click()`);
    await page.settle();
    expect(await page.evaluate(`({ rows: document.querySelectorAll('.mem-feed .mem-record').length, button: document.querySelector('.mem-types-value').textContent, note: !!document.querySelector('.mem-find-note') })`))
      .toEqual({ rows: 11, button: 'All types', note: false });
    // All projects: a button with its words (no separate "Project" label on screen), still named "Project".
    expect(await page.evaluate(`(() => { const button = document.querySelector('.project-picker-trigger');
      const name = button.getAttribute('aria-labelledby').split(' ').map(id => document.getElementById(id).textContent).join(' ');
      return { words: button.textContent, name, label: getComputedStyle(document.getElementById(button.getAttribute('aria-labelledby').split(' ')[0])).position }; })()`))
      .toEqual({ words: 'All projects', name: 'Project All projects', label: 'absolute' });
  } finally { await close(opened); }
  // About 1s here (2026-11-29; the file's 5 tests take 5.0–5.3s); 90s for a slow CI runner.
}, 90_000);

for (const width of [1440, 390]) {
  (chromeExecutablePath ? it : it.skip)(`the welcome is a panel above the toolbar: dismissed and saved, then brought back from the menu (${width}px)`, async () => {
    let opened: Opened | undefined;
    try {
      opened = await openApp({ width, height: width === 390 ? 844 : 900, welcome: 'shown' }, `claude-mem-timeline-welcome-${width}-`);
      const { page } = opened;
      // In the page, above the toolbar, never a dialog over the records; the records are there to read and press.
      const panel = await page.evaluate(`(() => {
        const panel = document.querySelector('.mem-welcome');
        const toolbar = document.querySelector('.mem-feed .mem-toolbar');
        return { title: panel.querySelector('h2').textContent, above: panel.getBoundingClientRect().bottom <= toolbar.getBoundingClientRect().top,
          dialog: !!document.querySelector('[role="dialog"]:not([hidden]), [aria-modal="true"]'), links: [...panel.querySelectorAll('a')].map(a => a.textContent),
          dismiss: panel.querySelector('button').getAttribute('aria-label'), sideways: document.documentElement.scrollWidth > innerWidth };
      })()`);
      expect(panel).toEqual({ title: 'Welcome to your memory', above: true, dialog: false, links: ['Memory settings', 'Read the docs'], dismiss: 'Dismiss welcome', sideways: false });

      await page.evaluate(`document.querySelector('.mem-welcome button').click()`);
      await page.settle();
      expect(await page.evaluate(`({ panel: !!document.querySelector('.mem-welcome'), saved: localStorage.getItem('${WELCOME_KEY}'),
        focus: document.activeElement === document.querySelector('.mem-feed .mem-search input') })`)).toEqual({ panel: false, saved: 'true', focus: true });

      // From another page, "Show welcome card" in "…" clears the flag, returns to the timeline and shows the panel, focused.
      await page.evaluate(`location.hash = '#/sessions'`);
      await until(page, `!!document.querySelector('main.mem-sessions')`, 'the Sessions list');
      await page.evaluate(`document.querySelector('.header-more').click()`);
      await page.settle();
      await page.evaluate(`[...document.querySelectorAll('.header-menu [role="menuitem"]')].find(item => item.textContent.trim() === 'Show welcome card').click()`);
      await until(page, `!!document.querySelector('.mem-feed .mem-welcome')`, 'the welcome panel back on the timeline');
      expect(await page.evaluate(`({ saved: localStorage.getItem('${WELCOME_KEY}'), focus: document.activeElement === document.querySelector('.mem-welcome'), hash: location.hash })`))
        .toEqual({ saved: null, focus: true, hash: '#/' });
    } finally { await close(opened); }
  // About 1s here (2026-11-29; the file's 5 tests take 5.0–5.3s); 90s for a slow CI runner.
  }, 90_000);
}

(chromeExecutablePath ? it : it.skip)('#/?find=<words> opens the timeline with them, and typing rewrites the address without a history entry per key', async () => {
  let opened: Opened | undefined;
  try {
    opened = await openApp({ hash: '#/?find=bugfix%20Observation', rows: 2 }, 'claude-mem-timeline-find-');
    const { page } = opened;
    expect(await page.evaluate(`({ words: document.querySelector('.mem-feed .mem-search input').value, hash: location.hash,
      rows: [...document.querySelectorAll('.mem-feed .mem-record .mem-row-title')].map(t => t.textContent) })`))
      .toEqual({ words: 'bugfix Observation', hash: '#/?find=bugfix%20Observation', rows: ['Observation 7', 'Observation 8'] });

    const historyLength = await page.evaluate(`history.length`);
    await page.evaluate(`(() => { const input = document.querySelector('.mem-feed .mem-search input'); input.focus(); input.select(); })()`);
    await page.send('Input.insertText', { text: 'Narrative 9' });
    await until(page, `location.hash === '#/?find=Narrative%209'`, 'the address to follow the words');
    expect(await page.evaluate(`({ length: history.length, rows: [...document.querySelectorAll('.mem-feed .mem-record .mem-row-title')].map(t => t.textContent) })`))
      .toEqual({ length: historyLength, rows: ['Observation 9'] });
    // The Timeline tab under these words is the page already shown: pressing it adds no entry and keeps the words.
    await page.evaluate(`document.querySelector('.mem-tabs a[aria-current="page"]').click()`);
    await page.settle();
    expect(await page.evaluate(`({ length: history.length, hash: location.hash, words: document.querySelector('.mem-feed .mem-search input').value })`))
      .toEqual({ length: historyLength, hash: '#/?find=Narrative%209', words: 'Narrative 9' });

    // Cleared, the address is the timeline's own; another page and Back bring the words back from the address.
    await page.evaluate(`(() => { const input = document.querySelector('.mem-feed .mem-search input'); input.select(); })()`);
    await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
    await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8 });
    await until(page, `location.hash === '#/'`, 'the plain timeline address');
    await page.send('Input.insertText', { text: 'Subtitle 1' });
    await until(page, `location.hash === '#/?find=Subtitle%201'`, 'the address with the new words');
    await page.evaluate(`location.hash = '#/sessions'`);
    await until(page, `!!document.querySelector('main.mem-sessions')`, 'the Sessions list');
    await page.evaluate(`history.back()`);
    await until(page, `document.querySelector('.mem-feed .mem-search input')?.value === 'Subtitle 1'`, 'the words back from the address');
    expect(await page.evaluate(`location.hash`)).toBe('#/?find=Subtitle%201');
  } finally { await close(opened); }
  // About 1s here (2026-11-29; the file's 5 tests take 5.0–5.3s); 90s for a slow CI runner.
}, 90_000);