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

17.6 KB
Raw Blame
import { expect, it } from 'bun:test';
import { composeViewerSyncStatus, type ViewerSyncStatus } from '../../../src/shared/viewer-sync-status';
import { FIND_WORK_PLACE, MEMORY_PLACE, MY_WORK_PLACES } from '../../../src/ui/app-places';
import { PRO_TRIAL_SHORT } from '../../../src/ui/viewer/constants/promo';
import { THEME_LABELS } from '../../../src/ui/viewer/components/ThemeToggle';
import { THEME_PREFERENCES, type ThemePreference } from '../../../src/ui/viewer/hooks/useTheme';
import {
  chromeExecutablePath, compileBrowserFixture, connectToPage, failOnCiWithoutChrome, htmlResponse, launchChrome,
  readViewerTemplateHtml, scriptResponse, UNTHROTTLED_TIMER_FLAGS, withTimeout, type DevToolsPage,
} from '../../helpers/chrome-devtools';

const FOLLOWS_SYSTEM: ThemePreference = 'system';

failOnCiWithoutChrome('CI requires Chrome for Memory\'s bar, its menu and its touch sizes.');

/**
 * Memory's bar (My Work design pass, Phase 11; Claude D01, Codex D21): the same bar as My Work's (the brain mark and
 * its name, My Work's places from src/ui/app-places.ts, Find work, Memory as the page shown, "…"), its "…" menu
 * (Settings, Memory logs, Show welcome card, the trial link, Documentation, the theme and the language), the phone's
 * bottom bar, and the server runtime's bar, which serves Memory alone at / and so shows no My Work place.
 */
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';
  import { setStoredWelcomeDismissed } from './src/ui/viewer/components/WelcomeCard';
  setStoredWelcomeDismissed(true);
  createRoot(document.getElementById('root')).render(<ErrorBoundary withHeader><App /></ErrorBoundary>);
  fetch('/ready');
`);

function serve(script: string, sync?: ViewerSyncStatus) {
  let markReady!: () => void;
  const ready = new Promise<void>(resolve => { markReady = resolve; });
  const base = Date.UTC(2026, 10, 15, 20, 0, 0);
  const server = Bun.serve({ hostname: '127.0.0.1', port: 0, idleTimeout: 0, fetch(request) {
    const url = new URL(request.url);
    // The worker serves Memory at /viewer (and My Work at /); the server runtime serves Memory at /.
    if (url.pathname === '/' || url.pathname === MEMORY_PLACE.address) 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-001'], sync })}\n\n`));
    } }), { headers: { 'Content-Type': 'text/event-stream' } });
    if (url.pathname === '/api/settings') return Response.json({ CLAUDE_MEM_PRO_PLAN: 'none' });
    const common = (id: number) => ({ id, project: 'project-001', platform_source: 'claude', content_session_id: 'session', memory_session_id: 'memory',
      created_at_epoch: base - id * 60_000, created_at: new Date(base - id * 60_000).toISOString() });
    if (url.pathname === '/api/observations') return Response.json({ items: Array.from({ length: 6 }, (_, i) => ({ ...common(i + 1), type: 'discovery',
      title: `Observation ${i + 1}`, subtitle: 'One line under the title', narrative: 'The narrative', text: null, facts: '["One fact"]',
      concepts: '[]', files_read: '[]', files_modified: '[]', prompt_number: 1 })), hasMore: false });
    if (url.pathname === '/api/summaries' || url.pathname === '/api/prompts') return Response.json({ items: [], hasMore: false });
    return Response.json({});
  } });
  return { server, ready };
}

async function openMemory(path: string, width: number, height: number, profile: string, sync?: ViewerSyncStatus) {
  const { server, ready } = serve(bundle(), sync);
  const url = new URL(path, server.url).href;
  const chrome = launchChrome(url, { remoteDebugging: true, profilePrefix: profile, extraFlags: [...UNTHROTTLED_TIMER_FLAGS, `--window-size=${width},${height}`] });
  await withTimeout(ready, 30_000, 'Memory did not become ready');
  const page = await connectToPage(chrome, url);
  await page.evaluate(`new Promise(resolve => { const check = () => document.querySelector('.mem-bar') && document.querySelector('.mem-toolbar') ? resolve(true) : setTimeout(check, 30); check(); })`);
  await page.settle();
  return { server, chrome, page };
}

async function key(page: DevToolsPage, keyName: string, code = keyName, keyCode = 0, modifiers = 0) {
  await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: keyName, code, windowsVirtualKeyCode: keyCode, modifiers });
  await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: keyName, code, windowsVirtualKeyCode: keyCode, modifiers });
  await page.settle();
}

/** Enter as a keyboard sends it, with its "\r" character, which is what presses a focused button. */
async function enter(page: DevToolsPage) {
  await page.send('Input.dispatchKeyEvent', { type: 'keyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13, text: '\r' });
  await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  await page.settle();
}

const BAR_FACTS = `(() => {
  const visible = element => element.getClientRects().length > 0 && getComputedStyle(element).visibility !== 'hidden';
  const bar = document.querySelector('.mem-bar');
  const tall = selector => [...document.querySelectorAll(selector)].filter(visible).map(element => Math.round(element.getBoundingClientRect().height));
  return {
    brand: { href: bar.querySelector('.mem-brand').getAttribute('href'), words: bar.querySelector('.mem-brand').textContent },
    places: [...bar.querySelectorAll('.mem-places a')].filter(visible).map(link => ({ words: link.textContent, href: link.getAttribute('href'), current: link.getAttribute('aria-current') })),
    findWork: bar.querySelector('.mem-findwork') && visible(bar.querySelector('.mem-findwork')) ? bar.querySelector('.mem-findwork').getAttribute('href') : null,
    memory: [...bar.querySelectorAll('.mem-memory-link')].filter(visible).map(link => ({ href: link.getAttribute('href'), current: link.getAttribute('aria-current'), name: link.textContent })),
    bottom: [...document.querySelectorAll('.mem-bottom-bar a')].filter(visible).map(link => ({ words: link.textContent, href: link.getAttribute('href') })),
    barHeight: Math.round(bar.getBoundingClientRect().height),
    shortControls: tall('.mem-bar a, .mem-bar button, .mem-bottom-bar a').filter(height => height < 44),
    scrollsSideways: document.documentElement.scrollWidth > window.innerWidth,
  };
})()`;

(chromeExecutablePath ? it : it.skip)('Memory at /viewer draws My Work\'s bar with Memory marked, and its "…" menu leads to settings, logs and the welcome card', async () => {
  let opened: Awaited<ReturnType<typeof openMemory>> | undefined;
  try {
    opened = await openMemory(MEMORY_PLACE.address, 1440, 900, 'claude-mem-viewer-shell-');
    const { page } = opened;
    const facts = await page.evaluate(BAR_FACTS);
    expect(facts.brand).toEqual({ href: '/', words: 'claude-mem' });
    // The places, in the one list's order, each a real link to its My Work address; none is the page shown.
    expect(facts.places).toEqual(MY_WORK_PLACES.map(place => ({ words: place.label, href: place.address, current: null })));
    expect(facts.findWork).toBe(FIND_WORK_PLACE.address);
    expect(facts.memory).toEqual([{ href: MEMORY_PLACE.address, current: 'page', name: MEMORY_PLACE.label }]);
    expect(facts.bottom).toEqual([]);
    expect(facts.barHeight).toBe(72);
    expect(facts.shortControls).toEqual([]);
    expect(facts.scrollsSideways).toBe(false);
    // One row: every control's middle sits in the bar's middle band.
    expect(await page.evaluate(`(() => { const bar = document.querySelector('.mem-bar').getBoundingClientRect();
      return [...document.querySelectorAll('.mem-bar a, .mem-bar button')].filter(e => e.getClientRects().length)
        .every(e => { const r = e.getBoundingClientRect(); return Math.abs((r.top + r.bottom) / 2 - (bar.top + bar.bottom) / 2) < 6; }); })()`)).toBe(true);
    // The sync state and the queue count left the bar (design pass: they are on My Work's Machine and sync).
    expect(await page.evaluate(`!!document.querySelector('.header-sync, .queue-bubble, .header-sync-phone-dot')`)).toBe(false);

    // The star count sits inside the closed menu, so GitHub is not asked for it while the page loads.
    expect(await page.evaluate(`performance.getEntriesByType('resource').some(entry => entry.name.includes('api.github.com'))`)).toBe(false);

    // The "…" menu: menu role, opened from the keyboard, Settings first, Arrow/Home/End movement, Escape back to "…".
    await page.evaluate(`document.querySelector('.mem-bar .header-more').focus()`);
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    const menu = await page.evaluate(`({ role: document.querySelector('.header-menu [role="menu"]')?.getAttribute('role'),
      expanded: document.querySelector('.header-more').getAttribute('aria-expanded'), focused: document.activeElement.textContent,
      items: [...document.querySelectorAll('.header-menu [role="menuitem"]')].filter(e => e.getClientRects().length).map(e => e.textContent) })`);
    expect(menu.role).toBe('menu');
    expect(menu.expanded).toBe('true');
    expect(menu.focused).toBe('Settings');
    // The timeline carries its own Cloud Sync offer, so the trial link is not in the menu here (it is on the other pages).
    expect(menu.items.slice(0, 4)).toEqual(['Settings', 'Memory logs', 'Show welcome card', 'Documentation']);
    expect(menu.items).not.toContain(PRO_TRIAL_SHORT);
    expect(menu.items).toContain('Documentation');
    expect(await page.evaluate(`[...document.querySelectorAll('.header-menu [role="menuitemradio"]')].map(item => item.getAttribute('aria-checked') + ':' + item.textContent).slice(0, ${THEME_PREFERENCES.length})`))
      // Nothing saved, so the choice that follows the system is the checked one.
      .toEqual(THEME_PREFERENCES.map(choice => `${choice === FOLLOWS_SYSTEM}:${THEME_LABELS[choice]}`));
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    expect(await page.evaluate(`document.activeElement.textContent`)).toBe('Memory logs');
    await key(page, 'Home', 'Home', 36);
    expect(await page.evaluate(`document.activeElement.textContent`)).toBe('Settings');
    await key(page, 'Escape', 'Escape', 27);
    expect(await page.evaluate(`({ expanded: document.querySelector('.header-more').getAttribute('aria-expanded'), back: document.activeElement === document.querySelector('.header-more') })`))
      .toEqual({ expanded: 'false', back: true });

    // Settings and Memory logs are Memory's own pages, each at its own address.
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    await enter(page);
    expect(await page.evaluate(`location.hash`)).toBe('#/settings');
    await page.evaluate(`document.querySelector('.mem-bar .header-more').focus()`);
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    await enter(page);
    expect(await page.evaluate(`location.hash`)).toBe('#/logs');
    expect(await page.evaluate(`[...document.querySelectorAll('.header-menu [role="menuitem"]')].map(item => item.textContent)`)).toContain(PRO_TRIAL_SHORT);
    // Show welcome card brings the welcome back on the timeline (its saved flag cleared) from any page.
    await page.evaluate(`document.querySelector('.mem-bar .header-more').focus()`);
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    expect(await page.evaluate(`document.activeElement.textContent`)).toBe('Show welcome card');
    await enter(page);
    expect(await page.evaluate(`({ hash: location.hash, flag: localStorage.getItem('claude-mem-welcome-dismissed-v3') })`)).toEqual({ hash: '#/', flag: null });

    // Between 768 and 1279px every place still fits on one row, with Find work as its mark.
    for (const width of [1023, 800]) {
      await page.send('Emulation.setDeviceMetricsOverride', { width, height: 900, deviceScaleFactor: 1, mobile: false });
      await page.settle();
      const narrow = await page.evaluate(BAR_FACTS);
      expect(narrow.places.map((place: { words: string }) => place.words)).toEqual(MY_WORK_PLACES.map(place => place.label));
      expect(narrow.scrollsSideways).toBe(false);
      expect(narrow.shortControls).toEqual([]);
      expect(await page.evaluate(`document.querySelector('.mem-findwork kbd').getClientRects().length`)).toBe(0);
    }
    await page.send('Emulation.clearDeviceMetricsOverride');
    await page.settle();

    // Cmd K opens My Work's Find work, as the shortcut beside it says.
    await key(page, 'k', 'KeyK', 75, 4);
    await withTimeout(page.evaluate(`new Promise(resolve => { const check = () => location.search === '?view=find' ? resolve(true) : setTimeout(check, 30); check(); })`),
      5_000, 'Cmd K did not open Find work');
    expect(await page.evaluate(`location.pathname + location.search`)).toBe(FIND_WORK_PLACE.address);
  } finally { opened?.page.close(); await opened?.chrome.close(); opened?.server.stop(true); }
}, 90_000);

(chromeExecutablePath ? it : it.skip)('on a 390px phone the places are in a bottom bar, the top keeps the mark, Find work and "…", and every control is 44px', async () => {
  let opened: Awaited<ReturnType<typeof openMemory>> | undefined;
  try {
    opened = await openMemory(MEMORY_PLACE.address, 390, 844, 'claude-mem-viewer-phone-', composeViewerSyncStatus(null, null, null));
    const { page } = opened;
    await withTimeout(page.evaluate(`new Promise(resolve => {
      const check = () => document.querySelector('.mem-gift') ? resolve(true) : setTimeout(check, 30);
      check();
    })`), 5_000, 'Eligible timeline gift did not appear');
    const facts = await page.evaluate(BAR_FACTS);
    expect(facts.places).toEqual([]);
    expect(facts.memory).toEqual([]);
    expect(facts.findWork).toBe(FIND_WORK_PLACE.address);
    expect(facts.bottom).toEqual(MY_WORK_PLACES.map(place => ({ words: place.shortLabel, href: place.address })));
    expect(facts.barHeight).toBeLessThanOrEqual(58);
    expect(facts.shortControls).toEqual([]);
    expect(facts.scrollsSideways).toBe(false);
    // The bottom bar sits at the foot of the window, under the page's own scroll box, and comes after the page in the
    // document, so Tab reaches the page before the places at its foot (as My Work's own bottom bar).
    expect(await page.evaluate(`Math.round(document.querySelector('.mem-bottom-bar').getBoundingClientRect().bottom) === window.innerHeight`)).toBe(true);
    expect(await page.evaluate(`Boolean(document.querySelector('main').compareDocumentPosition(document.querySelector('.mem-bottom-bar')) & Node.DOCUMENT_POSITION_FOLLOWING)`)).toBe(true);
    // The Cloud Sync offer opens in a new tab and comes before the timeline's find box.
    expect(await page.evaluate(`(() => {
      const gift = document.querySelector('.mem-gift');
      return {
        links: [...document.querySelectorAll('a[href="https://cmem.ai/sync?utm_source=timeline_gift&utm_campaign=holiday_cloud_sync"]')].map(link => ({ inGift: gift.contains(link), opensIn: link.target })),
        giftBeforeFind: Boolean(gift.compareDocumentPosition(document.querySelector('.mem-toolbar')) & Node.DOCUMENT_POSITION_FOLLOWING),
      };
    })()`)).toEqual({ links: [{ inGift: true, opensIn: '_blank' }], giftBeforeFind: true });
    // The timeline carries the offer, so the menu leaves its trial link out there.
    await page.evaluate(`document.querySelector('.header-more').focus()`);
    await key(page, 'ArrowDown', 'ArrowDown', 40);
    expect(await page.evaluate(`({ first: document.activeElement.textContent,
      trial: !!document.querySelector('.header-menu [role="menuitem"][href="https://cmem.ai/pro?from=viewer"]') })`))
      .toEqual({ first: 'Settings', trial: false });
  } finally { opened?.page.close(); await opened?.chrome.close(); opened?.server.stop(true); }
}, 60_000);

(chromeExecutablePath ? it : it.skip)('the server runtime serves Memory alone at /, so its bar is the mark and Memory, with no My Work place', async () => {
  let opened: Awaited<ReturnType<typeof openMemory>> | undefined;
  try {
    opened = await openMemory('/', 1440, 900, 'claude-mem-viewer-runtime-');
    const { page } = opened;
    for (const [width, height, mobile] of [[1440, 900, false], [390, 844, true]] as const) {
      await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile });
      await page.settle();
      const facts = await page.evaluate(BAR_FACTS);
      expect(facts.places).toEqual([]);
      expect(facts.bottom).toEqual([]);
      expect(facts.findWork).toBeNull();
      expect(facts.brand.words).toBe('claude-mem');
      expect(await page.evaluate(`[...document.querySelectorAll('a')].filter(link => link.getClientRects().length)
        .map(link => link.getAttribute('href')).filter(href => ${JSON.stringify(MY_WORK_PLACES.map(place => place.address).filter(address => address !== '/'))}.includes(href) || href === ${JSON.stringify(FIND_WORK_PLACE.address)})`)).toEqual([]);
      expect(facts.scrollsSideways).toBe(false);
      expect(facts.shortControls).toEqual([]);
    }
    // Memory itself (here, /) stays one press away, marked as the page shown, on a desktop.
    await page.send('Emulation.clearDeviceMetricsOverride');
    await page.settle();
    expect((await page.evaluate(BAR_FACTS)).memory).toEqual([{ href: '/', current: 'page', name: MEMORY_PLACE.label }]);
  } finally { opened?.page.close(); await opened?.chrome.close(); opened?.server.stop(true); }
}, 60_000);