diff --git a/packages/client/src/daemon-client.test.ts b/packages/client/src/daemon-client.test.ts index 4c5b99eb64..16b7f4edfc 100644 --- a/packages/client/src/daemon-client.test.ts +++ b/packages/client/src/daemon-client.test.ts @@ -2730,6 +2730,42 @@ test("foreground preserves RPCs waiting for a pending handshake", async () => { await expect(ping).resolves.toMatchObject({ requestId: "queued-ping" }); }); +test("foreground shares a pending credential lookup with the current connection attempt", async () => { + useHeartbeatClock(); + const stalled = new FakeDaemon(); + const replacement = new FakeDaemon(); + const daemons = [stalled, replacement]; + const credentials: Array<(value: string) => void> = []; + let attempts = 0; + const client = new DaemonClient({ + url: "ws://test", + clientId: "foreground-credential-lookup", + localCredential: () => new Promise((resolve) => credentials.push(resolve)), + transportFactory: () => daemons[attempts++]!.transport, + }); + clients.push(client); + + const connection = client.connect(); + void connection.catch(() => undefined); + client.ensureConnected({ verify: true }); + expect(credentials).toHaveLength(1); + credentials[0]!("initial-credential"); + await vi.advanceTimersByTimeAsync(5_000); + expect(attempts).toBe(1); + + client.ensureConnected({ verify: true }); + client.ensureConnected({ verify: true }); + expect(credentials).toHaveLength(2); + expect(stalled.closesFromClient()).toHaveLength(1); + credentials[1]!("replacement-credential"); + await vi.advanceTimersByTimeAsync(0); + expect(attempts).toBe(2); + replacement.openConnection(); + + await connection; + expect(client.getConnectionState()).toEqual({ status: "connected" }); +}); + test("foreground keeps a connect attempt that just started", async () => { useHeartbeatClock(); const pending = new FakeDaemon(); diff --git a/packages/client/src/daemon-client.ts b/packages/client/src/daemon-client.ts index 0f13528a54..5e0c298c7e 100644 --- a/packages/client/src/daemon-client.ts +++ b/packages/client/src/daemon-client.ts @@ -1581,13 +1581,13 @@ export class DaemonClient { } this.shouldReconnect = true; - this.connectPromise = new Promise((resolve, reject) => { + const connection = new Promise((resolve, reject) => { this.connectResolve = resolve; this.connectReject = reject; - this.attemptConnect(); }); - - return this.connectPromise; + this.connectPromise = connection; + this.attemptConnect(); + return connection; } private attemptConnect(): void { @@ -1616,14 +1616,23 @@ export class DaemonClient { this.reconnectTimeout = null; } + // Retire the old transport before credential lookup can yield. + this.disposeTransport( + 1001, + trigger === "STALE_CONNECT_ON_FOREGROUND" ? "Stale connection attempt" : "Reconnecting", + ); + this.lastServerInfoMessage = null; + this.authFailureReasonValue = null; + this.updateConnectionState( + { status: "connecting", attempt: this.reconnectAttempt }, + { event: trigger }, + ); + try { const resolution = resolveConnectionAuth(this.config); const selected = resolution instanceof Promise ? await resolution : resolution; if (!this.shouldReconnect) return; this.helloAuth = selected.helloAuth; - // Reconnect can overlap with browser close/error delivery ordering. - // Dispose any previous transport before constructing the next one. - if (trigger === "CONNECT_REQUEST") this.disposeTransport(); const baseTransportFactory = this.config.transportFactory ?? createWebSocketTransportFactory(this.config.webSocketFactory ?? defaultWebSocketFactory); @@ -1671,17 +1680,7 @@ export class DaemonClient { deliver: (frame) => this.handleTransportMessage(frame), onActivity: () => this.recordTransportActivity(), }); - this.lastServerInfoMessage = null; - this.authFailureReasonValue = null; - this.connectAttemptStartedAt = Date.now(); - this.updateConnectionState( - { - status: "connecting", - attempt: this.reconnectAttempt, - }, - { event: trigger }, - ); this.resetConnectTimeout(); const timeoutMs = Math.max(1, this.config.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS); this.connectTimeout = setTimeout(() => { @@ -1881,7 +1880,6 @@ export class DaemonClient { Date.now() - this.connectAttemptStartedAt >= FOREGROUND_STALE_CONNECT_MS ) { // Keep work queued while the client opens a fresh transport. - this.disposeTransport(1001, "Stale connection attempt"); void this.openConnectionAttempt("STALE_CONNECT_ON_FOREGROUND"); } return;