// MachineState and MachineConnection (WIN-8.14): what MachinesTests.swift checks of a machine's // live state, plus the Windows relay's probe verdicts. import { afterEach, describe, expect, it, vi } from 'vitest'; import type { Request, Response } from '../protocol'; import type { HealthProbe, Machine } from '../model/machine'; import type { MachineConnectionState } from '../model/sidebarItem'; import { MachineConnection, WAITING_FOR_NETWORK, type MachineBackend } from '../services/machines'; import type { NetworkEvent } from '../model/machineConnectionPolicy'; import type { NetworkMonitor } from '../services/networkMonitor'; import { MemoryStorage } from '../model/sidebarFixtures'; import { LiveMachineState, type MachineConnectionLike, type MachineStateOwner, isUserDisconnected, } from './machineState'; import type { ProjectState } from './projectState'; const MACHINE: Machine = { id: 'm1', name: 'studio', sshHost: 'studio-mac' }; const RUNNING: MachineConnectionState = { kind: 'connected', daemon: { kind: 'running' } }; const STOPPED: MachineConnectionState = { kind: 'connected', daemon: { kind: 'stopped' } }; function inventory(roots: string[]): Response { return { type: 'inventory', observed_at: '', project_root: null, complete: true, summary: { projects: roots.length, agents: 0, worktrees: 0 } as never, projects: roots.map((root) => ({ project_root: root, name: root, available: true, error: null, counts: {} as never, })), agents: [], worktrees: [], }; } class FakeDaemon { roots: string[] = []; requests: Request[] = []; initReply: Response = { type: 'init_result', created: true }; send = (request: Request): Promise => { this.requests.push(request); switch (request.type) { case 'inventory': return Promise.resolve(inventory([...this.roots])); case 'init': if (this.initReply.type === 'init_result') this.roots.push(request.project_root); return Promise.resolve(this.initReply); case 'remove_project': this.roots = this.roots.filter((root) => root !== request.project_root); return Promise.resolve({ type: 'project_removed', project_root: request.project_root, } as Response); default: return Promise.resolve({ type: 'error', code: 'UNSUPPORTED', message: request.type }); } }; } class FakeConnection implements MachineConnectionLike { connects = 0; disconnects = 0; startError: string | null = null; onState: (state: MachineConnectionState) => void = () => {}; connect() { this.connects += 1; } disconnect() { this.disconnects += 1; } refreshNow() {} startDaemon() { return Promise.resolve(this.startError); } } function owner(): MachineStateOwner & { followed: Set; active: string | null } { const followed = new Set(); const self = { registry: null, followed, active: null as string | null, setDaemonError: () => {}, projectState: () => null, setActiveProjectRoot: () => {}, setPendingSelectAgentId: () => {}, setPendingSelectWorktreeId: () => {}, machineChanged: () => {}, followProject: (project: ProjectState) => followed.add(project), unfollowProject: (project: ProjectState) => followed.delete(project), initializeActiveProjectIfNeeded: (root: string) => { self.active ??= root; }, }; return self; } function setup() { const daemon = new FakeDaemon(); const connection = new FakeConnection(); const storage = new MemoryStorage(); const appState = owner(); const subscriptions: string[] = []; const machine = new LiveMachineState({ machine: MACHINE, owner: appState, storage, makeClient: () => ({ send: daemon.send }), makeConnection: (_machine, onState) => { connection.onState = onState; return connection; }, projectEnvironment: { startSubscriptions: (root, machineId) => { subscriptions.push(`${String(machineId)}:${root}`); return Promise.resolve(); }, stopSubscriptions: () => Promise.resolve(true), sleep: () => new Promise(() => {}), log: () => {}, }, resumeDelayMs: () => 0, now: () => clock.now, }); return { machine, daemon, connection, storage, appState, subscriptions }; } const clock = { now: 1_000_000 }; const live: LiveMachineState[] = []; afterEach(() => { for (const machine of live.splice(0)) machine.disconnect(); }); async function settle() { for (let i = 0; i < 5; i++) await Promise.resolve(); await new Promise((resolve) => setTimeout(resolve, 0)); } describe('LiveMachineState', () => { it('given a running daemon, should list its projects and follow them on the machine', async () => { const t = setup(); live.push(t.machine); t.daemon.roots = ['/home/me/app', '/home/me/site']; t.machine.connect(); await settle(); expect(t.connection.connects).toBe(1); expect(t.machine.snapshot().statusText).toBe('Disconnected'); t.connection.onState({ kind: 'connecting' }); expect(t.machine.statusText).toBe('Connecting…'); t.connection.onState(RUNNING); await settle(); expect(t.machine.projects.map((p) => p.projectRoot)).toEqual(['/home/me/app', '/home/me/site']); expect(t.machine.projects.every((p) => p.machineId === 'm1')).toBe(true); expect(t.machine.projects[0]?.projectId).toBe('machine:m1:/home/me/app'); expect(t.machine.hasLoadedProjects).toBe(true); expect(t.machine.statusText).toBe('2 projects'); expect(t.subscriptions).toEqual(['m1:/home/me/app', 'm1:/home/me/site']); expect(t.appState.followed.size).toBe(2); const snapshot = t.machine.snapshot(); expect(snapshot.projects.map((p) => p.projectId)).toEqual([ 'machine:m1:/home/me/app', 'machine:m1:/home/me/site', ]); }); it('given a stopped daemon, should drop its projects; offline keeps them', async () => { const t = setup(); live.push(t.machine); t.daemon.roots = ['/srv/app']; t.machine.connect(); t.connection.onState(RUNNING); await settle(); t.connection.onState({ kind: 'offline', reason: 'ssh: timeout' }); expect(t.machine.projects).toHaveLength(1); expect(t.machine.snapshot().statusText).toBe('Offline'); t.connection.onState(STOPPED); expect(t.machine.projects).toHaveLength(0); expect(t.appState.followed.size).toBe(0); expect(t.machine.statusText).toBe('Daemon stopped'); }); it('given open project, should register the folder and list it under the machine', async () => { const t = setup(); live.push(t.machine); t.machine.connect(); t.connection.onState(RUNNING); await settle(); await t.machine.openProject('/home/me/new'); expect(t.daemon.requests).toContainEqual({ type: 'init', project_root: '/home/me/new' }); expect(t.machine.projects.map((p) => p.projectRoot)).toEqual(['/home/me/new']); expect(t.appState.active).toBe('machine:m1:/home/me/new'); t.daemon.initReply = { type: 'error', code: 'project_root_not_allowed', message: 'too broad' }; await expect(t.machine.openProject('/home/me')).rejects.toThrow('too broad'); }); it('given hide and remove, should hide on this PC or remove from the machine', async () => { const t = setup(); live.push(t.machine); t.daemon.roots = ['/a', '/b']; t.machine.connect(); t.connection.onState(RUNNING); await settle(); t.machine.hideProject('/a'); expect(t.machine.projects.map((p) => p.projectRoot)).toEqual(['/b']); expect(t.machine.hiddenProjectCount).toBe(1); await t.machine.refreshProjects(); expect(t.machine.projects.map((p) => p.projectRoot)).toEqual(['/b']); t.machine.showHiddenProjects(); await settle(); expect(t.machine.projects.map((p) => p.projectRoot)).toEqual(['/a', '/b']); await t.machine.removeProject('/b', true); expect(t.daemon.requests).toContainEqual({ type: 'remove_project', project_root: '/b', suspend_agents: true, }); expect(t.machine.projects.map((p) => p.projectRoot)).toEqual(['/a']); }); it('given start daemon failing, should report it as the action error', async () => { const t = setup(); live.push(t.machine); t.connection.startError = 'ssh exited with status 1'; t.machine.startDaemon(); expect(t.machine.isStartingDaemon).toBe(true); await settle(); expect(t.machine.isStartingDaemon).toBe(false); expect(t.machine.actionError).toBe( 'Could not start the daemon on studio: ssh exited with status 1', ); t.machine.dismissError(); expect(t.machine.actionError).toBeNull(); }); it('given drops and recoveries, should keep a connection log', async () => { const t = setup(); live.push(t.machine); t.machine.connect(); clock.now = 1_000; t.connection.onState(RUNNING); expect(t.machine.connectionLog).toEqual([]); clock.now = 2_000; t.connection.onState({ kind: 'offline', reason: 'Connection closed by 10.0.0.5 port 22', cause: 'server_refused', }); clock.now = 3_000; // Still down for the same cause: the same drop. t.connection.onState({ kind: 'offline', reason: 'again', cause: 'server_refused' }); clock.now = 6_500; t.connection.onState(RUNNING); expect(t.machine.connectionLog).toEqual([ { at: 2_000, cause: 'server_refused', message: 'Connection closed by 10.0.0.5 port 22', recoveredAfterMs: 4_500, }, ]); await settle(); }); it('given a reconnect, should start the project refresh after the resume jitter', async () => { const daemon = new FakeDaemon(); daemon.roots = ['/srv/app']; let onState: (state: MachineConnectionState) => void = () => {}; const machine = new LiveMachineState({ machine: MACHINE, owner: owner(), storage: new MemoryStorage(), makeClient: () => ({ send: daemon.send }), makeConnection: (_machine, report) => { onState = report; return new FakeConnection(); }, projectEnvironment: { startSubscriptions: () => Promise.resolve(), stopSubscriptions: () => Promise.resolve(true), sleep: () => new Promise(() => {}), log: () => {}, }, resumeDelayMs: () => 40, }); live.push(machine); const inventories = () => daemon.requests.filter((r) => r.type === 'inventory').length; machine.connect(); onState(RUNNING); await settle(); expect(inventories()).toBe(0); await new Promise((resolve) => setTimeout(resolve, 80)); expect(inventories()).toBe(1); // Going offline before the jitter ran cancels it. onState({ kind: 'offline', reason: 'x' }); onState(RUNNING); onState({ kind: 'offline', reason: 'y' }); await new Promise((resolve) => setTimeout(resolve, 80)); expect(inventories()).toBe(1); }); it('given an explicit disconnect, should stay disconnected at the next launch', async () => { const t = setup(); live.push(t.machine); t.machine.connect(); await settle(); t.machine.disconnect({ remember: true }); expect(t.connection.disconnects).toBe(1); expect(isUserDisconnected('m1', t.storage)).toBe(true); // Reports in flight from the closed connection do not reopen it. t.connection.onState(RUNNING); expect(t.machine.state).toEqual({ kind: 'disconnected' }); t.machine.connect(); expect(isUserDisconnected('m1', t.storage)).toBe(false); }); }); class FakeNetwork implements NetworkMonitor { isOnline = true; private readonly listeners = new Set<(event: NetworkEvent) => void>(); get listening(): number { return this.listeners.size; } subscribe(listener: (event: NetworkEvent) => void): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } emit(event: NetworkEvent): void { for (const listener of this.listeners) listener(event); } } describe('MachineConnection', () => { function connection(probes: HealthProbe[], options: { random?: () => number } = {}) { const states: MachineConnectionState[] = []; const delays: number[] = []; const gate: boolean[] = []; let probeCount = 0; let suspect: (() => void) | null = null; let wake: (() => void) | null = null; const now = { ms: 0 }; const backend: MachineBackend = { probe: () => { probeCount += 1; return Promise.resolve(probes.shift() ?? { kind: 'running' }); }, startDaemon: () => Promise.resolve(null), setReachable: (_id, reachable) => { gate.push(reachable); return Promise.resolve(); }, onSuspect: (_id, listener) => { suspect = listener; return () => { suspect = null; }; }, }; const network = new FakeNetwork(); const subject = new MachineConnection( MACHINE, (state) => { states.push(state); }, { backend, network, random: options.random ?? (() => 1), now: () => now.ms, sleep: (ms, signal) => { delays.push(ms); return new Promise((resolve) => { wake = resolve; signal.addEventListener('abort', () => { resolve(); }); }); }, }, ); const step = async () => { await settle(); const next = wake; wake = null; next?.(); await settle(); }; return { subject, states, delays, gate, network, now, step, probes: () => probeCount, suspect: () => { suspect?.(); }, }; } it('given relay verdicts, should report connecting, then each state, and back off offline', async () => { const offline: HealthProbe = { kind: 'offline', reason: 'kex_exchange_identification: Connection closed by remote host', cause: 'server_refused', summary: 'The server refused the login.', }; const c = connection([offline, offline, { kind: 'stopped' }, { kind: 'running' }]); c.subject.connect(); await c.step(); await c.step(); await c.step(); await settle(); expect(c.states).toEqual([{ kind: 'connecting' }, offline, STOPPED, RUNNING]); expect(c.delays.slice(0, 4)).toEqual([1_000, 2_000, 10_000, 10_000]); c.subject.disconnect(); expect(c.states.at(-1)).toEqual({ kind: 'disconnected' }); }); it('given consecutive offline probes, should wait 1, 2, 4, 8, then 15 s with equal jitter', async () => { const offline: HealthProbe = { kind: 'offline', reason: 'ssh: timed out', cause: 'network' }; const full = connection(Array(7).fill(offline)); full.subject.connect(); for (let i = 0; i < 6; i++) await full.step(); expect(full.delays.slice(0, 6)).toEqual([1_000, 2_000, 4_000, 8_000, 15_000, 15_000]); full.subject.disconnect(); const half = connection(Array(3).fill(offline), { random: () => 0 }); half.subject.connect(); for (let i = 0; i < 2; i++) await half.step(); expect(half.delays.slice(0, 3)).toEqual([500, 1_000, 2_000]); half.subject.disconnect(); }); it('given the machine reachable, should open the backend gate before reporting it', async () => { const c = connection([ { kind: 'running' }, { kind: 'offline', reason: 'x', cause: 'network' }, { kind: 'running' }, ]); c.subject.connect(); await settle(); // Connecting closes the gate (whatever a reloaded page left), running opens it first. expect(c.gate).toEqual([false, true]); expect(c.states).toEqual([{ kind: 'connecting' }, RUNNING]); await c.step(); expect(c.gate).toEqual([false, true, false]); await c.step(); expect(c.gate).toEqual([false, true, false, true]); c.subject.disconnect(); expect(c.gate.at(-1)).toBe(false); }); it('given a network change, should reset the backoff and probe at once', async () => { const offline: HealthProbe = { kind: 'offline', reason: 'x', cause: 'network' }; const c = connection([offline, offline, offline, offline]); c.subject.connect(); await c.step(); await c.step(); await settle(); expect(c.delays).toEqual([1_000, 2_000, 4_000]); expect(c.probes()).toBe(3); // Sleeping 4 s: a network change wakes it now, and the backoff starts over. c.network.emit({ kind: 'trigger', trigger: 'network-change' }); await settle(); expect(c.probes()).toBe(4); expect(c.delays.at(-1)).toBe(1_000); c.subject.disconnect(); expect(c.network.listening).toBe(0); }); it('given a network change during a probe, should probe again at once with the backoff reset', async () => { const offline: HealthProbe = { kind: 'offline', reason: 'x', cause: 'network' }; const pending: ((probe: HealthProbe) => void)[] = []; const delays: number[] = []; const network = new FakeNetwork(); const subject = new MachineConnection(MACHINE, () => {}, { backend: { probe: () => new Promise((resolve) => { pending.push(resolve); }), startDaemon: () => Promise.resolve(null), }, network, random: () => 1, now: () => 0, sleep: (ms, signal) => { delays.push(ms); return new Promise((resolve) => { signal.addEventListener('abort', () => { resolve(); }); }); }, }); subject.connect(); await settle(); // Two failures: the backoff is at 2 s. pending.shift()?.(offline); await settle(); subject.refreshNow(); await settle(); pending.shift()?.(offline); await settle(); expect(delays).toEqual([1_000, 2_000]); subject.refreshNow(); await settle(); // The network changes while the third probe is in flight. network.emit({ kind: 'trigger', trigger: 'network-change' }); pending.shift()?.(offline); await settle(); // No 4 s pause: the next probe is already out. expect(delays).toEqual([1_000, 2_000]); expect(pending.length).toBe(1); pending.shift()?.(offline); await settle(); // Paced from a reset backoff (second failure since the change), not the sixth. expect(delays).toEqual([1_000, 2_000, 2_000]); subject.disconnect(); }); it('given focus right after a probe, should not probe again', async () => { const c = connection([{ kind: 'running' }]); c.subject.connect(); await settle(); expect(c.probes()).toBe(1); c.now.ms = 500; c.network.emit({ kind: 'trigger', trigger: 'focus' }); await settle(); expect(c.probes()).toBe(1); c.now.ms = 5_000; c.network.emit({ kind: 'trigger', trigger: 'foreground' }); await settle(); expect(c.probes()).toBe(2); c.subject.disconnect(); }); it('given no network, should wait for it without probing', async () => { const c = connection([]); c.network.isOnline = false; c.subject.connect(); await settle(); expect(c.probes()).toBe(0); expect(c.states.at(-1)).toEqual(WAITING_FOR_NETWORK); // A missed `online` event: the periodic re-check still probes nothing while offline. await c.step(); expect(c.probes()).toBe(0); c.network.isOnline = true; c.network.emit({ kind: 'trigger', trigger: 'online' }); await settle(); expect(c.probes()).toBe(1); expect(c.states.at(-1)).toEqual(RUNNING); c.network.isOnline = false; c.network.emit({ kind: 'offline' }); await settle(); expect(c.states.at(-1)).toEqual(WAITING_FOR_NETWORK); expect(c.gate.at(-1)).toBe(false); c.subject.disconnect(); }); it('given a failing remote stream while connected, should probe now', async () => { const c = connection([{ kind: 'running' }, { kind: 'running' }]); c.subject.connect(); await settle(); expect(c.probes()).toBe(1); c.suspect(); await settle(); expect(c.probes()).toBe(2); c.subject.disconnect(); }); it('given failed probes, should keep the last state until three in a row', async () => { const c = connection([ { kind: 'running' }, { kind: 'failed', reason: 'x' }, { kind: 'busy' }, { kind: 'failed', reason: 'x' }, { kind: 'failed', reason: 'x' }, ]); c.subject.connect(); for (let i = 0; i < 5; i++) await c.step(); expect(c.states.slice(0, 3)).toEqual([{ kind: 'connecting' }, RUNNING, STOPPED]); expect(c.delays.slice(0, 5)).toEqual([10_000, 2_000, 2_000, 2_000, 10_000]); c.subject.disconnect(); }); it('given a probe that throws, should count it as a failure', async () => { const backend: MachineBackend = { probe: vi.fn(() => Promise.reject(new Error('invoke failed'))), startDaemon: () => Promise.resolve('no ssh'), }; const states: MachineConnectionState[] = []; const subject = new MachineConnection(MACHINE, (s) => states.push(s), { backend, network: new FakeNetwork(), sleep: () => new Promise(() => {}), }); subject.connect(); await settle(); expect(states).toEqual([{ kind: 'connecting' }]); await expect(subject.startDaemon()).resolves.toBe('no ssh'); subject.disconnect(); }); });