diff --git a/src/main/computer/macos-native-provider-client.test.ts b/src/main/computer/macos-native-provider-client.test.ts index 7867cbe2e..6205764ee 100644 --- a/src/main/computer/macos-native-provider-client.test.ts +++ b/src/main/computer/macos-native-provider-client.test.ts @@ -53,6 +53,11 @@ class FakeSocket extends EventEmitter { end(): void { this.destroyed = true } + + destroy(): this { + this.destroyed = true + return this + } } async function loadClientModule() { @@ -127,4 +132,41 @@ describe('MacOSNativeProviderClient', () => { await expect(secondCall).resolves.toEqual(capabilities) }) + + it('starts a replacement socket after the active helper connection errors', async () => { + const { MacOSNativeProviderClient } = await loadClientModule() + const client = new MacOSNativeProviderClient() + + const firstCall = client.capabilities() + const firstRejection = expect(firstCall).rejects.toThrow('active helper failed') + await vi.waitFor(() => expect(sockets).toHaveLength(1)) + const firstSocket = sockets[0]! + const firstSocketDirectory = mkdtempSyncMock.mock.results[0]?.value as string + await vi.waitFor(() => expect(firstSocket.writes).toHaveLength(1)) + + firstSocket.emit('error', new Error('active helper failed')) + await firstRejection + expect(firstSocket.destroyed).toBe(true) + expect(rmSyncMock).toHaveBeenCalledWith(firstSocketDirectory, { + recursive: true, + force: true + }) + + const secondCall = client.capabilities() + await vi.waitFor(() => expect(sockets).toHaveLength(2)) + const secondSocket = sockets[1]! + await vi.waitFor(() => expect(secondSocket.writes).toHaveLength(1)) + const secondRequest = JSON.parse(secondSocket.writes[0]!) as { id: number } + + const capabilities = { + protocolVersion: 1, + supports: {} + } + secondSocket.emit( + 'data', + `${JSON.stringify({ id: secondRequest.id, ok: true, result: capabilities })}\n` + ) + + await expect(secondCall).resolves.toEqual(capabilities) + }) }) diff --git a/src/main/computer/macos-native-provider-client.ts b/src/main/computer/macos-native-provider-client.ts index f7d2eec83..c89554655 100644 --- a/src/main/computer/macos-native-provider-client.ts +++ b/src/main/computer/macos-native-provider-client.ts @@ -266,6 +266,14 @@ export class MacOSNativeProviderClient { if (this.socket !== socket) { return } + // Why: an active transport error makes the helper socket unreliable; the + // next request must reconnect instead of reusing a broken socket. + this.socket = null + this.socketBuffer = '' + if (!socket.destroyed) { + socket.destroy() + } + this.cleanupSocketDirectory() this.rejectPending(new RuntimeClientError('accessibility_error', error.message)) } private cleanupSocketDirectory(): void {