Merge pull request #439

feat(remote): wake a sleeping host (Wake-on-LAN) from input, banner and native magic packet
This commit is contained in:
Ark0N
2026-09-19 12:18:18 +02:00
committed by GitHub
26 changed files with 4021 additions and 14 deletions
+149 -1
View File
@@ -55,6 +55,7 @@ vi.mock('../../src/remote-hosts.js', async (orig) => {
});
import { registerSessionRoutes } from '../../src/web/routes/session-routes.js';
import { RemoteWakeRegistry, REMOTE_WAKE_REQUEST_READY_TIMEOUT_MS } from '../../src/remote-wake.js';
import { resolveTerminalHistoryConfig } from '../../src/config/terminal-history.js';
interface LocalHarness {
@@ -62,6 +63,15 @@ interface LocalHarness {
ctx: MockRouteContext;
}
// Wake-on-LAN seam: the production registry opens a real TCP connection to the host
// and can run a real wake command, so every route registered here gets a fake one
// (the same seam `test/routes/session-remote-wake.test.ts` uses). Default: the host
// answers, so nothing ever wakes.
const wakeProbe = vi.fn(async () => true);
const wakeCommandRun = vi.fn(async () => true);
const wakeWaitUntilReady = vi.fn(async () => true);
let wakeRegistry: RemoteWakeRegistry;
/**
* Build a Fastify instance that mirrors production's uniform-envelope behavior
* (server.ts preSerialization hook) so the test wire format matches the contract:
@@ -108,7 +118,17 @@ describe('session-routes', () => {
let harness: LocalHarness;
beforeEach(async () => {
harness = await createEnvelopeHarness(registerSessionRoutes);
wakeProbe.mockReset().mockResolvedValue(true);
wakeCommandRun.mockReset().mockResolvedValue(true);
wakeWaitUntilReady.mockReset().mockResolvedValue(true);
wakeRegistry = new RemoteWakeRegistry({
probe: wakeProbe,
wake: wakeCommandRun,
waitUntilReady: wakeWaitUntilReady,
delay: async () => {},
log: () => {},
});
harness = await createEnvelopeHarness((app, ctx) => registerSessionRoutes(app, ctx, { remoteWake: wakeRegistry }));
// Reset remote store so tests start with empty hosts/cases and a passing tmux probe
remoteStore.hosts = [];
remoteStore.cases = [];
@@ -1990,6 +2010,134 @@ describe('session-routes', () => {
expect(JSON.parse(res.body)).toMatchObject({ success: false, errorCode: ApiErrorCode.OPERATION_FAILED });
});
describe('remote create/attach wakes a sleeping host (Wake-on-LAN)', () => {
const host = (extra: Record<string, unknown> = {}) => ({
id: 'hufflepuff',
label: 'Hufflepuff',
host: '192.168.50.137',
username: 'j',
wakeMac: '04:d9:f5:80:c6:58',
...extra,
});
const remoteCase = { name: 'hufflepuff-work', type: 'remote', hostId: 'hufflepuff', remotePath: '/home/j/work' };
const quickStart = () =>
harness.app.inject({
method: 'POST',
url: '/api/quick-start',
payload: { caseName: 'hufflepuff-work', mode: 'shell' },
});
it('wakes the host before the tmux probe when the user runs a remote case', async () => {
const startShell = vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
try {
remoteStore.hosts = [host()];
remoteStore.cases = [remoteCase];
wakeProbe.mockResolvedValue(false); // asleep
const res = await quickStart();
expect(res.statusCode).toBe(200);
expect(JSON.parse(res.body).success).toBe(true);
expect(wakeCommandRun).toHaveBeenCalledWith({ kind: 'mac', macs: [[4, 217, 245, 128, 198, 88]] });
// The request budget, not the 90 s session default: the reverse proxy would
// cut the request at 60 s while the session was still being built.
expect(wakeWaitUntilReady).toHaveBeenCalledWith(expect.objectContaining({ hostId: 'hufflepuff' }), {
timeoutMs: REMOTE_WAKE_REQUEST_READY_TIMEOUT_MS,
// The shutdown signal rides along so `WebServer.stop()` can end the poll.
signal: expect.any(AbortSignal),
});
} finally {
startShell.mockRestore();
}
});
it('does not wake a host that answers, and never probes a host without a wake target', async () => {
const startShell = vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
try {
remoteStore.hosts = [host()];
remoteStore.cases = [remoteCase];
// The fake probe answers `true` by default — a reachable host.
expect((await quickStart()).statusCode).toBe(200);
expect(wakeCommandRun).not.toHaveBeenCalled();
// No wake target at all: not even a probe, so hosts without WoL keep the
// exact behavior (and latency) they had before this feature.
wakeProbe.mockClear();
remoteStore.hosts = [host({ wakeMac: undefined })];
expect((await quickStart()).statusCode).toBe(200);
expect(wakeProbe).not.toHaveBeenCalled();
expect(wakeCommandRun).not.toHaveBeenCalled();
} finally {
startShell.mockRestore();
}
});
it('refuses the run when the host never comes back, and starts no session', async () => {
remoteStore.hosts = [host()];
remoteStore.cases = [remoteCase];
wakeProbe.mockResolvedValue(false);
wakeWaitUntilReady.mockResolvedValue(false);
const sessionsBefore = harness.ctx.sessions.size;
const res = await quickStart();
expect(res.statusCode).toBe(httpStatusForErrorCode(ApiErrorCode.OPERATION_FAILED));
expect(JSON.parse(res.body).error).toMatch(/did not come back after a wake-on-LAN request/);
// No half-created session: the failure is the answer, not a dead tab.
expect(harness.ctx.sessions.size).toBe(sessionsBefore);
});
it('blames the sleeping host, not tmux, when the host has no wake target', async () => {
remoteStore.hosts = [host({ wakeMac: undefined })];
remoteStore.cases = [remoteCase];
remoteStore.tmuxCheck = {
ok: false,
error: 'remote host 192.168.50.137 needs tmux installed for durable remote sessions',
};
wakeProbe.mockResolvedValue(false);
const res = await quickStart();
expect(res.statusCode).toBe(httpStatusForErrorCode(ApiErrorCode.OPERATION_FAILED));
expect(JSON.parse(res.body).error).toMatch(/has no wake-on-LAN target/);
});
it('keeps the tmux error when the host is up but tmux is really missing', async () => {
remoteStore.hosts = [host()];
remoteStore.cases = [remoteCase];
remoteStore.tmuxCheck = {
ok: false,
error: 'remote host 192.168.50.137 needs tmux installed for durable remote sessions',
};
// Probe answers `true`: the ssh failure is genuinely about tmux.
const res = await quickStart();
expect(JSON.parse(res.body).error).toMatch(/needs tmux installed/);
});
it('wakes the host when attaching to a discovered remote session', async () => {
const startInteractive = vi.spyOn(Session.prototype, 'startInteractive').mockResolvedValue(undefined);
const startShell = vi.spyOn(Session.prototype, 'startShell').mockResolvedValue(undefined);
try {
remoteStore.hosts = [host()];
wakeProbe.mockResolvedValue(false);
const res = await harness.app.inject({
method: 'POST',
url: '/api/sessions',
payload: { attachRemoteSession: { hostId: 'hufflepuff', remoteSessionName: 'codeman-abc12345' } },
});
expect(res.statusCode).toBe(200);
expect(wakeCommandRun).toHaveBeenCalledTimes(1);
} finally {
startInteractive.mockRestore();
startShell.mockRestore();
}
});
});
it('does not run local codex availability check for a remote codex case', async () => {
// A remote codex case must NOT be blocked by the LOCAL codex availability gate
// (the CLI runs on the remote host). Probe is stubbed ok in remoteStore.tmuxCheck.