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
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import { expect, it } from 'bun:test';
import {
chromeExecutablePath, compileBrowserFixture, connectToPage, failOnCiWithoutChrome, htmlResponse, launchChrome,
readViewerTemplateHtml, REPOSITORY_ROOT, scriptResponse, UNTHROTTLED_TIMER_FLAGS, withTimeout, type DevToolsPage, type OwnedChrome,
} from '../../helpers/chrome-devtools';
import {
readSavedThemeChoice, resolveTheme, THEME_CHOICE_STORAGE_KEY, THEME_CHOICES, type ResolvedTheme, type ThemeChoice, type ThemeStorage,
} from '../../../src/ui/theme-choice';
import { THEME_PRE_PAINT_SCRIPT } from '../../../src/ui/my-work/src/lib/theme-pre-paint';
import { PREFERENCES_STORAGE_KEY, PREFERENCES_VERSION } from '../../../src/ui/my-work/src/store/preferences';
import { THEME_LABELS } from '../../../src/ui/viewer/components/ThemeToggle';
import {
VIEWER_THEME_PRE_PAINT_MARK, VIEWER_THEME_PRE_PAINT_SCRIPT, withViewerThemePrePaintScript,
} from '../../../src/ui/viewer/utils/theme-pre-paint';
import { existsSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
failOnCiWithoutChrome('CI requires Chrome for the shared theme choice of My Work and Memory.');
/**
* One theme choice for My Work and Memory (My Work design pass, Phase 11): both save it under one key
* (src/ui/theme-choice.ts), so a choice made in one app is the other's on its next load. Memory puts the saved choice on
* <html> (`data-theme`) before the first paint with an inline script the build writes into viewer.html's <head> from
* src/ui/viewer/utils/theme-pre-paint.ts (its key and choices are the module's); it is run in a real Chrome against the
* answer useTheme takes from the module. Then both real apps on one origin, as the worker serves them (My Work at `/`, Memory at `/viewer`): dark chosen
* in My Work opens Memory dark, light chosen in Memory opens My Work light, and a theme My Work saved before Phase 11
* reaches Memory once My Work has opened.
*/
const BUILT_VIEWER_HTML = join(REPOSITORY_ROOT, 'plugin/ui/viewer.html');
const FOLLOWS_SYSTEM: ThemeChoice = 'system';
const DARK: ResolvedTheme = 'dark';
const LIGHT: ResolvedTheme = 'light';
/** Memory's pre-paint script: the inline <script> in the built page's <head>, before its stylesheet. */
function viewerPrePaintScript(): string {
const template = readViewerTemplateHtml();
const head = template.slice(0, template.indexOf('<style>'));
const scripts = [...head.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((match) => match[1]);
expect(scripts.length).toBe(1);
return scripts[0];
}
/** The template's page colour (`body` is `--color-bg-primary`) in one theme, as Chrome computes it. */
function pageColour(theme: ResolvedTheme): string {
const template = readViewerTemplateHtml();
const opener = `[data-theme="${theme}"] {`;
const start = template.indexOf(opener);
expect(start).toBeGreaterThan(-1);
const hex = /--color-bg-primary:\s*#([0-9a-f]{6});/i.exec(template.slice(start, template.indexOf('}', start)))?.[1];
if (!hex) throw new Error(`no six-digit --color-bg-primary in ${opener}`);
const [red, green, blue] = [0, 2, 4].map((offset) => parseInt(hex.slice(offset, offset + 2), 16));
return `rgb(${red}, ${green}, ${blue})`;
}
/** What useTheme draws for this saved value: the module's read of the shared key, resolved against the system. */
function memoryTheme(shared: string | null, blocked: boolean, systemDark: boolean): ResolvedTheme {
const storage: ThemeStorage = blocked
? { getItem: () => { throw new Error('blocked'); }, setItem: () => { throw new Error('blocked'); } }
: { getItem: (key) => (key === THEME_CHOICE_STORAGE_KEY ? shared : null), setItem: () => {} };
return resolveTheme(readSavedThemeChoice(storage) ?? FOLLOWS_SYSTEM, systemDark);
}
/** Records the first frame of every document, with its address, before the page's own scripts run. */
const RECORD_FIRST_FRAME = `
const params = new URLSearchParams(location.search);
if (params.has('case')) {
localStorage.clear();
if (params.has('shared')) localStorage.setItem(${JSON.stringify(THEME_CHOICE_STORAGE_KEY)}, params.get('shared'));
// Blocked site data: reading localStorage throws, as it does in Chrome when the person blocks site data.
if (params.get('blocked') === '1') Object.defineProperty(window, 'localStorage', { get() { throw new DOMException('The site data is blocked.', 'SecurityError'); } });
}
requestAnimationFrame(() => {
window.firstFrame = { at: location.pathname + location.search, dataTheme: document.documentElement.getAttribute('data-theme'),
dark: document.documentElement.classList.contains('dark'), colour: document.body ? getComputedStyle(document.body).backgroundColor : null };
});`;
async function openChrome(url: string, profilePrefix: string): Promise<{ chrome: OwnedChrome; page: DevToolsPage }> {
const chrome = launchChrome(url, { profilePrefix, remoteDebugging: true, extraFlags: UNTHROTTLED_TIMER_FLAGS });
const page = await connectToPage(chrome, url);
await page.send('Page.enable');
await page.send('Page.addScriptToEvaluateOnNewDocument', { source: RECORD_FIRST_FRAME });
return { chrome, page };
}
/**
* Waits until `expression` is truthy in the document at `at` (path and query). Until the new document commits, the page
* still answers from the one before, and a read at that moment fails; both are asked again on the next turn.
*/
async function waitFor(page: DevToolsPage, at: string, expression: string, what: string, milliseconds: number): Promise<any> {
return withTimeout((async () => {
for (;;) {
const value = await page.evaluate(`location.pathname + location.search === ${JSON.stringify(at)} ? (${expression}) : null`).catch(() => null);
if (value) return value;
// One poll every 10ms: a page here is ready in tens of milliseconds, and the caller's limit bounds the wait.
await Bun.sleep(10);
}
})(), milliseconds, `timed out waiting for ${what} at ${at}`);
}
(chromeExecutablePath ? it : it.skip)('Memory puts the saved theme on <html> in the first frame, from the shared key and choices, as useTheme will draw it', async () => {
// The template has one mark where the script goes and no script of its own; the build writes the script there from
// src/ui/viewer/utils/theme-pre-paint.ts, which takes the key and the choices from src/ui/theme-choice.ts.
const source = readFileSync(join(REPOSITORY_ROOT, 'src/ui/viewer-template.html'), 'utf8');
expect(source.split(VIEWER_THEME_PRE_PAINT_MARK).length).toBe(2);
expect(/<script>/.test(source)).toBe(false);
expect(() => withViewerThemePrePaintScript(source.replace(VIEWER_THEME_PRE_PAINT_MARK, ''))).toThrow(/pre-paint theme script/);
expect(viewerPrePaintScript()).toBe(VIEWER_THEME_PRE_PAINT_SCRIPT);
// The shipped page carries the same script (plugin/ is the committed build the worker serves).
if (existsSync(BUILT_VIEWER_HTML)) expect(readFileSync(BUILT_VIEWER_HTML, 'utf8')).toContain(`<script>${VIEWER_THEME_PRE_PAINT_SCRIPT}</script>`);
// The real template, with no bundle: only the pre-paint script and the stylesheet decide the first frame.
const template = readViewerTemplateHtml();
const server = Bun.serve({ hostname: '127.0.0.1', port: 0, fetch(request) {
const path = new URL(request.url).pathname;
if (path === '/viewer') return htmlResponse(template);
if (path === '/viewer-bundle.js') return scriptResponse('');
return new Response('not found', { status: 404 });
} });
let opened: { chrome: OwnedChrome; page: DevToolsPage } | undefined;
try {
opened = await openChrome(`${server.url.origin}/viewer`, 'claude-mem-viewer-theme-first-paint-');
const { page } = opened;
const cases: { shared: string | null; blocked: boolean; system: ResolvedTheme }[] = [];
for (const system of [DARK, LIGHT]) {
// Nothing saved, a value that is not a choice, and blocked site data follow the system; each choice is drawn.
cases.push({ shared: null, blocked: false, system }, { shared: 'sepia', blocked: false, system }, { shared: DARK, blocked: true, system });
for (const choice of THEME_CHOICES) cases.push({ shared: choice, blocked: false, system });
}
let caseNumber = 0;
for (const { shared, blocked, system } of cases) {
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: system }] });
const params = new URLSearchParams({ case: String(++caseNumber) });
if (shared !== null) params.set('shared', shared);
if (blocked) params.set('blocked', '1');
const at = `/viewer?${params}`;
await page.send('Page.navigate', { url: `${server.url.origin}${at}` });
// The static page is ready in a few milliseconds here; 10s is for a cold Chrome on a shared CI runner.
const frame = await waitFor(page, at, 'window.firstFrame?.at === location.pathname + location.search && window.firstFrame', 'the first frame', 10_000);
const expected = memoryTheme(shared, blocked, system === DARK);
expect({ shared, blocked, system, dataTheme: frame.dataTheme, colour: frame.colour })
.toEqual({ shared, blocked, system, dataTheme: expected, colour: pageColour(expected) });
}
expect(caseNumber).toBe(cases.length);
} finally {
opened?.page.close();
await opened?.chrome.close();
server.stop(true);
}
// 12 page loads and Chrome's start: under a second here (2026-11-28); 30s for a slow CI runner.
}, 30_000);
/** My Work, the real App on the sample source, with the pre-paint script the build puts in index.html. */
function myWorkBundle(): string {
return compileBrowserFixture(`
import React from './src/ui/my-work/node_modules/react';
import { createRoot } from './src/ui/my-work/node_modules/react-dom/client';
import App from './src/ui/my-work/src/App';
import { useStore } from './src/ui/my-work/src/store';
window.React = React;
window.store = useStore;
createRoot(document.getElementById('root')).render(<App />);
`, ['--loader:.webp=empty', '--loader:.css=empty', '--loader:.png=empty', '--loader:.svg=empty', '--loader:.ttf=empty']);
}
/** Memory, the real viewer App, its welcome already dismissed. */
function memoryBundle(): string {
return 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>);
`);
}
/** Both apps on one origin, as the worker serves them: My Work at `/`, Memory at `/viewer`, Memory's reads answered empty. */
function serveBothApps() {
const myWork = myWorkBundle();
const memory = memoryBundle();
const template = readViewerTemplateHtml();
return Bun.serve({ hostname: '127.0.0.1', port: 0, idleTimeout: 0, fetch(request) {
const path = new URL(request.url).pathname;
if (path === '/blank') return htmlResponse('<!doctype html><title>blank</title>');
if (path === '/') return htmlResponse(`<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><script>${THEME_PRE_PAINT_SCRIPT}</script><div id="root"></div><script src="/my-work.js"></script>`);
if (path === '/my-work.js') return scriptResponse(myWork);
if (path === '/viewer') return htmlResponse(template);
if (path === '/viewer-bundle.js') return scriptResponse(memory);
if (path === '/stream') return new Response(new ReadableStream({ start(controller) {
controller.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ type: 'initial_load', projects: [] })}\n\n`));
} }), { headers: { 'Content-Type': 'text/event-stream' } });
if (['/api/observations', '/api/summaries', '/api/prompts'].includes(path)) return Response.json({ items: [], hasMore: false });
if (path.startsWith('/api/')) return Response.json({});
return new Response('not found', { status: 404 });
} });
}
const MY_WORK_DRAWN = `document.querySelector('[data-slot="app-bar"]') && document.querySelector('main') && !document.querySelector('main [aria-busy="true"]')`;
const MEMORY_DRAWN = `!!document.querySelector('.header-more')`;
const SHARED_CHOICE = `localStorage.getItem(${JSON.stringify(THEME_CHOICE_STORAGE_KEY)})`;
/** The theme Memory's "…" menu marks as chosen, by its words (components/ThemeToggle.tsx THEME_LABELS); the language is a radio too. */
const MEMORY_MENU_CHOICE = `[...document.querySelectorAll('.header-menu [role="menuitemradio"][aria-checked="true"]')].map((item) => item.textContent.trim())
.filter((words) => ${JSON.stringify(Object.values(THEME_LABELS))}.includes(words))`;
/** Opens `at` in the same tab and waits for its app to draw; returns its first frame and how it draws once drawn. */
async function open(page: DevToolsPage, origin: string, at: string, drawn: string) {
await page.send('Page.navigate', { url: `${origin}${at}` });
// Each app draws in well under a second here (2026-11-28); 20s is for a cold Chrome on a shared CI runner.
await waitFor(page, at, drawn, 'the app to draw', 20_000);
return page.evaluate(`({ firstFrame: window.firstFrame, dataTheme: document.documentElement.getAttribute('data-theme'),
dark: document.documentElement.classList.contains('dark'), shared: ${SHARED_CHOICE} })`);
}
(chromeExecutablePath ? it : it.skip)('one theme for both apps: dark chosen in My Work opens Memory dark; light chosen in Memory opens My Work light', async () => {
const server = serveBothApps();
const origin = server.url.origin;
let opened: { chrome: OwnedChrome; page: DevToolsPage } | undefined;
try {
opened = await openChrome(`${origin}/blank`, 'claude-mem-theme-both-apps-');
const { page } = opened;
// The system is light, so a dark page can only be the choice.
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: LIGHT }] });
const myWork = await open(page, origin, '/?source=sample&visit=1', MY_WORK_DRAWN);
expect([myWork.dark, myWork.shared]).toEqual([false, null]);
// Dark, chosen the way Workspace's Theme chooses it (tests/ui/my-work/app-shell.browser.test.ts presses it there).
await page.evaluate(`window.store.getState().setTheme(${JSON.stringify(DARK)})`);
// One state change and one frame, well under 100ms here; 5s for a loaded runner.
await waitFor(page, '/?source=sample&visit=1', `document.documentElement.classList.contains('dark')`, 'My Work drawn dark', 5_000);
const memory = await open(page, origin, '/viewer?visit=2', MEMORY_DRAWN);
expect({ firstFrame: memory.firstFrame.dataTheme, colour: memory.firstFrame.colour, drawn: memory.dataTheme, shared: memory.shared })
.toEqual({ firstFrame: DARK, colour: pageColour(DARK), drawn: DARK, shared: DARK });
expect(await page.evaluate(MEMORY_MENU_CHOICE)).toEqual([THEME_LABELS.dark]);
// Now the system is dark, so a light page can only be the choice. Light, chosen in Memory's "…" menu.
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: DARK }] });
await page.evaluate(`document.querySelector('.header-more').click()`);
await page.evaluate(`[...document.querySelectorAll('.header-menu [role="menuitemradio"]')].find((item) => item.textContent.trim() === ${JSON.stringify(THEME_LABELS.light)}).click()`);
// One menu press and one frame, well under 100ms here; 5s for a loaded runner.
await waitFor(page, '/viewer?visit=2', `document.documentElement.getAttribute('data-theme') === ${JSON.stringify(LIGHT)}`, 'Memory drawn light', 5_000);
expect(await page.evaluate(SHARED_CHOICE)).toBe(LIGHT);
const back = await open(page, origin, '/?source=sample&visit=3', MY_WORK_DRAWN);
expect({ firstFrameDark: back.firstFrame.dark, drawnDark: back.dark, shared: back.shared }).toEqual({ firstFrameDark: false, drawnDark: false, shared: LIGHT });
expect(await page.evaluate('window.store.getState().view.theme')).toBe(LIGHT);
} finally {
opened?.page.close();
await opened?.chrome.close();
server.stop(true);
}
// Two bundles, Chrome's start and four page loads: about 1.5s here (2026-11-28); 60s for a slow CI runner.
}, 60_000);
(chromeExecutablePath ? it : it.skip)('a theme My Work saved in its display preferences before Phase 11 reaches Memory once My Work has opened', async () => {
const server = serveBothApps();
const origin = server.url.origin;
let opened: { chrome: OwnedChrome; page: DevToolsPage } | undefined;
try {
opened = await openChrome(`${origin}/blank`, 'claude-mem-theme-moved-');
const { page } = opened;
await page.send('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: LIGHT }] });
// As 17.0 left it: dark saved inside My Work's display preferences, nothing under the shared key.
// A one-line page, ready in milliseconds; 10s is for a cold Chrome on a shared CI runner.
await waitFor(page, '/blank', 'document.readyState === "complete"', 'the blank page', 10_000);
await page.evaluate(`localStorage.setItem(${JSON.stringify(PREFERENCES_STORAGE_KEY)}, ${JSON.stringify(JSON.stringify({ state: { sort: 'attention', theme: DARK }, version: PREFERENCES_VERSION }))})`);
const myWork = await open(page, origin, '/?source=sample&visit=1', MY_WORK_DRAWN);
expect({ firstFrameDark: myWork.firstFrame.dark, drawnDark: myWork.dark, shared: myWork.shared }).toEqual({ firstFrameDark: true, drawnDark: true, shared: DARK });
const memory = await open(page, origin, '/viewer?visit=2', MEMORY_DRAWN);
expect({ firstFrame: memory.firstFrame.dataTheme, drawn: memory.dataTheme }).toEqual({ firstFrame: DARK, drawn: DARK });
} finally {
opened?.page.close();
await opened?.chrome.close();
server.stop(true);
}
// Two bundles, Chrome's start and three page loads: about 1.5s here (2026-11-28); 60s for a slow CI runner.
}, 60_000);