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

6.3 KB
Raw Blame
import { expect, it } from 'bun:test';
import {
  FIXTURE_PAGE_HTML, UNTHROTTLED_TIMER_FLAGS, chromeExecutablePath, compileBrowserFixture,
  failOnCiWithoutChrome, htmlResponse, launchChrome, scriptResponse, withTimeout, type OwnedChrome,
} from '../../helpers/chrome-devtools';

failOnCiWithoutChrome('CI requires Chrome for the session project-case regression.');

(chromeExecutablePath ? it : it.skip)('keeps fetched and live sessions in the same case-insensitive project filter', async () => {
  const bundle = compileBrowserFixture(`
    import React from 'react';
    import { createRoot } from 'react-dom/client';
    import { App } from './src/ui/viewer/App';
    import { setStoredWelcomeDismissed } from './src/ui/viewer/components/WelcomeCard';
    setStoredWelcomeDismissed(true);
    location.hash = '#/sessions';
    let selectedPages = 0;
    const originalFetch = window.fetch.bind(window);
    window.fetch = async (...args) => {
      const response = await originalFetch(...args);
      if (String(args[0]).startsWith('/api/sessions?') && String(args[0]).includes('project=')) {
        const read = response.json.bind(response);
        response.json = async () => { const data = await read(); selectedPages++; return data; };
      }
      return response;
    };
    createRoot(document.getElementById('root')).render(<App />);
    const pause = () => new Promise(resolve => setTimeout(resolve, 20));
    async function until(predicate) {
      const deadline = Date.now() + 6000;
      while (!predicate()) {
        if (Date.now() > deadline) throw new Error('Session fixture did not settle');
        await pause();
      }
    }
    // The row shows a short id chip; its full id is on data-session-id (and in its title).
    const ids = () => [...document.querySelectorAll('.mem-session-id')].map(node => node.getAttribute('data-session-id')).sort();
    (async () => {
      try {
        const option = value => document.querySelector('.project-picker [role="option"][data-value="' + CSS.escape(value) + '"]');
        // The header's searchable Project filter: open it and choose the option.
        const choose = value => { const target = option(value); document.querySelector('.project-picker-trigger').click(); target.click(); };
        await until(() => document.querySelectorAll('.mem-session-link').length === 2 && option('Widget'));
        choose('Widget');
        await until(() => selectedPages >= 1 && !document.body.textContent.includes('Loading sessions'));
        await pause();
        const fetched = ids();
        await fetch('/emit?project=wIdGeT&id=live-case');
        await until(() => option('wIdGeT'));
        const live = ids();
        await fetch('/emit?project=Widget-other&id=unrelated');
        await until(() => option('Widget-other'));
        const unrelated = ids();
        choose('Äpp');
        await until(() => selectedPages >= 2 && !document.body.textContent.includes('Loading sessions'));
        await fetch('/emit?project=%C3%A4pp&id=unicode-other');
        await until(() => option('äpp'));
        await fetch('/result', { method: 'POST', body: JSON.stringify({ fetched, live, unrelated,
          unicode: ids(), selected: document.querySelector('.project-picker-value').textContent }) });
      } catch (error) { await fetch('/result', { method: 'POST', body: JSON.stringify({ failure: String(error) }) }); }
    })();
  `);
  let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
  let report!: (value: unknown) => void;
  const result = new Promise<unknown>(resolve => { report = resolve; });
  const now = Date.now();
  const sessions = ['Widget', 'widget'].map((project, index) => ({
    content_session_id: `saved-${index}`, platform_source: 'claude', project,
    custom_title: `Saved ${index}`, started_at_epoch: now - index, item_count: 1,
  }));
  let nextObservationId = 100;
  const server = Bun.serve({ hostname: '127.0.0.1', port: 0, async fetch(request) {
    const url = new URL(request.url);
    if (url.pathname === '/') return htmlResponse(FIXTURE_PAGE_HTML);
    if (url.pathname === '/fixture.js') return scriptResponse(bundle);
    if (url.pathname === '/stream') return new Response(new ReadableStream({ start(controller) {
      stream = controller;
      controller.enqueue(new TextEncoder().encode('data: {"type":"initial_load","projects":["Widget","Äpp"]}\n\n'));
    } }), { headers: { 'Content-Type': 'text/event-stream' } });
    if (url.pathname === '/api/sessions') return Response.json({
      sessions: url.searchParams.get('project') === 'Äpp' ? [] : sessions, hasMore: false,
    });
    if (url.pathname === '/api/processing-status') return Response.json({ isProcessing: false, queueDepth: 0 });
    if (url.pathname === '/api/projects') return Response.json({ projects: ['Widget', 'Äpp'], sources: ['claude'],
      projectsBySource: { claude: ['Widget', 'Äpp'] } });
    if (['/api/observations', '/api/summaries', '/api/prompts'].includes(url.pathname)) return Response.json({ items: [], hasMore: false });
    if (url.pathname === '/emit') {
      if (!stream) throw new Error('Owned SSE connection not ready');
      const observation = { id: nextObservationId++, project: url.searchParams.get('project'),
        content_session_id: url.searchParams.get('id'), platform_source: 'claude', created_at_epoch: now,
        type: 'discovery', title: 'Owned live row', facts: '[]', concepts: '[]', files_read: '[]', files_modified: '[]' };
      stream.enqueue(new TextEncoder().encode(`data: ${JSON.stringify({ type: 'new_observation', observation })}\n\n`));
      return new Response('emitted');
    }
    if (url.pathname === '/result') { report(await request.json()); return new Response('received'); }
    return Response.json({});
  } });
  let chrome: OwnedChrome | undefined;
  try {
    chrome = launchChrome(server.url.href, { profilePrefix: 'claude-mem-session-case-', extraFlags: UNTHROTTLED_TIMER_FLAGS });
    const actual = await withTimeout(result, 30000, 'Owned session project-case fixture timed out');
    console.log('SESSION_PROJECT_CASE_PROOF', JSON.stringify(actual));
    expect(actual).toEqual({ fetched: ['saved-0', 'saved-1'], live: ['live-case', 'saved-0', 'saved-1'],
      unrelated: ['live-case', 'saved-0', 'saved-1'], unicode: [], selected: 'Äpp' });
  } finally {
    await chrome?.close(); server.stop(true);
  }
}, 80000);