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

3.7 KB
Raw Blame
// Sync setup reports how many imported prompts the hub acknowledged. flush()
// returns at once while another flush runs (it only marks a re-run), so setup
// waits with flushUntilIdle(), which waits for that run and its re-run.
import { afterEach, describe, expect, it } from 'bun:test';
import { mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { SessionStore } from '../../../src/services/sqlite/SessionStore.js';
import { CloudSync } from '../../../src/services/sync/CloudSync.js';

const cleanups: Array<() => void> = [];
afterEach(() => { for (const cleanup of cleanups.splice(0).reverse()) cleanup(); });

/** A hub that acks every op, holding the first request until `release()`. */
function setup() {
  const dir = mkdtempSync(join(tmpdir(), 'sync-flush-until-idle-'));
  const store = new SessionStore(join(dir, 'memory.db'));
  let release!: () => void;
  let entered!: () => void;
  const held = new Promise<void>(resolve => { release = resolve; });
  const firstRequest = new Promise<void>(resolve => { entered = resolve; });
  let calls = 0, seq = 0;
  const sync = new CloudSync(store.db, {
    CLAUDE_MEM_CLOUD_SYNC_TOKEN: 'fixture-token', CLAUDE_MEM_CLOUD_SYNC_USER_ID: 'fixture-user',
    CLAUDE_MEM_CLOUD_SYNC_DEVICE_ID: 'fixture-device', CLAUDE_MEM_CLOUD_SYNC_HUB_URL: 'http://127.0.0.1:1',
  }, {
    settingsPath: join(dir, 'settings.json'), backoffInitialMs: 60_000,
    fetchImpl: (async (_url, init) => {
      if (++calls === 1) { entered(); await held; }
      const acked = (JSON.parse(String(init?.body)).ops as Array<{ body: string; operation_sha256: string }>).map(op => {
        const envelope = JSON.parse(op.body);
        return { id: envelope.id, kind: envelope.kind, origin_local_id: envelope.origin_local_id,
          entity_rev: envelope.entity_rev, operation_sha256: op.operation_sha256, seq: String(++seq) };
      });
      return Response.json({ acked, head_seq: String(seq), projected_seq: String(seq) });
    }) as typeof fetch,
  });
  cleanups.push(() => { release(); sync.stop(); store.close(); rmSync(dir, { recursive: true, force: true }); });
  const session = store.createSDKSession('host-session', 'project', 'first');
  store.saveUserPrompt('host-session', 1, 'first', session);
  const syncedAt = (text: string) =>
    (store.db.query('SELECT synced_at FROM user_prompts WHERE prompt_text = ?').get(text) as { synced_at: number | null }).synced_at;
  return { store, sync, session, release, firstRequest, syncedAt };
}

describe('CloudSync.flushUntilIdle', () => {
  it('waits for a flush already running, and its re-run, before setup reads the counts', async () => {
    const { store, sync, session, release, firstRequest, syncedAt } = setup();
    const running = sync.flush();
    await firstRequest;
    // Setup imports a prompt while the earlier flush is still waiting on the hub.
    store.saveUserPrompt('host-session', 2, 'imported', session);

    await sync.flush(); // the old call: returns at once, nothing acknowledged yet
    expect(syncedAt('imported')).toBeNull();

    let settled = false;
    const drained = sync.flushUntilIdle(10_000).then(result => { settled = true; return result; });
    await new Promise(resolve => setTimeout(resolve, 20));
    expect(settled).toBe(false);

    release();
    expect(await drained).toBe(true);
    await running;
    expect(syncedAt('first')).toBeGreaterThan(0);
    expect(syncedAt('imported')).toBeGreaterThan(0);
  });

  it('returns false at the deadline and leaves the rows queued', async () => {
    const { sync, firstRequest, syncedAt } = setup();
    const drained = sync.flushUntilIdle(50);
    await firstRequest;
    expect(await drained).toBe(false);
    expect(syncedAt('first')).toBeNull();
  });
});