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

9.2 KB
Raw Blame
import { describe, it, expect, beforeEach, afterEach, spyOn } from 'bun:test';
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import {
  buildDetachedWorkerDaemonSpawn,
  canStartProcessInOwnUserScope,
  isUserBusReachable,
  isUserManagerScope,
} from '../../src/services/infrastructure/ProcessManager.js';
import { logger } from '../../src/utils/logger.js';
import { buildSpawnSyncInvocation } from '../../src/shared/spawn.js';

/**
 * #5240 — Windows worker daemon launch under behaviour-blocking AV.
 *
 * The daemon used to launch as `powershell -NoProfile -WindowStyle Hidden
 * -EncodedCommand <base64 Start-Process>`. That command line is the
 * fileless-malware fingerprint Kaspersky (PDM:Exploit.Win32.Generic) and
 * BluePex killed, so the launcher's node.exe was blocked and the worker never
 * started (#3831, #5240).
 *
 * The contract now: a plain detached spawnHidden on win32 as well — no shell,
 * no base64, no powershell — with spawnHidden forcing windowsHide so the
 * daemon gets no console window (#3521).
 */
describe('Windows #5240 — worker daemon launch contract', () => {
  it('spawns the runtime directly on Windows, never through PowerShell', () => {
    const runtimePath = String.raw`C:\Users\Test User\.bun\bin\bun.exe`;
    const scriptPath = String.raw`C:\Users\Test User\.claude\plugins\marketplaces\thedotmack\plugin\scripts\worker-service.cjs`;

    const plan = buildDetachedWorkerDaemonSpawn(runtimePath, scriptPath, {}, 'win32');

    expect(plan.command).toBe(runtimePath);
    // Direct argv: a spaced script path stays one argument, so the old
    // PowerShell -ArgumentList quoting workaround (#3195) cannot recur.
    expect(plan.args).toEqual(['--no-install', scriptPath, '--daemon']);
    // Detached so the daemon outlives the hook or MCP server that launched it.
    expect(plan.options.detached).toBe(true);
    expect(plan.options.stdio).toBe('ignore');
  });

  it('never uses setsid on Windows even when /usr/bin/setsid exists', () => {
    const plan = buildDetachedWorkerDaemonSpawn('bun.exe', 'worker-service.cjs', {}, 'win32', true);

    expect(plan.command).toBe('bun.exe');
    expect(plan.args).toEqual(['--no-install', 'worker-service.cjs', '--daemon']);
  });

  it('uses setsid on POSIX when it is available', () => {
    const plan = buildDetachedWorkerDaemonSpawn(
      '/home/me/.bun/bin/bun',
      '/plugin/worker-service.cjs',
      {},
      'linux',
      true,
      false,
    );

    expect(plan.command).toBe('/usr/bin/setsid');
    expect(plan.args).toEqual(['/home/me/.bun/bin/bun', '--no-install', '/plugin/worker-service.cjs', '--daemon']);
  });

  it('falls back to launching the runtime directly when setsid is absent', () => {
    const plan = buildDetachedWorkerDaemonSpawn(
      '/home/me/.bun/bin/bun',
      '/plugin/worker-service.cjs',
      {},
      'linux',
      false,
      false,
    );

    expect(plan.command).toBe('/home/me/.bun/bin/bun');
    expect(plan.args).toEqual(['--no-install', '/plugin/worker-service.cjs', '--daemon']);
  });

  // #6686: setsid leaves the daemon in the caller's cgroup, so a host that
  // stops the session's systemd scope (T3 Code) SIGTERMed the shared worker.
  it('starts the daemon in its own systemd scope when the caller runs in a user-manager scope', () => {
    const plan = buildDetachedWorkerDaemonSpawn(
      '/home/me/.bun/bin/bun',
      '/plugin/worker-service.cjs',
      {},
      'linux',
      true,
      true,
    );

    expect(plan.command).toBe('/usr/bin/setsid');
    expect(plan.args).toEqual([
      '/usr/bin/systemd-run', '--user', '--scope', '--collect', '--',
      '/home/me/.bun/bin/bun', '--no-install', '/plugin/worker-service.cjs', '--daemon',
    ]);
  });

  it('starts the daemon through systemd-run without setsid when setsid is absent', () => {
    const plan = buildDetachedWorkerDaemonSpawn('/home/me/.bun/bin/bun', '/plugin/worker-service.cjs', {}, 'linux', false, true);

    expect(plan.command).toBe('/usr/bin/systemd-run');
    expect(plan.args).toEqual([
      '--user', '--scope', '--collect', '--',
      '/home/me/.bun/bin/bun', '--no-install', '/plugin/worker-service.cjs', '--daemon',
    ]);
  });

  it('never uses systemd-run outside Linux', () => {
    const plan = buildDetachedWorkerDaemonSpawn('/opt/bun', '/plugin/worker-service.cjs', {}, 'darwin', true, true);

    expect(plan.command).toBe('/usr/bin/setsid');
    expect(plan.args).toEqual(['/opt/bun', '--no-install', '/plugin/worker-service.cjs', '--daemon']);
  });

  it('recognizes a transient scope of the user manager, and nothing else, in /proc/self/cgroup', () => {
    // The T3 Code session scope from #6686.
    expect(isUserManagerScope(
      '0::/user.slice/user-1000.slice/[email protected]/app.slice/app-t3code.slice/app-t3code-agents.slice/app-t3code-agents-1.slice/t3code-claude-d0695cd0.scope\n',
    )).toBe(true);
    // A login session (SSH, TTY) belongs to the system manager.
    expect(isUserManagerScope('0::/user.slice/user-1000.slice/session-3.scope\n')).toBe(false);
    // A user service is already its own unit.
    expect(isUserManagerScope('0::/user.slice/user-1000.slice/[email protected]/app.slice/claude-mem-worker.service\n')).toBe(false);
    // Containers and cgroup v1 hosts.
    expect(isUserManagerScope('0::/\n')).toBe(false);
    expect(isUserManagerScope('1:name=systemd:/user.slice/user-1000.slice/[email protected]/app.slice/x.scope\n')).toBe(false);
  });

  // Without the bus socket, systemd-run exits before the daemon starts, so the
  // worker would never come up instead of only dying with the session.
  describe('user bus check', () => {
    let runtimeDir: string;

    beforeEach(() => {
      runtimeDir = mkdtempSync(join(tmpdir(), 'xdg-runtime-'));
    });

    afterEach(() => {
      rmSync(runtimeDir, { recursive: true, force: true });
    });

    it('reports the user bus reachable when XDG_RUNTIME_DIR holds the bus socket', () => {
      writeFileSync(join(runtimeDir, 'bus'), '');

      expect(isUserBusReachable({ XDG_RUNTIME_DIR: runtimeDir })).toBe(true);
    });

    it('reports the user bus unreachable when XDG_RUNTIME_DIR has no bus socket', () => {
      expect(isUserBusReachable({ XDG_RUNTIME_DIR: runtimeDir })).toBe(false);
    });

    it('reports the user bus unreachable when XDG_RUNTIME_DIR is unset', () => {
      expect(isUserBusReachable({})).toBe(false);
    });
  });

  // The bus socket can exist while systemd-run still fails. The real launch is
  // detached with stderr discarded, so without a trial launch the worker would
  // never start and nothing would say why. These run real executables standing
  // in for systemd-run.
  describe.skipIf(process.platform === 'win32')('systemd-run trial launch', () => {
    let binDir: string;
    let warnSpy: ReturnType<typeof spyOn>;

    const fakeSystemdRun = (name: string, body: string): string => {
      const scriptPath = join(binDir, name);
      writeFileSync(scriptPath, `#!/bin/sh\n${body}\n`);
      chmodSync(scriptPath, 0o755);
      return scriptPath;
    };

    beforeEach(() => {
      binDir = mkdtempSync(join(tmpdir(), 'fake-systemd-run-'));
      warnSpy = spyOn(logger, 'warn').mockImplementation(() => {});
    });

    afterEach(() => {
      warnSpy.mockRestore();
      rmSync(binDir, { recursive: true, force: true });
    });

    it('logs the failure and falls back when systemd-run exits non-zero', () => {
      const systemdRun = fakeSystemdRun('systemd-run', 'echo "Failed to start transient scope unit: Access denied" >&2\nexit 1');

      expect(canStartProcessInOwnUserScope(process.execPath, {}, systemdRun)).toBe(false);
      expect(warnSpy).toHaveBeenCalledTimes(1);
      const [, message, context] = warnSpy.mock.calls[0] as [string, string, Record<string, unknown>];
      expect(message).toContain('starting the worker without its own systemd scope');
      expect(context.exitStatus).toBe(1);
      expect(context.stderr).toBe('Failed to start transient scope unit: Access denied');
    });

    it('logs and falls back when systemd-run hangs past the timeout', () => {
      const systemdRun = fakeSystemdRun('systemd-run', 'exec sleep 10');

      expect(canStartProcessInOwnUserScope(process.execPath, {}, systemdRun, 200)).toBe(false);
      expect(warnSpy).toHaveBeenCalledTimes(1);
    });

    it('logs and falls back when systemd-run cannot be executed', () => {
      expect(canStartProcessInOwnUserScope(process.execPath, {}, join(binDir, 'missing-systemd-run'))).toBe(false);
      expect(warnSpy).toHaveBeenCalledTimes(1);
    });

    it('uses the scope when systemd-run runs the command after --', () => {
      // Like `systemd-run --scope`: drop its own flags, exec the command in place.
      const systemdRun = fakeSystemdRun('systemd-run', 'while [ "$1" != "--" ]; do shift; done\nshift\nexec "$@"');

      expect(canStartProcessInOwnUserScope(process.execPath, {}, systemdRun)).toBe(true);
      expect(warnSpy).not.toHaveBeenCalled();
    });
  });

  it('buildSpawnSyncInvocation forces windowsHide even when options try to disable it', () => {
    const invocation = buildSpawnSyncInvocation(
      String.raw`C:\Tools\bin\tool.exe`,
      ['run'],
      { encoding: 'utf-8', stdio: 'ignore', windowsHide: false },
      'win32',
    );
    expect(invocation.options.windowsHide).toBe(true);
  });
});