A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
[RSI] Persistent SupervisorLink for cross-worker requests (#2242)
Seth Kartenf87021bf2de3
diff --git a/packages/coding-agent/.changes/eng-6097-supervisor-link.md b/packages/coding-agent/.changes/eng-6097-supervisor-link.mdnew file mode 100644index 0000000000..63fa629b41--- /dev/null+++ b/packages/coding-agent/.changes/eng-6097-supervisor-link.md@@ -0,0 +1 @@+- Added a persistent supervisor connection for daemon workers: cross-worker requests (agent messages, roster reads, root-session creation, renames) now multiplex over one `SupervisorLink` instead of opening a fresh supervisor connection per call. Requests are never retried in-flight because daemon commands are not idempotent.diff --git a/packages/coding-agent/src/modes/daemon/daemon-mode.ts b/packages/coding-agent/src/modes/daemon/daemon-mode.tsindex 47e301d16d..c1dc74e997 100644--- a/packages/coding-agent/src/modes/daemon/daemon-mode.ts+++ b/packages/coding-agent/src/modes/daemon/daemon-mode.ts@@ -143,7 +143,6 @@ import {workerRosterEntryFromSummary,} from "./agent-roster.js";import { createCompactAssistantDelta } from "./compact-session-stream.js";-import { DaemonClient } from "./daemon-client.js";import { filterClientEnv, withClientEnv } from "./daemon-client-env.js";import { deserializeDaemonError, serializeDaemonError } from "./daemon-errors.js";import { bindActiveSessionState } from "./daemon-extension-binding.js";@@ -238,6 +237,7 @@ import {SNAPSHOT_TARGET_CHUNK_BYTES,type SnapshotTranscriptChunkSource,} from "./snapshot-transcript-cache.js";+import { SupervisorLink } from "./supervisor-link.js";import { WorkerRecoveryJournal } from "./worker-recovery-journal.js";export interface DaemonModeOptions {@@ -735,6 +735,15 @@ export class AgentDaemon {return raw ? normalizeSocketPath(raw) : undefined;}+ /** Persistent supervisor connection for cross-worker requests; one link per daemon process. */+ private supervisorLinkInstance?: SupervisorLink;+ private supervisorLink(): SupervisorLink | undefined {+ const supervisorSocketPath = this.supervisorSocketPathFromEnv();+ if (!supervisorSocketPath) return undefined;+ this.supervisorLinkInstance ??= new SupervisorLink({ socketPath: supervisorSocketPath });+ return this.supervisorLinkInstance;+ }+private startSupervisorMonitor(): void {const supervisorSocketPath = this.supervisorSocketPathFromEnv();if (!this.options.worker || !supervisorSocketPath) {@@ -2765,16 +2774,14 @@ export class AgentDaemon {parentState: ActiveSessionState,options: CreateRlmRootSessionOptions,): Promise<RlmCreateSessionResult> {- const supervisorSocketPath = this.supervisorSocketPathFromEnv();- if (!this.options.worker || !supervisorSocketPath) {+ const link = this.supervisorLink();+ if (!this.options.worker || !link) {throw new Error("rlm.create_session requires a daemon worker connected to its supervisor");}- const client = new DaemonClient(supervisorSocketPath);let activeSessionId: string | undefined;try {- await client.connect(3000);- await client.waitForHello(3000);+ const client = link;const runtimeConfig = parentState.runtime.runtimeConfig;const inheritsProvider = options.model.provider === parentState.runtime.session.model?.provider;const authSource = parentState.runtime.services.authStorage.getAuthStatus(options.model.provider).source;@@ -2842,11 +2849,9 @@ export class AgentDaemon {};} catch (error) {if (activeSessionId) {- await client.request({ type: "kill", activeSessionId }, 30_000).catch(() => undefined);+ await link.request({ type: "kill", activeSessionId }, 30_000).catch(() => undefined);}throw error;- } finally {- client.close();}}@@ -5810,13 +5815,10 @@ export class AgentDaemon {}private async listSupervisorAgentPeers(): Promise<AgentSessionMessageAgentSummary[]> {- const supervisorSocketPath = this.supervisorSocketPathFromEnv();- if (!this.options.worker || !supervisorSocketPath) return [];- const client = new DaemonClient(supervisorSocketPath);+ const link = this.supervisorLink();+ if (!this.options.worker || !link) return [];try {- await client.connect(1000);- await client.waitForHello();- const response = await client.request(+ const response = await link.request({ type: "list_agent_peers", workerToken: this.options.worker.authenticationToken },5000,);@@ -5825,8 +5827,6 @@ export class AgentDaemon {return (response.data as { peers: AgentSessionMessageAgentSummary[] }).peers;} catch {return [];- } finally {- client.close();}}@@ -6022,27 +6022,20 @@ export class AgentDaemon {}private async setStateSessionNameViaSupervisor(state: ActiveSessionState, name: string): Promise<void> {- const supervisorSocketPath = this.supervisorSocketPathFromEnv();- if (!this.options.worker || !supervisorSocketPath) {+ const link = this.supervisorLink();+ if (!this.options.worker || !link) {return this.setStateSessionName(state, name);}- const client = new DaemonClient(supervisorSocketPath);- try {- await client.connect(1000);- await client.waitForHello();- const response = await client.request(- {- type: "set_session_name",- activeSessionId: state.activeSessionId,- name,- workerToken: this.options.worker.authenticationToken,- },- 30_000,- );- if (!response.success) throw deserializeDaemonError(response);- } finally {- client.close();- }+ const response = await link.request(+ {+ type: "set_session_name",+ activeSessionId: state.activeSessionId,+ name,+ workerToken: this.options.worker.authenticationToken,+ },+ 30_000,+ );+ if (!response.success) throw deserializeDaemonError(response);}private setStateSessionNameForCommand(state: ActiveSessionState, name: string): Promise<void> {@@ -6318,50 +6311,45 @@ export class AgentDaemon {targetSelector: string,message: string,): Promise<AgentSessionMessageReceipt> {- const supervisorSocketPath = this.supervisorSocketPathFromEnv();- if (!supervisorSocketPath) {+ const link = this.supervisorLink();+ if (!link) {throw new Error(`Unknown active session: ${targetSelector}`);}const deadline = Date.now() + 30_000;- let client: DaemonClient | undefined;let lastError: unknown;+ // Connect-window loop only: the supervisor may still be starting up.+ // The message itself is sent exactly once - daemon commands are not+ // idempotent, so a rejected or timed-out send must never be retried.while (Date.now() < deadline && !this.shuttingDown) {- const candidate = new DaemonClient(supervisorSocketPath);try {- await candidate.connect(1000);- await candidate.waitForHello();- client = candidate;+ await link.ensureConnected();+ lastError = undefined;break;} catch (error) {lastError = error;- candidate.close();+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));}- await new Promise((resolveDelay) => setTimeout(resolveDelay, 250));}- if (!client) {+ if (lastError !== undefined) {throw lastError instanceof Error ? lastError : new Error(`Unknown active session: ${targetSelector}`);}- try {- const response = await client.request(- {- type: "send_message",- targetActiveSessionId: targetSelector,- message,- fromActiveSessionId: fromState.activeSessionId,- agentOrigin: true,- },- 30_000,- );- if (!response.success) {- throw deserializeDaemonError(response);- }- if (!response.data || typeof response.data !== "object") {- throw new Error("Supervisor returned an invalid agent-message receipt");- }- return response.data as AgentSessionMessageReceipt;- } finally {- client.close();+ const response = await link.request(+ {+ type: "send_message",+ targetActiveSessionId: targetSelector,+ message,+ fromActiveSessionId: fromState.activeSessionId,+ agentOrigin: true,+ },+ 30_000,+ );+ if (!response.success) {+ throw deserializeDaemonError(response);+ }+ if (!response.data || typeof response.data !== "object") {+ throw new Error("Supervisor returned an invalid agent-message receipt");}+ return response.data as AgentSessionMessageReceipt;}private async acceptAgentSessionMessage(@@ -7806,6 +7794,7 @@ export class AgentDaemon {this.shuttingDown = true;this.peerAdmissionsFenced = true;this.peerGrants.clear();+ this.supervisorLinkInstance?.close();if (this.supervisorMonitorTimer) {clearTimeout(this.supervisorMonitorTimer);this.supervisorMonitorTimer = undefined;diff --git a/packages/coding-agent/src/modes/daemon/supervisor-link.ts b/packages/coding-agent/src/modes/daemon/supervisor-link.tsnew file mode 100644index 0000000000..3d3ca6aade--- /dev/null+++ b/packages/coding-agent/src/modes/daemon/supervisor-link.ts@@ -0,0 +1,135 @@+import type { DaemonCommandBody } from "./daemon-client.js";+import { DaemonClient, DaemonSocketClosedError } from "./daemon-client.js";+import type { DaemonResponse } from "./daemon-protocol.js";++/**+ * Long-lived supervisor connection for a daemon worker.+ *+ * Holds one persistent connection and multiplexes cross-worker requests+ * (agent messages, roster reads, root-session creation, renames) over+ * it. Socket death is expected during supervisor restarts: teardown+ * happens on close or handshake failure, and the next request+ * reconnects. Requests are never retried (daemon commands are not+ * idempotent).+ */++export interface DaemonClientLike {+ connect(timeoutMs: number): Promise<void>;+ waitForHello(timeoutMs?: number): Promise<unknown>;+ request(command: DaemonCommandBody, timeoutMs: number): Promise<DaemonResponse>;+ onClose(listener: () => void): () => void;+ close(): void;+}++export interface SupervisorLinkOptions {+ socketPath: string;+ connectTimeoutMs?: number;+ /** Request-level default; call sites may override per request. */+ requestTimeoutMs?: number;+ /** Test seam: client factory. */+ factory?: (socketPath: string) => DaemonClientLike;+}++export class SupervisorLink {+ private client?: DaemonClientLike;+ /** Client mid-handshake; teardown must close it too (close() during connect). */+ private pendingClient?: DaemonClientLike;+ private connecting?: Promise<DaemonClientLike>;+ private closed = false;+ private readonly disposers = new Set<() => void>();++ constructor(private readonly options: SupervisorLinkOptions) {}++ /**+ * Send one request over the persistent link. Never retries: daemon+ * commands like create or send_message are not idempotent, so a+ * failed request surfaces its error to the caller. Only+ * DaemonSocketClosedError tears the link down; the NEXT request+ * reconnects. Command-level failures (timeouts, rejections) leave+ * the shared connection serving other in-flight requests. Call+ * sites that need an establishment window use ensureConnected in+ * their own retry loop.+ */+ async request(+ command: DaemonCommandBody,+ timeoutMs: number = this.options.requestTimeoutMs ?? 30_000,+ ): Promise<DaemonResponse> {+ if (this.closed) throw new Error("Supervisor link is closed");+ const client = await this.ensureConnected();+ try {+ return await client.request(command, timeoutMs);+ } catch (error) {+ // A command-level failure (timeout, rejection) leaves a healthy+ // socket serving other in-flight requests; only socket death+ // invalidates the shared connection.+ if (error instanceof DaemonSocketClosedError) this.teardown();+ throw error;+ }+ }++ /** Establish (or reuse) the authenticated connection. */+ async ensureConnected(): Promise<DaemonClientLike> {+ if (this.closed) throw new Error("Supervisor link is closed");+ return this.ensureConnectedInternal();+ }++ private async ensureConnectedInternal(): Promise<DaemonClientLike> {+ if (this.client) return this.client;+ this.connecting ??= (async () => {+ const client = (+ this.options.factory ?? ((socketPath: string) => new DaemonClient(socketPath) as DaemonClientLike)+ )(this.options.socketPath);+ this.pendingClient = client;+ const detach = client.onClose(() => this.teardown());+ this.disposers.add(detach);+ const cleanup = () => {+ // DaemonClient fires onClose only after a successful connect,+ // so a failed handshake must close its own socket here.+ this.disposers.delete(detach);+ detach();+ if (this.pendingClient === client) this.pendingClient = undefined;+ client.close();+ };+ try {+ await client.connect(this.options.connectTimeoutMs ?? 1000);+ await client.waitForHello();+ } catch (error) {+ cleanup();+ throw error;+ }+ if (this.closed || this.client !== undefined) {+ // Teardown ran mid-handshake or another coroutine won the race.+ cleanup();+ throw new Error("Supervisor link was closed during handshake");+ }+ this.pendingClient = undefined;+ this.client = client;+ return client;+ })();+ const connecting = this.connecting;+ try {+ return await connecting;+ } finally {+ // A teardown during the handshake lets a later caller install a+ // newer in-flight promise; this awaiter must never clear that one.+ if (this.connecting === connecting) this.connecting = undefined;+ }+ }++ /** Drop the cached connection; the next request reconnects. */+ teardown(): void {+ const clients = [this.client, this.pendingClient];+ this.client = undefined;+ this.pendingClient = undefined;+ this.connecting = undefined;+ for (const detach of this.disposers) detach();+ this.disposers.clear();+ for (const client of clients) client?.close();+ }++ /** Stop the link permanently; further requests fail fast without reconnecting. */+ close(): void {+ this.closed = true;+ this.teardown();+ }+}diff --git a/packages/coding-agent/test/daemon-mode.test.ts b/packages/coding-agent/test/daemon-mode.test.tsindex d52cc66414..05abc03892 100644--- a/packages/coding-agent/test/daemon-mode.test.ts+++ b/packages/coding-agent/test/daemon-mode.test.ts@@ -17,6 +17,15 @@ import {import fsPromises from "node:fs/promises";import { syncBuiltinESMExports } from "node:module";import { createServer, type Server, type Socket } from "node:net";++/** Close a fake supervisor and destroy lingering worker connections (persistent supervisor links keep sockets open). */+function closeFakeSupervisor(server: Server, sockets: Set<Socket>): Promise<void> {+ return new Promise<void>((resolveClose) => {+ server.close(() => resolveClose());+ for (const socket of sockets) socket.destroy();+ });+}+import { tmpdir } from "node:os";import { basename, join, resolve } from "node:path";import type { Api, Model } from "@earendil-works/pi-ai";@@ -1867,7 +1876,10 @@ describe("daemon mode helpers", () => {const tempDir = mkdtempSync(join(tmpdir(), "pa-root-session-"));const socketPath = join(tempDir, "supervisor.sock");const commands: Array<Record<string, unknown>> = [];+ const sockets = new Set<Socket>();const server: Server = createServer((socket) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));socket.on("error", () => undefined);socket.write(`${JSON.stringify({@@ -2022,7 +2034,7 @@ describe("daemon mode helpers", () => {vi.unstubAllEnvs();if (previousSupervisorSocket === undefined) delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];else process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSupervisorSocket;- await new Promise<void>((resolveClose) => server.close(() => resolveClose()));+ await closeFakeSupervisor(server, sockets);rmSync(tempDir, { recursive: true, force: true });}},@@ -2032,7 +2044,10 @@ describe("daemon mode helpers", () => {const tempDir = mkdtempSync(join(tmpdir(), "pa-root-timeout-"));const socketPath = join(tempDir, "supervisor.sock");const commands: Array<Record<string, unknown>> = [];+ const sockets = new Set<Socket>();const server = createServer((socket) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));socket.on("error", () => {});socket.write(`${JSON.stringify({@@ -2098,7 +2113,7 @@ describe("daemon mode helpers", () => {requestSpy.mockRestore();if (previousSocket === undefined) delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];else process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSocket;- await new Promise<void>((resolveClose) => server.close(() => resolveClose()));+ await closeFakeSupervisor(server, sockets);rmSync(tempDir, { recursive: true, force: true });}});@@ -2279,7 +2294,10 @@ describe("daemon mode helpers", () => {const tempDir = mkdtempSync(join(tmpdir(), "pa-msg-"));const socketPath = join(tempDir, "d.sock");let connectionCount = 0;+ const sockets = new Set<Socket>();const server: Server = createServer((socket) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));connectionCount++;socket.on("error", () => undefined);socket.write(@@ -2345,7 +2363,7 @@ describe("daemon mode helpers", () => {} else {process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSupervisorSocket;}- await new Promise<void>((resolve) => server.close(() => resolve()));+ await closeFakeSupervisor(server, sockets);rmSync(tempDir, { recursive: true, force: true });}});@@ -2354,7 +2372,10 @@ describe("daemon mode helpers", () => {const tempDir = mkdtempSync(join(tmpdir(), "pa-msg-disconnect-"));const socketPath = join(tempDir, "d.sock");let requestCount = 0;+ const sockets = new Set<Socket>();const server: Server = createServer((socket) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));socket.on("error", () => undefined);socket.write(`${JSON.stringify({@@ -2424,7 +2445,7 @@ describe("daemon mode helpers", () => {} else {process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSupervisorSocket;}- await new Promise<void>((resolve) => server.close(() => resolve()));+ await closeFakeSupervisor(server, sockets);rmSync(tempDir, { recursive: true, force: true });}});@@ -2437,7 +2458,10 @@ describe("daemon mode helpers", () => {const responseGate = new Promise<void>((resolve) => {releaseResponse = resolve;});+ const sockets = new Set<Socket>();const server = createServer((socket) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));socket.write(`${JSON.stringify({type: "daemon_hello",@@ -2505,7 +2529,7 @@ describe("daemon mode helpers", () => {} finally {if (previousSocketPath === undefined) delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];else process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSocketPath;- await new Promise<void>((resolve) => server.close(() => resolve()));+ await closeFakeSupervisor(server, sockets);rmSync(tempDir, { recursive: true, force: true });}});@@ -2514,7 +2538,10 @@ describe("daemon mode helpers", () => {const tempDir = mkdtempSync(join(tmpdir(), "pa-ambiguous-"));const socketPath = join(tempDir, "s");let requestCount = 0;+ const sockets = new Set<Socket>();const server = createServer((socket) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));socket.write(`${JSON.stringify({type: "daemon_hello",@@ -2563,7 +2590,7 @@ describe("daemon mode helpers", () => {} finally {if (previousSocketPath === undefined) delete process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV];else process.env[DAEMON_WORKER_SUPERVISOR_SOCKET_ENV] = previousSocketPath;- await new Promise<void>((resolve) => server.close(() => resolve()));+ await closeFakeSupervisor(server, sockets);rmSync(tempDir, { recursive: true, force: true });}});diff --git a/packages/coding-agent/test/supervisor-link.test.ts b/packages/coding-agent/test/supervisor-link.test.tsnew file mode 100644index 0000000000..d80d26b477--- /dev/null+++ b/packages/coding-agent/test/supervisor-link.test.ts@@ -0,0 +1,243 @@+import { describe, expect, it } from "vitest";+import type { DaemonCommandBody } from "../src/modes/daemon/daemon-client.js";+import { DaemonSocketClosedError } from "../src/modes/daemon/daemon-client.js";+import type { DaemonResponse } from "../src/modes/daemon/daemon-protocol.js";+import { type DaemonClientLike, SupervisorLink } from "../src/modes/daemon/supervisor-link.js";++interface MockClient extends DaemonClientLike {+ requests: DaemonCommandBody[];+ closeCount: number;+ simulateClose: (() => void) | undefined;+}++function makeMockClient(failFirstRequest = false): MockClient {+ const client = {+ requests: [] as DaemonCommandBody[],+ closeCount: 0,+ simulateClose: undefined as (() => void) | undefined,+ connect: async () => {},+ waitForHello: async () => ({}),+ onClose(listener: () => void) {+ client.simulateClose = listener;+ return () => {+ client.simulateClose = undefined;+ };+ },+ close() {+ client.closeCount += 1;+ },+ async request(command: DaemonCommandBody): Promise<DaemonResponse> {+ client.requests.push(command);+ if (failFirstRequest && client.requests.length === 1) {+ throw new Error("socket died mid-request");+ }+ return { id: "r", type: "response", command: command.type, success: true, data: { ok: true } };+ },+ };+ return client as MockClient;+}++/** Bounded wait: a hung promise surfaces as a test failure, never a stuck run. */+async function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timeoutId = setTimeout(() => reject(new Error(`Timed out after ${ms}ms`)), ms);+ promise.then(+ (value) => {+ clearTimeout(timeoutId);+ resolve(value);+ },+ (error: unknown) => {+ clearTimeout(timeoutId);+ reject(error);+ },+ );+ });+}++function makeLink(clients: MockClient[]) {+ return new SupervisorLink({+ socketPath: "/tmp/unused.sock",+ factory: () => {+ const client = makeMockClient();+ clients.push(client);+ return client;+ },+ });+}++describe("SupervisorLink", () => {+ it("reuses one connection across requests", async () => {+ const clients: MockClient[] = [];+ const link = makeLink(clients);+ await link.request({ type: "list_agent_peers" } as DaemonCommandBody);+ await link.request({ type: "agent_messages_status" } as DaemonCommandBody);+ expect(clients).toHaveLength(1);+ expect(clients[0].requests).toHaveLength(2);+ link.close();+ expect(clients[0].closeCount).toBe(1);+ });++ it("single-flights concurrent connects", async () => {+ const clients: MockClient[] = [];+ const link = makeLink(clients);+ await Promise.all([+ link.request({ type: "list_agent_peers" } as DaemonCommandBody),+ link.request({ type: "list_agent_peers" } as DaemonCommandBody),+ ]);+ expect(clients).toHaveLength(1);+ link.close();+ });++ it("reconnects after the socket closes", async () => {+ const clients: MockClient[] = [];+ const link = makeLink(clients);+ await link.request({ type: "list_agent_peers" } as DaemonCommandBody);+ clients[0].simulateClose?.();+ await link.request({ type: "list_agent_peers" } as DaemonCommandBody);+ expect(clients).toHaveLength(2);+ link.close();+ });++ it("does not retry a failed request; a healthy socket survives, a dead one reconnects", async () => {+ const clients: MockClient[] = [];+ const link = new SupervisorLink({+ socketPath: "/tmp/unused.sock",+ factory: () => {+ const client = makeMockClient(clients.length === 0);+ clients.push(client);+ return client;+ },+ });+ // Command-level failure: the shared socket stays up for the next request.+ await expect(link.request({ type: "send_message" } as DaemonCommandBody)).rejects.toThrow(+ "socket died mid-request",+ );+ const response = await link.request({ type: "send_message" } as DaemonCommandBody);+ expect(response.success).toBe(true);+ expect(clients).toHaveLength(1);++ // Socket-level failure: the link tears down, the next request reconnects.+ const closed = new DaemonSocketClosedError("/tmp/unused.sock", "shutdown");+ clients[0].request = async () => {+ throw closed;+ };+ await expect(link.request({ type: "send_message" } as DaemonCommandBody)).rejects.toThrow();+ const response2 = await link.request({ type: "send_message" } as DaemonCommandBody);+ expect(response2.success).toBe(true);+ expect(clients).toHaveLength(2);+ expect(clients[0].closeCount).toBe(1);+ link.close();+ });++ it("closes the client when the handshake fails", async () => {+ const clients: MockClient[] = [];+ const link = new SupervisorLink({+ socketPath: "/tmp/unused.sock",+ factory: () => {+ const client = makeMockClient();+ // First candidate fails the hello; the next connects cleanly.+ if (clients.length === 0) {+ client.waitForHello = async () => {+ throw new Error("hello timeout");+ };+ }+ clients.push(client);+ return client;+ },+ });+ await expect(link.request({ type: "send_message" } as DaemonCommandBody)).rejects.toThrow("hello timeout");+ expect(clients[0].closeCount).toBe(1);+ const response = await link.request({ type: "send_message" } as DaemonCommandBody);+ expect(response.success).toBe(true);+ expect(clients).toHaveLength(2);+ link.close();+ });++ it("closes a client still mid-handshake when close() runs", async () => {+ const clients: MockClient[] = [];+ const link = new SupervisorLink({+ socketPath: "/tmp/unused.sock",+ factory: () => {+ const client = makeMockClient();+ let rejectHello: ((error: Error) => void) | undefined;+ client.waitForHello = () =>+ new Promise((_, reject) => {+ rejectHello = reject;+ });+ const closeClient = client.close.bind(client);+ client.close = () => {+ // Socket death surfaces the pending handshake as a failure.+ closeClient();+ rejectHello?.(new Error("socket closed during handshake"));+ };+ clients.push(client);+ return client;+ },+ });+ const pending = link.ensureConnected();+ await new Promise((resolveTick) => setTimeout(resolveTick, 0));+ link.close();+ expect(clients[0].closeCount).toBe(1);+ await expect(pending).rejects.toThrow();+ });++ it("does not let a settled handshake clear a newer in-flight connect", async () => {+ const clients: MockClient[] = [];+ const connectWaiters: Array<{ resolve: () => void }> = [];+ const helloWaiters: Array<{ resolve: (hello: unknown) => void; reject: (error: Error) => void }> = [];+ const link = new SupervisorLink({+ socketPath: "/tmp/unused.sock",+ factory: () => {+ const client = makeMockClient();+ const index = clients.length;+ // Handshakes advance only when the test resolves them, so the+ // reconnect race is deterministic instead of timer-dependent.+ client.connect = () =>+ new Promise<void>((resolve) => {+ connectWaiters[index] = { resolve };+ });+ client.waitForHello = () =>+ new Promise((resolve, reject) => {+ helloWaiters[index] = { resolve, reject };+ });+ const closeClient = client.close.bind(client);+ client.close = () => {+ // Socket death surfaces a pending handshake as a failure.+ closeClient();+ helloWaiters[index]?.reject(new Error("socket closed during handshake"));+ };+ clients.push(client);+ return client;+ },+ });+ // Handshake A is mid-flight when the shared socket dies (teardown).+ const first = link.ensureConnected();+ connectWaiters[0]?.resolve();+ await withTimeout(new Promise((resolveTick) => setTimeout(resolveTick, 0)), 1000);+ link.teardown();+ // A later caller installs a newer in-flight handshake (B).+ const second = link.ensureConnected();+ // A settles and fails; it must not clear B's in-flight promise.+ await withTimeout(expect(first).rejects.toThrow("socket closed during handshake"), 1000);+ // A third caller must join B instead of opening a third connection.+ const third = link.ensureConnected();+ expect(clients).toHaveLength(2);+ connectWaiters[1]?.resolve();+ // B advances from connect() to waitForHello() on the next tick.+ await withTimeout(new Promise((resolveTick) => setTimeout(resolveTick, 0)), 1000);+ helloWaiters[1]?.resolve({});+ const [clientSecond, clientThird] = await withTimeout(Promise.all([second, third]), 1000);+ expect(clientSecond).toBe(clients[1]);+ expect(clientThird).toBe(clients[1]);+ expect(clients[0].closeCount).toBeGreaterThan(0);+ link.close();+ });++ it("stops reconnecting after close()", async () => {+ const clients: MockClient[] = [];+ const link = makeLink(clients);+ link.close();+ await expect(link.request({ type: "list_agent_peers" } as DaemonCommandBody)).rejects.toThrow();+ expect(clients).toHaveLength(0);+ });+});