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

18.2 KB
Raw Blame
import { describe, it, expect, mock, beforeEach, afterEach, spyOn } from 'bun:test';
import { logger } from '../../src/utils/logger.js';

import { Server } from '../../src/services/server/Server.js';
import type { ServerOptions } from '../../src/services/server/Server.js';
import { listenOnEphemeralPort } from '../helpers/ephemeral-port.js';

let loggerSpies: ReturnType<typeof spyOn>[] = [];

describe('Server', () => {
  let server: Server;
  let mockOptions: ServerOptions;

  beforeEach(() => {
    loggerSpies = [
      spyOn(logger, 'info').mockImplementation(() => {}),
      spyOn(logger, 'debug').mockImplementation(() => {}),
      spyOn(logger, 'warn').mockImplementation(() => {}),
      spyOn(logger, 'error').mockImplementation(() => {}),
    ];

    mockOptions = {
      getInitializationComplete: () => true,
      getMcpReady: () => true,
      onShutdown: mock(() => Promise.resolve()),
      onRestart: mock(() => Promise.resolve()),
      workerPath: '/test/worker-service.cjs',
      getAiStatus: () => ({
        provider: 'claude',
        authMethod: 'cli',
        lastInteraction: null,
      }),
    };
  });

  afterEach(async () => {
    loggerSpies.forEach(spy => spy.mockRestore());
    if (server && server.getHttpServer()) {
      try {
        await server.close();
      } catch {
        // Ignore errors on cleanup
      }
    }
    mock.restore();
  });

  describe('constructor', () => {
    it('should register pre-body-parser routes before normal middleware', async () => {
      server = new Server({
        ...mockOptions,
        preBodyParserRoutes: [{
          setupRoutes(app) {
            app.post('/api/auth/*splat', (req, res) => {
              res.json({
                bodyParsed: req.body !== undefined,
              });
            });
          },
        }],
      });

      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/auth/session`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Origin: 'http://localhost:37777',
        },
        body: JSON.stringify({ ok: true }),
      });

      expect(response.status).toBe(200);
      expect(response.headers.get('access-control-allow-origin')).toBe('http://localhost:37777');

      const body = await response.json();
      expect(body.bodyParsed).toBe(false);
    });
  });

  describe('listen', () => {
    it('should reject if port is already in use', async () => {
      server = new Server(mockOptions);
      const server2 = new Server(mockOptions);

      const testPort = await listenOnEphemeralPort(server);

      await expect(server2.listen(testPort, '127.0.0.1')).rejects.toThrow();

      // #3380 — a failed bind must never leave a non-listening handle behind
      // for graceful shutdown to trip on.
      expect(server2.getHttpServer()).toBeNull();
    });
  });

  describe('close', () => {
    it('should handle close when server not started', async () => {
      server = new Server(mockOptions);

      await expect(server.close()).resolves.toBeUndefined();
    });

    it('should allow starting a new server on same port after close', async () => {
      server = new Server(mockOptions);
      const testPort = await listenOnEphemeralPort(server);

      try {
        await server.close();
      } catch (e: any) {
        if (e.code !== 'ERR_SERVER_NOT_RUNNING') {
          throw e;
        }
      }

      await new Promise(resolve => setTimeout(resolve, 100));

      const server2 = new Server(mockOptions);
      await server2.listen(testPort, '127.0.0.1');

      expect(server2.getHttpServer()!.listening).toBe(true);

      try {
        await server2.close();
      } catch {
        // Ignore cleanup errors
      }
    });
  });

  describe('getHttpServer', () => {
    it('should return null before listen', () => {
      server = new Server(mockOptions);

      expect(server.getHttpServer()).toBeNull();
    });

    it('should return http.Server after listen', async () => {
      server = new Server(mockOptions);
      await listenOnEphemeralPort(server);

      const httpServer = server.getHttpServer();
      expect(httpServer).not.toBeNull();
      expect(httpServer!.listening).toBe(true);
    });
  });

  describe('health endpoint', () => {
    it('should return healthy status, readiness, platform and pid', async () => {
      server = new Server(mockOptions);
      const testPort = await listenOnEphemeralPort(server);
      const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
      expect(response.status).toBe(200);
      const body = await response.json();
      expect(body.status).toBe('ok');
      expect(body.initialized).toBe(true);
      expect(body.mcpReady).toBe(true);
      expect(typeof body.platform).toBe('string');
      expect(body.pid).toBeDefined();
      expect(typeof body.pid).toBe('number');
    });

    it('should reflect initialization state changes', async () => {
      let isInitialized = false;
      const dynamicOptions: ServerOptions = {
        getInitializationComplete: () => isInitialized,
        getMcpReady: () => true,
        onShutdown: mock(() => Promise.resolve()),
        onRestart: mock(() => Promise.resolve()),
        workerPath: '/test/worker-service.cjs',
        getAiStatus: () => ({ provider: 'claude', authMethod: 'cli', lastInteraction: null }),
      };

      server = new Server(dynamicOptions);
      const testPort = await listenOnEphemeralPort(server);

      let response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
      let body = await response.json();
      expect(body.initialized).toBe(false);

      isInitialized = true;

      response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
      body = await response.json();
      expect(body.initialized).toBe(true);
    });

    it('should return degraded health when BullMQ Redis health is errored', async () => {
      server = new Server({
        ...mockOptions,
        getQueueHealth: () => ({
          engine: 'bullmq',
          redis: {
            status: 'error',
            mode: 'external',
            host: '127.0.0.1',
            port: 6379,
            prefix: 'test_prefix',
            error: 'connection refused',
          },
        }),
      });
      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
      const body = await response.json();

      expect(response.status).toBe(503);
      expect(body.status).toBe('degraded');
      expect(body.queue.engine).toBe('bullmq');
      // A prober sees that Redis is why the answer is 503, but not the queue
      // backend's address, key namespace or error text; the loopback-only
      // doctor route keeps those (below).
      expect(body.queue.redis).toEqual({ status: 'error' });
      expect(body.queue.redis.host).toBeUndefined();
      expect(body.queue.redis.port).toBeUndefined();
      expect(body.queue.redis.prefix).toBeUndefined();
      expect(JSON.stringify(body)).not.toContain('connection refused');
    });

    it('keeps error text that can quote the queue address off the probe', async () => {
      server = new Server({
        ...mockOptions,
        getQueueHealth: () => ({
          engine: 'bullmq',
          redis: { status: 'ok', mode: 'external', host: 'valkey.internal', port: 6379, prefix: 'claude_mem' },
          lanes: [{
            kind: 'observation',
            name: 'observation',
            waiting: 2,
            active: 0,
            completed: 5,
            failed: 0,
            delayed: 0,
            stalled: 0,
            unavailable: true,
            unavailableReason: 'connect ECONNREFUSED valkey.internal:6379',
          }],
        }),
      });
      const testPort = await listenOnEphemeralPort(server);

      const probe = await (await fetch(`http://127.0.0.1:${testPort}/api/health`)).json();
      expect(probe.queue.lanes[0]).toMatchObject({ kind: 'observation', waiting: 2, unavailable: true });
      expect(probe.queue.lanes[0].unavailableReason).toBeUndefined();
      expect(JSON.stringify(probe)).not.toContain('valkey.internal');

      const doctor = await (await fetch(`http://127.0.0.1:${testPort}/api/admin/doctor`)).json();
      expect(doctor.health.queue.lanes[0].unavailableReason).toBe('connect ECONNREFUSED valkey.internal:6379');
    });

    it('publishes the dependency label, not a recorded message that quotes a path', async () => {
      const dependencyHealth = {
        degraded: true,
        statuses: [{
          dependency: 'claude_cli' as const,
          kind: 'setup_required' as const,
          message: 'Claude executable not found at /home/node/.local/bin/claude (CLAUDE_CODE_PATH)',
          remediation: 'Install or update Claude Code CLI, then restart claude-mem.',
          executablePath: '/home/node/.local/bin/claude',
          executableFingerprint: 'abc123',
          recordedAtMs: 1,
        }],
      };
      server = new Server({ ...mockOptions, getDependencyHealth: () => dependencyHealth });
      const testPort = await listenOnEphemeralPort(server);

      const probe = await (await fetch(`http://127.0.0.1:${testPort}/api/health`)).json();
      expect(probe.dependencies.degraded).toBe(true);
      expect(probe.dependencies.statuses[0]).toMatchObject({
        dependency: 'claude_cli',
        kind: 'setup_required',
        message: 'Claude CLI setup required',
      });
      expect(JSON.stringify(probe)).not.toContain('/home/node');

      // `claude-mem doctor` reads the recorded message here for its remediation row.
      const doctor = await (await fetch(`http://127.0.0.1:${testPort}/api/admin/doctor`)).json();
      expect(doctor.health.dependencies.statuses[0].message).toBe(dependencyHealth.statuses[0].message);
    });

    it('answers the unauthenticated probe with state, not deployment internals', async () => {
      server = new Server({
        ...mockOptions,
        getQueueHealth: () => ({
          engine: 'bullmq',
          redis: { status: 'ok', mode: 'external', host: 'valkey', port: 6379, prefix: 'claude_mem' },
        }),
        getDependencyHealth: () => ({
          degraded: false,
          statuses: [{
            dependency: 'claude_cli',
            kind: 'setup_required',
            message: 'not found',
            executablePath: '/home/node/.local/bin/claude',
            executableFingerprint: 'abc123',
            recordedAtMs: 1,
          }],
        }),
      });
      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
      const body = await response.json();

      expect(response.status).toBe(200);
      // What a probe reads stays.
      expect(body.status).toBe('ok');
      expect(body.queue.engine).toBe('bullmq');
      expect(body.dependencies.degraded).toBe(false);
      expect(body.dependencies.statuses[0].message).toBe('Claude CLI setup required');
      expect(body.queue.redis).toEqual({ status: 'ok' });
      // Deployment internals do not: the auth method, the queue's address and
      // key namespace, the install path, and each resolved executable.
      expect(body.workerPath).toBeUndefined();
      expect(body.ai.authMethod).toBeUndefined();
      expect(JSON.stringify(body)).not.toContain('valkey');
      expect(body.dependencies.statuses[0].executablePath).toBeUndefined();
      expect(body.dependencies.statuses[0].executableFingerprint).toBeUndefined();
    });

    it('keeps the worker path and queue address on the loopback-only doctor route', async () => {
      server = new Server({
        ...mockOptions,
        getQueueHealth: () => ({
          engine: 'bullmq',
          redis: {
            status: 'error',
            mode: 'external',
            host: '127.0.0.1',
            port: 6379,
            prefix: 'test_prefix',
            error: 'connection refused',
          },
        }),
      });
      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/admin/doctor`);
      const body = await response.json();

      expect(response.status).toBe(200);
      expect(body.health.workerPath).toBe('/test/worker-service.cjs');
      expect(body.health.queue.redis).toMatchObject({
        status: 'error',
        host: '127.0.0.1',
        port: 6379,
        prefix: 'test_prefix',
      });
    });
  });

  describe('readiness endpoint', () => {
    it('should return 200 when initialized', async () => {
      server = new Server(mockOptions);
      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/readiness`);

      expect(response.status).toBe(200);

      const body = await response.json();
      expect(body.status).toBe('ready');
      expect(body.mcpReady).toBe(true);
    });

    it('should return 503 when not initialized', async () => {
      const uninitializedOptions: ServerOptions = {
        getInitializationComplete: () => false,
        getMcpReady: () => false,
        onShutdown: mock(() => Promise.resolve()),
        onRestart: mock(() => Promise.resolve()),
        workerPath: '/test/worker-service.cjs',
        getAiStatus: () => ({ provider: 'claude', authMethod: 'cli', lastInteraction: null }),
      };

      server = new Server(uninitializedOptions);
      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/readiness`);

      expect(response.status).toBe(503);

      const body = await response.json();
      expect(body.status).toBe('initializing');
      expect(body.message).toContain('initializing');
    });
  });

  describe('version endpoint', () => {
    it('should return 200 with version', async () => {
      server = new Server(mockOptions);
      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/version`);

      expect(response.status).toBe(200);

      const body = await response.json();
      expect(body.version).toBeDefined();
      expect(typeof body.version).toBe('string');
    });
  });

  describe('404 handling', () => {
    it('should return 404 for unknown routes after finalizeRoutes', async () => {
      server = new Server(mockOptions);
      server.finalizeRoutes();

      const testPort = await listenOnEphemeralPort(server);

      const response = await fetch(`http://127.0.0.1:${testPort}/api/nonexistent`);

      expect(response.status).toBe(404);

      const body = await response.json();
      expect(body.error).toBe('NotFound');
    });

    // A route mounted after the terminal 404 handler could never be reached.
    it('refuses to register routes after finalizeRoutes', () => {
      server = new Server(mockOptions);
      server.finalizeRoutes();
      class LateRoutes { setupRoutes(): void {} }
      expect(() => server.registerRoutes(new LateRoutes())).toThrow(/LateRoutes after finalizeRoutes/);
    });

    it('refuses a second finalizeRoutes call', () => {
      server = new Server(mockOptions);
      expect(server.routesFinalized).toBe(false);
      server.finalizeRoutes();
      expect(server.routesFinalized).toBe(true);
      expect(() => server.finalizeRoutes()).toThrow(/already called/);
    });
  });

  describe('request activity (idle exit)', () => {
    const until = async (condition: () => boolean): Promise<void> => {
      const deadline = Date.now() + 5_000;
      while (!condition() && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 10));
    };

    it('counts an open request until its response finishes, and settles it exactly once', async () => {
      server = new Server(mockOptions);
      let finishHeldRequest!: () => void;
      const heldRequestMayFinish = new Promise<void>(resolve => { finishHeldRequest = resolve; });
      server.registerRoutes({
        setupRoutes(app) {
          app.get('/test/held', async (_req, res) => {
            res.write('started;');
            await heldRequestMayFinish;
            res.end('done');
          });
        },
      });
      const testPort = await listenOnEphemeralPort(server);
      expect(server.getInFlightRequestCount()).toBe(0);
      expect(server.getLastRequestAt()).toBeNull();

      const response = await fetch(`http://127.0.0.1:${testPort}/test/held`);
      expect(server.getInFlightRequestCount()).toBe(1);
      const startedAt = server.getLastRequestAt();
      expect(startedAt).not.toBeNull();

      finishHeldRequest();
      expect(await response.text()).toBe('started;done');
      await until(() => server.getInFlightRequestCount() === 0);
      // 'finish', then 'close', then the socket's 'close' may all follow: one decrement, never below 0.
      await new Promise(resolve => setTimeout(resolve, 50));
      expect(server.getInFlightRequestCount()).toBe(0);
      expect(server.getLastRequestAt()!).toBeGreaterThanOrEqual(startedAt!);
    });

    it('settles a streaming request when its client disconnects, like a closed viewer tab', async () => {
      server = new Server(mockOptions);
      server.registerRoutes({
        setupRoutes(app) {
          app.get('/test/stream', (_req, res) => {
            res.setHeader('Content-Type', 'text/event-stream');
            res.flushHeaders();
            res.write(': ping\n\n'); // never ends, like the viewer's /stream
          });
        },
      });
      const testPort = await listenOnEphemeralPort(server);
      const controller = new AbortController();
      const response = await fetch(`http://127.0.0.1:${testPort}/test/stream`, { signal: controller.signal });
      expect(response.status).toBe(200);
      expect(server.getInFlightRequestCount()).toBe(1);

      controller.abort();
      await until(() => server.getInFlightRequestCount() === 0);
      expect(server.getInFlightRequestCount()).toBe(0);
    });

    it('settles every request on a reused keep-alive connection', async () => {
      server = new Server(mockOptions);
      const testPort = await listenOnEphemeralPort(server);
      for (let request = 0; request < 3; request++) {
        const response = await fetch(`http://127.0.0.1:${testPort}/api/health`);
        expect(response.status).toBe(200);
        await response.text();
      }
      await until(() => server.getInFlightRequestCount() === 0);
      expect(server.getInFlightRequestCount()).toBe(0);
      expect(server.getLastRequestAt()).not.toBeNull();
    });
  });
});