|
| 1 | +import http from 'http'; |
| 2 | +import { EventEmitter } from 'events'; |
| 3 | +import { afterEach, describe, expect, it } from 'vitest'; |
| 4 | +import { createDefaultRemoteDaemonConfig, type RemoteDaemonConfig } from '../../../shared/types/remoteDaemon'; |
| 5 | +import { hashRemoteDaemonToken } from './auth'; |
| 6 | +import { PaneCommandRegistry } from './commandRegistry'; |
| 7 | +import { PaneRemoteTransportController } from './remoteTransportController'; |
| 8 | + |
| 9 | +interface TestEventStream { |
| 10 | + close(): void; |
| 11 | + nextEvent(timeoutMs?: number): Promise<{ event: string | null; data: string[] }>; |
| 12 | +} |
| 13 | + |
| 14 | +class ConfigManagerStub extends EventEmitter { |
| 15 | + private remoteDaemon: RemoteDaemonConfig; |
| 16 | + |
| 17 | + constructor(initialConfig: RemoteDaemonConfig) { |
| 18 | + super(); |
| 19 | + this.remoteDaemon = initialConfig; |
| 20 | + } |
| 21 | + |
| 22 | + getConfig(): { remoteDaemon: RemoteDaemonConfig } { |
| 23 | + return { remoteDaemon: this.remoteDaemon }; |
| 24 | + } |
| 25 | + |
| 26 | + async updateRemoteDaemonConfig(remoteDaemon: RemoteDaemonConfig): Promise<void> { |
| 27 | + this.remoteDaemon = remoteDaemon; |
| 28 | + this.emit('config-updated', { remoteDaemon }); |
| 29 | + } |
| 30 | +} |
| 31 | + |
| 32 | +const activeControllers: PaneRemoteTransportController[] = []; |
| 33 | +const activeRequests = new Set<http.ClientRequest>(); |
| 34 | + |
| 35 | +afterEach(async () => { |
| 36 | + for (const request of activeRequests) { |
| 37 | + request.destroy(); |
| 38 | + } |
| 39 | + activeRequests.clear(); |
| 40 | + |
| 41 | + for (const controller of activeControllers.splice(0)) { |
| 42 | + await controller.stopWatchingAndShutdown(); |
| 43 | + } |
| 44 | +}); |
| 45 | + |
| 46 | +function createEnabledRemoteConfig(overrides?: Partial<RemoteDaemonConfig['host']['config']>): RemoteDaemonConfig { |
| 47 | + const config = createDefaultRemoteDaemonConfig(); |
| 48 | + config.host.config = { |
| 49 | + ...config.host.config, |
| 50 | + enabled: true, |
| 51 | + listenHost: '127.0.0.1', |
| 52 | + listenPort: 0, |
| 53 | + ...overrides, |
| 54 | + }; |
| 55 | + config.host.clients = [{ |
| 56 | + id: 'client-1', |
| 57 | + label: 'Mac mini', |
| 58 | + createdAt: new Date('2026-05-14T00:00:00.000Z').toISOString(), |
| 59 | + tokenHash: hashRemoteDaemonToken('secret-token'), |
| 60 | + }]; |
| 61 | + return config; |
| 62 | +} |
| 63 | + |
| 64 | +async function openEventStream(server: NonNullable<ReturnType<PaneRemoteTransportController['getServer']>>, token: string): Promise<TestEventStream> { |
| 65 | + const address = server.getAddress(); |
| 66 | + if (!address) { |
| 67 | + throw new Error('Remote HTTP API server is not listening'); |
| 68 | + } |
| 69 | + |
| 70 | + return new Promise((resolve, reject) => { |
| 71 | + const request = http.request({ |
| 72 | + host: address.host, |
| 73 | + port: address.port, |
| 74 | + path: '/events', |
| 75 | + method: 'GET', |
| 76 | + headers: { |
| 77 | + Authorization: `Bearer ${token}`, |
| 78 | + }, |
| 79 | + }); |
| 80 | + |
| 81 | + activeRequests.add(request); |
| 82 | + request.once('error', reject); |
| 83 | + request.on('response', (response) => { |
| 84 | + const queuedEvents: Array<{ event: string | null; data: string[] }> = []; |
| 85 | + const waiters: Array<(event: { event: string | null; data: string[] }) => void> = []; |
| 86 | + let buffer = ''; |
| 87 | + |
| 88 | + response.on('data', (chunk) => { |
| 89 | + buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8'); |
| 90 | + |
| 91 | + let boundaryIndex = buffer.indexOf('\n\n'); |
| 92 | + while (boundaryIndex !== -1) { |
| 93 | + const rawEvent = buffer.slice(0, boundaryIndex); |
| 94 | + buffer = buffer.slice(boundaryIndex + 2); |
| 95 | + |
| 96 | + const parsedEvent = parseSseEvent(rawEvent); |
| 97 | + if (parsedEvent) { |
| 98 | + const waiter = waiters.shift(); |
| 99 | + if (waiter) { |
| 100 | + waiter(parsedEvent); |
| 101 | + } else { |
| 102 | + queuedEvents.push(parsedEvent); |
| 103 | + } |
| 104 | + } |
| 105 | + |
| 106 | + boundaryIndex = buffer.indexOf('\n\n'); |
| 107 | + } |
| 108 | + }); |
| 109 | + |
| 110 | + resolve({ |
| 111 | + close() { |
| 112 | + request.destroy(); |
| 113 | + }, |
| 114 | + nextEvent(timeoutMs = 1000) { |
| 115 | + if (queuedEvents.length > 0) { |
| 116 | + return Promise.resolve(queuedEvents.shift() as { event: string | null; data: string[] }); |
| 117 | + } |
| 118 | + |
| 119 | + return new Promise((eventResolve, eventReject) => { |
| 120 | + const timeout = setTimeout(() => { |
| 121 | + eventReject(new Error('Timed out waiting for SSE event')); |
| 122 | + }, timeoutMs); |
| 123 | + |
| 124 | + waiters.push((event) => { |
| 125 | + clearTimeout(timeout); |
| 126 | + eventResolve(event); |
| 127 | + }); |
| 128 | + }); |
| 129 | + }, |
| 130 | + }); |
| 131 | + }); |
| 132 | + |
| 133 | + request.end(); |
| 134 | + }); |
| 135 | +} |
| 136 | + |
| 137 | +function parseSseEvent(rawEvent: string): { event: string | null; data: string[] } | null { |
| 138 | + const lines = rawEvent.split('\n'); |
| 139 | + let event: string | null = null; |
| 140 | + const data: string[] = []; |
| 141 | + |
| 142 | + for (const line of lines) { |
| 143 | + if (line.startsWith('event: ')) { |
| 144 | + event = line.slice('event: '.length); |
| 145 | + continue; |
| 146 | + } |
| 147 | + |
| 148 | + if (line.startsWith('data: ')) { |
| 149 | + data.push(line.slice('data: '.length)); |
| 150 | + } |
| 151 | + } |
| 152 | + |
| 153 | + if (!event && data.length === 0) { |
| 154 | + return null; |
| 155 | + } |
| 156 | + |
| 157 | + return { event, data }; |
| 158 | +} |
| 159 | + |
| 160 | +async function waitFor(predicate: () => boolean, timeoutMs = 1500): Promise<void> { |
| 161 | + const startedAt = Date.now(); |
| 162 | + while (!predicate()) { |
| 163 | + if (Date.now() - startedAt > timeoutMs) { |
| 164 | + throw new Error('Timed out waiting for condition'); |
| 165 | + } |
| 166 | + |
| 167 | + await new Promise((resolve) => setTimeout(resolve, 10)); |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +describe('PaneRemoteTransportController', () => { |
| 172 | + it('starts and stops remote HTTP transport on config updates while keeping a stable event sink', async () => { |
| 173 | + const registry = new PaneCommandRegistry(); |
| 174 | + const configManager = new ConfigManagerStub(createDefaultRemoteDaemonConfig()); |
| 175 | + const controller = new PaneRemoteTransportController(registry, configManager as never); |
| 176 | + activeControllers.push(controller); |
| 177 | + controller.startWatchingConfig(); |
| 178 | + |
| 179 | + const daemonEventSink = controller.getEventSink(); |
| 180 | + await controller.syncToConfig(); |
| 181 | + expect(controller.getServer()).toBeNull(); |
| 182 | + |
| 183 | + await configManager.updateRemoteDaemonConfig(createEnabledRemoteConfig()); |
| 184 | + await waitFor(() => controller.getServer() !== null); |
| 185 | + |
| 186 | + const server = controller.getServer(); |
| 187 | + if (!server) { |
| 188 | + throw new Error('Remote HTTP API server did not start'); |
| 189 | + } |
| 190 | + |
| 191 | + const stream = await openEventStream(server, 'secret-token'); |
| 192 | + await stream.nextEvent(); |
| 193 | + |
| 194 | + daemonEventSink.send('session:created', { id: 'session-1' }); |
| 195 | + |
| 196 | + const daemonEvent = await stream.nextEvent(); |
| 197 | + expect(daemonEvent.event).toBe('daemon-event'); |
| 198 | + expect(JSON.parse(daemonEvent.data.join('\n'))).toEqual({ |
| 199 | + channel: 'session:created', |
| 200 | + args: [{ id: 'session-1' }], |
| 201 | + timestamp: expect.any(String), |
| 202 | + }); |
| 203 | + |
| 204 | + stream.close(); |
| 205 | + await configManager.updateRemoteDaemonConfig(createDefaultRemoteDaemonConfig()); |
| 206 | + await waitFor(() => controller.getServer() === null); |
| 207 | + }); |
| 208 | + |
| 209 | + it('stops the active remote HTTP transport when config changes to an invalid non-loopback bind', async () => { |
| 210 | + const registry = new PaneCommandRegistry(); |
| 211 | + const configManager = new ConfigManagerStub(createEnabledRemoteConfig()); |
| 212 | + const controller = new PaneRemoteTransportController(registry, configManager as never); |
| 213 | + activeControllers.push(controller); |
| 214 | + controller.startWatchingConfig(); |
| 215 | + |
| 216 | + await controller.syncToConfig(); |
| 217 | + expect(controller.getServer()).not.toBeNull(); |
| 218 | + |
| 219 | + await configManager.updateRemoteDaemonConfig(createEnabledRemoteConfig({ listenHost: '0.0.0.0' })); |
| 220 | + await waitFor(() => controller.getServer() === null); |
| 221 | + }); |
| 222 | +}); |
0 commit comments