Files
Codeman/test/tmux-restart-recovery.test.ts
T
Codeman maintainer 5deb0d4a4c fix(review): harden + wire remote-host SSH cases end-to-end (PR #145)
- UI: add the missing data-tab="case-remote" tab button; dispatch it through
  submitCaseModal()/switchCaseModalTab() to linkRemoteCase() (was dead code).
- Restore: restoreMuxSessions() now passes remote (muxSession.remote ??
  savedState.remote) into the Session constructor, so remote metadata round-trips
  on restart instead of reattaching from a local cwd / respawning LOCAL / being
  erased from state.json. Recovery tests added.
- Run flows: runClaude()/runShell() route remote cases through /api/quick-start
  (POST /api/sessions stat-validates workingDir locally); run*() skip the
  /api/*/status pre-check and omit inert config/env for remote cases.
- Quick-start: resolve the remote case BEFORE the local CLI availability gates and
  skip isCodex/Gemini/OpenCodeAvailable() when remote; REJECT
  envOverrides/effort/codex/gemini/openCode config for remote (they don't cross
  ssh) instead of silently dropping them.
- Injection: reject $, backtick, $( in remotePath + identityFile at the schema
  layer (they survive shellescape into the bash -c launch double-quote layer).
  Regression tests for $(...) and backtick payloads added.
- Remote socket/name: launch on a DEDICATED -L codeman-remote socket under a
  codeman-ssh-<id> name that fails a remote Codeman's SAFE_MUX_NAME_PATTERN, so a
  remote instance can't adopt the session; scope tmux set-options per-session
  (never -g) so they don't mutate other sessions.
- Kill: best-effort ssh 'tmux -L codeman-remote kill-session' on remote session
  kill (fire-and-forget, never blocks/throws the local kill) so the remote agent
  isn't orphaned forever.
- Probe: wire checkRemoteTmuxAvailable() into POST /api/quick-start (structured
  OPERATION_FAILED) and as courtesy validation in remote-link; add a default
  -o ConnectTimeout=10 to buildSshConnectionArgs (overridable via extraSshOptions).
- Command default: remote claude default is now
  'exec claude --dangerously-skip-permissions' (per-host override stays the escape
  hatch), mirroring local non-interactive semantics.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 19:49:58 +02:00

195 lines
5.8 KiB
TypeScript

/**
* @fileoverview Unit tests for tmux session recovery after server restart.
*
* Tests verify the test mode safety behavior of TmuxManager:
* - In test mode (VITEST=1), reconcileSessions never runs real tmux commands
* - All registered sessions are reported as alive
* - No real sessions are discovered
* - No state files are read/written
*
* SAFETY: No real tmux sessions are created, killed, or interacted with.
*
* Port: N/A (no server needed)
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { TmuxManager } from '../src/tmux-manager.js';
import { execSync } from 'node:child_process';
// Mock child_process
vi.mock('node:child_process', async () => {
const actual = await vi.importActual('node:child_process');
return {
...actual,
execSync: vi.fn(),
spawn: vi.fn(() => ({
unref: vi.fn(),
on: vi.fn(),
pid: 12345,
})),
};
});
// Mock fs to avoid reading/writing real state files
vi.mock('node:fs', async () => {
const actual = await vi.importActual('node:fs');
return {
...actual,
existsSync: vi.fn().mockReturnValue(false),
readFileSync: vi.fn(),
mkdirSync: vi.fn(),
writeFile: vi.fn((_path: string, _data: string, cb: (err: Error | null) => void) => cb(null)),
writeFileSync: vi.fn(),
};
});
describe('TmuxManager restart recovery (test mode safety)', () => {
let manager: TmuxManager;
const mockedExecSync = vi.mocked(execSync);
beforeEach(() => {
vi.clearAllMocks();
manager = new TmuxManager();
});
afterEach(() => {
manager.destroy();
});
it('should report all registered sessions as alive in test mode', async () => {
manager.registerSession({
sessionId: 'test-recovery-1',
muxName: 'codeman-de51ecaf',
pid: 1,
createdAt: Date.now(),
workingDir: '/tmp',
mode: 'claude',
attached: false,
name: 'Recovery Test',
respawnConfig: {
enabled: true,
idleTimeoutMs: 10000,
updatePrompt: 'continue',
interStepDelayMs: 2000,
sendClear: false,
sendInit: true,
},
});
const result = await manager.reconcileSessions();
expect(result.alive).toContain('test-recovery-1');
expect(result.dead).toHaveLength(0);
expect(result.discovered).toHaveLength(0);
// Session metadata should be preserved
const recovered = manager.getSession('test-recovery-1');
expect(recovered).toBeDefined();
expect(recovered!.name).toBe('Recovery Test');
expect(recovered!.respawnConfig?.enabled).toBe(true);
});
it('should never discover real sessions in test mode', async () => {
const result = await manager.reconcileSessions();
expect(result.discovered).toHaveLength(0);
});
it('preserves remote SSH metadata across reconcile (mux-sessions.json round-trip source)', async () => {
manager.registerSession({
sessionId: 'remote-recovery-1',
muxName: 'codeman-de51ecaf',
pid: 1,
createdAt: Date.now(),
workingDir: '/home/ubuntu/work',
mode: 'claude',
attached: false,
name: 'Remote Recovery',
remote: {
hostId: 'gpu-box',
label: 'GPU Box',
host: '10.0.0.42',
username: 'ubuntu',
remotePath: '/home/ubuntu/work',
},
});
const result = await manager.reconcileSessions();
expect(result.alive).toContain('remote-recovery-1');
// restoreMuxSessions() reads MuxSession.remote off exactly this map to rebuild
// the recovered Session — if it were dropped here the session would respawn LOCAL.
const recovered = manager.getSession('remote-recovery-1');
expect(recovered?.remote).toMatchObject({ hostId: 'gpu-box', host: '10.0.0.42', remotePath: '/home/ubuntu/work' });
});
it('should not execute any tmux commands in test mode', async () => {
manager.registerSession({
sessionId: 'alive-session',
muxName: 'codeman-a11eeaaa',
pid: 1,
createdAt: Date.now(),
workingDir: '/tmp',
mode: 'claude',
attached: false,
});
mockedExecSync.mockClear();
await manager.reconcileSessions();
// Verify no tmux commands were executed
const tmuxCalls = mockedExecSync.mock.calls.filter(([cmd]) => typeof cmd === 'string' && cmd.includes('tmux'));
expect(tmuxCalls).toHaveLength(0);
});
it('should handle multiple sessions correctly in test mode', async () => {
manager.registerSession({
sessionId: 'session-1',
muxName: 'codeman-a11eeaaa',
pid: 1,
createdAt: Date.now(),
workingDir: '/tmp',
mode: 'claude',
attached: false,
name: 'Session 1',
});
manager.registerSession({
sessionId: 'session-2',
muxName: 'codeman-b22ffbbb',
pid: 2,
createdAt: Date.now(),
workingDir: '/tmp',
mode: 'shell',
attached: false,
name: 'Session 2',
});
const result = await manager.reconcileSessions();
expect(result.alive).toContain('session-1');
expect(result.alive).toContain('session-2');
expect(result.alive).toHaveLength(2);
expect(result.dead).toHaveLength(0);
expect(result.discovered).toHaveLength(0);
});
it('should safely remove sessions via killSession in test mode', async () => {
manager.registerSession({
sessionId: 'kill-me',
muxName: 'codeman-deadbeef',
pid: 99999,
createdAt: Date.now(),
workingDir: '/tmp',
mode: 'claude',
attached: false,
});
mockedExecSync.mockClear();
const result = await manager.killSession('kill-me');
expect(result).toBe(true);
expect(manager.getSession('kill-me')).toBeUndefined();
// Verify no real kill commands were executed
const killCalls = mockedExecSync.mock.calls.filter(([cmd]) => typeof cmd === 'string' && cmd.includes('kill'));
expect(killCalls).toHaveLength(0);
});
});