Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

16.7 KB
Raw Blame
vi.mock('./tailcatIngress.js', () => ({ ensureTailcatIngress: vi.fn().mockResolvedValue(undefined) }));
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { EventEmitter } from 'node:events';
import {
  parseServeListenAddr,
  ensureServeKey,
  startServeProcess,
  ensureTailcatServe,
  getTailcatServeStatus,
  stopTailcatServe,
  retryTailcatServe,
  restoreServe,
  _resetLiveServeForTests,
  _liveServeForTests,
  DEFAULT_KEY_NAME,
  DEFAULT_SERVE_PORT,
} from './tailcatServe.js';

vi.mock('../lib/fileUtils.js', async (original) => ({
  ...(await original()),
  readJSONFile: vi.fn(),
  ensureDir: vi.fn().mockResolvedValue(undefined),
  atomicWrite: vi.fn().mockResolvedValue(undefined),
}));
import { instanceEvents } from './instanceEvents.js';
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';

vi.mock('../lib/bufferedSpawn.js', async (original) => ({
  ...(await original()),
  bufferedSpawn: vi.fn(),
}));
import { bufferedSpawn } from '../lib/bufferedSpawn.js';

// No installed CLI or package manager: exercise the real shared installation failure.
vi.mock('../lib/commandExists.js', () => ({ commandOutput: vi.fn().mockResolvedValue(null) }));
vi.mock('../lib/processEnv.js', async (original) => ({
  ...(await original()),
  findCommandOnPath: vi.fn().mockReturnValue(null),
}));

const EXAMPLE_TC = 'tcEXAMPLE' + 'C'.repeat(40);

function fakeChild() {
  const child = new EventEmitter();
  child.killed = false;
  child.stderr = new EventEmitter();
  child.stdout = new EventEmitter();
  child.kill = vi.fn(() => {
    child.killed = true;
    child.emit('exit', 0, null);
  });
  return child;
}

describe('tailcatServe helpers', () => {
  beforeEach(() => {
    _resetLiveServeForTests();
    vi.restoreAllMocks();
    vi.clearAllMocks();
    vi.spyOn(instanceEvents, 'emit');
    readJSONFile.mockResolvedValue({ version: 1, serve: null });
  });

  afterEach(() => {
    _resetLiveServeForTests();
    vi.useRealTimers();
  });

  it('surfaces shared installation failure without starting a tunnel', async () => {
    const startServe = vi.fn();
    await expect(ensureTailcatServe({ startServe })).rejects.toMatchObject({
      status: 503, code: 'TAILCAT_MISSING',
    });
    expect(startServe).not.toHaveBeenCalled();
    expect(await getTailcatServeStatus()).toMatchObject({ live: false });
  });

  it('parses --json listenAddr and rejects placeholders', () => {
    expect(parseServeListenAddr(JSON.stringify({ listenAddr: EXAMPLE_TC }))).toBe(EXAMPLE_TC);
    expect(parseServeListenAddr(`noise\n{"listenAddr":"${EXAMPLE_TC}"}\n`)).toBe(EXAMPLE_TC);
    expect(parseServeListenAddr(EXAMPLE_TC)).toBe(EXAMPLE_TC);
    expect(parseServeListenAddr('tcEXAMPLE…')).toBe(null);
    expect(parseServeListenAddr('')).toBe(null);
  });

  it('ensureServeKey treats an existing key as success', async () => {
    bufferedSpawn.mockResolvedValue({
      success: false,
      code: 1,
      timedOut: false,
      stderr: 'key already exists; use --force to overwrite\n',
      stdout: '',
    });
    const result = await ensureServeKey({ bin: '/usr/bin/tailcat', keyName: 'portos-api' });
    expect(result).toMatchObject({ created: false, keyName: 'portos-api' });
    expect(bufferedSpawn).toHaveBeenCalledWith(
      '/usr/bin/tailcat',
      ['genkey', '--key=portos-api'],
      expect.any(Object),
    );
  });

  it('startServeProcess resolves when stdout prints listenAddr JSON', async () => {
    const child = fakeChild();
    const spawnFn = vi.fn(() => {
      queueMicrotask(() => child.stdout.emit('data', `${JSON.stringify({ listenAddr: EXAMPLE_TC })}\n`));
      return child;
    });
    const started = await startServeProcess({
      bin: '/usr/bin/tailcat',
      localPort: DEFAULT_SERVE_PORT,
      keyName: 'portos-api',
      spawnFn,
      readyMs: 2_000,
      readFileFn: async () => { throw new Error('no file'); },
      mkdirFn: async () => {},
    });
    expect(started.tcAddress).toBe(EXAMPLE_TC);
    expect(started.localPort).toBe(DEFAULT_SERVE_PORT);
    expect(spawnFn).toHaveBeenCalledWith(
      '/usr/bin/tailcat',
      ['serve', '--verbose', '--full-address', '--json', '--key=portos-api', String(DEFAULT_SERVE_PORT)],
      expect.any(Object),
    );
  });

  it('ensureTailcatServe persists enabled config and returns copyable address', async () => {
    const child = fakeChild();
    let saved = null;
    atomicWrite.mockImplementation(async (_path, data) => { saved = data; });
    readJSONFile.mockImplementation(async () => saved || { version: 1, serve: null });

    const status = await ensureTailcatServe({
      ensureInstalled: async () => ({ bin: '/usr/bin/tailcat', installed: false }),
      primeDerpMap: async () => ({ primed: false }),
      ensureKey: async () => ({ created: true, keyName: DEFAULT_KEY_NAME }),
      startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: DEFAULT_KEY_NAME }),
    });

    expect(status.live).toBe(true);
    expect(status.enabled).toBe(true);
    expect(status.tcAddress).toBe(EXAMPLE_TC);
    expect(status.hasAddress).toBe(true);
    expect(status.tcAddressRedacted).not.toBe(EXAMPLE_TC);
    expect(status.tcAddressRedacted).toContain('…');
    expect(_liveServeForTests()?.child).toBe(child);
    expect(saved?.serve?.enabled).toBe(true);
    expect(saved?.serve?.tcAddress).toBe(EXAMPLE_TC);
    expect(instanceEvents.emit.mock.calls).toEqual([['tailcat:serve:changed'], ['tailcat:serve:changed']]);
  });

  it('records an unexpected exit without overwriting a later retry or stop', async () => {
    let saved = { version: 1, serve: null };
    readJSONFile.mockImplementation(async () => saved);
    atomicWrite.mockImplementation(async (_path, data) => { saved = data; });
    const child = fakeChild();
    const deps = {
      ensureInstalled: async () => ({ bin: '/example/tailcat' }),
      primeDerpMap: async () => ({}),
      ensureKey: async () => ({}),
      startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: DEFAULT_KEY_NAME }),
    };
    await ensureTailcatServe(deps);
    instanceEvents.emit.mockClear();
    child.emit('exit', 1, null);
    await vi.waitFor(() => expect(saved.serve.status).toBe('failed'));
    expect(await getTailcatServeStatus()).toMatchObject({ live: false, status: 'failed', enabled: true });
    expect(saved.serve.lastError).toContain('code=1');
    expect(instanceEvents.emit).toHaveBeenCalledWith('tailcat:serve:changed');

    const replacement = fakeChild();
    await retryTailcatServe({ ...deps, startServe: async () => ({ child: replacement, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: DEFAULT_KEY_NAME }) });
    child.emit('exit', 1, null);
    expect(await getTailcatServeStatus()).toMatchObject({ live: true, status: 'active' });
    await stopTailcatServe();
    replacement.emit('exit', 0, 'SIGTERM');
    expect(await getTailcatServeStatus()).toMatchObject({ live: false, status: 'stopped', enabled: false, lastError: null });
  });

  it('invalidates process loss even when recording the failure fails', async () => {
    let saved = { version: 1, serve: null };
    readJSONFile.mockImplementation(async () => saved);
    atomicWrite.mockImplementation(async (_path, data) => { saved = data; });
    const child = fakeChild();
    await ensureTailcatServe({
      ensureInstalled: async () => ({ bin: '/example/tailcat' }),
      primeDerpMap: async () => ({}),
      ensureKey: async () => ({}),
      startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: DEFAULT_KEY_NAME }),
    });
    atomicWrite.mockRejectedValueOnce(new Error('Example disk failure'));
    instanceEvents.emit.mockClear();
    child.emit('exit', 1, null);
    await vi.waitFor(() => expect(instanceEvents.emit).toHaveBeenCalledWith('tailcat:serve:changed'));
    expect(await getTailcatServeStatus()).toMatchObject({ live: false, status: 'stopped' });
  });

  it('stopTailcatServe disables restore-on-boot', async () => {
    const child = fakeChild();
    let saved = {
      version: 1,
      serve: {
        enabled: true,
        status: 'active',
        localPort: DEFAULT_SERVE_PORT,
        keyName: 'portos-api',
        tcAddress: EXAMPLE_TC,
        lastError: null,
        lastErrorAt: null,
        createdAt: '2026-01-01T00:00:00.000Z',
      },
    };
    readJSONFile.mockImplementation(async () => saved);
    atomicWrite.mockImplementation(async (_path, data) => { saved = data; });

    await ensureTailcatServe({
      ensureInstalled: async () => ({ bin: '/x', installed: false }),
      primeDerpMap: async () => ({}),
      ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
      startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
    });
    expect(_liveServeForTests()).not.toBe(null);

    const stopped = await stopTailcatServe({ disable: true });
    expect(stopped.live).toBe(false);
    expect(stopped.enabled).toBe(false);
    expect(stopped.status).toBe('stopped');
    expect(child.kill).toHaveBeenCalled();
    expect(_liveServeForTests()).toBe(null);
  });

  it('restoreServe starts when enabled and skips when disabled', async () => {
    const child = fakeChild();
    readJSONFile.mockResolvedValue({
      version: 1,
      serve: {
        enabled: true,
        status: 'active',
        localPort: DEFAULT_SERVE_PORT,
        keyName: 'portos-api',
        tcAddress: EXAMPLE_TC,
        lastError: null,
        lastErrorAt: null,
        createdAt: '2026-01-01T00:00:00.000Z',
      },
    });
    atomicWrite.mockResolvedValue(undefined);

    const ok = await restoreServe({
      ensureInstalled: async () => ({ bin: '/usr/bin/tailcat' }),
      primeDerpMap: async () => ({}),
      ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
      startServe: async () => ({ child, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
    });
    expect(ok).toEqual({ restored: true });
    expect(instanceEvents.emit).toHaveBeenCalledWith('tailcat:serve:changed');
    expect(_liveServeForTests()?.child).toBe(child);

    _resetLiveServeForTests();
    readJSONFile.mockResolvedValue({ version: 1, serve: { enabled: false, status: 'stopped', localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api', tcAddress: null } });
    const skipped = await restoreServe({
      ensureInstalled: async () => ({ bin: '/usr/bin/tailcat' }),
      startServe: async () => { throw new Error('should not run'); },
    });
    expect(skipped).toMatchObject({ restored: false, reason: 'disabled' });
  });

  it('retryTailcatServe kills a live child then restarts', async () => {
    const first = fakeChild();
    const second = fakeChild();
    let saved = {
      version: 1,
      serve: {
        enabled: true,
        status: 'failed',
        localPort: DEFAULT_SERVE_PORT,
        keyName: 'portos-api',
        tcAddress: EXAMPLE_TC,
        lastError: 'boom',
        lastErrorAt: '2026-01-01T00:00:00.000Z',
        createdAt: '2026-01-01T00:00:00.000Z',
      },
    };
    readJSONFile.mockImplementation(async () => saved);
    atomicWrite.mockImplementation(async (_path, data) => { saved = data; });

    // Seed a live child by ensuring once.
    await ensureTailcatServe({
      ensureInstalled: async () => ({ bin: '/x' }),
      primeDerpMap: async () => ({}),
      ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
      startServe: async () => ({ child: first, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
    });

    const status = await retryTailcatServe({
      ensureInstalled: async () => ({ bin: '/x' }),
      primeDerpMap: async () => ({}),
      ensureKey: async () => ({ created: false, keyName: 'portos-api' }),
      startServe: async () => ({ child: second, tcAddress: EXAMPLE_TC, localPort: DEFAULT_SERVE_PORT, keyName: 'portos-api' }),
    });
    expect(first.kill).toHaveBeenCalled();
    expect(status.live).toBe(true);
    expect(_liveServeForTests()?.child).toBe(second);
  });

  it('reports fragmented relay failures, recovery, expiry and replacement isolation through serve status', async () => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
    let saved = { version: 1, serve: null };
    readJSONFile.mockImplementation(async () => saved);
    atomicWrite.mockImplementation(async (_path, data) => { saved = data; });
    const children = [];
    const deps = {
      ensureInstalled: async () => ({ bin: '/example/tailcat' }),
      primeDerpMap: async () => ({}),
      ensureKey: async () => ({}),
      startServe: (options) => startServeProcess({
        ...options,
        mkdirFn: async () => {},
        readFileFn: async () => '',
        spawnFn: () => {
          const child = fakeChild();
          children.push(child);
          Promise.resolve().then(() => child.stdout.emit('data', `${JSON.stringify({ listenAddr: EXAMPLE_TC })}\n`));
          return child;
        },
      }),
    };
    expect(await ensureTailcatServe(deps)).toMatchObject({ live: true, relayStatus: 'unknown' });
    const child = children[0];
    instanceEvents.emit.mockClear();
    const writes = atomicWrite.mock.calls.length;
    const raw = `magicsock: derp.Recv(derp-301): ${EXAMPLE_TC} https://user:[email protected]:443 context deadline exceeded`;
    child.stderr.emit('data', raw.slice(0, 45));
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown' });
    child.stderr.emit('data', raw.slice(45) + '\n');
    const failed = await getTailcatServeStatus();
    expect(failed).toMatchObject({ live: true, status: 'active', relayStatus: 'degraded',
      relayError: 'Tailcat relay connection timed out.', relayObservedAt: '2026-01-01T00:00:00.000Z' });
    expect(failed.relayError).not.toMatch(/example-secret|relay.example|tcEX/);
    expect(instanceEvents.emit).toHaveBeenCalledWith('tailcat:serve:changed');
    expect(atomicWrite).toHaveBeenCalledTimes(writes);

    child.stderr.emit('data', 'derphttp.Client.Connect: connecting to derp-301 (example)\n');
    child.stderr.emit('data', 'magicsock: derp-302 connected; connGen=1\n');
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'degraded' });
    child.stderr.emit('data', 'magicsock: derp-301 connected; connGen=2\n');
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'connected', relayError: null });
    child.stderr.emit('data', 'magicsock: closing connection to derp-301 (conn-close), age 10s\n');
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'degraded' });
    await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown', relayError: null, relayObservedAt: null });

    child.stderr.emit('data', 'magicsock: derp-302 connected; connGen=3\n');
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'connected' });
    await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown' });

    // Oversized lines are dropped as a whole, not classified from a private suffix.
    child.stderr.emit('data', 'x'.repeat(5000));
    child.stderr.emit('data', raw + '\n');
    expect(await getTailcatServeStatus()).toMatchObject({ relayStatus: 'unknown' });
    child.stderr.emit('data', raw + '\n');
    await retryTailcatServe(deps);
    instanceEvents.emit.mockClear();
    child.stderr.emit('data', raw + '\n');
    expect(await getTailcatServeStatus()).toMatchObject({ live: true, relayStatus: 'unknown', relayError: null });
    expect(instanceEvents.emit).not.toHaveBeenCalled();
    children[1].stderr.emit('data', raw + '\n');
    await stopTailcatServe();
    instanceEvents.emit.mockClear();
    await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
    expect(await getTailcatServeStatus()).toMatchObject({ live: false, relayStatus: 'unknown', relayError: null });
    expect(instanceEvents.emit).not.toHaveBeenCalled();
  });

  it('getTailcatServeStatus never invents a live process', async () => {
    const status = await getTailcatServeStatus();
    expect(status).toMatchObject({
      enabled: false,
      live: false,
      localPort: DEFAULT_SERVE_PORT,
      keyName: DEFAULT_KEY_NAME,
      hasAddress: false,
      tcAddress: null,
    });
  });
});

it('rejects direct main-port serving before spawning or installing', async () => {
  const spawnFn = vi.fn();
  await expect(startServeProcess({ bin: 'tailcat', localPort: 5555, spawnFn })).rejects.toMatchObject({ code: 'TAILCAT_SERVE_BAD_PORT' });
  const ensureInstalled = vi.fn();
  await expect(ensureTailcatServe({ localPort: 5555, ensureInstalled })).rejects.toMatchObject({ code: 'TAILCAT_SERVE_BAD_PORT' });
  expect(spawnFn).not.toHaveBeenCalled();
  expect(ensureInstalled).not.toHaveBeenCalled();
});