From 17225d6f938c80b52e9dc2e543539f0b78cb07b6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 12:20:06 +0000 Subject: [PATCH 01/62] docs: record lifecycle simplification baseline (WI-R/W) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/03-complexity-reduction-analysis.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index c5e4df0cf..d11f66667 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -749,6 +749,20 @@ E, U or H; their test cases can be prepared in parallel. Integrate and rerun aff combined revision before P. Plan the live gate early; unavailable live infrastructure does not block independent deterministic work. +**Run started (2026-11-30, 12:16 UTC):** baseline +`3d66aa9374fefadcde8c236e0384cc8d18310372`; implementation branch +`dev/tnaum/connection-lifecycle-simplification`, targeting `feature/connection-lifecycle`. +The operator requested a stacked draft PR, then Case 2 after the implementation push, fixes for +any failures, and readiness only after the required gates pass. The existing untracked relay +and telemetry directories are outside this work. + +**Baseline evidence (2026-11-30):** at the starting revision, `npm run build` passed +(exit 0, 51.09 s). The exact first-run Vitest command above passed all 271 tests in four +files (5.44 s wall time). Evidence: command-runner agent +`6fe1d510-b864-4fc4-81f1-2667393cb664`, completed baseline report. This establishes the +pre-change host baseline, not R/W completion, rendered behavior, packaged activation or live +expiry/sleep-wake. Planning advisor: `claude-opus-5.5`; command runner: `mai-code-2-flash`. + | ID / status | Deliverable | How the agent demonstrates it | | --- | --- | --- | | **R — not run** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. | From 62848a71c05d716cdb35a23a67f1a2c39b41ec4e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 12:27:11 +0000 Subject: [PATCH 02/62] docs: map approved lifecycle checkpoints to implementation slices Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index d11f66667..71dcf37be 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -773,6 +773,51 @@ expiry/sleep-wake. Planning advisor: `claude-opus-5.5`; command runner: `mai-cod | **H — not run** | Shared host checks stop delayed side effects without making ordinary reads carry identity policy. | Exercise [review cases C01–C03](./02-pr1136-copilot-review.md): pause create after client resolution; pause query generation before sampling and again at model selection; pause Playground document opening, including a retained Shell link. End the old lifetime, install the replacement, release the pause. Assert zero stale writes, replacement-schema samples, model sends after invalidation, or replacement bindings, as applicable. Run the same paths without invalidation to rule out a blanket disable. Use fake DB/model boundaries, not real data or model calls. | | **P — not run** | Combined candidate and release evidence. | Rerun affected checks after integration. Walk a normal read and a delayed write/send in the diff: the read uses a shared path, the delayed side effect checks its captured origin. Record obsolete recovery handlers/tests removed and guards intentionally retained. Update user-facing docs/localization and affected telemetry contracts for the behavior actually shipped. Run the repository handoff gates and the live checks below on the identified candidate. | +**Implementation mapping (2026-11-30, advised by `claude-opus-5.5`):** the seven +accepted checkpoints remain the plan; the lettered slices below do not expand its scope. +Coordination decision (leader, 99% confidence): run disjoint files in parallel, but serialize +shared controllers/routers and teardown edits so every work-item commit has clear ownership. + +- **R / `mai-code-2`:** enforce the existing pinned-account tree sign-in contract and add + recovery/late-failure controls in the sign-in, client and auth tests. It is independent of W + and F, but must not edit F's client implementation. The advisor recommended this model for + the small source change and focused tests. +- **W / `mai-code-2`:** characterize held worker-token replies and evaluations across + Disconnect/reconnect, including a valid-worker positive control and retained text. Own the + manager/evaluator, PTY and execution tests; preserve `TDD:` contracts. Existing production + guards should suffice; a discovered production lifecycle defect returns to the advisor. +- **F1 / `gpt-6.1-sol`:** reuse the existing binding-retirement cutoff as the one-way host + lifetime end, with its reason and synchronous cancellation. Explicit teardown ends that + lifetime before awaiting; same-account replacement does not. Detach retained surfaces from + the active registry and cover absent/held clients and pending startup. +- **F2 / `gpt-6.1-sol`, after F1:** route native Dashboard actions to the originating panel + session, never a replacement panel; remove frozen panels from the live-panel lookup. + F1/F2 are genuinely complex host lifecycle and cross-module work. +- **E / `gpt-6.1-sol`, after F1/F2:** ordinary Disconnect completes before either edit + wizard. Preserve the epoch/latch across disconnected editing and both storage writes; + cancellation or supersession writes nothing and partial failures remain visible. +- **H1 / `mai-code-2`, after F1:** fence the shared client-operation callback and add C01 + effect-level regressions. **H2/H3 / `gpt-6.1-sol`, after F2:** propagate the captured host + lifetime/cancellation through schema/model and Playground handoffs; serialize H2/H3 because + they share the Collection router. The Sol slices involve multiple async side-effect boundaries. +- **U1 / `mai-code-2`, after F2:** terminal notice only, X/copy without writes, ordinary + recoverable errors without freezing, and rendered-scenario updates. Exclude F2's Dashboard + row/session wiring from parallel ownership. **U2 / `mai-code-2`, after H2/H3:** remove + obsolete host Retry/unlock procedures and protocol; shared routers/controllers require serialization. +- **P / `mai-code-2` documentation, `mai-code-2-flash` checks:** align only directly affected + docs/contracts, rerun the integrated effects, collect rendered and packaged evidence, and + preserve separate live gates. The authorized order is implementation push and stacked + draft PR, then Case 2, then readiness only if all required gates and pre-review pass. + +**F shared boundary:** `retireConnectionBindings(clusterId, generation, reason)` records +an ended lifetime without lowering its cutoff; `getRetiredBindingReason(binding)` preserves +the first end reason; `getBindingLifetimeSignal(binding)` aborts synchronously on teardown. +`ClustersClient.assertBindingActive(binding)` rejects ended lifetimes or current holds at +side-effect boundaries. `takeConnectionSurfaces(clusterId)` removes and returns the active +surfaces, so an old frozen snapshot is not closed by the next session's Close all. +Keep the existing internal physical generation and binding guards until replacement coverage +exists; no second general-purpose lifetime framework or worker-pin removal is authorized. + For each completed slice update **its row** with status, revision, exact command or test name, observed result and a short evidence pointer. Use `pass`, `fail`, or `blocked: `; where layers differ, record them separately (e.g. `host pass; live blocked: test account`). From af8ace13b721191b7adb0d567d9c000c152679aa Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:04:36 +0000 Subject: [PATCH 03/62] docs: record R/W/F dispatch and pending live gates Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 22 ++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index 71dcf37be..3ce03c4c3 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -762,6 +762,15 @@ files (5.44 s wall time). Evidence: command-runner agent `6fe1d510-b864-4fc4-81f1-2667393cb664`, completed baseline report. This establishes the pre-change host baseline, not R/W completion, rendered behavior, packaged activation or live expiry/sleep-wake. Planning advisor: `claude-opus-5.5`; command runner: `mai-code-2-flash`. +At docs-only revision `17225d6f938c80b52e9dc2e543539f0b78cb07b6`, the expanded baseline +command passed 413 tests in 13 files (16.52 s), including sign-in, worker/PTY execution, +teardown and all three controller/router suites. No failures or `TDD:` failures occurred. +Exact command/evidence: agent `666c92f9-15bf-4764-a3c9-fa13a6cebfeb`, baseline-extension +report; the original build and four initial suites were not rerun for docs-only changes. + +```sh +npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts src/documentdb/connectionTeardown.test.ts src/documentdb/connectionSurfaces.test.ts src/commands/disconnect/disconnect.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts +``` | ID / status | Deliverable | How the agent demonstrates it | | --- | --- | --- | @@ -778,15 +787,18 @@ accepted checkpoints remain the plan; the lettered slices below do not expand it Coordination decision (leader, 99% confidence): run disjoint files in parallel, but serialize shared controllers/routers and teardown edits so every work-item commit has clear ownership. -- **R / `mai-code-2`:** enforce the existing pinned-account tree sign-in contract and add +- **R / `mai-code-2`, implementation running:** agent + `48d5a5d1-32c4-4352-a808-ae0dd072317f`. Enforce the existing pinned-account tree sign-in contract and add recovery/late-failure controls in the sign-in, client and auth tests. It is independent of W and F, but must not edit F's client implementation. The advisor recommended this model for the small source change and focused tests. -- **W / `mai-code-2`:** characterize held worker-token replies and evaluations across +- **W / `mai-code-2`, implementation running:** agent + `6b87164b-c07d-4fb5-a918-488b29840278`. Characterize held worker-token replies and evaluations across Disconnect/reconnect, including a valid-worker positive control and retained text. Own the manager/evaluator, PTY and execution tests; preserve `TDD:` contracts. Existing production guards should suffice; a discovered production lifecycle defect returns to the advisor. -- **F1 / `gpt-6.1-sol`:** reuse the existing binding-retirement cutoff as the one-way host +- **F1 / `gpt-6.1-sol`, implementation running:** agent + `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Reuse the existing binding-retirement cutoff as the one-way host lifetime end, with its reason and synchronous cancellation. Explicit teardown ends that lifetime before awaiting; same-account replacement does not. Detach retained surfaces from the active registry and cover absent/held clients and pending startup. @@ -808,6 +820,10 @@ shared controllers/routers and teardown edits so every work-item commit has clea docs/contracts, rerun the integrated effects, collect rendered and packaged evidence, and preserve separate live gates. The authorized order is implementation push and stacked draft PR, then Case 2, then readiness only if all required gates and pre-review pass. + **Live blocked, operator response (2026-11-30):** an authorized disposable Entra target is + unavailable; the operator will have manual tests performed at a selected candidate checkpoint. + A dedicated physical sleep/wake environment is unavailable. Deterministic implementation + continues; these responses are not live passes or permission to waive required readiness gates. **F shared boundary:** `retireConnectionBindings(clusterId, generation, reason)` records an ended lifetime without lowering its cutoff; `getRetiredBindingReason(binding)` preserves From b58b745016c05e981d368935bedb6ba373b1c5d3 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:11:44 +0000 Subject: [PATCH 04/62] fix: keep tree recovery pinned to the original account (WI-R) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/signInAgain/signInAgain.test.ts | 41 ++++++++++-- src/commands/signInAgain/signInAgain.ts | 12 +--- src/documentdb/ClustersClient.test.ts | 63 +++++++++++++++++++ .../auth/MicrosoftEntraIDAuthHandler.test.ts | 50 +++++++++++++++ 4 files changed, 149 insertions(+), 17 deletions(-) diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index d5c465bcd..d75989a1f 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -95,11 +95,10 @@ describe('signInAgain', () => { ); }); - it.each([ - { id: pin.accountId, label: pin.accountLabel }, - { id: 'different-account', label: 'Explicitly selected in VS Code' }, - ])('requests one pinned forced session and forwards the accepted account', async (account): Promise => { - vi.mocked(getEntraSession).mockResolvedValueOnce({ account } as vscode.AuthenticationSession); + it('requests one pinned forced session and forwards the repaired account', async (): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); vi.mocked(ClustersClient.startAfterSignIn).mockResolvedValueOnce({} as ClustersClient); await signInAgain(actionContext(), { clusterId }); @@ -116,10 +115,40 @@ describe('signInAgain', () => { clusterId, 1, CredentialCache.getCredentials(clusterId), - { verifiedIdentity: expect.objectContaining({ accountId: account.id }) }, + { verifiedIdentity: pin }, ); }); + it.each([pin.accountLabel, 'Explicitly selected in VS Code'])( + 'rejects a different account with label %s without changing the repair pin or hold', + async (label): Promise => { + const credentials = CredentialCache.getCredentials(clusterId); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: 'different-account', label }, + } as vscode.AuthenticationSession); + + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBeInstanceOf( + EntraIdentityMismatchError, + ); + + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + mode: 'forceNew', + tenantId: pin.tenantId, + providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + }), + ); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + expect(showClusterConnectFailure).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ error: expect.any(EntraIdentityMismatchError) }), + ); + }, + ); + it('observes renewal only for the client established by this sign-in', async (): Promise => { vi.mocked(getEntraSession).mockResolvedValueOnce({ account: { id: pin.accountId, label: pin.accountLabel }, diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index db777d794..f7be417d2 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -184,17 +184,7 @@ async function signInAgainInternal( throw new UserCancelledError('signInAgain'); } if (session.account.id !== identity.accountId) { - if (expectedIdentity) { - throw new EntraIdentityMismatchError(); - } - // VS Code only confirms account changes when the account *label* is different. - // A same-label/different-ID session is not an explicit user choice. - if ( - session.account.label === identity.accountLabel || - (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud') - ) { - throw new EntraIdentityMismatchError(); - } + throw new EntraIdentityMismatchError(); } return session; }); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index ad78c6845..95b93acd5 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -971,6 +971,69 @@ describe('regular connection startup diagnostics', () => { await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); }); + it('serves the next explicit operation once on a repaired same-account generation', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + ClustersClient.reportFailure(old.binding, new MongoServerError({ code: 18 })); + + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const operation = vi.fn(async (client: ClustersClient) => client); + + await expect(runWithClient(old.binding, operation)).resolves.toBe(repaired); + + expect(repaired.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(operation).toHaveBeenCalledExactlyOnceWith(repaired); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('ignores a late failure from the generation replaced by same-account repair', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + ClustersClient.reportFailure(old.binding, new MongoServerError({ code: 18 })); + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const closes = mockClose.mock.calls.length; + const lateFailure = new MongoServerError({ code: 18 }); + + expect(ClustersClient.reportFailure(old.binding, lateFailure)).toBeUndefined(); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getBinding(clusterId)).toBe(repaired.binding); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledTimes(closes); + expect(await ClustersClient.getClient(clusterId)).toBe(repaired); + expect(mockConnect).toHaveBeenCalledTimes(2); + + expect(ClustersClient.reportFailure(repaired.binding, lateFailure)).toBe('credentialsRejected'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + expect(mockClose).toHaveBeenCalledTimes(closes + 1); + }); + it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { const old = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('topologyClosed'); diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index b8bd10338..7236d00ed 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -1133,6 +1133,56 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(output).not.toContain('access-token'); }); + it.each(['success', 'noSession', 'rejection'] as const)( + 'keeps a non-interactive callback silent on %s', + async (outcome): Promise => { + const cause = new Error('provider rejected silent lookup'); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: false, pinnedEntraIdentity }, + ).configureAuth(); + if (outcome === 'noSession') { + getSessionFromVSCode.mockResolvedValueOnce(undefined); + } else if (outcome === 'rejection') { + getSessionFromVSCode.mockRejectedValueOnce(cause); + } + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + + if (outcome === 'success') { + await expect(result).resolves.toEqual({ accessToken: session.accessToken }); + } else if (outcome === 'noSession') { + await expect(result).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'noSession', + }); + } else { + await expect(result).rejects.toBeInstanceOf(TokenCallbackError); + } + expect(getSessionFromVSCode.mock.calls).toEqual([ + [ + 'microsoft', + [ + 'https://ossrdbms-aad.database.windows.net/.default', + `VSCODE_TENANT:${pinnedEntraIdentity.tenantId}`, + ], + { silent: true, account }, + ], + [ + 'microsoft', + [ + 'https://ossrdbms-aad.database.windows.net/.default', + `VSCODE_TENANT:${pinnedEntraIdentity.tenantId}`, + ], + { silent: true, account }, + ], + ]); + }, + ); + it('reports a missing silent session as unavailable input without recording a token failure', async () => { getSessionFromVSCode.mockResolvedValueOnce(undefined); const events: string[] = []; From d6be5ea89e5ec6748971fdf8b0a52bb6c29eb7ce Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:12:12 +0000 Subject: [PATCH 05/62] docs: record WI-R review and the WI-W test blocker Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index 3ce03c4c3..e225d224f 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -784,19 +784,41 @@ npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/playg **Implementation mapping (2026-11-30, advised by `claude-opus-5.5`):** the seven accepted checkpoints remain the plan; the lettered slices below do not expand its scope. +Advisor verdict: follow the mapping, **82/100 confidence**. The remaining technical risks +require direct effects checks for synchronous cutoff retirement, retained-registry exclusion +and originating Dashboard menu routing; they are not substitutes for passing tests. Coordination decision (leader, 99% confidence): run disjoint files in parallel, but serialize shared controllers/routers and teardown edits so every work-item commit has clear ownership. -- **R / `mai-code-2`, implementation running:** agent +- **R / `mai-code-2`, implementation committed; integrated checks pending:** agent `48d5a5d1-32c4-4352-a808-ae0dd072317f`. Enforce the existing pinned-account tree sign-in contract and add recovery/late-failure controls in the sign-in, client and auth tests. It is independent of W and F, but must not edit F's client implementation. The advisor recommended this model for the small source change and focused tests. + **Done (2026-11-30), commit `b58b74501`:** tree recovery now rejects every different account + ID, retaining the pinned-account success path and existing messages. Seven regressions + cover account rejection, silent callbacks, same-account replacement and late-failure + attribution. Decision: implement the operator's pinned-account contract without new wording; + advised (`claude-opus-5.5`), review approved at 88% confidence. The changed acceptance test + preserves exact pinned-session/startup assertions and adds zero-startup/unchanged-pin/hold + assertions for rejection; no `TDD:` contract was weakened. + **Interim host pass:** the three R suites passed within the R/W command below at + `af8ace13b` plus the working changes; the combined command failed in W, not R. + Build and affected suites are being rerun on the stabilized R/F1 candidate before + claiming the integrated gate. - **W / `mai-code-2`, implementation running:** agent `6b87164b-c07d-4fb5-a918-488b29840278`. Characterize held worker-token replies and evaluations across Disconnect/reconnect, including a valid-worker positive control and retained text. Own the manager/evaluator, PTY and execution tests; preserve `TDD:` contracts. Existing production guards should suffice; a discovered production lifecycle defect returns to the advisor. + **Host fail (2026-11-30), revision `af8ace13b` plus R/W/F1 working changes:** + `npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/ClustersClient.test.ts src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts src/documentdb/shell/ShellSessionManager.test.ts src/documentdb/playground/PlaygroundEvaluator.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts` + passed 601 tests in seven files but failed the new held-evaluation test in + `PlaygroundEvaluator.test.ts` after 15 s, with one unhandled rejection: expected + `Worker terminated`, received `The connection is unavailable.` The credential-cleanup + assertion also failed. Evidence: runner `05e84afa-064f-49cb-95bb-5e07f6ac1441` + (22.22 s). Technical diagnosis is assigned to the advisor; no production behavior or + existing contract has been changed to make this failure disappear. - **F1 / `gpt-6.1-sol`, implementation running:** agent `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Reuse the existing binding-retirement cutoff as the one-way host lifetime end, with its reason and synchronous cancellation. Explicit teardown ends that From 4c5ff5fa231e7a07d5a273e2902830b74167b48b Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:17:19 +0000 Subject: [PATCH 06/62] test: fence worker replies and evaluation replay across teardown (WI-W) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../playground/PlaygroundEvaluator.test.ts | 57 ++++++++++++++ .../playground/WorkerSessionManager.test.ts | 75 +++++++++++++++++++ 2 files changed, 132 insertions(+) diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index ca56a3536..73ee534b4 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -523,6 +523,63 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { }, ); + it('does not replay or rebind an old evaluation after Disconnect replaces its worker', async (): Promise => { + await initializeSession(AuthMethodId.MicrosoftEntraID); + await requestToken({ type: 'tokenRequest', requestId: 'pin' }); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, 'bind', undefined, capture); + const binding = capture.mock.calls[0][0] as PlaygroundWorkerBinding; + const bound = { ...connection, ...binding }; + + let rejectOld!: (error: Error) => void; + mocks.worker.sendEval.mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectOld = reject; + }), + ); + const oldRun = evaluator.evaluate(bound, 'old'); + const oldOutcome = expect(oldRun).rejects.toThrow('Worker terminated'); + await vi.waitFor(() => + expect(mocks.worker.sendEval.mock.calls.at(-1)?.[0]).toMatchObject({ type: 'eval', code: 'old' }), + ); + + try { + ClustersClient.latch(clusterId, 'userDisconnected'); + evaluator.killWorker(); + ClustersClient.unlatch(clusterId); + mocks.worker.isConnectedTo.mockReturnValue(false); + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism: AuthMethodId.MicrosoftEntraID, + entraIdConfig: { tenantId: 'interactive-tenant' }, + }); + await evaluator.evaluate(bound, 'new'); + mocks.worker.isConnectedTo.mockReturnValue(true); + + rejectOld(new Error('Worker terminated')); + await oldOutcome; + const response = await requestToken({ type: 'tokenRequest', requestId: 'replacement-token' }); + expect(response).toHaveBeenCalledExactlyOnceWith({ + type: 'tokenResponse', + requestId: 'replacement-token', + accessToken, + }); + expect( + mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code), + ).toEqual(['1', 'bind', 'old', 'new']); + expect(mocks.interactiveToken.mock.calls.at(-1)?.[2]).toEqual({ + silent: true, + account: { id: 'private-account', label: accountLabel }, + }); + } finally { + ClustersClient.unlatch(clusterId); + mocks.getCredentials.mockClear(); + } + }); + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( 'uses the captured %s identity and original connection despite forged request fields', async (authMethod): Promise => { diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index cdfdfdf30..fe9695267 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -1375,6 +1375,81 @@ describe('WorkerSessionManager', () => { }, ); + it('does not deliver a held token reply after Disconnect replaces the worker', async (): Promise => { + let releaseOldReply!: () => void; + const oldReply = new Promise((resolve) => { + releaseOldReply = resolve; + }); + const onTokenRequest = vi.fn>( + async (message, postResponse) => { + if (message.requestId === 'old-token') { + await oldReply; + } + postResponse({ + type: 'tokenResponse', + requestId: message.requestId, + accessToken: `${message.requestId}-access-token`, + }); + }, + ); + callbacks.onTokenRequest = onTokenRequest; + const manager = new WorkerSessionManager(callbacks); + try { + const old = await startWorker(true, {}, manager); + old.worker._emit('message', { + type: 'initResult', + requestId: old.requestId, + success: true, + }); + await old.initPromise; + + old.worker._emit('message', { type: 'tokenRequest', requestId: 'old-token' }); + await vi.waitFor(() => expect(onTokenRequest).toHaveBeenCalledTimes(1)); + + ClustersClient.latch('test-cluster', 'userDisconnected'); + manager.killWorker(); + ClustersClient.unlatch('test-cluster'); + + const replacement = await startWorker(true, {}, manager); + replacement.worker._emit('message', { + type: 'initResult', + requestId: replacement.requestId, + success: true, + }); + await replacement.initPromise; + + releaseOldReply(); + await onTokenRequest.mock.results[0].value; + const postMessage = ( + workerThreads as unknown as { + _mockPostMessage: Mock; + } + )._mockPostMessage; + const tokenReplies = (): MainToWorkerMessage[] => + postMessage.mock.calls + .map(([message]) => message as MainToWorkerMessage) + .filter((message) => message.type === 'tokenResponse'); + expect(tokenReplies()).toEqual([]); + + replacement.worker._emit('message', { + type: 'tokenRequest', + requestId: 'replacement-token', + }); + await onTokenRequest.mock.results[1].value; + expect(tokenReplies()).toEqual([ + { + type: 'tokenResponse', + requestId: 'replacement-token', + accessToken: 'replacement-token-access-token', + }, + ]); + expect(manager.isAlive).toBe(true); + } finally { + ClustersClient.unlatch('test-cluster'); + manager.dispose(); + } + }); + it.each(['returned', 'failed'] as const)( 'cancels a still-attached worker when an invalidated token lookup %s', async (outcome): Promise => { From 8c4854f0dcc13343dabeed884a8a5c38af0d9852 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:17:54 +0000 Subject: [PATCH 07/62] docs: record WI-W pass and bounded WI-F1 correction Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index e225d224f..ace823cac 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -806,7 +806,7 @@ shared controllers/routers and teardown edits so every work-item commit has clea `af8ace13b` plus the working changes; the combined command failed in W, not R. Build and affected suites are being rerun on the stabilized R/F1 candidate before claiming the integrated gate. -- **W / `mai-code-2`, implementation running:** agent +- **W / `mai-code-2`, host pass; integrated rerun pending:** agent `6b87164b-c07d-4fb5-a918-488b29840278`. Characterize held worker-token replies and evaluations across Disconnect/reconnect, including a valid-worker positive control and retained text. Own the manager/evaluator, PTY and execution tests; preserve `TDD:` contracts. Existing production @@ -819,11 +819,39 @@ shared controllers/routers and teardown edits so every work-item commit has clea assertion also failed. Evidence: runner `05e84afa-064f-49cb-95bb-5e07f6ac1441` (22.22 s). Technical diagnosis is assigned to the advisor; no production behavior or existing contract has been changed to make this failure disappear. + **Done (2026-11-30), commit `4c5ff5fa2`:** added held-token and in-flight evaluation + regressions. The first attempt latched before the evaluation reached the worker; advised + (`claude-opus-5.5`), about 90% confidence, the correction waits for the actual `old` + `sendEval` effect before teardown. Exact no-replay sequence, replacement reply count and + silent pinned-account assertions are unchanged. No production behavior or existing + `TDD:` contract changed. + **Host pass:** at `d6be5ea89` plus W/F1 working changes, + `npx vitest run src/documentdb/shell/ShellSessionManager.test.ts src/documentdb/playground/PlaygroundEvaluator.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts` + passed all 391 tests in five files (14.58 s), no failures/unhandled errors/TDD failures. + Evidence: runner `05e84afa-064f-49cb-95bb-5e07f6ac1441`, corrected-test rerun. - **F1 / `gpt-6.1-sol`, implementation running:** agent `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Reuse the existing binding-retirement cutoff as the one-way host lifetime end, with its reason and synchronous cancellation. Explicit teardown ends that lifetime before awaiting; same-account replacement does not. Detach retained surfaces from the active registry and cover absent/held clients and pending startup. + **Review/checks fail (2026-11-30):** advised (`claude-opus-5.5`), changes requested at + 85% confidence. Failed storage removal must not leave kept tabs/old RPCs claiming the + connection was removed; the detached-surface failure path needs truthful disconnected + feedback without reviving the lifetime. This is an introduced regression, not an accepted + cosmetic exception. + At `af8ace13b` plus working R/F1 changes, `npm run build` failed after 55 s with TS2352 + in `src/commands/disconnect/disconnect.test.ts:190`: the new shell fixture lacks its + required terminal and complete info. The F1 command above, preceded by the three R suites, + passed 292/293 tests in 10/11 files (5 s), failing + `keeps teardown scoped to the current registered surfaces for one cluster` because a new + `it()` was nested inside it. Evidence: runner `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2` + and advisor `873c8316-29fd-47c1-aa2d-ff9dce2f1254`. Neither failure is a `TDD:` + behavior-contract failure; fix the fixture/registration, not the assertions. + **Correction authorized by the advisor:** only the matching newest failed-removal + retirement range can be corrected to `userDisconnected`, under the existing epoch/latch + guard. Captured detached surfaces receive the truthful notice; their signals stay aborted + and earlier/later lifetimes are untouched. Fix the shell fixture with complete proper types + and move the surface test to top level. Worker rework is running; review and checks must rerun. - **F2 / `gpt-6.1-sol`, after F1:** route native Dashboard actions to the originating panel session, never a replacement panel; remove frozen panels from the live-panel lookup. F1/F2 are genuinely complex host lifecycle and cross-module work. @@ -846,10 +874,18 @@ shared controllers/routers and teardown edits so every work-item commit has clea unavailable; the operator will have manual tests performed at a selected candidate checkpoint. A dedicated physical sleep/wake environment is unavailable. Deterministic implementation continues; these responses are not live passes or permission to waive required readiness gates. + **Prerequisite evidence:** runner `f2f3b0ec-2762-4135-b213-b7778305f791` verified an + integrated browser page at `about:blank` (`readyState: complete`). Direct cached Chromium + launches failed because `libatk-1.0.so.0` is missing; pinned VS Code 1.109.0 is cached and + the X11 display socket is reachable, but packaged activation is untested. Use the working + integrated browser for U; attempt candidate packaged checks or matching candidate CI for P. + Neither a blank-page check nor an old VSIX is candidate rendered/activation/live evidence. **F shared boundary:** `retireConnectionBindings(clusterId, generation, reason)` records an ended lifetime without lowering its cutoff; `getRetiredBindingReason(binding)` preserves the first end reason; `getBindingLifetimeSignal(binding)` aborts synchronously on teardown. +On failed Remove, correct only the matching latest retirement range to the truthful +`userDisconnected` reason; its lifetime remains permanently ended. `ClustersClient.assertBindingActive(binding)` rejects ended lifetimes or current holds at side-effect boundaries. `takeConnectionSurfaces(clusterId)` removes and returns the active surfaces, so an old frozen snapshot is not closed by the next session's Close all. From dce388d99a9aff16d94c802a79260a0ff52288ec Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:24:59 +0000 Subject: [PATCH 08/62] docs: record passing host baselines and WI-F1 technical gate Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 39 ++++++++++++++++++- 1 file changed, 37 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index ace823cac..7527c1b48 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -774,8 +774,8 @@ npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/playg | ID / status | Deliverable | How the agent demonstrates it | | --- | --- | --- | -| **R — not run** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. | -| **W — not run** | Shell and Playground renew independently; explicit teardown stops the old worker, not the user's text. | Exercise both manager/evaluator suites, PTY and `executePlaygroundCode.test.ts`. Hold a token reply or evaluation across Disconnect, release it after reconnect: no delivery to the replacement worker, automatic command replay or silent rebinding; scrollback/file contents survive. Positive control: a valid pinned worker receives its reply and executes once. | +| **R — host pass; integrated/live pending** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. Commit/revision/command evidence is recorded under R below. | +| **W — host pass; integrated/live pending** | Shell and Playground renew independently; explicit teardown stops the old worker, not the user's text. | Exercise both manager/evaluator suites, PTY and `executePlaygroundCode.test.ts`. Hold a token reply or evaluation across Disconnect, release it after reconnect: no delivery to the replacement worker, automatic command replay or silent rebinding; scrollback/file contents survive. Positive control: a valid pinned worker receives its reply and executes once. Commit/revision/command evidence is recorded under W below. | | **F — not run** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. | | **E — not run** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. | | **U — not run** | X dismisses the frozen notice; Close closes the tab. Ordinary recoverable errors do not freeze it. | Update the existing rendered scenarios below. Keep a draft, dismiss with X, select/copy the original text, attempt Save, release a stale response: draft unchanged, no new save RPC. Close/cancel the dirty-close confirmation separately. Pair with a failed live query → same-account repair → user runs again in the **same tab**, with no unlock RPC and no automatic replay. On uncertain write outcome retain text and never claim nothing was written. | @@ -806,6 +806,11 @@ shared controllers/routers and teardown edits so every work-item commit has clea `af8ace13b` plus the working changes; the combined command failed in W, not R. Build and affected suites are being rerun on the stabilized R/F1 candidate before claiming the integrated gate. + **Stabilized host pass:** at `8c4854f0d` plus F1 working changes, `npm run build` + passed (exit 0, 43 s), and the combined R/F1 command recorded below passed all + 302 tests in 11 files (5 s). Evidence: runner + `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2`, corrected F1 rerun. R's same-account + repair and late-failure tests are green; this still does not pass the live gates. - **W / `mai-code-2`, host pass; integrated rerun pending:** agent `6b87164b-c07d-4fb5-a918-488b29840278`. Characterize held worker-token replies and evaluations across Disconnect/reconnect, including a valid-worker positive control and retained text. Own the @@ -829,6 +834,8 @@ shared controllers/routers and teardown edits so every work-item commit has clea `npx vitest run src/documentdb/shell/ShellSessionManager.test.ts src/documentdb/playground/PlaygroundEvaluator.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts` passed all 391 tests in five files (14.58 s), no failures/unhandled errors/TDD failures. Evidence: runner `05e84afa-064f-49cb-95bb-5e07f6ac1441`, corrected-test rerun. + The root build also passed on the stabilized R/W/F1 working candidate (43 s); + no test type errors remained. Integrated candidate rerun is still required. - **F1 / `gpt-6.1-sol`, implementation running:** agent `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Reuse the existing binding-retirement cutoff as the one-way host lifetime end, with its reason and synchronous cancellation. Explicit teardown ends that @@ -852,6 +859,24 @@ shared controllers/routers and teardown edits so every work-item commit has clea guard. Captured detached surfaces receive the truthful notice; their signals stay aborted and earlier/later lifetimes are untouched. Fix the shell fixture with complete proper types and move the surface test to top level. Worker rework is running; review and checks must rerun. + **Rerun pass, review still pending:** at `8c4854f0d` plus F1 working changes, + `npm run build` passed (43 s), and the exact command below passed 302/302 tests + in 11/11 files (5 s). Evidence: runner `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2`. + Advisor review then found a repeated-failed-Remove regression: a no-op retirement + correction must not prevent the epoch/latch-guarded restoration of `userDisconnected`. + Decision: advisor, 88% confidence, restore that latch unconditionally inside the existing + guard and add two regressions; keep the exact-range correction and all supersession guards. + This corrective slice must be checked and reviewed before F1 is committed. + **Technical gate, no edits made:** the worker found that the new `laterGeneration` + superseded-delete fixture keeps the epoch unchanged, so the unconditional restoration + would change its latch/redisable expectations. The advisor must distinguish incidental + fixture expectations from a real newer-lifetime protection before approving a correction. + Preserve the epoch-superseded case and retirement-range immutability; do not weaken the + newer-lifetime contract to make the tests green. + + ```sh + npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/ClustersClient.test.ts src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts src/documentdb/connectionTeardown.test.ts src/documentdb/connectionSurfaces.test.ts src/documentdb/connectionBindingRetirement.test.ts src/commands/disconnect/disconnect.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts + ``` - **F2 / `gpt-6.1-sol`, after F1:** route native Dashboard actions to the originating panel session, never a replacement panel; remove frozen panels from the live-panel lookup. F1/F2 are genuinely complex host lifecycle and cross-module work. @@ -880,6 +905,16 @@ shared controllers/routers and teardown edits so every work-item commit has clea the X11 display socket is reachable, but packaged activation is untested. Use the working integrated browser for U; attempt candidate packaged checks or matching candidate CI for P. Neither a blank-page check nor an old VSIX is candidate rendered/activation/live evidence. + **E/H/U pre-edit baseline pass:** at `8c4854f0d` plus F1 working changes, + the command below passed 167 tests in 14 files (12.82 s). The distinct browser-manifest + command passed 47 tests in one file (1.28 s). No missing paths, failures or `TDD:` + failures. Evidence: runner `83db6668-3669-435b-b1a0-76a8ed2c89d0`. + These are host/fixture baselines, not rendered U or candidate P gates. + + ```sh + npx vitest run src/commands/updateCredentials src/commands/updateConnectionString src/services/copilotService.test.ts src/commands/playground/newPlayground.test.ts src/documentdb/playground/PlaygroundService.test.ts src/documentdb/shell/ShellTerminalLinkProvider.test.ts src/webviews/documentdb/useBoundViewRecovery.test.tsx src/webviews/components/DisconnectedOverlay.test.tsx src/webviews/documentdb/documentView/documentView.test.tsx src/webviews/_integration/describeUnavailableConnection.test.ts + npx vitest run --config build/verification/browser/vitest.config.ts build/verification/browser/scenarios.test.ts + ``` **F shared boundary:** `retireConnectionBindings(clusterId, generation, reason)` records an ended lifetime without lowering its cutoff; `getRetiredBindingReason(binding)` preserves From b7fd8bff53c364618d18a20e59ea9c3099213ba9 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:30:49 +0000 Subject: [PATCH 09/62] fix: permanently end retained host lifetimes on teardown (WI-F1) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/disconnect/disconnect.test.ts | 82 ++++- src/commands/disconnect/disconnect.ts | 14 +- src/documentdb/ClusterSession.ts | 6 +- src/documentdb/ClustersClient.ts | 31 +- .../connectionBindingRetirement.test.ts | 174 ++++++++++ src/documentdb/connectionBindingRetirement.ts | 62 +++- src/documentdb/connectionSurfaces.test.ts | 34 +- src/documentdb/connectionSurfaces.ts | 8 +- src/documentdb/connectionTeardown.test.ts | 323 +++++++++++++++++- src/documentdb/connectionTeardown.ts | 49 ++- .../documentdb/boundViewOperations.ts | 10 +- .../collectionViewController.test.ts | 14 + .../collectionViewController.ts | 1 + .../collectionViewRouter.test.ts | 92 ++++- .../documentsViewController.test.ts | 16 + .../documentView/documentsViewController.ts | 1 + .../documentView/documentsViewRouter.test.ts | 102 +++++- 17 files changed, 962 insertions(+), 57 deletions(-) create mode 100644 src/documentdb/connectionBindingRetirement.test.ts diff --git a/src/commands/disconnect/disconnect.test.ts b/src/commands/disconnect/disconnect.test.ts index 3b1bfcc65..234f6b428 100644 --- a/src/commands/disconnect/disconnect.test.ts +++ b/src/commands/disconnect/disconnect.test.ts @@ -7,17 +7,24 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { getConnectionSurfaces } from '../../documentdb/connectionSurfaces'; import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { type PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; import { connectDisconnected, disconnect } from './disconnect'; vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { exists: vi.fn(), getLatchReason: vi.fn(), unlatch: vi.fn() }, + ClustersClient: { exists: vi.fn(), hasPendingStartup: vi.fn(), getLatchReason: vi.fn(), unlatch: vi.fn() }, })); +vi.mock('../../documentdb/connectionSurfaces', () => ({ getConnectionSurfaces: vi.fn() })); vi.mock('../../documentdb/connectionTeardown', () => ({ teardownConnection: vi.fn() })); +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: vi.fn() })); +vi.mock('../playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators: vi.fn() })); vi.mock('../../extensionVariables', () => ({ ext: { state: { notifyChildrenChanged: vi.fn() } } })); vi.mock('../../tree/documentdb/ClusterItemBase', () => ({ ClusterItemBase: class {} })); vi.mock('../retryAuthentication/retryAuthentication', () => ({ refreshAuthenticationNode: vi.fn() })); @@ -38,7 +45,11 @@ describe('tree disconnect recovery', () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(ClustersClient.exists).mockReturnValue(true); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(getConnectionSurfaces).mockReturnValue([]); + vi.mocked(getPlaygroundEvaluators).mockReturnValue(new Map()); + vi.mocked(getRegisteredShellTerminals).mockReturnValue([]); }); it.each([disconnect, connectDisconnected])( @@ -47,6 +58,9 @@ describe('tree disconnect recovery', () => { for (const reason of ['connectionRemoved', 'credentialsChanged', 'identityChanged'] as const) { vi.clearAllMocks(); vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + if (command === disconnect) { + vi.mocked(ClustersClient.exists).mockReturnValue(false); + } const context = actionContext(); const node = clusterNode(); @@ -154,4 +168,70 @@ describe('tree disconnect recovery', () => { expect(refreshAuthenticationNode).not.toHaveBeenCalled(); expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); }); + + it.each(['surface', 'startup', 'evaluator', 'shell', 'heldClient'] as const)( + 'does not bypass ordinary Disconnect for a surviving %s on a rejected or absent client', + async (survivor): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(survivor === 'heldClient'); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(survivor === 'startup'); + if (survivor === 'surface') { + vi.mocked(getConnectionSurfaces).mockReturnValue([ + { clusterId: 'stable-cluster', kind: 'documentView', disable: vi.fn(), dispose: vi.fn() }, + ]); + } + if (survivor === 'evaluator') { + vi.mocked(getPlaygroundEvaluators).mockReturnValue( + new Map([['stable-cluster', {} as PlaygroundEvaluator]]), + ); + } + if (survivor === 'shell') { + const terminal: vscode.Terminal = { + name: 'Test shell', + processId: Promise.resolve(undefined), + creationOptions: {}, + exitStatus: undefined, + state: { isInteractedWith: false, shell: undefined }, + shellIntegration: undefined, + sendText: vi.fn(), + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(), + }; + const shell: ReturnType[number] = { + terminal, + info: { + clusterId: 'stable-cluster', + clusterDisplayName: 'Cluster', + activeDatabase: 'database', + isInitialized: true, + isEvaluating: false, + workerState: 'ready', + authMethod: 'NoAuth', + username: undefined, + }, + disconnect: vi.fn(), + }; + vi.mocked(getRegisteredShellTerminals).mockReturnValue([shell]); + } + const node = clusterNode(); + await disconnect(actionContext(), node); + expect(teardownConnection).toHaveBeenCalledExactlyOnceWith( + 'stable-cluster', + 'userDisconnected', + expect.any(Function), + ); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }, + ); + + it('leaves credentialsUpdating safely terminal even with surviving surfaces', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsUpdating'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(true); + const node = clusterNode(); + await disconnect(actionContext(), node); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); }); diff --git a/src/commands/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts index 08296041a..ea0c02eaa 100644 --- a/src/commands/disconnect/disconnect.ts +++ b/src/commands/disconnect/disconnect.ts @@ -6,11 +6,14 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import { l10n, window } from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { getConnectionSurfaces } from '../../documentdb/connectionSurfaces'; import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { type TreeElement } from '../../tree/TreeElement'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; function isClusterNode(node: TreeElement | undefined): node is ClusterItemBase { @@ -25,7 +28,16 @@ export async function disconnect(context: IActionContext, node?: TreeElement): P const { clusterId } = node.cluster; const reason = ClustersClient.getLatchReason(clusterId); - if (!ClustersClient.exists(clusterId) || reason) { + if ( + reason === 'userDisconnected' || + reason === 'connectionRemoved' || + reason === 'credentialsUpdating' || + (!ClustersClient.exists(clusterId) && + !ClustersClient.hasPendingStartup(clusterId) && + getConnectionSurfaces(clusterId).length === 0 && + !getPlaygroundEvaluators().has(clusterId) && + !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId)) + ) { if ( node.cluster.viewId !== String(Views.ConnectionsView) && node.cluster.viewId !== String(Views.DiscoveryView) && diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index c665e3f4b..e71ad1a02 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -14,7 +14,7 @@ import { getDataAtPath } from '../utils/slickgrid/mongo/toSlickGridTable'; import { toSlickGridTree, type TreeData } from '../utils/slickgrid/mongo/toSlickGridTree'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; -import { isRetiredConnectionBinding } from './connectionBindingRetirement'; +import { getRetiredBindingReason, isRetiredConnectionBinding } from './connectionBindingRetirement'; import { classifyConnectionFailure } from './connectionFailures'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { runWithClient } from './runWithClient'; @@ -109,9 +109,7 @@ export class ClusterSession { if (signal?.aborted) { throw new UserCancelledError('staleCollectionViewOperation'); } - const reason = isRetiredConnectionBinding(this.binding) - ? 'credentialsChanged' - : ClustersClient.getLatchReason(this.binding.clusterId); + const reason = getRetiredBindingReason(this.binding) ?? ClustersClient.getLatchReason(this.binding.clusterId); if (reason) { throw new ConnectionUnavailableError(reason); } diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 90f361f25..f57c04eda 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -53,7 +53,11 @@ import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; import { emitTokenRenewal } from './auth/tokenRenewalTelemetry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; -import { isRetiredConnectionBinding, retireConnectionBindings } from './connectionBindingRetirement'; +import { + getRetiredBindingReason, + retireConnectionBindings, + type EndedLifetimeReason, +} from './connectionBindingRetirement'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; @@ -890,9 +894,7 @@ export class ClustersClient { binding: ConnectionBinding, options?: { readonly background?: boolean; readonly trigger?: ClientStartupTrigger }, ): Promise { - if (isRetiredConnectionBinding(binding)) { - throw new ConnectionUnavailableError('credentialsChanged'); - } + ClustersClient.assertBindingActive(binding); const client = await ClustersClient.acquireClient( binding.clusterId, undefined, @@ -902,14 +904,25 @@ export class ClustersClient { options?.background === true, binding.fingerprint, ); - if (isRetiredConnectionBinding(binding)) { - throw new ConnectionUnavailableError('credentialsChanged'); - } + ClustersClient.assertBindingActive(binding); return client; } - public static retireBoundViews(clusterId: string): void { - retireConnectionBindings(clusterId, ClustersClient._generations.get(clusterId) ?? 0); + public static retireBoundViews(clusterId: string, reason: EndedLifetimeReason = 'credentialsChanged'): number { + const generation = ClustersClient._generations.get(clusterId) ?? 0; + retireConnectionBindings(clusterId, generation, reason); + return generation; + } + + public static assertBindingActive(binding: ConnectionBinding): void { + const reason = getRetiredBindingReason(binding) ?? ClustersClient.getLatchReason(binding.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + } + + public static hasPendingStartup(clusterId: string): boolean { + return ClustersClient._pendingStartups.has(clusterId); } /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ diff --git a/src/documentdb/connectionBindingRetirement.test.ts b/src/documentdb/connectionBindingRetirement.test.ts new file mode 100644 index 000000000..038ad55b4 --- /dev/null +++ b/src/documentdb/connectionBindingRetirement.test.ts @@ -0,0 +1,174 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient, type ConnectionBinding } from './ClustersClient'; +import { + correctFailedRemovalRetirement, + getBindingLifetimeSignal, + getRetiredBindingReason, + isRetiredConnectionBinding, + retireConnectionBindings, +} from './connectionBindingRetirement'; +import { runWithClient } from './runWithClient'; + +beforeEach((): void => { + vi.clearAllMocks(); +}); + +afterEach((): void => { + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +it('keeps same-account physical replacements in one lifetime and aborts it synchronously on session end', (): void => { + const binding = { clusterId: 'lifetime-signal', fingerprint: 'same-account', generation: 1 }; + const replacement = { ...binding, generation: 2 }; + const signal = getBindingLifetimeSignal(binding); + const abort = vi.fn(); + signal.addEventListener('abort', abort); + + expect(getBindingLifetimeSignal(replacement)).toBe(signal); + expect(isRetiredConnectionBinding(binding)).toBe(false); + expect(signal.aborted).toBe(false); + + retireConnectionBindings(binding.clusterId, replacement.generation, 'userDisconnected'); + + expect(abort).toHaveBeenCalledOnce(); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + expect(getBindingLifetimeSignal(replacement).aborted).toBe(true); + const fresh = getBindingLifetimeSignal({ ...binding, generation: 3 }); + expect(fresh).not.toBe(signal); + expect(fresh.aborted).toBe(false); +}); + +it('preserves the first reason per ended range without lowering the cutoff or ending the fresh lifetime twice', (): void => { + const binding = { clusterId: 'lifetime-reasons', fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 2, 'userDisconnected'); + const freshSignal = getBindingLifetimeSignal({ ...binding, generation: 3 }); + retireConnectionBindings(binding.clusterId, 1, 'connectionRemoved'); + retireConnectionBindings(binding.clusterId, 2, 'credentialsChanged'); + expect(freshSignal.aborted).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('userDisconnected'); + + retireConnectionBindings(binding.clusterId, 4, 'connectionRemoved'); + expect(freshSignal.aborted).toBe(true); + expect(getRetiredBindingReason({ ...binding, generation: 2 })).toBe('userDisconnected'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('connectionRemoved'); + expect(isRetiredConnectionBinding({ ...binding, generation: 4 })).toBe(true); + expect(getRetiredBindingReason({ ...binding, generation: 5 })).toBeUndefined(); +}); + +it('corrects only the last failed removal without reviving signals or changing an earlier disconnected range', (): void => { + const first = { clusterId: 'failed-removal-reasons', fingerprint: 'same-account', generation: 1 }; + const firstSignal = getBindingLifetimeSignal(first); + retireConnectionBindings(first.clusterId, 1, 'userDisconnected'); + const second = { ...first, generation: 2 }; + const secondSignal = getBindingLifetimeSignal(second); + retireConnectionBindings(first.clusterId, 2, 'connectionRemoved'); + const freshSignal = getBindingLifetimeSignal({ ...first, generation: 3 }); + + expect(correctFailedRemovalRetirement(first.clusterId, 2)).toBe(true); + expect(getRetiredBindingReason(first)).toBe('userDisconnected'); + expect(getRetiredBindingReason(second)).toBe('userDisconnected'); + expect(firstSignal.aborted).toBe(true); + expect(secondSignal.aborted).toBe(true); + expect(getBindingLifetimeSignal(second).aborted).toBe(true); + expect(freshSignal.aborted).toBe(false); + expect(() => ClustersClient.assertBindingActive(second)).toThrow( + expect.objectContaining({ reason: 'userDisconnected' }), + ); + expect(correctFailedRemovalRetirement(first.clusterId, 2)).toBe(true); +}); + +it('does not correct a missing, wrong or superseded removal generation', (): void => { + const binding = { clusterId: 'superseded-removal-reasons', fingerprint: 'same-account', generation: 2 }; + expect(correctFailedRemovalRetirement(binding.clusterId, 2)).toBe(false); + retireConnectionBindings(binding.clusterId, 2, 'connectionRemoved'); + expect(correctFailedRemovalRetirement(binding.clusterId, 1)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + retireConnectionBindings(binding.clusterId, 3, 'connectionRemoved'); + expect(correctFailedRemovalRetirement(binding.clusterId, 2)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('connectionRemoved'); +}); + +it.each(['userDisconnected', 'credentialsChanged'] as const)( + 'accepts the matching last generation without changing a range ended for %s', + (reason): void => { + const binding = { clusterId: `non-removal-reasons-${reason}`, fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 1, reason); + expect(correctFailedRemovalRetirement(binding.clusterId, 1)).toBe(true); + expect(getRetiredBindingReason(binding)).toBe(reason); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + }, +); + +it('checks stored lifetime reasons before a later hold, while live bindings obey the current hold', (): void => { + const binding = { clusterId: 'lifetime-hold', fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 1, 'userDisconnected'); + vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue('credentialsRejected'); + expect(() => ClustersClient.assertBindingActive(binding)).toThrow( + expect.objectContaining({ reason: 'userDisconnected' }), + ); + expect(() => ClustersClient.assertBindingActive({ ...binding, generation: 2 })).toThrow( + expect.objectContaining({ reason: 'credentialsRejected' }), + ); +}); + +it('rejects a client resolved across retirement before it can reach a driver operation', async (): Promise => { + const binding = { clusterId: 'lifetime-pending-resolution', fingerprint: 'same-account', generation: 1 }; + let release!: (client: ClustersClient) => void; + const pending = new Promise((resolve) => { + release = resolve; + }); + const acquisition = vi.spyOn( + ClustersClient as unknown as { acquireClient: () => Promise }, + 'acquireClient', + ).mockReturnValue(pending); + const effect = vi.fn(); + const operation = runWithClient(binding, effect); + expect(acquisition).toHaveBeenCalledOnce(); + retireConnectionBindings(binding.clusterId, 1, 'connectionRemoved'); + release({ binding: { ...binding, generation: 2 } } as ClustersClient); + await expect(operation).resolves.toEqual({ unavailable: { reason: 'connectionRemoved' } }); + expect(effect).not.toHaveBeenCalled(); +}); + +it('never acquires, polls the database or prompts for an ended binding; a fresh background operation works once', async (): Promise => { + vi.useFakeTimers(); + const binding: ConnectionBinding = { + clusterId: 'lifetime-background', + fingerprint: 'same-account', + generation: 1, + }; + const replacement = { binding: { ...binding, generation: 2 } } as ClustersClient; + const acquisition = vi.spyOn( + ClustersClient as unknown as { acquireClient: () => Promise }, + 'acquireClient', + ).mockResolvedValue(replacement); + const database = vi.fn(async (): Promise => {}); + retireConnectionBindings(binding.clusterId, 1, 'userDisconnected'); + const poll = vi.fn(async (): Promise => { + await runWithClient(binding, database, { background: true }); + }); + const timer = setInterval(() => void poll(), 100); + try { + await vi.advanceTimersByTimeAsync(500); + } finally { + clearInterval(timer); + } + expect(poll).toHaveBeenCalledTimes(5); + expect(acquisition).not.toHaveBeenCalled(); + expect(database).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + await runWithClient(replacement.binding, database, { background: true }); + expect(acquisition).toHaveBeenCalledOnce(); + expect(database).toHaveBeenCalledExactlyOnceWith(replacement); +}); diff --git a/src/documentdb/connectionBindingRetirement.ts b/src/documentdb/connectionBindingRetirement.ts index cedb5ba99..9a6c4c293 100644 --- a/src/documentdb/connectionBindingRetirement.ts +++ b/src/documentdb/connectionBindingRetirement.ts @@ -5,13 +5,63 @@ import { type ConnectionBinding } from './ClustersClient'; -const retiredThroughGeneration = new Map(); +export type EndedLifetimeReason = 'userDisconnected' | 'connectionRemoved' | 'credentialsChanged'; -export function retireConnectionBindings(clusterId: string, generation: number): void { - retiredThroughGeneration.set(clusterId, Math.max(retiredThroughGeneration.get(clusterId) ?? 0, generation)); +interface BindingLifetime { + readonly ended: { readonly generation: number; readonly reason: EndedLifetimeReason }[]; + controller: AbortController; } -export function isRetiredConnectionBinding({ clusterId, generation }: ConnectionBinding): boolean { - const retiredThrough = retiredThroughGeneration.get(clusterId); - return retiredThrough !== undefined && generation <= retiredThrough; +const lifetimes = new Map(); +const endedSignal = AbortSignal.abort(); + +export function retireConnectionBindings( + clusterId: string, + generation: number, + reason: EndedLifetimeReason, +): void { + const lifetime: BindingLifetime = lifetimes.get(clusterId) ?? { ended: [], controller: new AbortController() }; + if (generation <= (lifetime.ended.at(-1)?.generation ?? -1)) { + return; + } + lifetime.ended.push({ generation, reason }); + const controller = lifetime.controller; + lifetime.controller = new AbortController(); + lifetimes.set(clusterId, lifetime); + controller.abort(); +} + +export function getRetiredBindingReason({ + clusterId, + generation, +}: ConnectionBinding): EndedLifetimeReason | undefined { + return lifetimes.get(clusterId)?.ended.find((range) => generation <= range.generation)?.reason; +} + +export function correctFailedRemovalRetirement(clusterId: string, generation: number): boolean { + const lifetime = lifetimes.get(clusterId); + const last = lifetime?.ended.at(-1); + if (!lifetime || !last || last.generation !== generation) { + return false; + } + if (last.reason === 'connectionRemoved') { + lifetime.ended[lifetime.ended.length - 1] = { generation, reason: 'userDisconnected' }; + } + return true; +} + +export function isRetiredConnectionBinding(binding: ConnectionBinding): boolean { + return getRetiredBindingReason(binding) !== undefined; +} + +export function getBindingLifetimeSignal(binding: ConnectionBinding): AbortSignal { + if (isRetiredConnectionBinding(binding)) { + return endedSignal; + } + let lifetime = lifetimes.get(binding.clusterId); + if (!lifetime) { + lifetime = { ended: [], controller: new AbortController() }; + lifetimes.set(binding.clusterId, lifetime); + } + return lifetime.controller.signal; } diff --git a/src/documentdb/connectionSurfaces.test.ts b/src/documentdb/connectionSurfaces.test.ts index 23957e479..47d039f63 100644 --- a/src/documentdb/connectionSurfaces.test.ts +++ b/src/documentdb/connectionSurfaces.test.ts @@ -4,7 +4,12 @@ *--------------------------------------------------------------------------------------------*/ import { expect, it, vi } from 'vitest'; -import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; +import { + getConnectionSurfaces, + registerConnectionSurface, + takeConnectionSurfaces, + type ConnectionSurface, +} from './connectionSurfaces'; it('keeps teardown scoped to the current registered surfaces for one cluster', (): void => { const makeSurface = (clusterId: string, kind: ConnectionSurface['kind']): ConnectionSurface => ({ @@ -13,6 +18,7 @@ it('keeps teardown scoped to the current registered surfaces for one cluster', ( disable: vi.fn(), dispose: vi.fn(), }); + const document = makeSurface('cluster-a', 'documentView'); const dashboard = makeSurface('cluster-a', 'clusterDashboard'); const otherCluster = makeSurface('cluster-b', 'collectionView'); @@ -34,3 +40,29 @@ it('keeps teardown scoped to the current registered surfaces for one cluster', ( expect(getConnectionSurfaces('cluster-a')).toEqual([]); expect(getConnectionSurfaces('cluster-b')).toEqual([]); }); + +it('detaches ended surfaces without disposing snapshots or letting their registrations remove fresh surfaces', (): void => { + const old: ConnectionSurface = { + clusterId: 'detached-cluster', + kind: 'documentView', + isDirty: () => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + const fresh: ConnectionSurface = { ...old, dispose: vi.fn() }; + const oldRegistration = registerConnectionSurface(old); + expect(takeConnectionSurfaces(old.clusterId)).toEqual([old]); + expect(getConnectionSurfaces(old.clusterId)).toEqual([]); + expect(takeConnectionSurfaces(old.clusterId)).toEqual([]); + const freshRegistration = registerConnectionSurface(fresh); + try { + oldRegistration.dispose(); + expect(getConnectionSurfaces(old.clusterId)).toEqual([fresh]); + expect(old.isDirty?.()).toBe(true); + expect(old.dispose).not.toHaveBeenCalled(); + expect(old.disable).not.toHaveBeenCalled(); + } finally { + oldRegistration.dispose(); + freshRegistration.dispose(); + } +}); diff --git a/src/documentdb/connectionSurfaces.ts b/src/documentdb/connectionSurfaces.ts index f48f199fd..c65125aec 100644 --- a/src/documentdb/connectionSurfaces.ts +++ b/src/documentdb/connectionSurfaces.ts @@ -27,7 +27,7 @@ export function registerConnectionSurface(surface: ConnectionSurface): Disposabl surfaces.add(surface); return { dispose(): void { - if (surfaces.delete(surface) && surfaces.size === 0) { + if (surfaces.delete(surface) && surfaces.size === 0 && surfacesByCluster.get(clusterId) === surfaces) { surfacesByCluster.delete(clusterId); } }, @@ -37,3 +37,9 @@ export function registerConnectionSurface(surface: ConnectionSurface): Disposabl export function getConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { return [...(surfacesByCluster.get(clusterId) ?? [])]; } + +export function takeConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { + const surfaces = getConnectionSurfaces(clusterId); + surfacesByCluster.delete(clusterId); + return surfaces; +} diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts index 03bc04070..0815d11d0 100644 --- a/src/documentdb/connectionTeardown.test.ts +++ b/src/documentdb/connectionTeardown.test.ts @@ -7,7 +7,14 @@ import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; -import { registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; +import { + getBindingLifetimeSignal, + getRetiredBindingReason, + retireConnectionBindings, + type EndedLifetimeReason, +} from './connectionBindingRetirement'; +import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; +import { type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { commitTeardown, confirmTeardown, @@ -24,6 +31,9 @@ const mocks = vi.hoisted(() => ({ latch: vi.fn(), unlatch: vi.fn(), deleteClient: vi.fn(), + exists: vi.fn(), + hasPendingStartup: vi.fn(), + retireBoundViews: vi.fn(), clearLastVerifiedIdentity: vi.fn(), deleteCredentials: vi.fn(), clearEntraTokenFailure: vi.fn(), @@ -55,7 +65,7 @@ vi.mock('../services/SettingsService', () => ({ SettingsService: { getSetting: m vi.mock('../services/taskService/taskService', () => ({ TaskService: { getConflictingTasks: mocks.getConflictingTasks }, })); -vi.mock('./ClustersClient', () => ({ ClustersClient: { ...mocks, exists: () => true } })); +vi.mock('./ClustersClient', () => ({ ClustersClient: mocks })); vi.mock('./CredentialCache', () => ({ CredentialCache: { deleteCredentials: mocks.deleteCredentials } })); vi.mock('./auth/entraErrors/entraTokenFailures', () => ({ clearEntraTokenFailure: mocks.clearEntraTokenFailure })); vi.mock('./shell/ShellTerminalLinkProvider', () => ({ @@ -83,6 +93,9 @@ describe('connection teardown', () => { beforeEach(() => { vi.resetAllMocks(); mocks.getConflictingTasks.mockReturnValue([]); + mocks.exists.mockReturnValue(true); + mocks.hasPendingStartup.mockReturnValue(false); + mocks.retireBoundViews.mockReturnValue(1); mocks.getRegisteredShellTerminals.mockReturnValue([]); mocks.getPlaygroundEvaluators.mockReturnValue(new Map()); vi.spyOn(vscode.l10n, 't').mockImplementation(l10n.t); @@ -130,21 +143,36 @@ describe('connection teardown', () => { }); mocks.getSetting.mockReturnValue('keepOpenDisabled'); const draft = register('documentView', true); + const binding = { clusterId, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, binding.generation, reason); + return binding.generation; + }); const untouchedView = register('documentView', true, otherId); const failedDelete = new Error('Storage write failed'); + let fresh: ConnectionSurface | undefined; await expect( withConnectionRemoval([clusterId, otherId], async (remove) => { await remove(clusterId, async () => { expect(latches.get(otherId)).toBe('connectionRemoved'); expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + fresh = register('collectionView'); throw failedDelete; }); }), ).rejects.toBe(failedDelete); expect(latches.get(clusterId)).toBe('userDisconnected'); - expect(draft.disable).toHaveBeenLastCalledWith('userDisconnected'); + expect(vi.mocked(draft.disable).mock.calls).toEqual([['connectionRemoved'], ['userDisconnected']]); + expect(getRetiredBindingReason(binding)).toBe('userDisconnected'); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + expect(getBindingLifetimeSignal({ ...binding, generation: 2 }).aborted).toBe(false); + expect(getConnectionSurfaces(clusterId)).toEqual([fresh]); + expect(fresh?.disable).not.toHaveBeenCalled(); + expect(draft.isDirty?.()).toBe(true); expect(draft.dispose).not.toHaveBeenCalled(); expect(latches.has(otherId)).toBe(false); expect(untouchedView.disable).not.toHaveBeenCalled(); @@ -292,4 +320,293 @@ describe('connection teardown', () => { expect(latchForTeardown([clusterId, otherId], 'connectionRemoved')).toBe(false); expect(mocks.latch).not.toHaveBeenCalled(); }); + + it.each([false, true])( + 'retires and detaches the lifetime before any surface, worker or asynchronous close (already latched: %s)', + async (alreadyLatched): Promise => { + const target = `ordered-teardown-${alreadyLatched}`; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + if (alreadyLatched) { + mocks.getLatchReason.mockReturnValue('connectionRemoved'); + } + mocks.retireBoundViews.mockImplementation((id: string, reason: 'connectionRemoved'): number => { + expect(alreadyLatched || mocks.latch.mock.calls.length === 1).toBe(true); + retireConnectionBindings(id, 1, reason); + return 1; + }); + const onRetired = vi.fn((generation: number, surfaces: readonly ConnectionSurface[]): void => { + expect(generation).toBe(1); + expect(surfaces).toEqual([draft]); + expect(signal.aborted).toBe(true); + expect(getConnectionSurfaces(target)).toEqual([]); + expect(draft.disable).not.toHaveBeenCalled(); + }); + vi.mocked(draft.disable).mockImplementation((): void => { + expect(signal.aborted).toBe(true); + expect(getConnectionSurfaces(target)).toEqual([]); + }); + const disconnect = vi.fn((): void => { + expect(signal.aborted).toBe(true); + expect(draft.disable).toHaveBeenCalledOnce(); + }); + mocks.getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId: target }, disconnect }]); + let finishClose!: () => void; + mocks.deleteClient.mockImplementation((): Promise => { + expect(signal.aborted).toBe(true); + return new Promise((resolve) => { + finishClose = resolve; + }); + }); + const teardown = commitTeardown(target, { + reason: 'connectionRemoved', + choice: 'keepOpenDisabled', + alreadyLatched, + onRetired, + refreshTree, + }); + expect(signal.aborted).toBe(true); + expect(onRetired).toHaveBeenCalledOnce(); + expect(disconnect).toHaveBeenCalledOnce(); + expect(refreshTree).not.toHaveBeenCalled(); + finishClose(); + await expect(teardown).resolves.toBe('committed'); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(draft.isDirty?.()).toBe(true); + }, + ); + + it.each(['userDisconnected', 'connectionRemoved'] as const)( + 'keeps an old dirty snapshot out of the next session %s Close all, dirty confirmation and counts', + async (reason): Promise => { + const draft = register('documentView', true); + const collection = register('collectionView'); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + const fresh = register('collectionView'); + mocks.getSetting.mockReturnValue('closeAll'); + await teardownConnection(clusterId, reason, refreshTree); + + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.isDirty?.()).toBe(true); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(collection.dispose).not.toHaveBeenCalled(); + expect(fresh.dispose).toHaveBeenCalledOnce(); + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.event).toHaveBeenLastCalledWith( + 'connection.disconnect', + expect.objectContaining({ measurements: expect.objectContaining({ surfaceCount: 1 }) }), + ); + }, + ); + + it.each(['surface', 'startup', 'evaluator', 'shell', 'heldClient'] as const)( + 'tears down surviving %s even when the cached connection is absent or credentials are rejected', + async (survivor): Promise => { + mocks.exists.mockReturnValue(survivor === 'heldClient'); + mocks.getLatchReason.mockReturnValue('credentialsRejected'); + const draft = survivor === 'surface' ? register('documentView', true) : undefined; + const disconnect = vi.fn(); + mocks.hasPendingStartup.mockReturnValue(survivor === 'startup'); + if (survivor === 'evaluator') { + mocks.getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + } + if (survivor === 'shell') { + mocks.getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + } + await expect( + commitTeardown(clusterId, { reason: 'userDisconnected', choice: 'keepOpenDisabled', refreshTree }), + ).resolves.toBe('committed'); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); + expect(mocks.deleteClient).toHaveBeenCalledOnce(); + if (draft) { + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + } + if (survivor === 'shell') { + expect(disconnect).toHaveBeenCalledOnce(); + } + }, + ); + + it.each(['userDisconnected', 'connectionRemoved', 'credentialsUpdating', undefined] as const)( + 'skips only terminal %s or a fully idle target', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + if (reason) { + register('collectionView'); + mocks.hasPendingStartup.mockReturnValue(true); + } + await expect( + commitTeardown(clusterId, { reason: 'userDisconnected', choice: 'close', refreshTree }), + ).resolves.toBe('superseded'); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.retireBoundViews).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); + + it.each(['epoch', 'laterGeneration'] as const)( + 'does not correct a failed Remove superseded by %s during storage deletion', + async (superseding): Promise => { + const target = `superseded-removal-${superseding}`; + const old = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const later = { ...old, generation: 2 }; + let epoch = 0; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation(() => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, old.generation, reason); + return old.generation; + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + const draft = register('documentView', true, target); + const oldSignal = getBindingLifetimeSignal(old); + let fresh: ConnectionSurface | undefined; + const failedDelete = new Error('Storage write failed'); + + await expect( + withConnectionRemoval([target], async (remove) => { + await remove(target, async () => { + fresh = register('collectionView', false, target); + if (superseding === 'epoch') { + epoch++; + } + retireConnectionBindings(target, later.generation, 'connectionRemoved'); + throw failedDelete; + }); + }), + ).rejects.toBe(failedDelete); + + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(latch).toBe('connectionRemoved'); + expect(getRetiredBindingReason(old)).toBe('connectionRemoved'); + expect(getRetiredBindingReason(later)).toBe('connectionRemoved'); + expect(oldSignal.aborted).toBe(true); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + expect(fresh?.disable).not.toHaveBeenCalled(); + expect(getConnectionSurfaces(target)).toEqual([fresh]); + }, + ); + + it.each(['disconnect', 'failedRemove', 'credentialsChanged'] as const)( + 'restores the still-stored connection after repeated same-generation failed Removes following %s', + async (preceding): Promise => { + const target = `repeated-removal-${preceding}`; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + let epoch = 0; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation((): ConnectionUnavailableReason | undefined => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, binding.generation, reason); + return binding.generation; + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + if (preceding !== 'failedRemove') { + await expect( + commitTeardown(target, { + reason: preceding === 'disconnect' ? 'userDisconnected' : 'credentialsChanged', + choice: 'keepOpenDisabled', + refreshTree, + }), + ).resolves.toBe('committed'); + } + let nextSignal: AbortSignal | undefined; + for (let attempt = 0; attempt < 2; attempt++) { + const captured = register('documentView', true, target); + const fresh: ConnectionSurface = { + clusterId: target, + kind: 'collectionView', + disable: vi.fn(), + dispose: vi.fn(), + }; + let freshRegistration: vscode.Disposable | undefined; + const failedDelete = new Error('Storage write failed'); + const deleteStored = vi.fn(async (): Promise => { + freshRegistration = registerConnectionSurface(fresh); + throw failedDelete; + }); + try { + await expect( + withConnectionRemoval([target], async (remove) => { + await remove(target, deleteStored); + }), + ).rejects.toBe(failedDelete); + + expect(deleteStored).toHaveBeenCalledOnce(); + expect(latch).toBe('userDisconnected'); + expect(getRetiredBindingReason(binding)).toBe( + preceding === 'credentialsChanged' ? 'credentialsChanged' : 'userDisconnected', + ); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + const currentNextSignal = getBindingLifetimeSignal({ ...binding, generation: 2 }); + expect(currentNextSignal.aborted).toBe(false); + if (nextSignal) { + expect(currentNextSignal).toBe(nextSignal); + } + nextSignal = currentNextSignal; + expect(vi.mocked(captured.disable).mock.calls).toEqual([ + ['connectionRemoved'], + ['userDisconnected'], + ]); + expect(captured.isDirty?.()).toBe(true); + expect(captured.dispose).not.toHaveBeenCalled(); + expect(fresh.disable).not.toHaveBeenCalled(); + expect(getConnectionSurfaces(target)).toEqual([fresh]); + } finally { + freshRegistration?.dispose(); + } + } + expect(draft.isDirty?.()).toBe(true); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(vi.mocked(draft.disable).mock.calls).toEqual( + preceding === 'failedRemove' + ? [['connectionRemoved'], ['userDisconnected']] + : [[preceding === 'disconnect' ? 'userDisconnected' : 'credentialsChanged']], + ); + }, + ); + + it('leaves a successful Remove retirement unchanged and reports storage success only after deletion', async (): Promise => { + const target = 'successful-removal'; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + mocks.getEpoch.mockReturnValue(1); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + mocks.getLatchReason.mockReturnValue(reason); + }); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, binding.generation, reason); + return binding.generation; + }); + const deleteStored = vi.fn(async (): Promise => { + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + expect(signal.aborted).toBe(true); + }); + await withConnectionRemoval([target], async (remove) => { + await remove(target, deleteStored); + }); + + expect(deleteStored).toHaveBeenCalledOnce(); + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + }); }); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts index b52147385..06c8b703f 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -16,7 +16,8 @@ import { TaskService } from '../services/taskService/taskService'; import { settingsKeys } from '../settingsKeys'; import { clearEntraTokenFailure } from './auth/entraErrors/entraTokenFailures'; import { ClustersClient } from './ClustersClient'; -import { getConnectionSurfaces } from './connectionSurfaces'; +import { correctFailedRemovalRetirement } from './connectionBindingRetirement'; +import { getConnectionSurfaces, takeConnectionSurfaces, type ConnectionSurface } from './connectionSurfaces'; import { CredentialCache } from './CredentialCache'; import { getRegisteredShellTerminals } from './shell/ShellTerminalLinkProvider'; @@ -33,6 +34,7 @@ export interface TeardownOptions { readonly dropCredentials?: boolean; /** A caller that fenced a batch or a save must still hold the matching latch. */ readonly alreadyLatched?: boolean; + readonly onRetired?: (generation: number, surfaces: readonly ConnectionSurface[]) => void; readonly refreshTree: () => void; } @@ -122,15 +124,23 @@ export async function commitTeardown( clusterId: string, options: TeardownOptions, ): Promise<'committed' | 'blockedByTask' | 'superseded'> { - const { reason, choice, dropCredentials, alreadyLatched, refreshTree } = options; + const { reason, choice, dropCredentials, alreadyLatched, onRetired, refreshTree } = options; if (alreadyLatched) { if (ClustersClient.getLatchReason(clusterId) !== reason) { return 'superseded'; } } else { + const latch = ClustersClient.getLatchReason(clusterId); if ( reason === 'userDisconnected' && - (!ClustersClient.exists(clusterId) || ClustersClient.getLatchReason(clusterId)) + (latch === 'userDisconnected' || + latch === 'connectionRemoved' || + latch === 'credentialsUpdating' || + (!ClustersClient.exists(clusterId) && + !ClustersClient.hasPendingStartup(clusterId) && + getConnectionSurfaces(clusterId).length === 0 && + !getPlaygroundEvaluators().has(clusterId) && + !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId))) ) { return 'superseded'; } @@ -141,7 +151,10 @@ export async function commitTeardown( } try { - for (const surface of getConnectionSurfaces(clusterId)) { + const generation = ClustersClient.retireBoundViews(clusterId, reason); + const surfaces = takeConnectionSurfaces(clusterId); + onRetired?.(generation, surfaces); + for (const surface of surfaces) { if (choice === 'close') { surface.dispose(); } else { @@ -195,7 +208,16 @@ async function removeConnections( properties.surfacesChoice = confirmed.choice; const targets = new Map( - clusterIds(ids).map((id) => [id, { previous: ClustersClient.getLatchReason(id), epoch: 0, started: false }]), + clusterIds(ids).map((id) => [ + id, + { + previous: ClustersClient.getLatchReason(id), + epoch: 0, + started: false, + generation: undefined as number | undefined, + surfaces: [] as readonly ConnectionSurface[], + }, + ]), ); if ( [...targets.values()].some( @@ -229,6 +251,10 @@ async function removeConnections( choice: confirmed.choice, dropCredentials: true, alreadyLatched: true, + onRetired: (generation, surfaces): void => { + target.generation = generation; + target.surfaces = surfaces; + }, refreshTree: () => {}, }); if (result !== 'committed' || ClustersClient.getEpoch(id) !== target.epoch) { @@ -247,10 +273,15 @@ async function removeConnections( } if (target.started) { // A failed storage delete must not leave the surviving connection locked as removed. - ClustersClient.latch(id, 'userDisconnected'); - if (confirmed.choice === 'keepOpenDisabled') { - for (const surface of getConnectionSurfaces(id)) { - surface.disable('userDisconnected'); + if ( + target.generation !== undefined && + correctFailedRemovalRetirement(id, target.generation) + ) { + ClustersClient.latch(id, 'userDisconnected'); + if (confirmed.choice === 'keepOpenDisabled') { + for (const surface of target.surfaces) { + surface.disable('userDisconnected'); + } } } } else if (target.previous) { diff --git a/src/webviews/documentdb/boundViewOperations.ts b/src/webviews/documentdb/boundViewOperations.ts index 69cfad9d4..2f285b112 100644 --- a/src/webviews/documentdb/boundViewOperations.ts +++ b/src/webviews/documentdb/boundViewOperations.ts @@ -6,7 +6,7 @@ import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; -import { isRetiredConnectionBinding } from '../../documentdb/connectionBindingRetirement'; +import { getRetiredBindingReason } from '../../documentdb/connectionBindingRetirement'; import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { runWithClient } from '../../documentdb/runWithClient'; import { @@ -27,9 +27,7 @@ export async function recoverBoundView( return { recovered: { text: '' } }; } - const reason = isRetiredConnectionBinding(binding) - ? 'credentialsChanged' - : ClustersClient.getLatchReason(binding.clusterId); + const reason = getRetiredBindingReason(binding) ?? ClustersClient.getLatchReason(binding.clusterId); if (reason) { return describeUnavailableConnection(reason); } @@ -61,9 +59,7 @@ export function guardBoundViewOperation(binding: ConnectionBinding, signal?: Abo if (signal?.aborted) { throw new UserCancelledError('staleBoundViewOperation'); } - const reason = isRetiredConnectionBinding(binding) - ? 'credentialsChanged' - : ClustersClient.getLatchReason(clusterId); + const reason = getRetiredBindingReason(binding) ?? ClustersClient.getLatchReason(clusterId); if (reason) { throw new ConnectionUnavailableError(reason); } diff --git a/src/webviews/documentdb/collectionView/collectionViewController.test.ts b/src/webviews/documentdb/collectionView/collectionViewController.test.ts index 590fa34c3..db3cbc7f0 100644 --- a/src/webviews/documentdb/collectionView/collectionViewController.test.ts +++ b/src/webviews/documentdb/collectionView/collectionViewController.test.ts @@ -128,6 +128,20 @@ it('registers the Collection View and pushes a typed unavailable payload', (): v expect(getConnectionSurfaces(clusterId)).toEqual([]); }); +it('detaches a kept Collection snapshot without disposing it or touching the next panel registration', (): void => { + openPanel(); + const [snapshot] = getConnectionSurfaces(clusterId); + const oldDispose = vi.spyOn(opened[0], 'dispose'); + snapshot.disable('userDisconnected'); + expect(getConnectionSurfaces(clusterId)).toEqual([]); + expect(oldDispose).not.toHaveBeenCalled(); + openPanel('fresh'); + const [fresh] = getConnectionSurfaces(clusterId); + expect(fresh).not.toBe(snapshot); + opened[0].dispose(); + expect(getConnectionSurfaces(clusterId)).toEqual([fresh]); +}); + it('reconnects the existing session without replaying a query', async (): Promise => { openPanel(); mocks.resolveBoundClient.mockResolvedValue({ binding: { ...originalBinding, generation: 2 } }); diff --git a/src/webviews/documentdb/collectionView/collectionViewController.ts b/src/webviews/documentdb/collectionView/collectionViewController.ts index 77e350699..cc42360a4 100644 --- a/src/webviews/documentdb/collectionView/collectionViewController.ts +++ b/src/webviews/documentdb/collectionView/collectionViewController.ts @@ -83,6 +83,7 @@ export function openCollectionWebview( const binding = ClusterSession.getSession(initialData.sessionId).getBinding(); const postUnavailable = (reason: ConnectionUnavailableReason): void => { + registration.dispose(); const message: ConnectionUnavailableMessage = { type: 'collectionView.connectionUnavailable', unavailable: describeUnavailableConnection(reason).unavailable, diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts index 9cb9ba85d..887c1fe25 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts @@ -3,8 +3,10 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { beforeEach, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; +import { ClustersClient } from '../../../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../../../documentdb/connectionBindingRetirement'; import { ConnectionUnavailableError } from '../../../documentdb/ConnectionUnavailableError'; import { DocumentViewMode } from '../../../documentdb/DocumentViewMode'; import { API } from '../../../DocumentDBExperiences'; @@ -16,18 +18,18 @@ const mocks = vi.hoisted(() => ({ getEpoch: vi.fn(), assertCurrent: vi.fn(), runFindQueryWithCache: vi.fn(), + getSession: vi.fn(), findCollection: vi.fn(), updateGlobalState: vi.fn(), })); +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal()), + callWithTelemetryAndErrorHandling: vi.fn(async (): Promise => {}), +})); vi.mock('../../../documentdb/ClusterSession', () => ({ ClusterSession: { - getSession: () => ({ - getBinding: mocks.getBinding, - getEpoch: mocks.getEpoch, - assertCurrent: mocks.assertCurrent, - runFindQueryWithCache: mocks.runFindQueryWithCache, - }), + getSession: mocks.getSession, }, })); vi.mock('../../../extensionVariables', () => ({ @@ -58,12 +60,12 @@ const describeUnavailable = vi.fn((reason: ConnectionUnavailableError['reason']) })); const callCollectionView = createCallerFactory(collectionsViewRouter); -function createCaller(): ReturnType { +function createCaller(sessionId = 'session', clusterId = binding.clusterId): ReturnType { const context: RouterContext = { dbExperience: API.DocumentDB, webviewName: 'collectionView', - sessionId: 'session', - clusterId: binding.clusterId, + sessionId, + clusterId, clusterDisplayName: 'Cluster', viewId: 'connectionsView', databaseName: 'database', @@ -81,9 +83,19 @@ beforeEach((): void => { })); mocks.getBinding.mockReturnValue(binding); mocks.getEpoch.mockReturnValue(1); + mocks.getSession.mockReturnValue({ + getBinding: mocks.getBinding, + getEpoch: mocks.getEpoch, + assertCurrent: mocks.assertCurrent, + runFindQueryWithCache: mocks.runFindQueryWithCache, + }); vi.spyOn(vscode.commands, 'executeCommand').mockResolvedValue(undefined); }); +afterEach((): void => { + vi.restoreAllMocks(); +}); + it('returns structured unavailability from a Collection View query', async (): Promise => { mocks.runFindQueryWithCache.mockRejectedValueOnce(new ConnectionUnavailableError('credentialsRejected')); @@ -141,3 +153,63 @@ it('captures the transfer binding before asynchronous collection lookup', async }, ); }); + +it.each(['userDisconnected', 'connectionRemoved', 'credentialsChanged'] as const)( + 'preserves the old Collection query and blocks its RPC after %s; a fresh session queries once', + async (reason): Promise => { + const { ClusterSession } = await vi.importActual( + '../../../documentdb/ClusterSession', + ); + const old = { ...binding, clusterId: `collection-ended-${reason}` }; + const fresh = { ...old, generation: 2 }; + const database = vi.fn().mockResolvedValue([]); + const client = { binding: old, runFindQuery: database } as unknown as ClustersClient; + const replacement = { binding: fresh, runFindQuery: database } as unknown as ClustersClient; + const getClient = vi.spyOn(ClustersClient, 'getClient').mockResolvedValue(client); + const acquisition = vi.spyOn( + ClustersClient as unknown as { acquireClient: () => Promise }, + 'acquireClient', + ).mockResolvedValue(client); + const getBinding = vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(old); + mocks.getSession.mockImplementation((sessionId: string) => ClusterSession.getSession(sessionId)); + const oldId = await ClusterSession.initNewSession(old.clusterId); + let freshId: string | undefined; + try { + const snapshot = createCaller(oldId, old.clusterId); + const query = { + filter: '{"field":"snapshot"}', + pageNumber: 1, + pageSize: 50, + executionIntent: 'refresh' as const, + }; + await expect(snapshot.runFindQuery(query)).resolves.toEqual({ documentCount: 0 }); + expect(database).toHaveBeenCalledOnce(); + retireConnectionBindings(old.clusterId, old.generation, reason); + getBinding.mockReturnValue(fresh); + getClient.mockResolvedValue(replacement); + acquisition.mockResolvedValue(replacement); + freshId = await ClusterSession.initNewSession(old.clusterId); + acquisition.mockClear(); + database.mockClear(); + + await expect(snapshot.runFindQuery({ ...query, filter: '{"field":"new"}' })).resolves.toMatchObject({ + unavailable: { reason }, + }); + await expect(snapshot.getFieldCompletionData()).resolves.toMatchObject({ unavailable: { reason } }); + expect(acquisition).not.toHaveBeenCalled(); + expect(database).not.toHaveBeenCalled(); + expect(ClusterSession.getSession(oldId).getCurrentFindQueryParams().filter).toBe(query.filter); + + await expect(createCaller(freshId, old.clusterId).runFindQuery(query)).resolves.toEqual({ + documentCount: 0, + }); + expect(acquisition).toHaveBeenCalledOnce(); + expect(database).toHaveBeenCalledOnce(); + } finally { + ClusterSession.closeSession(oldId); + if (freshId) { + ClusterSession.closeSession(freshId); + } + } + }, +); diff --git a/src/webviews/documentdb/documentView/documentsViewController.test.ts b/src/webviews/documentdb/documentView/documentsViewController.test.ts index eeae65f45..93f7e52fb 100644 --- a/src/webviews/documentdb/documentView/documentsViewController.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewController.test.ts @@ -123,6 +123,22 @@ it('registers the panel, sends typed disable payloads and unregisters on dispose expect(context.binding).toBe(originalBinding); }); +it('detaches a kept dirty Document snapshot without discarding its panel or the next registration', (): void => { + const oldContext = openPanel(originalBinding, 'add'); + const [snapshot] = getConnectionSurfaces(clusterId); + const oldDispose = vi.spyOn(opened[0], 'dispose'); + snapshot.disable('userDisconnected'); + expect(snapshot.isDirty?.()).toBe(true); + expect(oldDispose).not.toHaveBeenCalled(); + expect(getConnectionSurfaces(clusterId)).toEqual([]); + openPanel({ ...originalBinding, generation: 2 }); + const [fresh] = getConnectionSurfaces(clusterId); + expect(fresh).not.toBe(snapshot); + opened[0].dispose(); + expect(getConnectionSurfaces(clusterId)).toEqual([fresh]); + expect(oldContext.binding).toBe(originalBinding); +}); + it('resumes a same-identity binding without replaying document operations', async (): Promise => { const context = openPanel(); mocks.resolveBoundClient.mockResolvedValue({ binding: { ...originalBinding, generation: 2 } }); diff --git a/src/webviews/documentdb/documentView/documentsViewController.ts b/src/webviews/documentdb/documentView/documentsViewController.ts index a21f6f96f..1537e4fed 100644 --- a/src/webviews/documentdb/documentView/documentsViewController.ts +++ b/src/webviews/documentdb/documentView/documentsViewController.ts @@ -52,6 +52,7 @@ export function openDocumentWebview( let dirty = initialData.mode === 'add'; const postUnavailable = (reason: ConnectionUnavailableReason): void => { + registration.dispose(); const message: ConnectionUnavailableMessage = { type: 'documentView.connectionUnavailable', unavailable: describeUnavailableConnection(reason).unavailable, diff --git a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts index 64db2c42b..8a18c2426 100644 --- a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts @@ -5,8 +5,12 @@ import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import { EJSON, ObjectId } from 'bson'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; -import { type ClustersClient } from '../../../documentdb/ClustersClient'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { type ClustersClient, type ConnectionBinding } from '../../../documentdb/ClustersClient'; +import { + correctFailedRemovalRetirement, + retireConnectionBindings, +} from '../../../documentdb/connectionBindingRetirement'; import { ConnectionUnavailableError } from '../../../documentdb/ConnectionUnavailableError'; import { API } from '../../../DocumentDBExperiences'; import { recordSurveyActivity } from '../../../services/survey/SurveyService'; @@ -48,16 +52,16 @@ const input = { documentContent: EJSON.stringify(document) }; const callDocumentView = createCallerFactory(documentsViewRouter); -function createCaller(signal?: AbortSignal): ReturnType { +function createCaller(signal?: AbortSignal, capturedBinding = binding): ReturnType { const context: RouterContext = { dbExperience: API.DocumentDB, webviewName: 'documentView', - clusterId: binding.clusterId, + clusterId: capturedBinding.clusterId, viewId: 'connectionsView', databaseName: 'database', collectionName: 'collection', documentId: 'id', - binding, + binding: capturedBinding, setDirty, describeUnavailable, recoverUnavailable, @@ -68,6 +72,10 @@ function createCaller(signal?: AbortSignal): ReturnType } describe('Document View bound operations', () => { + afterEach((): void => { + vi.restoreAllMocks(); + }); + beforeEach(() => { vi.resetAllMocks(); describeUnavailable.mockImplementation((reason: ConnectionUnavailableError['reason']) => ({ @@ -209,4 +217,88 @@ describe('Document View bound operations', () => { await expect(createCaller().saveDocument(input)).rejects.toMatchObject({ cause: failure }); expect(upsertDocument).toHaveBeenCalledOnce(); }); + + it.each(['userDisconnected', 'connectionRemoved', 'credentialsChanged'] as const)( + 'blocks an old Document RPC after %s before acquisition or driver calls; a fresh panel saves once', + async (reason): Promise => { + const { ClustersClient: actualClient } = await vi.importActual< + typeof import('../../../documentdb/ClustersClient') + >('../../../documentdb/ClustersClient'); + const old: ConnectionBinding = { ...binding, clusterId: `document-ended-${reason}` }; + const fresh = { ...old, generation: 2 }; + const acquisition = vi.spyOn( + actualClient as unknown as { acquireClient: () => Promise }, + 'acquireClient', + ).mockResolvedValue({ binding: fresh, pointRead, upsertDocument } as unknown as ClustersClient); + mocks.resolveBoundClient.mockImplementation(actualClient.resolveBoundClient); + mocks.getBinding.mockReturnValue(fresh); + const snapshot = createCaller(undefined, old); + await snapshot.reportDirty(true); + retireConnectionBindings(old.clusterId, old.generation, reason); + + await expect(snapshot.saveDocument(input)).resolves.toMatchObject({ unavailable: { reason } }); + await expect(snapshot.getDocumentById(serializedId)).resolves.toMatchObject({ unavailable: { reason } }); + expect(acquisition).not.toHaveBeenCalled(); + expect(upsertDocument).not.toHaveBeenCalled(); + expect(pointRead).not.toHaveBeenCalled(); + expect(setDirty).toHaveBeenCalledExactlyOnceWith(true); + expect(viewPanelTitleSetter).not.toHaveBeenCalled(); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + + upsertDocument.mockResolvedValue({ documentId: id, document }); + await expect(createCaller(undefined, fresh).saveDocument(input)).resolves.toMatchObject({ + documentId: serializedId, + }); + expect(acquisition).toHaveBeenCalledOnce(); + expect(upsertDocument).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + }, + ); + + it('reports a failed Remove as disconnected through an old RPC without acquiring or writing to the replacement', async (): Promise => { + const { ClustersClient: actualClient } = await vi.importActual< + typeof import('../../../documentdb/ClustersClient') + >('../../../documentdb/ClustersClient'); + const old = { ...binding, clusterId: 'document-failed-removal' }; + const fresh = { ...old, generation: 2 }; + const acquisition = vi.spyOn( + actualClient as unknown as { acquireClient: () => Promise }, + 'acquireClient', + ).mockResolvedValue({ binding: fresh, pointRead, upsertDocument } as unknown as ClustersClient); + mocks.resolveBoundClient.mockImplementation(actualClient.resolveBoundClient); + mocks.getBinding.mockReturnValue(fresh); + const snapshot = createCaller(undefined, old); + await snapshot.reportDirty(true); + retireConnectionBindings(old.clusterId, old.generation, 'connectionRemoved'); + expect(correctFailedRemovalRetirement(old.clusterId, old.generation)).toBe(true); + + await expect(snapshot.saveDocument(input)).resolves.toMatchObject({ + unavailable: { reason: 'userDisconnected' }, + }); + await expect(snapshot.getDocumentById(serializedId)).resolves.toMatchObject({ + unavailable: { reason: 'userDisconnected' }, + }); + expect(acquisition).not.toHaveBeenCalled(); + expect(upsertDocument).not.toHaveBeenCalled(); + expect(pointRead).not.toHaveBeenCalled(); + expect(setDirty).toHaveBeenCalledExactlyOnceWith(true); + }); + + it('keeps the draft and drops an already-sent save reply when the old lifetime ends without replay', async (): Promise => { + const old = { ...binding, clusterId: 'document-ended-save-reply' }; + mocks.getBinding.mockReturnValue({ ...old, generation: 2 }); + upsertDocument.mockImplementationOnce(async () => { + retireConnectionBindings(old.clusterId, old.generation, 'userDisconnected'); + return { documentId: id, document }; + }); + const caller = createCaller(undefined, old); + await caller.reportDirty(true); + await expect(caller.saveDocument(input)).resolves.toMatchObject({ + unavailable: { reason: 'userDisconnected' }, + }); + expect(upsertDocument).toHaveBeenCalledOnce(); + expect(setDirty).toHaveBeenCalledExactlyOnceWith(true); + expect(viewPanelTitleSetter).not.toHaveBeenCalled(); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + }); }); From 21c5442870c5fcc834b6448d45640d49d54d7462 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:31:58 +0000 Subject: [PATCH 10/62] docs: record approved WI-F1 boundary and final evidence Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 31 +++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index 7527c1b48..2c05f8ad0 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -776,7 +776,7 @@ npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/playg | --- | --- | --- | | **R — host pass; integrated/live pending** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. Commit/revision/command evidence is recorded under R below. | | **W — host pass; integrated/live pending** | Shell and Playground renew independently; explicit teardown stops the old worker, not the user's text. | Exercise both manager/evaluator suites, PTY and `executePlaygroundCode.test.ts`. Hold a token reply or evaluation across Disconnect, release it after reconnect: no delivery to the replacement worker, automatic command replay or silent rebinding; scrollback/file contents survive. Positive control: a valid pinned worker receives its reply and executes once. Commit/revision/command evidence is recorded under W below. | -| **F — not run** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. | +| **F — F1 host pass; F2/integrated pending** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. Commit/revision/command evidence is recorded under F1/F2 below. | | **E — not run** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. | | **U — not run** | X dismisses the frozen notice; Close closes the tab. Ordinary recoverable errors do not freeze it. | Update the existing rendered scenarios below. Keep a draft, dismiss with X, select/copy the original text, attempt Save, release a stale response: draft unchanged, no new save RPC. Close/cancel the dirty-close confirmation separately. Pair with a failed live query → same-account repair → user runs again in the **same tab**, with no unlock RPC and no automatic replay. On uncertain write outcome retain text and never claim nothing was written. | | **H — not run** | Shared host checks stop delayed side effects without making ordinary reads carry identity policy. | Exercise [review cases C01–C03](./02-pr1136-copilot-review.md): pause create after client resolution; pause query generation before sampling and again at model selection; pause Playground document opening, including a retained Shell link. End the old lifetime, install the replacement, release the pause. Assert zero stale writes, replacement-schema samples, model sends after invalidation, or replacement bindings, as applicable. Run the same paths without invalidation to rule out a blanket disable. Use fake DB/model boundaries, not real data or model calls. | @@ -836,7 +836,7 @@ shared controllers/routers and teardown edits so every work-item commit has clea Evidence: runner `05e84afa-064f-49cb-95bb-5e07f6ac1441`, corrected-test rerun. The root build also passed on the stabilized R/W/F1 working candidate (43 s); no test type errors remained. Integrated candidate rerun is still required. -- **F1 / `gpt-6.1-sol`, implementation running:** agent +- **F1 / `gpt-6.1-sol`, committed and host-verified:** agent `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Reuse the existing binding-retirement cutoff as the one-way host lifetime end, with its reason and synchronous cancellation. Explicit teardown ends that lifetime before awaiting; same-account replacement does not. Detach retained surfaces from @@ -873,6 +873,29 @@ shared controllers/routers and teardown edits so every work-item commit has clea fixture expectations from a real newer-lifetime protection before approving a correction. Preserve the epoch-superseded case and retirement-range immutability; do not weaken the newer-lifetime contract to make the tests green. + **Gate resolved, advised (`claude-opus-5.5`), 85% confidence:** use the narrower helper + eligibility contract instead of the unconditional caller proposal. A matching latest + generation returns true even when its reason is already truthful; rewrite only + `connectionRemoved`, never existing `userDisconnected`/`credentialsChanged`. Missing or + later generations return false. The caller's existing epoch/latch/eligibility guards and + both superseded-test branches stay unchanged. Add repeated-failure and already-ended + reason cases; the operator's newer-lifetime contract is preserved without a new framework. + **Done (2026-11-30), commit `b7fd8bff5`:** explicit teardown now synchronously retires the + old host lifetime and detaches retained Collection/Document surfaces before async cleanup; + same-account client replacement stays live. Direct stale RPC/background-effect tests have + fresh-client positive controls. Failed storage removal restores truthful feedback without + reviving the lifetime or touching earlier/later ranges; repeated failures remain retryable. + Decisions: reuse the existing cutoff/cancellation boundary, advised (`claude-opus-5.5`); + final exact revision approved at 90% confidence. Correct the introduced failed-removal + feedback and idempotency defects within that boundary, advised at 85-88% confidence. + No user wording, persisted schema or `TDD:` contract changed. + **Final affected host pass:** at `dce388d99` plus final F1 changes, + `npx vitest run src/documentdb/connectionBindingRetirement.test.ts src/documentdb/connectionTeardown.test.ts` + passed 40/40 tests in two files (4 s, exit 0). Evidence: runner + `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2`; final advisor + `873c8316-29fd-47c1-aa2d-ff9dce2f1254`. The preceding root build and 302-test + R/F1 run passed before the final small helper/test delta. Rerun the integrated candidate + after F2/E/U/H; Dashboard native-menu coverage is still F2, not passed by F1. ```sh npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/ClustersClient.test.ts src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts src/documentdb/connectionTeardown.test.ts src/documentdb/connectionSurfaces.test.ts src/documentdb/connectionBindingRetirement.test.ts src/commands/disconnect/disconnect.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts @@ -887,6 +910,10 @@ shared controllers/routers and teardown edits so every work-item commit has clea effect-level regressions. **H2/H3 / `gpt-6.1-sol`, after F2:** propagate the captured host lifetime/cancellation through schema/model and Playground handoffs; serialize H2/H3 because they share the Collection router. The Sol slices involve multiple async side-effect boundaries. + **H1 preparation returned:** agent `12d342e8-2c9c-42f2-b4d8-619c13473792` added nine + create-command race/control cases in the new namespace-helper test file. No production + code or existing tests changed and no tests were run. The shared source guard remains + gated on F1 approval; preparation alone is not H host evidence. - **U1 / `mai-code-2`, after F2:** terminal notice only, X/copy without writes, ordinary recoverable errors without freezing, and rendered-scenario updates. Exclude F2's Dashboard row/session wiring from parallel ownership. **U2 / `mai-code-2`, after H2/H3:** remove From a0cb19066930f4f948cb1b4f05206686e3b6b0cb Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:35:33 +0000 Subject: [PATCH 11/62] docs: record WI-F2/E/H1 dispatch after boundary approval Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index 2c05f8ad0..159b5556e 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -900,12 +900,22 @@ shared controllers/routers and teardown edits so every work-item commit has clea ```sh npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/ClustersClient.test.ts src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts src/documentdb/connectionTeardown.test.ts src/documentdb/connectionSurfaces.test.ts src/documentdb/connectionBindingRetirement.test.ts src/commands/disconnect/disconnect.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts ``` -- **F2 / `gpt-6.1-sol`, after F1:** route native Dashboard actions to the originating panel +- **F2 / `gpt-6.1-sol`, running after F1:** agent + `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Route native Dashboard actions to the originating panel session, never a replacement panel; remove frozen panels from the live-panel lookup. F1/F2 are genuinely complex host lifecycle and cross-module work. -- **E / `gpt-6.1-sol`, after F1/F2:** ordinary Disconnect completes before either edit +- **E / `gpt-6.1-sol`, running after F1 in parallel with F2:** agent + `dfd29c24-8a4e-4f14-990e-6ad883077a38`. Ordinary Disconnect completes before either edit wizard. Preserve the epoch/latch across disconnected editing and both storage writes; cancellation or supersession writes nothing and partial failures remain visible. + The settled internal interface is + `ensureDisconnectedForEdit(clusterId: string, refreshTree: () => void): Promise`. + Capture its returned epoch after ordinary teardown, before wizard/storage reads; pass the + epoch guard to the existing save path. Reuse `Disconnect?` and the approved + `Disconnect and update` button, remove the obsolete post-save Shell notice, and retain + the existing partial-save warning. No new persisted schema or general source parameter. + Coordination decision: E's owned teardown/save/update files do not overlap F2's Dashboard + files, so F1 approval is the actual prerequisite; F2 is not an edit dependency. - **H1 / `mai-code-2`, after F1:** fence the shared client-operation callback and add C01 effect-level regressions. **H2/H3 / `gpt-6.1-sol`, after F2:** propagate the captured host lifetime/cancellation through schema/model and Playground handoffs; serialize H2/H3 because @@ -914,6 +924,9 @@ shared controllers/routers and teardown edits so every work-item commit has clea create-command race/control cases in the new namespace-helper test file. No production code or existing tests changed and no tests were run. The shared source guard remains gated on F1 approval; preparation alone is not H host evidence. + **H1 source implementation running after F1 approval:** the same `mai-code-2` worker + now owns the shared last-synchronous operation check and the prepared namespace-helper + tests. E/F2 use disjoint files. Review and focused runtime evidence remain pending. - **U1 / `mai-code-2`, after F2:** terminal notice only, X/copy without writes, ordinary recoverable errors without freezing, and rendered-scenario updates. Exclude F2's Dashboard row/session wiring from parallel ownership. **U2 / `mai-code-2`, after H2/H3:** remove From 95cd11d0ad6249f16b8ea284a9236ca7379761ec Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:48:31 +0000 Subject: [PATCH 12/62] fix: fence namespace writes at the last host boundary (WI-H1) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/dashboardBoundCommands.test.ts | 1 + .../importDocuments/importDocuments.test.ts | 1 + src/commands/runBoundNamespaceCommand.test.ts | 178 ++++++++++++++++++ src/documentdb/runWithClient.ts | 1 + .../collectionViewController.test.ts | 1 + .../documentsViewController.test.ts | 1 + .../documentView/documentsViewRouter.test.ts | 1 + 7 files changed, 184 insertions(+) create mode 100644 src/commands/runBoundNamespaceCommand.test.ts diff --git a/src/commands/dashboardBoundCommands.test.ts b/src/commands/dashboardBoundCommands.test.ts index 942277ea6..72ab417b2 100644 --- a/src/commands/dashboardBoundCommands.test.ts +++ b/src/commands/dashboardBoundCommands.test.ts @@ -48,6 +48,7 @@ vi.mock('../documentdb/ClustersClient', () => ({ getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), reportFailure: vi.fn(), }, })); diff --git a/src/commands/importDocuments/importDocuments.test.ts b/src/commands/importDocuments/importDocuments.test.ts index 46ca5021c..e992196ac 100644 --- a/src/commands/importDocuments/importDocuments.test.ts +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -22,6 +22,7 @@ vi.mock('../../documentdb/ClustersClient', () => ({ getClient: vi.fn(), getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), reportFailure: vi.fn(), }, isBulkWriteError: vi.fn(() => false), diff --git a/src/commands/runBoundNamespaceCommand.test.ts b/src/commands/runBoundNamespaceCommand.test.ts new file mode 100644 index 000000000..96302db36 --- /dev/null +++ b/src/commands/runBoundNamespaceCommand.test.ts @@ -0,0 +1,178 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { afterEach, expect, it, vi } from 'vitest'; +import { ClustersClient, type ConnectionBinding } from '../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../documentdb/connectionBindingRetirement'; +import { runBoundNamespaceCommand } from './runBoundNamespaceCommand'; + +interface Deferred { + readonly promise: Promise; + resolve(value: T): void; +} + +interface CreateClientFixture { + readonly client: ClustersClient; + readonly createDatabase: ClustersClient['createDatabase']; + readonly createCollection: ClustersClient['createCollection']; + readonly dropDatabase: ClustersClient['dropDatabase']; +} + +interface CreateEffect { + readonly name: string; + readonly method: 'createDatabase' | 'createCollection'; + readonly run: (client: ClustersClient) => Promise; +} + +const createEffects: readonly CreateEffect[] = [ + { + name: 'database', + method: 'createDatabase', + run: async (client) => client.createDatabase('database'), + }, + { + name: 'collection', + method: 'createCollection', + run: async (client) => client.createCollection('database', 'collection'), + }, +]; + +let clusterSequence = 0; + +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((resolvePromise): void => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +function createBinding(): ConnectionBinding { + return { + clusterId: `run-bound-namespace-${++clusterSequence}`, + fingerprint: 'original', + generation: 0, + }; +} + +function createClient(binding: ConnectionBinding): CreateClientFixture { + const createDatabase = vi.fn().mockResolvedValue(undefined); + const createCollection = vi + .fn() + .mockResolvedValue({} as Awaited>); + const dropDatabase = vi.fn().mockResolvedValue(true); + return { + client: { + binding, + generation: binding.generation, + fingerprint: binding.fingerprint, + createDatabase, + createCollection, + dropDatabase, + } as unknown as ClustersClient, + createDatabase, + createCollection, + dropDatabase, + }; +} + +afterEach((): void => { + vi.restoreAllMocks(); +}); + +it.each(createEffects)('does not create a $name after its binding lifetime ends during resolution', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + ClustersClient._clients.set(binding.clusterId, replacement.client); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + resolution.resolve(replacement.client); + + await expect(pending).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); + ClustersClient._clients.delete(binding.clusterId); +}); + +it.each(createEffects)('does not create a $name when a current latch starts during resolution', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + ClustersClient.latch(binding.clusterId, 'credentialsUpdating'); + resolution.resolve(replacement.client); + + try { + await expect(pending).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + } finally { + ClustersClient.unlatch(binding.clusterId); + } +}); + +it.each(createEffects)('does not revive a retired $name binding when its teardown latch clears', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + ClustersClient._clients.set(binding.clusterId, replacement.client); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + ClustersClient.latch(binding.clusterId, 'credentialsChanged'); + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + ClustersClient.unlatch(binding.clusterId); + resolution.resolve(replacement.client); + + await expect(pending).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); + ClustersClient._clients.delete(binding.clusterId); +}); + +it.each(createEffects)('creates a $name once when the resolved client is a live same-identity replacement', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + resolution.resolve(replacement.client); + await pending; + + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).toHaveBeenCalledOnce(); +}); + +it('preserves stale delete-confirmation cancellation while resolution is pending', async (): Promise => { + const binding = createBinding(); + const client = createClient(binding); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + const confirmationEpoch = ClustersClient.getEpoch(binding.clusterId); + + const pending = runBoundNamespaceCommand( + binding.clusterId, + binding, + async (resolved) => resolved.dropDatabase('database'), + confirmationEpoch, + ); + ClustersClient.invalidate(binding.clusterId); + resolution.resolve(client.client); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(client.dropDatabase).not.toHaveBeenCalled(); +}); diff --git a/src/documentdb/runWithClient.ts b/src/documentdb/runWithClient.ts index 30c370542..70906fb25 100644 --- a/src/documentdb/runWithClient.ts +++ b/src/documentdb/runWithClient.ts @@ -54,6 +54,7 @@ export async function runWithClient( } try { + ClustersClient.assertBindingActive(binding); return await op(client); } catch (error) { // Resolution can advance the generation without changing the surface's identity. diff --git a/src/webviews/documentdb/collectionView/collectionViewController.test.ts b/src/webviews/documentdb/collectionView/collectionViewController.test.ts index db3cbc7f0..0c137e8e4 100644 --- a/src/webviews/documentdb/collectionView/collectionViewController.test.ts +++ b/src/webviews/documentdb/collectionView/collectionViewController.test.ts @@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({ getEpoch: vi.fn(() => 1), getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), unlatch: vi.fn(), getCredentials: vi.fn(), postMessage: vi.fn(), diff --git a/src/webviews/documentdb/documentView/documentsViewController.test.ts b/src/webviews/documentdb/documentView/documentsViewController.test.ts index 93f7e52fb..4589ffb5d 100644 --- a/src/webviews/documentdb/documentView/documentsViewController.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewController.test.ts @@ -20,6 +20,7 @@ const mocks = vi.hoisted(() => ({ getEpoch: vi.fn(() => 1), getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), unlatch: vi.fn(), getCredentials: vi.fn(), executeCommand: vi.fn(), diff --git a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts index 8a18c2426..765ed4992 100644 --- a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts @@ -20,6 +20,7 @@ import { documentsViewRouter, type RouterContext } from './documentsViewRouter'; const mocks = vi.hoisted(() => ({ resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), getBinding: vi.fn(), getEpoch: vi.fn(), getLatchReason: vi.fn(), From b322b7463865c451677885343152d9f0c124c7e6 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 13:55:53 +0000 Subject: [PATCH 13/62] docs: record WI-H1 pass and scoped E/U/F2 corrections Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 65 +++++++++++++++++-- 1 file changed, 61 insertions(+), 4 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index 159b5556e..e25c6ca0f 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -777,9 +777,9 @@ npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/playg | **R — host pass; integrated/live pending** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. Commit/revision/command evidence is recorded under R below. | | **W — host pass; integrated/live pending** | Shell and Playground renew independently; explicit teardown stops the old worker, not the user's text. | Exercise both manager/evaluator suites, PTY and `executePlaygroundCode.test.ts`. Hold a token reply or evaluation across Disconnect, release it after reconnect: no delivery to the replacement worker, automatic command replay or silent rebinding; scrollback/file contents survive. Positive control: a valid pinned worker receives its reply and executes once. Commit/revision/command evidence is recorded under W below. | | **F — F1 host pass; F2/integrated pending** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. Commit/revision/command evidence is recorded under F1/F2 below. | -| **E — not run** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. | -| **U — not run** | X dismisses the frozen notice; Close closes the tab. Ordinary recoverable errors do not freeze it. | Update the existing rendered scenarios below. Keep a draft, dismiss with X, select/copy the original text, attempt Save, release a stale response: draft unchanged, no new save RPC. Close/cancel the dirty-close confirmation separately. Pair with a failed live query → same-account repair → user runs again in the **same tab**, with no unlock RPC and no automatic replay. On uncertain write outcome retain text and never claim nothing was written. | -| **H — not run** | Shared host checks stop delayed side effects without making ordinary reads carry identity policy. | Exercise [review cases C01–C03](./02-pr1136-copilot-review.md): pause create after client resolution; pause query generation before sampling and again at model selection; pause Playground document opening, including a retained Shell link. End the old lifetime, install the replacement, release the pause. Assert zero stale writes, replacement-schema samples, model sends after invalidation, or replacement bindings, as applicable. Run the same paths without invalidation to rule out a blanket disable. Use fake DB/model boundaries, not real data or model calls. | +| **E — correcting; host not run** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. | +| **U — U1 implementing; rendered/U2 pending** | X dismisses the frozen notice; Close closes the tab. Ordinary recoverable errors do not freeze it. | Update the existing rendered scenarios below. Keep a draft, dismiss with X, select/copy the original text, attempt Save, release a stale response: draft unchanged, no new save RPC. Close/cancel the dirty-close confirmation separately. Pair with a failed live query → same-account repair → user runs again in the **same tab**, with no unlock RPC and no automatic replay. On uncertain write outcome retain text and never claim nothing was written. | +| **H — H1 host pass; H2/H3 pending** | Shared host checks stop delayed side effects without making ordinary reads carry identity policy. | Exercise [review cases C01–C03](./02-pr1136-copilot-review.md): pause create after client resolution; pause query generation before sampling and again at model selection; pause Playground document opening, including a retained Shell link. End the old lifetime, install the replacement, release the pause. Assert zero stale writes, replacement-schema samples, model sends after invalidation, or replacement bindings, as applicable. Run the same paths without invalidation to rule out a blanket disable. Use fake DB/model boundaries, not real data or model calls. | | **P — not run** | Combined candidate and release evidence. | Rerun affected checks after integration. Walk a normal read and a delayed write/send in the diff: the read uses a shared path, the delayed side effect checks its captured origin. Record obsolete recovery handlers/tests removed and guards intentionally retained. Update user-facing docs/localization and affected telemetry contracts for the behavior actually shipped. Run the repository handoff gates and the live checks below on the identified candidate. | **Implementation mapping (2026-11-30, advised by `claude-opus-5.5`):** the seven @@ -904,6 +904,22 @@ shared controllers/routers and teardown edits so every work-item commit has clea `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Route native Dashboard actions to the originating panel session, never a replacement panel; remove frozen panels from the live-panel lookup. F1/F2 are genuinely complex host lifecycle and cross-module work. + **F2 pre-edit gate resolved:** the existing ordinary-unreachable/Retry-lock test predates + D2. Advisor `4b1a9f9a-4c67-40c4-8e3f-2a8fcdeb5cbe`, 85% confidence, confirmed that + it must now preserve same-account/no-replay coverage while allowing the next explicit + native action without Retry. Keep explicit-end copy-only/frozen protections. NamespaceTable + already has `configuration.dashboardSessionId`; no extra parent prop wiring is needed. + The worker is implementing those scoped changes and its direct H1 mock dependencies. + **F2 implementation returned; first host check failed:** at `95cd11d0a` plus F2/E + working changes, + `npx vitest run src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts` + passed 48/49 tests in one of two files (2.57 s runtime). The new + `blocks frozen poll timers before acquisition, database calls or prompts and lets a fresh poll run once` + failed before its behavior assertions because the VS Code mock lacked `authentication`. + Source inspection confirmed neither suite nor test has a `TDD:` prefix; fix only the + fixture, retaining the effect assertions. Evidence: runner + `786c177f-56f7-4d20-9574-ac466cb4ac5a`. F2 advisor review and the fixture correction + are active; no F2 pass is claimed. - **E / `gpt-6.1-sol`, running after F1 in parallel with F2:** agent `dfd29c24-8a4e-4f14-990e-6ad883077a38`. Ordinary Disconnect completes before either edit wizard. Preserve the epoch/latch across disconnected editing and both storage writes; @@ -916,6 +932,16 @@ shared controllers/routers and teardown edits so every work-item commit has clea the existing partial-save warning. No new persisted schema or general source parameter. Coordination decision: E's owned teardown/save/update files do not overlap F2's Dashboard files, so F1 approval is the actual prerequisite; F2 is not an edit dependency. + **Partial implementation returned, not verified:** the worker added 35 cases and the + ordinary-disconnect edit flow, then stopped on an idle-startup race: a new client can start + during an unlatched idle wizard without changing its epoch. No completion is claimed. + **Gate resolved:** advisor `06b2055c-d1d9-416f-a12c-7a2af7657e55`, 85% confidence, + chose a behavior-preserving atomic pre-save predicate, not a new wizard hold or changed + cancellation/presentation. Export `canSaveEdit(clusterId, epoch)` using matching epoch + and either `userDisconnected` or the existing idle predicate; use it after prompts and + in `canStart`. Registered disconnected shells must remain allowed under `userDisconnected`. + The existing synchronous task guard/latch then excludes startup during both storage writes. + Add concurrent-work/no-write cases and positive controls; the worker is finishing this correction. - **H1 / `mai-code-2`, after F1:** fence the shared client-operation callback and add C01 effect-level regressions. **H2/H3 / `gpt-6.1-sol`, after F2:** propagate the captured host lifetime/cancellation through schema/model and Playground handoffs; serialize H2/H3 because @@ -927,10 +953,41 @@ shared controllers/routers and teardown edits so every work-item commit has clea **H1 source implementation running after F1 approval:** the same `mai-code-2` worker now owns the shared last-synchronous operation check and the prepared namespace-helper tests. E/F2 use disjoint files. Review and focused runtime evidence remain pending. -- **U1 / `mai-code-2`, after F2:** terminal notice only, X/copy without writes, ordinary + **H1 implementation returned:** the shared operation fence and nine effect cases are + written. Direct-dependent Class mock fixtures need the new method; the H1 worker owns + the five disjoint fixtures, and F2 owns its two Dashboard fixtures. No existing test + assertions or behavior are being changed merely to accommodate a mock method. Advisor + `789b6f3c-8f68-4bed-ba93-3fd0c2ec9d78` is reviewing the source boundary. + **H1 Done (2026-11-30), commit `95cd11d0a`:** the shared binding check now runs after + client resolution at the last synchronous point before the operation callback. Nine + regressions cover stale creates, temporary holds, permanent retirement, same-account + replacement and stale delete confirmation. Decisions: advised (`claude-opus-5.5`), + source review approved at about 90% confidence; retain the existing failure-attribution path. + Existing fixtures gained the required mock method without changing assertions. + **H1 host pass:** at `a0cb19066` plus H1/F2/E working changes, the command below passed + 151 tests in seven files (4.55 s), no failures. Evidence: runner + `14f3d87b-cf9c-40f6-96f0-3650c02abfd8`, advisor + `789b6f3c-8f68-4bed-ba93-3fd0c2ec9d78`. H2/H3 and integrated rerun remain pending. + + ```sh + npx vitest run src/commands/runBoundNamespaceCommand.test.ts src/commands/dashboardBoundCommands.test.ts src/commands/importDocuments/importDocuments.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts src/documentdb/ClustersClient.test.ts + ``` +- **U1 / `mai-code-2`, running after F1 in parallel with F2:** agent + `559eab2f-1c5b-4190-9c53-0e959a8c756e`. Terminal notice only, X/copy without writes, ordinary recoverable errors without freezing, and rendered-scenario updates. Exclude F2's Dashboard row/session wiring from parallel ownership. **U2 / `mai-code-2`, after H2/H3:** remove obsolete host Retry/unlock procedures and protocol; shared routers/controllers require serialization. + Coordination decision: F2's existing session configuration makes its files disjoint from U1. + Keep the approved notice and existing translated repair instruction, removing only the obsolete + Retry clause rather than introducing new recovery prose; uncertain-write cautions remain. + Rendered runs stay last, on the integrated candidate, not during parallel source edits. + **Close-path gate resolved:** advisor `439e40a0-1e6c-4d2a-9322-3c127897f0e9`, + 85% confidence, approved temporary close-only use of the existing recovery RPC for U1. + The hook accepts only `{ action: 'close' }`; keep dirty confirmation, cancellation, + double-click guard and translated close failures. U1 must remove all Retry/unlock calls from the UI. + U2 must replace this with a dedicated `closeView` procedure and remove the old protocol, + including its action field, after H2/H3. This is an intermediate compatibility slice, + not final protocol-removal evidence. - **P / `mai-code-2` documentation, `mai-code-2-flash` checks:** align only directly affected docs/contracts, rerun the integrated effects, collect rendered and packaged evidence, and preserve separate live gates. The authorized order is implementation push and stacked From 7417e01eaffb487023990a3c8d5e723993704845 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 14:41:28 +0000 Subject: [PATCH 14/62] fix: isolate frozen Dashboard actions by panel session (WI-F2) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../clusterDashboardContextMenu.ts | 1 + .../clusterDashboardController.test.ts | 213 +++++++++++++----- .../clusterDashboardController.ts | 75 +++--- .../clusterDashboardRouter.test.ts | 94 +++++++- .../components/NamespaceTable.tsx | 1 + 5 files changed, 284 insertions(+), 100 deletions(-) diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardContextMenu.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardContextMenu.ts index b1af46b06..d9b729e68 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardContextMenu.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardContextMenu.ts @@ -31,6 +31,7 @@ export type ClusterDashboardContextMenuCommandId = * hands to the context-menu command. */ export interface ClusterDashboardContextMenuContext { + readonly clusterDashboardSessionId?: string; readonly clusterDashboardClusterId: string; readonly clusterDashboardSelectedDatabase?: string; readonly clusterDashboardDatabase: string; diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts index 6ad09e566..357effafb 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts @@ -47,6 +47,7 @@ vi.mock('../../../documentdb/ClustersClient', () => ({ getEpoch: vi.fn(), getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), unlatch: vi.fn(), }, })); @@ -61,6 +62,7 @@ import * as vscode from 'vscode'; import { copyNamespaceReference } from '../../../commands/copyReference/copyReference'; import { openCollectionViewInternal } from '../../../commands/openCollectionView/openCollectionView'; import { ClustersClient } from '../../../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../../../documentdb/connectionBindingRetirement'; import { getConnectionSurfaces } from '../../../documentdb/connectionSurfaces'; import { ConnectionUnavailableError } from '../../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../../documentdb/CredentialCache'; @@ -68,6 +70,7 @@ import { openAppWebview } from '../../_integration/openAppWebview'; import { CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS } from './clusterDashboardContextMenu'; import { openClusterDashboardWebview, + getOpenClusterDashboardSessionId, registerClusterDashboardContextMenuCommands, type ClusterDashboardWebviewConfigurationType, } from './clusterDashboardController'; @@ -110,7 +113,7 @@ function createFakeController(): FakeController { const CLUSTER = 'cluster-under-test'; const binding = { clusterId: CLUSTER, fingerprint: 'host-only-dashboard-fingerprint', generation: 1 }; -function open(clusterId: string, selectedDatabaseName?: string): FakeController { +function open(clusterId: string, selectedDatabaseName?: string, generation = 1): FakeController { return openClusterDashboardWebview( { clusterId, @@ -120,7 +123,7 @@ function open(clusterId: string, selectedDatabaseName?: string): FakeController showDashboardOnConnect: false, selectedDatabaseName, }, - { ...binding, clusterId }, + { ...binding, clusterId, generation }, ) as unknown as FakeController; } @@ -164,33 +167,40 @@ describe('openClusterDashboardWebview panel lifecycle', () => { }); it.each([ - ['userDisconnected', binding, true, true], - ['userDisconnected', { ...binding, fingerprint: 'other-identity' }, true, false], - ['credentialsChanged', binding, true, false], - ['userDisconnected', binding, false, false], + ['userDisconnected', binding, true], + ['userDisconnected', { ...binding, fingerprint: 'other-identity' }, true], + ['credentialsChanged', binding, true], + ['userDisconnected', binding, false], ] as const)( - 'resumes only the auto-opened Dashboard after an explicit same-identity reconnect (%s, %j, %s)', - (reason, connectedBinding, autoOpen, resumes): void => { + 'opens fresh work without revealing or auto-retrying an ended Dashboard (%s, %j, %s)', + (reason, connectedBinding, autoOpen): void => { vi.clearAllMocks(); - const panel = open(CLUSTER); - const { context, config } = vi.mocked(openAppWebview).mock.calls[0][0]; - (context as RouterContext).describeUnavailable(reason); - - openClusterDashboardWebview( + const clusterId = `ended-dashboard-${reason}-${connectedBinding.fingerprint}-${autoOpen}`; + const panel = open(clusterId); + const { config } = vi.mocked(openAppWebview).mock.calls[0][0]; + const [surface] = getConnectionSurfaces(clusterId); + retireConnectionBindings(clusterId, 1, reason); + surface.disable(reason); + expect(getOpenClusterDashboardSessionId(clusterId)).toBeUndefined(); + + const fresh = openClusterDashboardWebview( config as ClusterDashboardWebviewConfigurationType, - { ...connectedBinding, generation: 2 }, + { ...connectedBinding, clusterId, generation: 2 }, undefined, autoOpen, ); - expect(panel.revealToForeground).toHaveBeenCalledOnce(); - if (resumes) { - expect(panel.panel.webview.postMessage).toHaveBeenCalledExactlyOnceWith({ - type: 'clusterDashboard.retryAfterReconnect', - }); - } else { - expect(panel.panel.webview.postMessage).not.toHaveBeenCalled(); - } + expect(fresh).not.toBe(panel); + expect(panel.revealToForeground).not.toHaveBeenCalled(); + expect(panel.panel.webview.postMessage).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ type: 'clusterDashboard.connectionUnavailable' }), + ); + const freshSession = getOpenClusterDashboardSessionId(clusterId); + surface.disable(reason); + expect(getOpenClusterDashboardSessionId(clusterId)).toBe(freshSession); + const [freshSurface] = getConnectionSurfaces(clusterId); + freshSurface.dispose(); + expect(panel.isDisposed).toBe(false); panel.dispose(); }, ); @@ -231,7 +241,7 @@ describe('openClusterDashboardWebview panel lifecycle', () => { reason: 'userDisconnected', title: expect.any(String), detail: expect.any(String), - action: 'retry', + action: 'close', }, }); @@ -257,7 +267,7 @@ describe('cluster dashboard unavailable recovery', () => { binding: { ...binding, generation: 2 }, } as never); - context.describeUnavailable('userDisconnected'); + context.describeUnavailable('signInRequired'); await expect(context.recoverUnavailable({ action: 'retry' })).resolves.toEqual({ recovered: { text: 'Reconnected' }, }); @@ -324,12 +334,12 @@ describe('cluster dashboard unavailable recovery', () => { }); describe('cluster dashboard native context menu commands', () => { - function registerAndOpen(): { + function registerAndOpen(clusterId = CLUSTER): { handlers: Map Promise>; controller: FakeController; } { vi.clearAllMocks(); - vi.mocked(ClustersClient.getBinding).mockReturnValue(binding); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, clusterId }); vi.mocked(ClustersClient.getEpoch).mockReturnValue(0); vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); const handlers = new Map Promise>(); @@ -339,13 +349,14 @@ describe('cluster dashboard native context menu commands', () => { }); registerClusterDashboardContextMenuCommands({ subscriptions: [] } as unknown as vscode.ExtensionContext); - return { handlers, controller: open(CLUSTER, 'sales') }; + return { handlers, controller: open(clusterId, 'sales') }; } it('opens the collection view on the host rather than relaying through the webview', async () => { const { handlers, controller } = registerAndOpen(); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.manageIndexes)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', @@ -370,6 +381,7 @@ describe('cluster dashboard native context menu commands', () => { const { handlers, controller } = registerAndOpen(); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteCollection)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', @@ -413,6 +425,7 @@ describe('cluster dashboard native context menu commands', () => { }); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteCollection)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', @@ -426,7 +439,7 @@ describe('cluster dashboard native context menu commands', () => { reason: 'userDisconnected', title: expect.any(String), detail: expect.any(String), - action: 'retry', + action: 'close', }, }); controller.dispose(); @@ -439,12 +452,13 @@ describe('cluster dashboard native context menu commands', () => { controller.dispose(); }); - it('keeps only local reference copying available in this panel until Retry succeeds', async () => { - const { handlers, controller } = registerAndOpen(); - const other = open(CLUSTER, 'inventory'); + it('leaves ordinary failures live without Retry, but keeps an explicitly disconnected panel copy-only', async () => { + const clusterId = 'native-recovery-and-disconnect'; + const { handlers, controller } = registerAndOpen(clusterId); const dashboardContext = vi.mocked(openAppWebview).mock.calls[0][0].context as RouterContext; const row = { - clusterDashboardClusterId: CLUSTER, + clusterDashboardSessionId: getOpenClusterDashboardSessionId(clusterId, 'sales'), + clusterDashboardClusterId: clusterId, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', clusterDashboardCollection: 'orders', @@ -452,39 +466,53 @@ describe('cluster dashboard native context menu commands', () => { const exportRow = handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.exportDocuments); dashboardContext.describeUnavailable('unreachable'); + await exportRow?.(row); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + expect(controller.panel.webview.postMessage).not.toHaveBeenCalled(); + vi.mocked(ClustersClient.getBinding).mockReturnValueOnce(undefined); + await exportRow?.(row); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + expect(controller.panel.webview.postMessage).toHaveBeenCalledWith( + expect.objectContaining({ unavailable: expect.objectContaining({ reason: 'unreachable' }) }), + ); + await exportRow?.(row); + expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(2); + + const [surface] = getConnectionSurfaces(clusterId); + retireConnectionBindings(clusterId, 1, 'userDisconnected'); + surface.disable('userDisconnected'); + vi.mocked(resolveNamespaceNode).mockClear(); await exportRow?.(row); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.copyReference)?.(row); expect(copyNamespaceReference).toHaveBeenCalledWith(expect.anything(), 'sales', 'orders'); expect(resolveNamespaceNode).not.toHaveBeenCalled(); - expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); - expect(controller.panel.webview.postMessage).toHaveBeenCalledExactlyOnceWith({ - type: 'clusterDashboard.connectionUnavailable', - unavailable: expect.objectContaining({ reason: 'unreachable' }), + expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(2); + await expect(dashboardContext.recoverUnavailable({ action: 'retry' })).resolves.toMatchObject({ + unavailable: { reason: 'userDisconnected' }, }); - - vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValueOnce( - new ConnectionUnavailableError('unreachable'), - ); - await expect(dashboardContext.recoverUnavailable({ action: 'retry' })).resolves.toHaveProperty('unavailable'); - await exportRow?.(row); - expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); - - await exportRow?.({ ...row, clusterDashboardSelectedDatabase: 'inventory' }); - expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); - - vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValueOnce({ binding } as ClustersClient); - await expect(dashboardContext.recoverUnavailable({ action: 'retry' })).resolves.toHaveProperty('recovered'); - expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); // No replay. + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); await exportRow?.(row); expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(2); + + const other = open(clusterId, 'inventory', 2); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, clusterId, generation: 2 }); + await exportRow?.({ + ...row, + clusterDashboardSelectedDatabase: 'inventory', + clusterDashboardSessionId: getOpenClusterDashboardSessionId(clusterId, 'inventory'), + }); + expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(3); + await dashboardContext.recoverUnavailable({ action: 'close' }); + expect(controller.isDisposed).toBe(true); + expect(other.isDisposed).toBe(false); other.dispose(); - controller.dispose(); }); it('refreshes inventory after import returns, since it changes the figures on screen', async () => { const { handlers, controller } = registerAndOpen(); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.importDocuments)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', @@ -509,6 +537,7 @@ describe('cluster dashboard native context menu commands', () => { const { handlers, controller } = registerAndOpen(); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.exportDocuments)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', @@ -531,6 +560,7 @@ describe('cluster dashboard native context menu commands', () => { vi.mocked(resolveNamespaceNode).mockResolvedValueOnce(undefined); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteDatabase)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', @@ -544,11 +574,12 @@ describe('cluster dashboard native context menu commands', () => { controller.dispose(); }); - it('restores the recovery dialog for a row action when its client is no longer cached', async () => { + it('reports a missing client without freezing the next manual row action', async () => { const { handlers, controller } = registerAndOpen(); vi.mocked(ClustersClient.getBinding).mockReturnValueOnce(undefined); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.exportDocuments)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'sales', @@ -561,13 +592,91 @@ describe('cluster dashboard native context menu commands', () => { }); expect(resolveNamespaceNode).not.toHaveBeenCalled(); expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.exportDocuments)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), + clusterDashboardClusterId: CLUSTER, + clusterDashboardSelectedDatabase: 'sales', + clusterDashboardDatabase: 'sales', + clusterDashboardCollection: 'orders', + }); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); controller.dispose(); }); + it.each([undefined, 'unknown-session', 42])( + 'rejects native context with missing or unknown session %s rather than routing to the live panel', + async (sessionId): Promise => { + const { handlers, controller } = registerAndOpen(); + await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteCollection)?.({ + clusterDashboardSessionId: sessionId, + clusterDashboardClusterId: CLUSTER, + clusterDashboardSelectedDatabase: 'sales', + clusterDashboardDatabase: 'sales', + clusterDashboardCollection: 'orders', + }); + expect(resolveNamespaceNode).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + expect(controller.panel.webview.postMessage).not.toHaveBeenCalled(); + controller.dispose(); + }, + ); + + it.each([ + CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteCollection, + CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteDatabase, + ])( + 'keeps an old native %s scoped to its frozen snapshot while a fresh same-cluster action works once', + async (commandId): Promise => { + const clusterId = `frozen-native-${commandId}`; + const { handlers, controller } = registerAndOpen(clusterId); + const row = { + clusterDashboardSessionId: getOpenClusterDashboardSessionId(clusterId, 'sales'), + clusterDashboardClusterId: clusterId, + clusterDashboardSelectedDatabase: 'sales', + clusterDashboardDatabase: 'sales', + clusterDashboardCollection: + commandId === CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteCollection ? 'orders' : undefined, + }; + const [surface] = getConnectionSurfaces(clusterId); + retireConnectionBindings(clusterId, 1, 'userDisconnected'); + surface.disable('userDisconnected'); + const fresh = open(clusterId, 'sales', 2); + const freshBinding = { ...binding, clusterId, generation: 2 }; + vi.mocked(ClustersClient.getBinding).mockReturnValue(freshBinding); + const database = vi.fn(async (): Promise => {}); + vi.mocked(vscode.commands.executeCommand).mockImplementation(database); + + await handlers.get(commandId)?.(row); + expect(database).not.toHaveBeenCalled(); + expect(resolveNamespaceNode).not.toHaveBeenCalled(); + expect(fresh.panel.webview.postMessage).not.toHaveBeenCalled(); + surface.disable('userDisconnected'); + const freshSession = getOpenClusterDashboardSessionId(clusterId, 'sales'); + expect(freshSession).not.toBe(row.clusterDashboardSessionId); + expect(freshSession).toBeDefined(); + await handlers.get(commandId)?.({ ...row, clusterDashboardSessionId: freshSession }); + expect(database).toHaveBeenCalledOnce(); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + commandId === CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteCollection + ? 'vscode-documentdb.command.dropCollection' + : 'vscode-documentdb.command.dropDatabase', + { id: 'tree-node' }, + null, + { source: 'webview;clusterDashboard', binding: freshBinding }, + ); + controller.dispose(); + await handlers.get(commandId)?.(row); + expect(database).toHaveBeenCalledOnce(); + expect(getOpenClusterDashboardSessionId(clusterId, 'sales')).toBe(freshSession); + fresh.dispose(); + }, + ); + it('asks the panel to step into a database, the one action the host cannot take', async () => { const { handlers, controller } = registerAndOpen(); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.viewCollections)?.({ + clusterDashboardSessionId: getOpenClusterDashboardSessionId(CLUSTER, 'sales'), clusterDashboardClusterId: CLUSTER, clusterDashboardSelectedDatabase: 'sales', clusterDashboardDatabase: 'inventory', diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts index eff0f1014..3930d1a74 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts @@ -16,6 +16,7 @@ import { type DeepLinkTelemetry } from '../../../deepLinks/deepLinkTelemetry'; import { copyNamespaceReference } from '../../../commands/copyReference/copyReference'; import { openCollectionViewInternal } from '../../../commands/openCollectionView/openCollectionView'; import { ClustersClient, type ConnectionBinding } from '../../../documentdb/ClustersClient'; +import { getRetiredBindingReason } from '../../../documentdb/connectionBindingRetirement'; import { registerConnectionSurface } from '../../../documentdb/connectionSurfaces'; import { ConnectionUnavailableError, @@ -113,13 +114,13 @@ export type ClusterDashboardWebviewConfigurationType = { * its panel, while a different database can remain open beside it. */ const openPanels = new Map(); +const panelsBySession = new Map(); interface OpenPanel { readonly controller: AppWebviewController; readonly config: ClusterDashboardWebviewConfigurationType; readonly binding: ConnectionBinding; readonly postUnavailable: (reason: ConnectionUnavailableReason) => void; - readonly getUnavailable: () => ConnectionUnavailableMessage['unavailable'] | undefined; } /** @@ -212,6 +213,7 @@ function isContextMenuContext(value: unknown): value is ClusterDashboardContextM const context = value as Partial; return ( typeof context.clusterDashboardClusterId === 'string' && + typeof context.clusterDashboardSessionId === 'string' && typeof context.clusterDashboardDatabase === 'string' && (context.clusterDashboardSelectedDatabase === undefined || typeof context.clusterDashboardSelectedDatabase === 'string') && @@ -261,28 +263,22 @@ async function runRowAction( const databaseName = menuContext.clusterDashboardDatabase; const collectionName = menuContext.clusterDashboardCollection; actionContext.telemetry.properties.namespaceLevel = collectionName === undefined ? 'database' : 'collection'; - const unavailable = panel.getUnavailable(); - if (unavailable) { + const retiredReason = getRetiredBindingReason(panel.binding); + if (retiredReason) { if (action.kind === 'treeCommand' && action.commandId === 'vscode-documentdb.command.copyReference') { // The retained row has enough information to copy without expanding the tree. await copyNamespaceReference(actionContext, databaseName, collectionName); } else { const message: ConnectionUnavailableMessage = { type: 'clusterDashboard.connectionUnavailable', - unavailable, + unavailable: describeUnavailableConnection(retiredReason).unavailable, }; await panel.controller.panel.webview.postMessage(message); } return; } - const assertBound = guardBoundViewOperation(panel.binding); - const assertCurrent = (): void => { - if (panel.getUnavailable()) { - throw new UserCancelledError('staleBoundViewOperation'); - } - assertBound(); - }; + const assertCurrent = guardBoundViewOperation(panel.binding); if (!ClustersClient.getBinding(panel.binding.clusterId)) { throw new ConnectionUnavailableError(ClustersClient.getLatchReason(panel.binding.clusterId) ?? 'unreachable'); } @@ -348,7 +344,7 @@ async function runRowAction( await postInventoryChanged(panel, databaseName); } } finally { - if (action.reportsBusy && !panel.controller.isDisposed && !panel.getUnavailable()) { + if (action.reportsBusy && !panel.controller.isDisposed && !getRetiredBindingReason(panel.binding)) { await postNamespaceBusy(panel, databaseName, collectionName, 'delete', false); } } @@ -362,9 +358,7 @@ export function registerClusterDashboardContextMenuCommands(context: vscode.Exte return; } - const panel = openPanels.get( - getPanelKey(menuContext.clusterDashboardClusterId, menuContext.clusterDashboardSelectedDatabase), - ); + const panel = panelsBySession.get(menuContext.clusterDashboardSessionId ?? ''); if (!panel || panel.controller.isDisposed) { return; } @@ -404,42 +398,34 @@ export function openClusterDashboardWebview( initialData: ClusterDashboardWebviewConfigurationType, binding: ConnectionBinding, deepLink?: DeepLinkTelemetry, - autoOpenOnConnect = false, + _autoOpenOnConnect = false, ): AppWebviewController { const panelKey = getPanelKey(initialData.clusterId, initialData.selectedDatabaseName); const existingPanel = openPanels.get(panelKey); if (existingPanel && !existingPanel.controller.isDisposed) { existingPanel.controller.revealToForeground(); - if ( - autoOpenOnConnect && - existingPanel.getUnavailable()?.reason === 'userDisconnected' && - existingPanel.binding.fingerprint === binding.fingerprint - ) { - void existingPanel.controller.panel.webview.postMessage({ type: 'clusterDashboard.retryAfterReconnect' }); - } return existingPanel.controller; } // Assigned here rather than by the caller so a reveal of an existing panel cannot mint a // second id for the same session. - initialData = { ...initialData, dashboardSessionId: randomUUID() }; + const dashboardSessionId = randomUUID(); + initialData = { ...initialData, dashboardSessionId }; // Declared before `trpcContext` because that context closes over it, and assigned after, // because `openAppWebview` needs the context. `const` is not available for that ordering. // eslint-disable-next-line prefer-const let controller: AppWebviewController; - let unavailable: ReturnType | undefined; - const rememberUnavailable = ( + const describeUnavailable = ( reason: ConnectionUnavailableReason, ): ReturnType => { - unavailable = describeUnavailableConnection(reason); - return unavailable; + return describeUnavailableConnection(getRetiredBindingReason(binding) ?? reason); }; const postUnavailable = (reason: ConnectionUnavailableReason): void => { const message: ConnectionUnavailableMessage = { type: 'clusterDashboard.connectionUnavailable', - unavailable: rememberUnavailable(reason).unavailable, + unavailable: describeUnavailable(reason).unavailable, }; if (!controller.isDisposed) { void controller.panel.webview.postMessage(message); @@ -452,18 +438,9 @@ export function openClusterDashboardWebview( webviewName: 'clusterDashboard', clusterId: initialData.clusterId, binding, - describeUnavailable: rememberUnavailable, - recoverUnavailable: async (request) => { - const previous = unavailable; - const response = await recoverBoundView(binding, 'clusterDashboard', () => controller.dispose(), request); - if (request.action === 'retry') { - if (unavailable !== previous && unavailable) { - return unavailable; - } - unavailable = 'unavailable' in response ? response : undefined; - } - return response; - }, + describeUnavailable, + recoverUnavailable: (request) => + recoverBoundView(binding, 'clusterDashboard', () => controller.dispose(), request), clusterDisplayName: initialData.clusterDisplayName, viewId: initialData.viewId, dashboardSessionId: initialData.dashboardSessionId, @@ -504,23 +481,31 @@ export function openClusterDashboardWebview( }, }); - openPanels.set(panelKey, { + const panelEntry: OpenPanel = { controller, config: initialData, binding, postUnavailable, - getUnavailable: () => unavailable?.unavailable, - }); + }; + openPanels.set(panelKey, panelEntry); + panelsBySession.set(dashboardSessionId, panelEntry); const session = initialData; trackDashboardLifetime(controller, (lifetime) => reportDashboardClosed(lifetime, session)); const registration = registerConnectionSurface({ clusterId: initialData.clusterId, kind: 'clusterDashboard', - disable: postUnavailable, + disable: (reason): void => { + registration.dispose(); + if (openPanels.get(panelKey) === panelEntry) { + openPanels.delete(panelKey); + } + postUnavailable(reason); + }, dispose: () => controller.dispose(), }); controller.onDisposed(() => { registration.dispose(); + panelsBySession.delete(dashboardSessionId); if (openPanels.get(panelKey)?.controller === controller) { openPanels.delete(panelKey); } diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts index 57dda925a..ef355bcf9 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; vi.mock('../../../services/survey/SurveyService', (): object => ({ recordSurveyActivityWithInvitation: vi.fn() })); @@ -12,6 +12,7 @@ import { type Document, type MongoClient } from 'mongodb'; import * as vscode from 'vscode'; import { ClustersClient } from '../../../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../../../documentdb/connectionBindingRetirement'; import { ConnectionUnavailableError } from '../../../documentdb/ConnectionUnavailableError'; import { API } from '../../../DocumentDBExperiences'; @@ -22,6 +23,7 @@ const mockUpdateGlobalSetting = vi.fn(); vi.mock('vscode', async (importOriginal) => ({ ...(await importOriginal()), commands: { executeCommand: vi.fn() }, + authentication: { getSession: vi.fn() }, })); vi.mock('../../../commands/openCollectionView/openCollectionView', () => ({ @@ -31,6 +33,7 @@ vi.mock('../../../commands/openCollectionView/openCollectionView', () => ({ vi.mock('../../../documentdb/ClustersClient', () => ({ ClustersClient: { resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), getBinding: vi.fn(), getEpoch: vi.fn(), getLatchReason: vi.fn(), @@ -79,12 +82,13 @@ const binding = { clusterId: 'cluster-id', fingerprint: 'dashboard-fingerprint', function createContext( onNamespaceBusy?: RouterContext['onNamespaceBusy'], selectedDatabaseName?: string, + capturedBinding = binding, ): WithTelemetry { return { dbExperience: API.DocumentDB, webviewName: 'clusterDashboard', - clusterId: 'cluster-id', - binding, + clusterId: capturedBinding.clusterId, + binding: capturedBinding, describeUnavailable: (reason) => ({ unavailable: { reason, title: 'Connection unavailable', detail: 'Close this view.', action: 'close' }, }), @@ -142,6 +146,12 @@ describe('collectRawCommandReplies', () => { }); describe('clusterDashboardRouter create actions', () => { + afterEach((): void => { + vi.restoreAllMocks(); + vi.useRealTimers(); + vi.mocked(ClustersClient.resolveBoundClient).mockReset(); + }); + beforeEach(() => { vi.clearAllMocks(); vi.mocked(ClustersClient.getBinding).mockReturnValue(binding); @@ -226,6 +236,84 @@ describe('clusterDashboardRouter create actions', () => { }); }); + it('blocks frozen poll timers before acquisition, database calls or prompts and lets a fresh poll run once', async (): Promise => { + const { ClustersClient: actualClient } = await vi.importActual< + typeof import('../../../documentdb/ClustersClient') + >('../../../documentdb/ClustersClient'); + const old = { ...binding, clusterId: 'frozen-dashboard-poll' }; + const fresh = { ...old, generation: 2 }; + const command = vi.fn(async (): Promise => ({ ok: 1, uptime: 42 })); + const acquisition = vi.spyOn( + actualClient as unknown as { acquireClient: () => Promise }, + 'acquireClient', + ).mockResolvedValue({ + binding: fresh, + getMongoClient: () => ({ db: () => ({ admin: () => ({ command }) }) }), + } as unknown as ClustersClient); + vi.mocked(ClustersClient.resolveBoundClient).mockImplementation(actualClient.resolveBoundClient); + vi.mocked(ClustersClient.getBinding).mockReturnValue(fresh); + retireConnectionBindings(old.clusterId, old.generation, 'userDisconnected'); + const frozen = createCallerFactory(clusterDashboardRouter)(createContext(undefined, undefined, old)); + const poll = vi.fn(async (): Promise => { + await expect(frozen.measureRtt()).resolves.toMatchObject({ + unavailable: { reason: 'userDisconnected' }, + }); + }); + vi.useFakeTimers(); + const scheduledPolls: Promise[] = []; + const timer = setInterval((): void => { + scheduledPolls.push(poll()); + }, 100); + try { + await vi.advanceTimersByTimeAsync(500); + } finally { + clearInterval(timer); + } + const resolvedPolls = await Promise.all(scheduledPolls); + expect(scheduledPolls).toHaveLength(5); + expect(resolvedPolls).toHaveLength(5); + expect(poll).toHaveBeenCalledTimes(5); + expect(acquisition).not.toHaveBeenCalled(); + expect(command).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + expect(vscode.authentication.getSession).not.toHaveBeenCalled(); + await expect( + createCallerFactory(clusterDashboardRouter)(createContext(undefined, undefined, fresh)).measureRtt(), + ).resolves.toMatchObject({ uptimeSeconds: 42 }); + expect(acquisition).toHaveBeenCalledOnce(); + expect(command).toHaveBeenCalledTimes(2); + }); + + it.each(['createDatabase', 'createCollection'] as const)( + 'rejects old %s RPCs after explicit teardown without tree lookup or writes; a fresh action works once', + async (action): Promise => { + const old = { ...binding, clusterId: `frozen-dashboard-${action}` }; + const fresh = { ...old, generation: 2 }; + vi.mocked(ClustersClient.getBinding).mockReturnValue(fresh); + mockResolveClusterNode.mockResolvedValue({ id: 'cluster-tree-id' }); + mockResolveNamespaceNode.mockResolvedValue({ id: 'database-tree-id' }); + retireConnectionBindings(old.clusterId, old.generation, 'userDisconnected'); + const frozen = createCallerFactory(clusterDashboardRouter)(createContext(undefined, undefined, old)); + const input = { databaseName: 'database', activationSource: 'inventoryToolbar' as const }; + await expect( + action === 'createDatabase' ? frozen.createDatabase(input) : frozen.createCollection(input), + ).resolves.toMatchObject({ unavailable: { reason: 'userDisconnected' } }); + expect(mockResolveClusterNode).not.toHaveBeenCalled(); + expect(mockResolveNamespaceNode).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + const live = createCallerFactory(clusterDashboardRouter)(createContext(undefined, undefined, fresh)); + await (action === 'createDatabase' ? live.createDatabase(input) : live.createCollection(input)); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + expect(vscode.commands.executeCommand).toHaveBeenCalledWith( + `vscode-documentdb.command.${action}`, + action === 'createDatabase' ? { id: 'cluster-tree-id' } : { id: 'database-tree-id' }, + null, + expect.objectContaining({ binding: fresh }), + ); + }, + ); + it('returns unavailable when a storage collector observes rejected credentials', async () => { const rejected = new Error('authentication failed'); const client = { diff --git a/src/webviews/documentdb/clusterDashboard/components/NamespaceTable.tsx b/src/webviews/documentdb/clusterDashboard/components/NamespaceTable.tsx index d67af1c4e..3d826efb4 100644 --- a/src/webviews/documentdb/clusterDashboard/components/NamespaceTable.tsx +++ b/src/webviews/documentdb/clusterDashboard/components/NamespaceTable.tsx @@ -350,6 +350,7 @@ export const NamespaceTable = ({ preventDefaultContextMenuItems: true, clusterDashboardNamespace: isDatabases ? 'database' : 'collection', clusterDashboardClusterId: configuration.clusterId, + clusterDashboardSessionId: configuration.dashboardSessionId, clusterDashboardSelectedDatabase: configuration.selectedDatabaseName, clusterDashboardDatabase: isDatabases ? row.name : databaseName, clusterDashboardCollection: isDatabases ? undefined : row.name, From 1d971f4c1eb7f0790544ee8b1f5c1e03f0de2a58 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 14:41:28 +0000 Subject: [PATCH 15/62] fix: complete ordinary Disconnect before editing settings (WI-E) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/commands/saveConnectionEdit.test.ts | 543 ++++++++++++++++++ src/commands/saveConnectionEdit.ts | 38 +- .../updateConnectionString.test.ts | 203 ++++++- .../updateConnectionString.ts | 20 +- .../updateCredentials.test.ts | 250 ++++++-- .../updateCredentials/updateCredentials.ts | 26 +- src/documentdb/connectionTeardown.test.ts | 74 ++- src/documentdb/connectionTeardown.ts | 53 +- 8 files changed, 1088 insertions(+), 119 deletions(-) create mode 100644 src/commands/saveConnectionEdit.test.ts diff --git a/src/commands/saveConnectionEdit.test.ts b/src/commands/saveConnectionEdit.test.ts new file mode 100644 index 000000000..52b2ae3d1 --- /dev/null +++ b/src/commands/saveConnectionEdit.test.ts @@ -0,0 +1,543 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { EventEmitter } from 'node:events'; +import { MongoClient, type MongoClientOptions } from 'mongodb'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../documentdb/ClustersClient'; +import { getBindingLifetimeSignal } from '../documentdb/connectionBindingRetirement'; +import { registerConnectionSurface } from '../documentdb/connectionSurfaces'; +import { canSaveEdit } from '../documentdb/connectionTeardown'; +import { CredentialCache } from '../documentdb/CredentialCache'; +import { API } from '../DocumentDBExperiences'; +import { ext } from '../extensionVariables'; +import type * as storageModule from '../services/connectionStorageService'; +import { + ConnectionStorageService, + ConnectionType, + ItemType, + type ConnectionItem, +} from '../services/connectionStorageService'; +import { type DocumentDBClusterItem } from '../tree/connections-view/DocumentDBClusterItem'; +import { showConfirmationAsInSettings } from '../utils/dialogs/showConfirmation'; +import { refreshView } from './refreshView/refreshView'; +import { saveConnectionEdit } from './saveConnectionEdit'; +import { ExecuteStep as UpdateStringExecuteStep } from './updateConnectionString/ExecuteStep'; +import { updateConnectionString } from './updateConnectionString/updateConnectionString'; +import { type UpdateCSWizardContext } from './updateConnectionString/UpdateCSWizardContext'; +import { ExecuteStep as UpdateCredentialsExecuteStep } from './updateCredentials/ExecuteStep'; +import { updateCredentials } from './updateCredentials/updateCredentials'; +import { type UpdateCredentialsWizardContext } from './updateCredentials/UpdateCredentialsWizardContext'; + +type EditContext = UpdateCredentialsWizardContext | UpdateCSWizardContext; +const capturedContexts: EditContext[] = []; +const driverConnect = vi.fn(); +const driverClose = vi.fn(); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const { wizardPrompt, getPlaygroundEvaluators, getRegisteredShellTerminals } = vi.hoisted(() => ({ + wizardPrompt: vi.fn<(context: EditContext) => Promise>(), + getPlaygroundEvaluators: vi.fn(), + getRegisteredShellTerminals: vi.fn(), +})); +const registrations: vscode.Disposable[] = []; + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal<{ AzureWizard: typeof AzureWizard; UserCancelledError: typeof UserCancelledError }>()), + // Match the client-suite fixture: the shared VS Code stub has no CancellationError. + parseError: (error: unknown): { message: string; errorType: string } => ({ + message: error instanceof Error ? error.message : String(error), + errorType: + typeof error === 'object' && + error !== null && + 'code' in error && + (typeof error.code === 'string' || typeof error.code === 'number') + ? String(error.code) + : error instanceof Error + ? error.constructor.name + : typeof error, + }), + AzureWizard: class { + constructor(private readonly context: EditContext) { + capturedContexts.push(context); + } + public async prompt(): Promise { + if ('originalConnectionString' in this.context) { + this.context.newConnectionString = 'mongodb://new.example.com/'; + } else { + this.context.selectedAuthenticationMethod = AuthMethodId.NativeAuth; + this.context.nativeAuthConfig = { connectionUser: 'new-user', connectionPassword: 'new-password' }; + } + await wizardPrompt(this.context); + } + public async execute(): Promise { + if ('originalConnectionString' in this.context) { + await new UpdateStringExecuteStep().execute(this.context); + } else { + await new UpdateCredentialsExecuteStep().execute(this.context); + } + } + }, + callWithTelemetryAndErrorHandling: async ( + _name: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + const context = makeContext(); + try { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow && !(error instanceof UserCancelledError)) { + throw error; + } + return undefined; + } + }, +})); +vi.mock('mongodb', async (importOriginal) => ({ + ...(await importOriginal()), + MongoClient: vi.fn(), +})); +vi.mock('../documentdb/LlmEnhancedFeatureApis', () => ({ llmEnhancedFeatureApis: vi.fn() })); +vi.mock('../documentdb/client/QueryInsightsApis', () => ({ QueryInsightsApis: vi.fn() })); +vi.mock('../documentdb/utils/getClusterMetadata', () => ({ + getClusterMetadata: vi.fn().mockResolvedValue({}), + getDomainMetadata: vi.fn().mockReturnValue({}), +})); +vi.mock('../documentdb/srv/prepareDriverConnectionString', () => ({ + prepareDriverConnectionString: async (input: { + connectionString: string; + options: MongoClientOptions; + }): Promise<{ connectionString: string; options: MongoClientOptions }> => ({ + connectionString: input.connectionString, + options: input.options, + }), +})); +vi.mock('../services/connectionStorageService', async (importOriginal) => ({ + ...(await importOriginal()), + ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, +})); +vi.mock('../services/SettingsService', () => ({ + SettingsService: { getSetting: (): undefined => undefined }, +})); +vi.mock('../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: (): readonly unknown[] => [] }, +})); +vi.mock('./playground/executePlaygroundCode', () => ({ + getPlaygroundEvaluators, + stopPlaygroundEvaluator: vi.fn(), +})); +vi.mock('../documentdb/shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals, +})); +vi.mock('./refreshView/refreshView', () => ({ refreshView: vi.fn() })); +vi.mock('../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../extensionVariables', () => ({ + ext: { + connectionsBranchDataProvider: { + hasNodeErrorState: vi.fn(), + resetNodeErrorState: vi.fn(), + refresh: vi.fn(), + }, + outputChannel: { debug: vi.fn(), info: vi.fn(), trace: vi.fn(), warn: vi.fn(), error: vi.fn() }, + }, +})); + +function makeContext(): IActionContext { + return { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + valuesToMask: [], + } as unknown as IActionContext; +} + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((finish) => { + resolve = finish; + }); + return { promise, resolve }; +} + +describe('disconnected connection edits', () => { + let clusterId: string; + let number = 0; + let node: DocumentDBClusterItem; + let stored: ConnectionItem; + + function cacheStoredCredentials(): void { + const method = + stored.properties.selectedAuthMethod === AuthMethodId.NativeAuth + ? AuthMethodId.NativeAuth + : AuthMethodId.NoAuth; + CredentialCache.setAuthCredentials( + clusterId, + method, + stored.secrets.connectionString, + stored.secrets.nativeAuthConfig, + ); + } + + beforeEach((): void => { + vi.clearAllMocks(); + clusterId = `disconnected-edit-${number++}`; + node = { + id: `folder/${clusterId}`, + storageId: clusterId, + cluster: { clusterId, storageZone: ConnectionType.Clusters, treeId: `folder/${clusterId}` }, + } as unknown as DocumentDBClusterItem; + stored = { + id: clusterId, + name: 'Saved connection', + properties: { + type: ItemType.Connection, + api: API.DocumentDB, + selectedAuthMethod: AuthMethodId.NoAuth, + availableAuthMethods: [AuthMethodId.NativeAuth, AuthMethodId.NoAuth], + }, + secrets: { connectionString: 'mongodb://old.example.com/' }, + }; + capturedContexts.length = 0; + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(false); + vi.mocked(refreshView).mockReset().mockResolvedValue(undefined); + wizardPrompt.mockReset().mockResolvedValue(undefined); + getPlaygroundEvaluators.mockReturnValue(new Map()); + getRegisteredShellTerminals.mockReturnValue([]); + cacheStoredCredentials(); + vi.mocked(ConnectionStorageService.get).mockImplementation(async () => structuredClone(stored)); + vi.mocked(ConnectionStorageService.save) + .mockReset() + .mockImplementation(async (_zone, item): Promise => { + stored = structuredClone(item) as ConnectionItem; + }); + driverConnect.mockReset().mockResolvedValue(undefined); + driverClose.mockResolvedValue(undefined); + vi.mocked(MongoClient).mockImplementation(function () { + return Object.assign(new EventEmitter(), { + connect: driverConnect, + close: driverClose, + }) as unknown as MongoClient; + }); + showWarning.mockImplementation(async (_message, _options, ...items) => + items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); + }); + + afterEach(async (): Promise => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } + await ClustersClient.deleteClient(clusterId); + CredentialCache.deleteCredentials(clusterId); + ClustersClient.clearLastVerifiedIdentity(clusterId); + ClustersClient.unlatch(clusterId); + }); + + it.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)( + 'excludes real client startup between both %s writes, including a metadata failure', + async (_commandName, update): Promise => { + const original = await ClustersClient.getClient(clusterId); + expect(original.binding.clusterId).toBe(clusterId); + expect(driverConnect).toHaveBeenCalledOnce(); + const secretWritten = deferred(); + const finishMetadata = deferred(); + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored.secrets = structuredClone(item.secrets); + secretWritten.resolve(); + await finishMetadata.promise; + throw new Error('Metadata write failed'); + }); + + const updating = update(makeContext(), node); + await secretWritten.promise; + expect(driverClose).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsUpdating'); + expect(ClustersClient.exists(clusterId)).toBe(false); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toMatchObject({ + reason: 'credentialsUpdating', + }); + expect(driverConnect).toHaveBeenCalledOnce(); + finishMetadata.resolve(); + await updating; + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + const edited = capturedContexts[0]; + if ('originalConnectionString' in edited) { + expect(edited.connectionStringSaved).toBe(false); + } else { + expect(edited.credentialsSaved).not.toBe(true); + } + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(driverConnect).toHaveBeenCalledOnce(); + }, + ); + + it.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)( + 'allows a fresh client using the fully saved %s after explicit reconnect', + async (_name, update): Promise => { + const original = await ClustersClient.getClient(clusterId); + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored = structuredClone(item) as ConnectionItem; + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + expect(driverConnect).toHaveBeenCalledOnce(); + cacheStoredCredentials(); + ClustersClient.unlatch(clusterId); + const current = await ClustersClient.getClient(clusterId); + expect(current).not.toBe(original); + expect(current.generation).toBeGreaterThan(original.generation); + expect(driverConnect).toHaveBeenCalledTimes(2); + expect(driverClose).toHaveBeenCalledOnce(); + }, + ); + + it('does not start saving after its wizard epoch was superseded', async (): Promise => { + const save = vi.fn<() => Promise>(); + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.invalidate(clusterId); + + await expect( + saveConnectionEdit(node, save, { canStart: (): boolean => canSaveEdit(clusterId, epoch) }), + ).rejects.toBeInstanceOf(UserCancelledError); + + expect(ConnectionStorageService.get).not.toHaveBeenCalled(); + expect(save).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + }); + + it('does not save or restore a hold superseded during the storage read', async (): Promise => { + const readStarted = deferred(); + const finishRead = deferred(); + ClustersClient.latch(clusterId, 'userDisconnected'); + vi.mocked(ConnectionStorageService.get).mockImplementationOnce(async () => { + readStarted.resolve(); + await finishRead.promise; + return structuredClone(stored); + }); + const save = vi.fn<() => Promise>(); + const saving = saveConnectionEdit(node, save); + await readStarted.promise; + ClustersClient.latch(clusterId, 'connectionRemoved'); + finishRead.resolve(); + + await expect(saving).rejects.toBeInstanceOf(UserCancelledError); + + expect(save).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('connectionRemoved'); + }); + + it('reconnects after Yes with a fresh session while the kept old tab remains read-only', async (): Promise => { + const original = await ClustersClient.getClient(clusterId); + const lifetime = getBindingLifetimeSignal(original.binding); + const draft = { + clusterId, + kind: 'documentView' as const, + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + registrations.push(registerConnectionSurface(draft)); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + wizardPrompt.mockImplementationOnce(async (context): Promise => { + if ('isErrorState' in context) { + context.reconnectAfterError = true; + } + }); + let connected: ClustersClient | undefined; + vi.mocked(refreshView).mockImplementationOnce(async (): Promise => { + connected = await ClustersClient.getClient(clusterId); + }); + const unlatch = vi.spyOn(ClustersClient, 'unlatch'); + try { + await updateCredentials(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(unlatch).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(unlatch).toHaveBeenCalledBefore( + vi.mocked(ext.connectionsBranchDataProvider.resetNodeErrorState), + ); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).toHaveBeenCalledBefore( + vi.mocked(refreshView), + ); + expect(connected).toBeDefined(); + expect(connected).not.toBe(original); + expect(connected?.generation).toBeGreaterThan(original.generation); + expect(driverConnect).toHaveBeenCalledTimes(2); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.isDirty()).toBe(true); + expect(lifetime.aborted).toBe(true); + await expect(ClustersClient.resolveBoundClient(original.binding)).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + if (!connected) { + throw new Error('Expected refresh to open a fresh connection.'); + } + await expect(ClustersClient.resolveBoundClient(connected.binding)).resolves.toBe(connected); + expect(driverConnect).toHaveBeenCalledTimes(2); + } finally { + unlatch.mockRestore(); + } + }); + + it.each(['No', 'failed save', 'connectionRemoved'] as const)( + 'does not unlatch or start another session after %s', + async (outcome): Promise => { + await ClustersClient.getClient(clusterId); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + wizardPrompt.mockImplementationOnce(async (context): Promise => { + if ('isErrorState' in context) { + context.reconnectAfterError = outcome !== 'No'; + } + }); + if (outcome === 'failed save') { + vi.mocked(ConnectionStorageService.save).mockRejectedValueOnce(new Error('Save failed')); + } else if (outcome === 'connectionRemoved') { + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored = structuredClone(item) as ConnectionItem; + ClustersClient.latch(clusterId, 'connectionRemoved'); + }); + } + const unlatch = vi.spyOn(ClustersClient, 'unlatch'); + try { + await updateCredentials(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(unlatch).not.toHaveBeenCalled(); + const reason = outcome === 'connectionRemoved' ? 'connectionRemoved' : 'userDisconnected'; + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason }); + expect(driverConnect).toHaveBeenCalledOnce(); + if (outcome !== 'connectionRemoved') { + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + } + } finally { + unlatch.mockRestore(); + } + }, + ); + + describe.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)('%s idle-wizard exclusion', (_name, update): void => { + it.each(['client', 'pending startup', 'surface', 'shell', 'evaluator'] as const)( + 'does not save when a %s appears during the wizard without changing the epoch', + async (work): Promise => { + const epoch = ClustersClient.getEpoch(clusterId); + const original = structuredClone(stored); + const started = deferred(); + const finishStartup = deferred(); + let startup: Promise | undefined; + const disconnect = vi.fn(); + const surface = { + clusterId, + kind: 'documentView' as const, + disable: vi.fn(), + dispose: vi.fn(), + }; + wizardPrompt.mockImplementationOnce(async (): Promise => { + if (work === 'client') { + await ClustersClient.getClient(clusterId); + } else if (work === 'pending startup') { + driverConnect.mockImplementationOnce(async (): Promise => { + started.resolve(); + await finishStartup.promise; + }); + startup = ClustersClient.getClient(clusterId); + await started.promise; + } else if (work === 'surface') { + registrations.push(registerConnectionSurface(surface)); + } else if (work === 'shell') { + getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + } else { + getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + } + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(stored).toEqual(original); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); + expect(driverConnect).toHaveBeenCalledTimes(work === 'client' || work === 'pending startup' ? 1 : 0); + expect(driverClose).not.toHaveBeenCalled(); + expect(disconnect).not.toHaveBeenCalled(); + expect(surface.disable).not.toHaveBeenCalled(); + expect(surface.dispose).not.toHaveBeenCalled(); + finishStartup.resolve(); + if (startup) { + await startup; + expect(ClustersClient.exists(clusterId)).toBe(true); + } + }, + ); + + it('saves a user-disconnected connection with a still-registered old shell', async (): Promise => { + ClustersClient.latch(clusterId, 'userDisconnected'); + const disconnect = vi.fn(); + getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + expect(disconnect).not.toHaveBeenCalled(); + expect(driverConnect).not.toHaveBeenCalled(); + expect(driverClose).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('allows saving when a startup attempted during the wizard has failed and disappeared', async (): Promise => { + const epoch = ClustersClient.getEpoch(clusterId); + wizardPrompt.mockImplementationOnce(async (): Promise => { + driverConnect.mockRejectedValueOnce(new Error('Startup failed')); + await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('Startup failed'); + expect(ClustersClient.hasPendingStartup(clusterId)).toBe(false); + expect(ClustersClient.exists(clusterId)).toBe(false); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/commands/saveConnectionEdit.ts b/src/commands/saveConnectionEdit.ts index 4cd90a3c1..2144c7579 100644 --- a/src/commands/saveConnectionEdit.ts +++ b/src/commands/saveConnectionEdit.ts @@ -8,16 +8,13 @@ import { isDeepStrictEqual } from 'node:util'; import * as vscode from 'vscode'; import { clearEntraTokenFailure } from '../documentdb/auth/entraErrors/entraTokenFailures'; import { ClustersClient } from '../documentdb/ClustersClient'; -import { getConnectionSurfaces } from '../documentdb/connectionSurfaces'; -import { confirmTeardown, latchForTeardown } from '../documentdb/connectionTeardown'; +import { latchForTeardown } from '../documentdb/connectionTeardown'; import { CredentialCache } from '../documentdb/CredentialCache'; -import { getRegisteredShellTerminals } from '../documentdb/shell/ShellTerminalLinkProvider'; import { ext } from '../extensionVariables'; import { ConnectionStorageService, isConnection, type StoredItem } from '../services/connectionStorageService'; import { checkCanProceedAndInformUser } from '../services/taskService/resourceUsageHelper'; import { type DocumentDBClusterItem } from '../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../tree/connections-view/models/ConnectionClusterModel'; -import { stopPlaygroundEvaluator } from './playground/executePlaygroundCode'; function storedSettings(item: StoredItem | undefined): object | undefined { if (!item || !isConnection(item)) { @@ -31,8 +28,8 @@ function storedSettings(item: StoredItem | undefined): object | undefined { } /** - * Hold the existing latch across storage writes, then use what actually persisted to decide - * whether to retire views. Secret storage and metadata are not written atomically. + * Exclude startup across both storage writes and verify what actually persisted. + * The old session has already ended; secret storage and metadata are not written atomically. */ export async function saveConnectionEdit( node: DocumentDBClusterItem, @@ -44,10 +41,6 @@ export async function saveConnectionEdit( ): Promise { const { clusterId } = node.cluster; const zone = resolveStorageZone(node.cluster); - if ((await confirmTeardown(clusterId, 'credentialsChanged')).outcome !== 'confirmed') { - throw new UserCancelledError(); - } - if (options?.canStart?.() === false) { throw new UserCancelledError(); } @@ -85,12 +78,6 @@ export async function saveConnectionEdit( } if (isCurrent() && !isDeepStrictEqual(originalSettings, storedSettings(after))) { changed = true; - ClustersClient.retireBoundViews(clusterId); - for (const surface of getConnectionSurfaces(clusterId)) { - surface.disable('credentialsChanged'); - } - stopPlaygroundEvaluator(clusterId); - const closing = ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); CredentialCache.deleteCredentials(clusterId); clearEntraTokenFailure(clusterId); if ( @@ -114,7 +101,6 @@ export async function saveConnectionEdit( ), ); } - await closing; if (isCurrent()) { options?.publishCredentials?.(after); } @@ -132,21 +118,3 @@ export async function saveConnectionEdit( } return changed; } - -export async function offerShellDisconnect(node: DocumentDBClusterItem): Promise { - const shells = getRegisteredShellTerminals().filter(({ info }) => info.clusterId === node.cluster.clusterId); - if (!shells.length) { - return; - } - const disconnect = vscode.l10n.t('Disconnect'); - const selected = await vscode.window.showInformationMessage( - vscode.l10n.t('Open shells are still using the previous connection settings.'), - { modal: true }, - disconnect, - ); - if (selected === disconnect) { - for (const shell of shells) { - shell.disconnect?.(); - } - } -} diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 4b6703005..e62096c84 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -9,10 +9,11 @@ import { type IActionContext, type callWithTelemetryAndErrorHandling, } from '@microsoft/vscode-azext-utils'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { API, DocumentDBExperience } from '../../DocumentDBExperiences'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { registerConnectionSurface } from '../../documentdb/connectionSurfaces'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; @@ -36,10 +37,22 @@ import { ExecuteStep } from './ExecuteStep'; import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; import { updateConnectionString } from './updateConnectionString'; -const { capturedContexts, showInputBox, showQuickPick } = vi.hoisted(() => ({ +const { + capturedContexts, + showInputBox, + showQuickPick, + getConflictingTasks, + getPlaygroundEvaluators, + getRegisteredShellTerminals, + stopPlaygroundEvaluator, +} = vi.hoisted(() => ({ capturedContexts: [] as UpdateCSWizardContext[], showInputBox: vi.fn(), showQuickPick: vi.fn(), + getConflictingTasks: vi.fn(), + getPlaygroundEvaluators: vi.fn(), + getRegisteredShellTerminals: vi.fn(), + stopPlaygroundEvaluator: vi.fn(), })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -73,9 +86,13 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ _name: string, callback: (context: IActionContext) => Promise, ): Promise => { + const context = makeContext(); try { - return await callback(makeContext()); - } catch { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow && !(error instanceof UserCancelledError)) { + throw error; + } return undefined; } }, @@ -90,6 +107,7 @@ vi.mock('../../documentdb/ClustersClient', () => ({ connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), + hasPendingStartup: vi.fn(), getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), getExistingClient: vi.fn(), @@ -107,6 +125,9 @@ vi.mock('../../services/SettingsService', () => ({ SettingsService: { getSetting: vi.fn(() => false) }, })); vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../../services/taskService/taskService', () => ({ TaskService: { getConflictingTasks } })); +vi.mock('../playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators, stopPlaygroundEvaluator })); +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals })); vi.mock('../../extensionVariables', () => ({ ext: { outputChannel: { appendLine: vi.fn(), append: vi.fn(), debug: vi.fn(), info: vi.fn(), error: vi.fn() }, @@ -119,6 +140,13 @@ vi.mock('../../tree/connections-view/LocalQuickStart/LocalQuickStartItem', () => const originalUri = 'mongodb://old.example.com/'; const approvedUri = 'mongodb://new.mongocluster.cosmos.azure.com/'; const deleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const registrations: vscode.Disposable[] = []; function makeContext(): IActionContext { return { @@ -158,10 +186,35 @@ describe('updateConnectionString rejected-destination recovery', () => { let provider: ConnectionsBranchDataProvider; let storedConnection: ConnectionItem; let item: DocumentDBClusterItem; + let epoch: number; + let latch: ReturnType; beforeEach((): void => { CredentialCache.deleteCredentials('stable-id'); vi.resetAllMocks(); + epoch = 0; + latch = undefined; + vi.mocked(ClustersClient.getEpoch).mockImplementation(() => epoch); + vi.mocked(ClustersClient.getLatchReason).mockImplementation(() => latch); + vi.mocked(ClustersClient.latch).mockImplementation((_id, reason): void => { + latch = reason; + epoch++; + }); + vi.mocked(ClustersClient.unlatch).mockImplementation((): void => { + latch = undefined; + epoch++; + }); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); + getConflictingTasks.mockReturnValue([]); + getPlaygroundEvaluators.mockReturnValue(new Map()); + getRegisteredShellTerminals.mockReturnValue([]); + showWarning.mockImplementation(async (_message, _options, ...items) => + items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); capturedContexts.length = 0; provider = new ConnectionsBranchDataProvider(); ext.connectionsBranchDataProvider = provider; @@ -184,6 +237,12 @@ describe('updateConnectionString rejected-destination recovery', () => { ); }); + afterEach((): void => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } + }); + it.each([ [approvedUri, AuthMethodId.ManagedIdentity], ['mongodb://new.example.com/', AuthMethodId.NoAuth], @@ -193,11 +252,12 @@ describe('updateConnectionString rejected-destination recovery', () => { const failedChildren = await provider.getChildren(item); expect(provider.hasNodeErrorState(item.id)).toBe(true); expect(item.lastConnectionFailureReason).toBe('entraDestinationRejected'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(true); const resetError = vi.spyOn(provider, 'resetNodeErrorState'); const refresh = vi.spyOn(provider, 'refresh'); showInputBox.mockResolvedValue(newUri); vi.mocked(ClustersClient.deleteClient).mockImplementation(async (): Promise => { - expect(storedConnection.secrets.connectionString).toBe(newUri); + expect(storedConnection.secrets.connectionString).toBe(originalUri); expect(provider.hasNodeErrorState(item.id)).toBe(true); expect(CredentialCache.hasCredentials('stable-id')).toBe(true); }); @@ -214,11 +274,12 @@ describe('updateConnectionString rejected-destination recovery', () => { expect(CredentialCache.hasCredentials('stable-id')).toBe(false); expect(item.lastConnectionFailureReason).toBeUndefined(); expect(item.lastConnectionOutcome).toBeUndefined(); - expect(vi.mocked(ConnectionStorageService.save).mock.invocationCallOrder[0]).toBeLessThan( - vi.mocked(ClustersClient.deleteClient).mock.invocationCallOrder[0], - ); + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(showInputBox); + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(vi.mocked(ConnectionStorageService.save)); expect(deleteCredentials.mock.invocationCallOrder[0]).toBeLessThan(resetError.mock.invocationCallOrder[0]); - expect(resetError.mock.invocationCallOrder[0]).toBeLessThan(refresh.mock.invocationCallOrder[0]); + expect(resetError.mock.invocationCallOrder[0]).toBeLessThan( + refresh.mock.invocationCallOrder[refresh.mock.invocationCallOrder.length - 1], + ); const client = { listDatabases: vi.fn().mockResolvedValue([]), connectionCorrelationId: 'retry' }; vi.mocked(ClustersClient.connectInteractive).mockImplementation( async (clusterId): Promise => { @@ -231,6 +292,7 @@ describe('updateConnectionString rejected-destination recovery', () => { }, ); + ClustersClient.unlatch('stable-id'); const retriedChildren = await provider.getChildren(item); expect(retriedChildren).not.toEqual(failedChildren); @@ -280,38 +342,141 @@ describe('updateConnectionString rejected-destination recovery', () => { }, ); - it('retires the old client and bindings after an ordinary saved edit', async (): Promise => { + it('ends the old session before an ordinary saved edit', async (): Promise => { const resetError = vi.spyOn(provider, 'resetNodeErrorState'); const refresh = vi.spyOn(provider, 'refresh'); item.lastConnectionOutcome = 'connected'; + vi.mocked(ClustersClient.exists).mockReturnValue(true); await updateConnectionString(makeContext(), item); expect(capturedContexts[0].connectionStringSaved).toBe(true); expect(storedConnection.secrets.connectionString).toBe(approvedUri); - expect(ClustersClient.retireBoundViews).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(ClustersClient.retireBoundViews).toHaveBeenCalledExactlyOnceWith('stable-id', 'userDisconnected'); expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { alreadyInvalidated: true }); expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(resetError).not.toHaveBeenCalled(); expect(CredentialCache.getCredentials('stable-id')).toBeUndefined(); expect(item.lastConnectionOutcome).toBe('connected'); - expect(refresh).toHaveBeenCalledOnce(); + expect(refresh).toHaveBeenCalledTimes(2); + expect(latch).toBe('userDisconnected'); }); - it('saves an ordinary edit when the epoch changes while the input is open', async (): Promise => { + it('does not save an ordinary edit superseded while the input is open', async (): Promise => { const refresh = vi.spyOn(provider, 'refresh'); item.lastConnectionOutcome = 'connected'; showInputBox.mockImplementationOnce(async (): Promise => { - vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + epoch++; return approvedUri; }); await updateConnectionString(makeContext(), item); - expect(storedConnection.secrets.connectionString).toBe(approvedUri); - expect(capturedContexts[0].connectionStringSaved).toBe(true); - expect(ClustersClient.retireBoundViews).toHaveBeenCalledExactlyOnceWith('stable-id'); - expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); - expect(refresh).toHaveBeenCalledOnce(); + expect(storedConnection.secrets.connectionString).toBe(originalUri); + expect(capturedContexts[0].connectionStringSaved).toBe(false); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(deleteCredentials).not.toHaveBeenCalled(); + expect(refresh).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); }); + + it.each(['cancel offer', 'cancel tabs', 'active transfer', 'dirty close refusal', 'close failure'] as const)( + 'does not begin the wizard or save after %s', + async (outcome): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + const draft = { + clusterId: 'stable-id', + kind: 'documentView' as const, + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + registrations.push(registerConnectionSurface(draft)); + const task = { taskName: 'Copy orders', taskType: 'copy', cancel: vi.fn() }; + if (outcome === 'active transfer') { + getConflictingTasks.mockReturnValue([task]); + } else if (outcome === 'cancel offer') { + showWarning.mockResolvedValueOnce(undefined); + } else if (outcome === 'cancel tabs') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else if (outcome === 'dirty close refusal') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else { + vi.mocked(ClustersClient.deleteClient).mockRejectedValueOnce( + new Error('private driver connection details'), + ); + } + + const pending = updateConnectionString(makeContext(), item); + if (outcome === 'close failure') { + await expect(pending).rejects.toThrow('Could not finish closing the connection.'); + expect(latch).toBe('userDisconnected'); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(draft.disable).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(stopPlaygroundEvaluator).not.toHaveBeenCalled(); + } + expect(showInputBox).not.toHaveBeenCalled(); + expect(ConnectionStorageService.get).not.toHaveBeenCalled(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(task.cancel).not.toHaveBeenCalled(); + }, + ); + + it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + showInputBox.mockRejectedValueOnce(new UserCancelledError()); + + await expect(updateConnectionString(makeContext(), item)).rejects.toBeInstanceOf(UserCancelledError); + + expect(latch).toBe('userDisconnected'); + expect(ClustersClient.deleteClient).toHaveBeenCalledOnce(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }); + + it.each(['idle', 'userDisconnected', 'held client', 'evicted surface', 'pending startup'] as const)( + 'edits %s without overlooking surviving connection work', + async (state): Promise => { + latch = state === 'userDisconnected' ? 'userDisconnected' : 'credentialsRejected'; + vi.mocked(ClustersClient.exists).mockReturnValue(state === 'held client'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(state === 'pending startup'); + const draft = { + clusterId: 'stable-id', + kind: 'documentView' as const, + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + if (state === 'evicted surface') { + registrations.push(registerConnectionSurface(draft)); + } + + await updateConnectionString(makeContext(), item); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + if (state === 'idle' || state === 'userDisconnected') { + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(stopPlaygroundEvaluator).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + } else { + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(showInputBox); + expect(stopPlaygroundEvaluator).toHaveBeenCalledBefore(showInputBox); + expect(latch).toBe('userDisconnected'); + } + if (state === 'evicted surface') { + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.dispose).not.toHaveBeenCalled(); + } + }, + ); }); diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index 27229623a..2734435d8 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -5,7 +5,9 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; +import { window } from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { canSaveEdit, ensureDisconnectedForEdit } from '../../documentdb/connectionTeardown'; import { maskSensitiveValuesInTelemetry } from '../../documentdb/utils/connectionStringHelpers'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; @@ -14,7 +16,7 @@ import { ConnectionStorageService } from '../../services/connectionStorageServic import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; import { refreshView } from '../refreshView/refreshView'; -import { offerShellDisconnect, saveConnectionEdit } from '../saveConnectionEdit'; +import { saveConnectionEdit } from '../saveConnectionEdit'; import { ConnectionStringStep } from './ConnectionStringStep'; import { ExecuteStep } from './ExecuteStep'; import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; @@ -23,13 +25,13 @@ import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; * Updates the connection string (hosts, ports, etc.) for a cluster connection. * * Architecture: - * 1. Loads the current connection string with credentials masked + * 1. Ends the old session, then loads the current connection string with credentials masked * 2. Runs wizard to collect new connection string: * - ConnectionStringStep: Enter new connection string * 3. ExecuteStep: Saves updated connection string to storage * 4. Post-wizard: Refreshes the view * - * A changed value retires views tied to the previous settings. + * Tabs kept during Disconnect remain read-only, even if the edit is cancelled. */ export async function updateConnectionString(context: IActionContext, node: DocumentDBClusterItem): Promise { if (!node) { @@ -37,8 +39,8 @@ export async function updateConnectionString(context: IActionContext, node: Docu } const recoveringRejectedDestination = node.lastConnectionFailureReason === 'entraDestinationRejected'; const clusterId = node.cluster.clusterId; - const epoch = ClustersClient.getEpoch(clusterId); const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const epoch = await ensureDisconnectedForEdit(clusterId, () => ext.connectionsBranchDataProvider.refresh()); const recovering = recoveringRejectedDestination || recoveringRejectedCredentials; const isRecoveryCurrent = recovering ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; @@ -50,7 +52,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); - if (isRecoveryCurrent?.() === false) { + if (ClustersClient.getEpoch(clusterId) !== epoch) { return; } const connectionString = connection?.secrets?.connectionString || ''; @@ -80,7 +82,8 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); - if (isRecoveryCurrent?.() === false) { + if (!canSaveEdit(clusterId, epoch)) { + void window.showErrorMessage(l10n.t('This connection changed. Refresh the tree and try again.')); return; } const changed = @@ -93,7 +96,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu await wizard.execute(); return wizardContext.connectionStringSaved === true; }, - { canStart: isRecoveryCurrent }, + { canStart: () => canSaveEdit(clusterId, epoch) }, ) : false; if (recovering && changed && wizardContext.connectionStringSaved) { @@ -103,7 +106,4 @@ export async function updateConnectionString(context: IActionContext, node: Docu } await refreshView(context, Views.ConnectionsView); - if (changed) { - await offerShellDisconnect(node); - } } diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index 0e9d59238..d7c517812 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -3,11 +3,12 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { UserCancelledError, type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { registerConnectionSurface, type ConnectionSurface } from '../../documentdb/connectionSurfaces'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { SelectEntraTokenSourceStep } from '../../documentdb/wizards/authenticate/SelectEntraTokenSourceStep'; import { API } from '../../DocumentDBExperiences'; @@ -15,12 +16,14 @@ import { ext } from '../../extensionVariables'; import type * as storageModule from '../../services/connectionStorageService'; import { ItemType } from '../../services/connectionStorageService'; import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; +import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { ExecuteStep } from './ExecuteStep'; import { updateCredentials } from './updateCredentials'; import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardContext'; const capturedContexts: UpdateCredentialsWizardContext[] = []; const mockExecute = vi.fn<(context: UpdateCredentialsWizardContext) => Promise>().mockResolvedValue(undefined); +const mockPrompt = vi.fn<() => Promise>(); const mockGet = vi.fn(); const mockSave = vi.fn(); const mockGetEpoch = vi.fn(() => 0); @@ -29,6 +32,17 @@ const mockRetireBoundViews = vi.hoisted(() => vi.fn()); const mockDeleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); const mockShutdownEvaluator = vi.fn(); const mockGetRegisteredShellTerminals = vi.fn(); +const mockGetPlaygroundEvaluators = vi.fn(); +const mockGetConflictingTasks = vi.fn(); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const registrations: vscode.Disposable[] = []; +let epoch = 0; +let latch: ReturnType; vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ AzureWizard: typeof AzureWizard }>()), @@ -37,12 +51,27 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ capturedContexts.push(context); } public prompt(): Promise { - return Promise.resolve(); + return mockPrompt(); } public execute(): Promise { return mockExecute(this.context); } }, + callWithTelemetryAndErrorHandling: async ( + _name: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + try { + await callback({ + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + } as unknown as IActionContext); + } catch (error) { + if (!(error instanceof UserCancelledError)) { + throw error; + } + } + }, })); vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ @@ -58,6 +87,8 @@ vi.mock('../../documentdb/ClustersClient', () => ({ getLastFailedStartupCorrelationId: (): undefined => undefined, getEpoch: (): number => mockGetEpoch(), getLatchReason: vi.fn(), + exists: vi.fn(), + hasPendingStartup: vi.fn(), latch: vi.fn(), unlatch: vi.fn(), retireBoundViews: mockRetireBoundViews, @@ -67,15 +98,20 @@ vi.mock('../../documentdb/ClustersClient', () => ({ })); vi.mock('../playground/executePlaygroundCode', () => ({ stopPlaygroundEvaluator: (...args: unknown[]): unknown => mockShutdownEvaluator(...args), + getPlaygroundEvaluators: (): unknown => mockGetPlaygroundEvaluators(), })); vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: (): unknown => mockGetRegisteredShellTerminals(), })); vi.mock('../refreshView/refreshView', () => ({ refreshView: vi.fn() })); vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../../services/SettingsService', () => ({ SettingsService: { getSetting: (): undefined => undefined } })); +vi.mock('../../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: (...args: unknown[]): unknown => mockGetConflictingTasks(...args) }, +})); vi.mock('../../extensionVariables', () => ({ ext: { - connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(), resetNodeErrorState: vi.fn() }, + connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(), resetNodeErrorState: vi.fn(), refresh: vi.fn() }, outputChannel: { error: vi.fn(), warn: vi.fn() }, }, })); @@ -83,13 +119,42 @@ vi.mock('../../extensionVariables', () => ({ beforeEach(() => { CredentialCache.deleteCredentials('stable-cluster-id'); vi.clearAllMocks(); - mockGetEpoch.mockReturnValue(0); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + epoch = 0; + latch = undefined; + mockGetEpoch.mockImplementation((): number => epoch); + vi.mocked(ClustersClient.getLatchReason).mockImplementation(() => latch); + vi.mocked(ClustersClient.latch).mockImplementation((_id, reason): void => { + latch = reason; + epoch++; + }); + vi.mocked(ClustersClient.unlatch).mockImplementation((): void => { + latch = undefined; + epoch++; + }); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); + mockDeleteClient.mockReset().mockResolvedValue(undefined); + mockPrompt.mockReset().mockResolvedValue(undefined); + mockExecute.mockReset().mockResolvedValue(undefined); + mockGetConflictingTasks.mockReturnValue([]); + mockGetPlaygroundEvaluators.mockReturnValue(new Map()); vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(false); mockGetRegisteredShellTerminals.mockReturnValue([]); + showWarning.mockImplementation(async (_message, _options, ...items) => + items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); capturedContexts.length = 0; }); +afterEach((): void => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } +}); + async function inferMethods( host: string, suffix?: string, @@ -232,7 +297,8 @@ describe('updateCredentials post-wizard updates', () => { ); }); - it('retires old views after a saved password-only edit', async (): Promise => { + it('disconnects before prompting and saving a password-only edit', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); let storedConnection: storageModule.ConnectionItem = originalConnection; const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; mockGet.mockImplementation(async () => structuredClone(storedConnection)); @@ -251,15 +317,19 @@ describe('updateCredentials post-wizard updates', () => { expect(storedConnection.secrets.nativeAuthConfig).toEqual(newCredentials); expect(CredentialCache.getCredentials(node.cluster.clusterId)?.nativeAuthConfig).toEqual(newCredentials); expect(capturedContexts[0].credentialsSaved).toBe(true); - expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, 'userDisconnected'); expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { alreadyInvalidated: true }); expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).toHaveBeenCalledBefore(mockPrompt); + expect(mockDeleteClient).toHaveBeenCalledBefore(mockSave); + expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'userDisconnected'); }); it.each([true, false])( 'only clears rejection and refreshes the recovery node when an unchanged edit saves (%s)', async (saved) => { - vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + latch = 'credentialsRejected'; + vi.mocked(ClustersClient.exists).mockReturnValue(true); vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); mockExecute.mockImplementationOnce((wizardContext) => { wizardContext.reconnectAfterError = true; @@ -269,19 +339,23 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); - expect(mockRetireBoundViews).not.toHaveBeenCalled(); + expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, 'userDisconnected'); + expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'userDisconnected'); if (saved) { expect(ClustersClient.unlatch).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(ClustersClient.unlatch).toHaveBeenCalledBefore( + vi.mocked(ext.connectionsBranchDataProvider.resetNodeErrorState), + ); expect(ext.connectionsBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); } else { - expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'credentialsRejected'); expect(ClustersClient.unlatch).not.toHaveBeenCalled(); expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); } }, ); - it('retires old views if the secret write persisted but the edit reported failure', async (): Promise => { + it('keeps the ended session disconnected if a secret write persists but metadata fails', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); const stored = structuredClone(originalConnection); mockGet.mockImplementation(async () => structuredClone(stored)); mockExecute.mockImplementationOnce(async (wizardContext): Promise => { @@ -298,8 +372,11 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); expect(capturedContexts[0].credentialsSaved).not.toBe(true); - expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); - expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce(); + expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, 'userDisconnected'); + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); }); it.each<{ authMethod: AuthMethodId; secrets: Partial }>([ @@ -318,7 +395,7 @@ describe('updateCredentials post-wizard updates', () => { }, { authMethod: AuthMethodId.NoAuth, secrets: {} }, ])( - 'caches the saved $authMethod credentials and shuts down the old client and playground', + 'caches the saved $authMethod credentials without redundantly tearing down an idle connection', async ({ authMethod, secrets }) => { const savedConnection: storageModule.ConnectionItemInput = { ...originalConnection, @@ -352,10 +429,8 @@ describe('updateCredentials post-wizard updates', () => { }); expect(CredentialCache.hasCredentials(node.cluster.treeId)).toBe(false); expect(mockDeleteCredentials).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); - expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { - alreadyInvalidated: true, - }); - expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).not.toHaveBeenCalled(); + expect(mockShutdownEvaluator).not.toHaveBeenCalled(); }, ); @@ -392,7 +467,7 @@ describe('updateCredentials post-wizard updates', () => { expect(CredentialCache.getCredentials(node.cluster.clusterId)).toBeUndefined(); }); - it('offers to disconnect only shells using the previous connection settings', async () => { + it('stops only matching shells before editing without a post-save shell modal', async () => { const disconnect = vi.fn(); const disconnectOther = vi.fn(); mockGet @@ -408,15 +483,6 @@ describe('updateCredentials post-wizard updates', () => { mockExecute.mockImplementationOnce(async (wizardContext) => { wizardContext.credentialsSaved = true; }); - vi.spyOn(vscode.l10n, 't').mockImplementation((message) => - typeof message === 'string' ? message : message.message, - ); - const showInformation: ( - message: string, - options: vscode.MessageOptions, - ...items: string[] - ) => Thenable = vscode.window.showInformationMessage; - vi.mocked(showInformation).mockResolvedValueOnce('Disconnect'); mockGetRegisteredShellTerminals.mockReturnValue([ { info: { clusterId: 'another-cluster-id' }, disconnect: disconnectOther }, { info: { clusterId: node.cluster.clusterId }, disconnect }, @@ -424,16 +490,11 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); - expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( - 'Open shells are still using the previous connection settings.', - { modal: true }, - 'Disconnect', - ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); expect(disconnect).toHaveBeenCalledOnce(); expect(disconnectOther).not.toHaveBeenCalled(); - const modalCallOrder = vi.mocked(vscode.window.showInformationMessage).mock.invocationCallOrder[0]; - expect(mockDeleteClient.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); - expect(mockShutdownEvaluator.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); + expect(disconnect).toHaveBeenCalledBefore(mockPrompt); + expect(mockShutdownEvaluator).toHaveBeenCalledBefore(mockPrompt); }); it.each([ @@ -450,4 +511,119 @@ describe('updateCredentials post-wizard updates', () => { expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); }); + + it.each(['cancel offer', 'cancel tabs', 'active transfer', 'dirty close refusal', 'close failure'] as const)( + 'does not begin the wizard or save after %s', + async (outcome): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + const draft: ConnectionSurface = { + clusterId: node.cluster.clusterId, + kind: 'documentView', + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + registrations.push(registerConnectionSurface(draft)); + const task = { taskName: 'Copy orders', taskType: 'copy', cancel: vi.fn() }; + if (outcome === 'active transfer') { + mockGetConflictingTasks.mockReturnValue([task]); + } else if (outcome === 'cancel offer') { + showWarning.mockResolvedValueOnce(undefined); + } else if (outcome === 'cancel tabs') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else if (outcome === 'dirty close refusal') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else { + mockDeleteClient.mockRejectedValueOnce(new Error('private driver connection details')); + } + + const pending = updateCredentials(context, node); + if (outcome === 'close failure') { + await expect(pending).rejects.toThrow('Could not finish closing the connection.'); + expect(latch).toBe('userDisconnected'); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(draft.disable).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mockDeleteClient).not.toHaveBeenCalled(); + expect(mockShutdownEvaluator).not.toHaveBeenCalled(); + } + expect(mockPrompt).not.toHaveBeenCalled(); + expect(mockGet).not.toHaveBeenCalled(); + expect(mockSave).not.toHaveBeenCalled(); + expect(task.cancel).not.toHaveBeenCalled(); + }, + ); + + it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + mockPrompt.mockRejectedValueOnce(new UserCancelledError()); + + await expect(updateCredentials(context, node)).rejects.toBeInstanceOf(UserCancelledError); + + expect(latch).toBe('userDisconnected'); + expect(mockDeleteClient).toHaveBeenCalledOnce(); + expect(mockSave).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }); + + it.each(['idle', 'userDisconnected', 'held client', 'evicted surface', 'pending startup'] as const)( + 'edits %s without overlooking surviving connection work', + async (state): Promise => { + latch = state === 'userDisconnected' ? 'userDisconnected' : 'credentialsRejected'; + vi.mocked(ClustersClient.exists).mockReturnValue(state === 'held client'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(state === 'pending startup'); + const draft: ConnectionSurface = { + clusterId: node.cluster.clusterId, + kind: 'documentView', + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + if (state === 'evicted surface') { + registrations.push(registerConnectionSurface(draft)); + } + mockExecute.mockImplementationOnce(async (wizardContext): Promise => { + wizardContext.nativeAuthConfig = { connectionUser: 'old-user', connectionPassword: 'new-password' }; + await new ExecuteStep().execute(wizardContext); + }); + + await updateCredentials(context, node); + + expect(mockSave).toHaveBeenCalledOnce(); + if (state === 'idle' || state === 'userDisconnected') { + expect(mockDeleteClient).not.toHaveBeenCalled(); + expect(mockShutdownEvaluator).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + } else { + expect(mockDeleteClient).toHaveBeenCalledBefore(mockPrompt); + expect(mockShutdownEvaluator).toHaveBeenCalledBefore(mockPrompt); + expect(latch).toBe('userDisconnected'); + } + if (state === 'evicted surface') { + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.dispose).not.toHaveBeenCalled(); + } + }, + ); + + it('does not save an ordinary edit superseded while the wizard is open', async (): Promise => { + mockPrompt.mockImplementationOnce(async (): Promise => { + epoch++; + }); + + await updateCredentials(context, node); + + expect(mockExecute).not.toHaveBeenCalled(); + expect(mockSave).not.toHaveBeenCalled(); + expect(mockDeleteCredentials).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); + }); }); diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 72b703ab8..543ace0d9 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -5,6 +5,7 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; +import { window } from 'vscode'; import { AuthMethodId, authMethodFromString, @@ -13,6 +14,7 @@ import { } from '../../documentdb/auth/AuthMethod'; import { evaluateEntraDestinationFromSettings } from '../../documentdb/auth/entraDestinationSettings'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { canSaveEdit, ensureDisconnectedForEdit } from '../../documentdb/connectionTeardown'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; @@ -22,7 +24,7 @@ import { ConnectionStorageService, isConnection } from '../../services/connectio import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; import { refreshView } from '../refreshView/refreshView'; -import { offerShellDisconnect, saveConnectionEdit } from '../saveConnectionEdit'; +import { saveConnectionEdit } from '../saveConnectionEdit'; import { PromptAuthMethodStep } from '../updateCredentials/PromptAuthMethodStep'; import { ExecuteStep } from './ExecuteStep'; import { PromptPasswordStep } from './PromptPasswordStep'; @@ -35,7 +37,7 @@ import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardCo * Updates the authentication credentials for a cluster connection. * * Architecture: - * 1. Loads stored credentials and determines available authentication methods + * 1. Ends the old session, then loads stored credentials and available authentication methods * 2. Runs wizard to collect new credentials from user: * - PromptAuthMethodStep: Select authentication method * - SelectEntraTokenSourceStep: Select account sign-in or a managed identity (if needed) @@ -44,8 +46,7 @@ import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardCo * - PromptPasswordStep: Enter password (if needed) * - PromptReconnectStepForErrorNodes: Ask to reconnect (only for error nodes) * 3. ExecuteStep: Saves updated credentials to storage - * 4. Post-wizard: Refreshes cached credentials, drops the client and playground worker, - * warns about open shells, and optionally resets error state for reconnection + * 4. Post-wizard: Refreshes cached credentials and optionally resets error state for reconnection * * For error recovery nodes, prompts whether to reconnect immediately. If user chooses * not to reconnect, the error state is preserved and the node remains as an error node. @@ -56,8 +57,8 @@ export async function updateCredentials(context: IActionContext, node: DocumentD throw new Error(l10n.t('No node selected.')); } const clusterId = node.cluster.clusterId; - const epoch = ClustersClient.getEpoch(clusterId); const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const epoch = await ensureDisconnectedForEdit(clusterId, () => ext.connectionsBranchDataProvider.refresh()); const isRecoveryCurrent = recoveringRejection ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; @@ -76,7 +77,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); - if (isRecoveryCurrent?.() === false) { + if (ClustersClient.getEpoch(clusterId) !== epoch) { return; } // Type guard ensures we have connection properties (not a folder) @@ -145,10 +146,11 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); - if (isRecoveryCurrent?.() === false) { + if (!canSaveEdit(clusterId, epoch)) { + void window.showErrorMessage(l10n.t('This connection changed. Refresh the tree and try again.')); return; } - const changed = await saveConnectionEdit( + await saveConnectionEdit( node, async (isCurrent) => { wizardContext.isRecoveryCurrent = isCurrent; @@ -156,7 +158,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD return wizardContext.credentialsSaved === true; }, { - canStart: isRecoveryCurrent, + canStart: () => canSaveEdit(clusterId, epoch), publishCredentials: (updated): void => { if (!updated || !isConnection(updated)) { return; @@ -186,13 +188,13 @@ export async function updateCredentials(context: IActionContext, node: DocumentD // Clearing the error state triggers a fresh connection attempt on refresh. if (wizardContext.credentialsSaved && node.id && wizardContext.isErrorState) { if (wizardContext.reconnectAfterError) { + if (ClustersClient.getLatchReason(clusterId) === 'userDisconnected') { + ClustersClient.unlatch(clusterId); + } ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); context.telemetry.properties.reconnected = 'true'; } } await refreshView(context, Views.ConnectionsView); - if (changed) { - await offerShellDisconnect(node); - } } diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts index 0815d11d0..005ea592c 100644 --- a/src/documentdb/connectionTeardown.test.ts +++ b/src/documentdb/connectionTeardown.test.ts @@ -18,6 +18,7 @@ import { type ConnectionUnavailableReason } from './ConnectionUnavailableError'; import { commitTeardown, confirmTeardown, + ensureDisconnectedForEdit, latchForTeardown, teardownConnection, withConnectionRemoval, @@ -79,7 +80,12 @@ vi.mock('../commands/playground/executePlaygroundCode', () => ({ const clusterId = 'example-cluster'; const otherId = 'other-cluster'; const refreshTree = vi.fn(); -const showWarning = vi.mocked(vscode.window.showWarningMessage); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); const showError = vi.mocked(vscode.window.showErrorMessage); const registrations: vscode.Disposable[] = []; @@ -609,4 +615,70 @@ describe('connection teardown', () => { expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); }); + + it('returns the post-Disconnect epoch only after ordinary teardown finishes', async (): Promise => { + let epoch = 7; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + const draft = register('documentView', true); + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[1]); + let finishClose!: () => void; + const closingStarted = new Promise((resolve) => { + mocks.deleteClient.mockImplementationOnce((): Promise => { + resolve(); + return new Promise((finish) => { + finishClose = finish; + }); + }); + }); + const edited = vi.fn(); + const disconnecting = ensureDisconnectedForEdit(clusterId, refreshTree); + void disconnecting.then(edited); + await closingStarted; + expect(edited).not.toHaveBeenCalled(); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + finishClose(); + await expect(disconnecting).resolves.toBe(8); + expect(refreshTree).toHaveBeenCalledOnce(); + expect(mocks.deleteCredentials).not.toHaveBeenCalled(); + expect(mocks.clearLastVerifiedIdentity).not.toHaveBeenCalled(); + }); + + it.each(['userDisconnected', 'credentialsRejected', undefined] as const)( + 'captures the safe-idle epoch without another teardown for %s', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + mocks.getEpoch.mockReturnValue(7); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).resolves.toBe(7); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); + + it.each(['connectionRemoved', 'credentialsUpdating'] as const)( + 'does not edit a %s target even without a client', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).rejects.toThrow( + 'A connection is already being updated or removed. Try again when it finishes.', + ); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); }); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts index 06c8b703f..0a1e93d38 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -53,6 +53,53 @@ function operationName(intent: TeardownReason): string { } } +function isConnectionIdle(clusterId: string): boolean { + return ( + !ClustersClient.exists(clusterId) && + !ClustersClient.hasPendingStartup(clusterId) && + getConnectionSurfaces(clusterId).length === 0 && + !getPlaygroundEvaluators().has(clusterId) && + !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId) + ); +} + +export function canSaveEdit(clusterId: string, epoch: number): boolean { + return ( + ClustersClient.getEpoch(clusterId) === epoch && + (ClustersClient.getLatchReason(clusterId) === 'userDisconnected' || isConnectionIdle(clusterId)) + ); +} + +export async function ensureDisconnectedForEdit(clusterId: string, refreshTree: () => void): Promise { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason === 'connectionRemoved' || reason === 'credentialsUpdating') { + throw new Error(vscode.l10n.t('A connection is already being updated or removed. Try again when it finishes.')); + } + if (TaskService.getConflictingTasks({ clusterId }).length > 0) { + await checkCanProceedAndInformUser({ clusterId }, operationName('userDisconnected')); + throw new UserCancelledError(); + } + const epoch = ClustersClient.getEpoch(clusterId); + if (canSaveEdit(clusterId, epoch)) { + return epoch; + } + + const disconnectAndUpdate = vscode.l10n.t('Disconnect and update'); + const selected = await vscode.window.showWarningMessage( + vscode.l10n.t('Disconnect?'), + { modal: true }, + disconnectAndUpdate, + ); + if (selected !== disconnectAndUpdate || ClustersClient.getEpoch(clusterId) !== epoch) { + throw new UserCancelledError(); + } + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + if (ClustersClient.getLatchReason(clusterId) !== 'userDisconnected') { + throw new UserCancelledError(); + } + return ClustersClient.getEpoch(clusterId); +} + /** Read-only preflight. A folder can ask once for all its descendants. */ export async function confirmTeardown( target: string | readonly string[], @@ -136,11 +183,7 @@ export async function commitTeardown( (latch === 'userDisconnected' || latch === 'connectionRemoved' || latch === 'credentialsUpdating' || - (!ClustersClient.exists(clusterId) && - !ClustersClient.hasPendingStartup(clusterId) && - getConnectionSurfaces(clusterId).length === 0 && - !getPlaygroundEvaluators().has(clusterId) && - !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId))) + isConnectionIdle(clusterId)) ) { return 'superseded'; } From 52a70c00b7903912587eae3d752ace06d18c98e7 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 14:42:03 +0000 Subject: [PATCH 16/62] docs: record committed WI-F2/E passes and remaining corrections Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../03-complexity-reduction-analysis.md | 70 ++++++++++++++++++- 1 file changed, 68 insertions(+), 2 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index e25c6ca0f..2c6d2ccec 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -776,8 +776,8 @@ npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/playg | --- | --- | --- | | **R — host pass; integrated/live pending** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. Commit/revision/command evidence is recorded under R below. | | **W — host pass; integrated/live pending** | Shell and Playground renew independently; explicit teardown stops the old worker, not the user's text. | Exercise both manager/evaluator suites, PTY and `executePlaygroundCode.test.ts`. Hold a token reply or evaluation across Disconnect, release it after reconnect: no delivery to the replacement worker, automatic command replay or silent rebinding; scrollback/file contents survive. Positive control: a valid pinned worker receives its reply and executes once. Commit/revision/command evidence is recorded under W below. | -| **F — F1 host pass; F2/integrated pending** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. Commit/revision/command evidence is recorded under F1/F2 below. | -| **E — correcting; host not run** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. | +| **F — host pass; integrated pending** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. Commit/revision/command evidence is recorded under F1/F2 below. | +| **E — host pass; integrated pending** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. Commit/revision/command evidence is recorded under E below. | | **U — U1 implementing; rendered/U2 pending** | X dismisses the frozen notice; Close closes the tab. Ordinary recoverable errors do not freeze it. | Update the existing rendered scenarios below. Keep a draft, dismiss with X, select/copy the original text, attempt Save, release a stale response: draft unchanged, no new save RPC. Close/cancel the dirty-close confirmation separately. Pair with a failed live query → same-account repair → user runs again in the **same tab**, with no unlock RPC and no automatic replay. On uncertain write outcome retain text and never claim nothing was written. | | **H — H1 host pass; H2/H3 pending** | Shared host checks stop delayed side effects without making ordinary reads carry identity policy. | Exercise [review cases C01–C03](./02-pr1136-copilot-review.md): pause create after client resolution; pause query generation before sampling and again at model selection; pause Playground document opening, including a retained Shell link. End the old lifetime, install the replacement, release the pause. Assert zero stale writes, replacement-schema samples, model sends after invalidation, or replacement bindings, as applicable. Run the same paths without invalidation to rule out a blanket disable. Use fake DB/model boundaries, not real data or model calls. | | **P — not run** | Combined candidate and release evidence. | Rerun affected checks after integration. Walk a normal read and a delayed write/send in the diff: the read uses a shared path, the delayed side effect checks its captured origin. Record obsolete recovery handlers/tests removed and guards intentionally retained. Update user-facing docs/localization and affected telemetry contracts for the behavior actually shipped. Run the repository handoff gates and the live checks below on the identified candidate. | @@ -920,6 +920,18 @@ shared controllers/routers and teardown edits so every work-item commit has clea fixture, retaining the effect assertions. Evidence: runner `786c177f-56f7-4d20-9574-ac466cb4ac5a`. F2 advisor review and the fixture correction are active; no F2 pass is claimed. + **Done (2026-11-30), commit `7417e01ea`:** native actions resolve the originating + Dashboard session only; retained snapshots leave the live-panel index without deleting a + newer panel. Ordinary failures do not lock the next explicit action. Decisions: advised + (`claude-opus-5.5`), source approved at 88% confidence; poll evidence reviewed at 87%. + Eight focused regressions were added; five scheduled frozen polls are explicitly awaited + and resolved, with zero acquisition/DB effects and a fresh-poll positive control. + The missing authentication fixture and two terminal `retry` expectations were corrected + without relaxing zero-delete, reason, ordering or polling assertions. + **F2 host pass:** at `b322b7463` plus F2/E/U1/H2 working changes, the same two-suite + command above passed all 49 tests in two files (2.70 s). Evidence: runner + `786c177f-56f7-4d20-9574-ac466cb4ac5a`. Final wave build also passed + (43.19 s); integrated rerun remains required. - **E / `gpt-6.1-sol`, running after F1 in parallel with F2:** agent `dfd29c24-8a4e-4f14-990e-6ad883077a38`. Ordinary Disconnect completes before either edit wizard. Preserve the epoch/latch across disconnected editing and both storage writes; @@ -942,6 +954,29 @@ shared controllers/routers and teardown edits so every work-item commit has clea in `canStart`. Registered disconnected shells must remain allowed under `userDisconnected`. The existing synchronous task guard/latch then excludes startup during both storage writes. Add concurrent-work/no-write cases and positive controls; the worker is finishing this correction. + **E first host check failed:** at `b322b7463` plus E/F2/U1 working changes, + `npx vitest run src/commands/updateCredentials src/commands/updateConnectionString src/commands/saveConnectionEdit.test.ts src/documentdb/connectionTeardown.test.ts` + passed 143 tests and failed two failed-startup/disappearance positive controls (3.22 s). + Their real startup error path hit a missing `vscode.CancellationError` in the fixture + parser; the worker repaired only the parser fixture, keeping the original failure and + zero/positive-save assertions. Evidence: runner `3b7b403c-c6b3-46fc-b2cf-23a2860b3158`. + **E review:** advisor approved the atomic edit flow at 87% confidence, then confirmed + that the existing Yes/Reconnect choice became a no-op after restoring `userDisconnected`. + Correct it at 90% confidence: only a successful error-node Yes choice clears that hold + before resetting errors and refreshing; No, failure and another hold never clear it. + This honors the existing choice without reviving old views. Four regressions were added. + **Done (2026-11-30), commit `1d971f4c1`:** ordinary Disconnect now precedes either edit; + atomic save eligibility prevents newly started work from crossing an idle wizard, and the + existing storage latch prevents mixed settings. Existing partial-save feedback is retained. + Successful explicit Yes/Reconnect starts a fresh session; kept dirty tabs stay retired. + Decisions: advised (`claude-opus-5.5`), core review 87%, final Reconnect correction + approved at 92%. No temporary wizard hold, schema change or cancellation-policy change. + New effect cases cover both actual command paths, failed startup, active/pending work, + storage exclusion and the four Reconnect outcomes. + **E host pass:** at `b322b7463` plus final E/F2/U1/H2 working changes, the exact E + command above passed 149 tests in eight files (3.28 s), no failures. Evidence: runner + `3b7b403c-c6b3-46fc-b2cf-23a2860b3158`. Final root build passed + (43.19 s), including the typed fixture repairs. Integrated candidate rerun remains. - **H1 / `mai-code-2`, after F1:** fence the shared client-operation callback and add C01 effect-level regressions. **H2/H3 / `gpt-6.1-sol`, after F2:** propagate the captured host lifetime/cancellation through schema/model and Playground handoffs; serialize H2/H3 because @@ -972,6 +1007,25 @@ shared controllers/routers and teardown edits so every work-item commit has clea ```sh npx vitest run src/commands/runBoundNamespaceCommand.test.ts src/commands/dashboardBoundCommands.test.ts src/commands/importDocuments/importDocuments.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts src/documentdb/ClustersClient.test.ts ``` +- **H2 / `gpt-6.1-sol`, implementation running:** agent + `b07a97fc-1db9-4155-9be9-3983e34df17c`; planned by advisor + `77bcdc61-58c3-480b-8775-0fee9bcbe27b` at 88% confidence. The sole producer is + Collection View, so `QueryGenerationContext` replaces `clusterId` with required + `binding: ConnectionBinding` and `signal: AbortSignal`. Capture the origin before + availability, but create the operation-epoch guard afterwards so same-account replacement + stays usable. Guard every sample; cancellation reaches the existing post-model-selection + send fence. Catch typed unavailable inside the telemetry callback rather than letting it + be swallowed, and pass client cancellation from QueryEditor. +- **H3 / `gpt-6.1-sol`, exact contract settled; queued after H2:** advisor follow-up, + 85% confidence, reuses `DocumentDBShellPty._disconnectRevision`, not the host epoch. + Same-account recovery does not change that counter; explicit teardown does. A retained + Shell's links capture origin at click and remain unbound after any Disconnect. + Required `PlaygroundHandoffOrigin` has four cases: binding plus optional original pin/signal; + shell fingerprint/pin with an `isCurrent()` counter check; saved tree origin with epoch; + or none for anonymous/uninitialized/disconnected Shells. The saved case has no fingerprint + because no identity was captured. Validate after document display, remove any restored + connection on rejection, and preserve the supplied original pin using the existing service API. + No new lifetime framework or `PlaygroundService` change is authorized. - **U1 / `mai-code-2`, running after F1 in parallel with F2:** agent `559eab2f-1c5b-4190-9c53-0e959a8c756e`. Terminal notice only, X/copy without writes, ordinary recoverable errors without freezing, and rendered-scenario updates. Exclude F2's Dashboard @@ -988,6 +1042,18 @@ shared controllers/routers and teardown edits so every work-item commit has clea U2 must replace this with a dedicated `closeView` procedure and remove the old protocol, including its action field, after H2/H3. This is an intermediate compatibility slice, not final protocol-removal evidence. + **U1 review/checks:** the one-way notice, close confirmation and stale-text protections + are present, but the advisor found repeating Dashboard recoverable-poll toasts and a + stale-close busy flag. Fix only failed-sample accounting for nonterminal polls and clear + the busy flag when still mounted; preserve the latest notice. A poll scenario and the + close-race assertion were added. + At `b322b7463` plus working changes, the wave `npm run build` failed (43.16 s) on + 13 E test-fixture overload/unused-import diagnostics and one U1 deferred-resolver type. + U1 unit command passed 20/25 tests (11.01 s); five Document View normal-save/dirty/ID/error + cases failed and require root-cause diagnosis, not assertion changes. The browser manifest + command passed 47 tests (1.96 s), which is not rendered proof. Evidence: runner + `35fcbb46-f009-4eeb-90ee-cae3703b37de`. Owners are fixing the typed fixtures and the + advisor is investigating valid Save completion suppression. - **P / `mai-code-2` documentation, `mai-code-2-flash` checks:** align only directly affected docs/contracts, rerun the integrated effects, collect rendered and packaged evidence, and preserve separate live gates. The authorized order is implementation push and stacked From 54e890813f08e7cf015116a430bc5da18e60ae4a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 14:44:35 +0000 Subject: [PATCH 17/62] fix: cancel stale query sampling and model sends (WI-H2) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../queryGenerationCommands.test.ts | 262 ++++++++++++++++++ .../queryGenerationCommands.ts | 166 ++++++----- src/services/copilotService.test.ts | 51 ++++ .../collectionViewRouter.test.ts | 187 +++++++++++++ .../collectionView/collectionViewRouter.ts | 128 +++++---- .../components/queryEditor/QueryEditor.tsx | 29 +- 6 files changed, 693 insertions(+), 130 deletions(-) create mode 100644 src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts diff --git a/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts new file mode 100644 index 000000000..610ab9fd0 --- /dev/null +++ b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts @@ -0,0 +1,262 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createTestActionContext, UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { type Document } from 'mongodb'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { getBindingLifetimeSignal, retireConnectionBindings } from '../../documentdb/connectionBindingRetirement'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CopilotService } from '../../services/copilotService'; +import { PromptTemplateService } from '../../services/promptTemplateService'; +import { generateQuery, QueryGenerationType, type QueryGenerationContext } from './queryGenerationCommands'; + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { trace: vi.fn() } }, +})); +vi.mock('../../services/copilotService', () => ({ + CopilotService: { isAvailable: vi.fn(), sendMessage: vi.fn() }, +})); +vi.mock('../../services/promptTemplateService', () => ({ + PromptTemplateService: { getQueryGenerationPromptTemplate: vi.fn() }, +})); +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + LanguageModelChatMessage: { User: vi.fn((content: string) => ({ role: 1, content })) }, +})); + +interface Deferred { + readonly promise: Promise; + resolve(value: T): void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((complete): void => { + resolve = complete; + }); + return { promise, resolve }; +} + +let sequence = 0; +let context: IActionContext; +let binding: ConnectionBinding; +let queryContext: QueryGenerationContext; +let sampleDocuments: ReturnType>; +let listCollections: ReturnType>; +let client: ClustersClient; + +beforeEach(async (): Promise => { + vi.resetAllMocks(); + context = await createTestActionContext(); + binding = { clusterId: `query-generation-${++sequence}`, fingerprint: 'original', generation: 1 }; + queryContext = { + binding, + signal: getBindingLifetimeSignal(binding), + databaseName: 'database', + collectionName: 'collection', + naturalLanguageQuery: 'Find active records', + generationType: QueryGenerationType.SingleCollection, + }; + sampleDocuments = vi.fn().mockResolvedValue([{ active: true }]); + listCollections = vi.fn().mockResolvedValue([{ name: 'first' }, { name: 'second' }]); + client = { binding, getSampleDocuments: sampleDocuments, listCollections } as unknown as ClustersClient; + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(binding); + vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(1); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockResolvedValue(client); + vi.spyOn(ClustersClient, 'reportFailure').mockReturnValue(undefined); + vi.mocked(CopilotService.isAvailable).mockResolvedValue(true); + vi.mocked(CopilotService.sendMessage).mockResolvedValue({ + text: JSON.stringify({ explanation: 'Generated', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + vi.mocked(PromptTemplateService.getQueryGenerationPromptTemplate).mockResolvedValue('Fake prompt'); +}); + +afterEach((): void => { + vi.restoreAllMocks(); +}); + +it.each(['userDisconnected', 'credentialsChanged', 'connectionRemoved'] as const)( + 'does not sample a replacement after %s during availability', + async (reason): Promise => { + const availability = deferred(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, queryContext); + expect(CopilotService.isAvailable).toHaveBeenCalledOnce(); + retireConnectionBindings(binding.clusterId, binding.generation, reason); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, fingerprint: 'replacement', generation: 2 }); + availability.resolve(true); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); + }, +); + +it('preserves request cancellation during availability without sampling', async (): Promise => { + const availability = deferred(); + const controller = new AbortController(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, { ...queryContext, signal: controller.signal }); + controller.abort(); + availability.resolve(true); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('samples and sends once after same-account physical replacement during availability', async (): Promise => { + const availability = deferred(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, queryContext); + const replacementBinding = { ...binding, generation: 2 }; + const replacementSamples = vi.fn().mockResolvedValue([{ active: true }]); + vi.mocked(ClustersClient.getBinding).mockReturnValue(replacementBinding); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValue({ + binding: replacementBinding, + getSampleDocuments: replacementSamples, + } as unknown as ClustersClient); + availability.resolve(true); + + await expect(pending).resolves.toMatchObject({ explanation: 'Generated' }); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(replacementSamples).toHaveBeenCalledExactlyOnceWith('database', 'collection', 10); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledWith(binding, { trigger: 'collectionView' }); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledWith(expect.any(Array), { + featureSource: 'queryGeneration', + signal: queryContext.signal, + }); +}); + +it('does not start the second collection sample after invalidation during the first', async (): Promise => { + const firstSample = deferred(); + sampleDocuments.mockReturnValueOnce(firstSample.promise); + const pending = generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }); + await vi.waitFor(() => expect(sampleDocuments).toHaveBeenCalledExactlyOnceWith('database', 'first', 3)); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + firstSample.resolve([{ active: true }]); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not sample after retirement during collection listing', async (): Promise => { + const listing = deferred>>(); + listCollections.mockReturnValueOnce(listing.promise); + const pending = generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }); + await vi.waitFor(() => expect(listCollections).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + listing.resolve([{ name: 'first' }]); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not send after retirement during prompt preparation', async (): Promise => { + const template = deferred(); + vi.mocked(PromptTemplateService.getQueryGenerationPromptTemplate).mockReturnValueOnce(template.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(PromptTemplateService.getQueryGenerationPromptTemplate).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + template.resolve('Fake prompt'); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('returns a successful model response after same-account repair advances the epoch', async (): Promise => { + const modelResponse = deferred>>(); + vi.mocked(CopilotService.sendMessage).mockReturnValueOnce(modelResponse.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(CopilotService.sendMessage).toHaveBeenCalledOnce()); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + modelResponse.resolve({ + text: JSON.stringify({ explanation: 'Generated after repair', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + + await expect(pending).resolves.toMatchObject({ + generatedQuery: JSON.stringify({ filter: '{"active":true}' }, null, 2), + explanation: 'Generated after repair', + }); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('cancels a model response after retirement even when the fake model ignores abort', async (): Promise => { + const modelResponse = deferred>>(); + vi.mocked(CopilotService.sendMessage).mockReturnValueOnce(modelResponse.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(CopilotService.sendMessage).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + expect(vi.mocked(CopilotService.sendMessage).mock.calls[0][1]?.signal?.aborted).toBe(true); + modelResponse.resolve({ + text: JSON.stringify({ explanation: 'Late response', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + await expect(pending).rejects.toHaveProperty('stepName', 'staleBoundViewOperation'); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('preserves a schema sampling failure as the cause', async (): Promise => { + const cause = new Error('Synthetic sampling failure'); + sampleDocuments.mockRejectedValueOnce(cause); + + await expect(generateQuery(context, queryContext)).rejects.toMatchObject({ + message: expect.stringContaining('Failed to gather schema information'), + cause, + }); + expect(ClustersClient.reportFailure).toHaveBeenCalledWith(binding, expect.objectContaining({ cause })); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it.each([ + new UserCancelledError('Synthetic cancellation'), + new ConnectionUnavailableError('credentialsUpdating'), +])('rethrows terminal sampling errors unchanged: $name', async (error): Promise => { + sampleDocuments.mockRejectedValueOnce(error); + + await expect(generateQuery(context, queryContext)).rejects.toBe(error); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('samples both collections and sends one request in normal cross-collection generation', async (): Promise => { + await expect( + generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }), + ).resolves.toMatchObject({ explanation: 'Generated' }); + + expect(listCollections).toHaveBeenCalledExactlyOnceWith('database'); + expect(sampleDocuments.mock.calls).toEqual([ + ['database', 'first', 3], + ['database', 'second', 3], + ]); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); diff --git a/src/commands/llmEnhancedCommands/queryGenerationCommands.ts b/src/commands/llmEnhancedCommands/queryGenerationCommands.ts index bce7621c0..956591cfa 100644 --- a/src/commands/llmEnhancedCommands/queryGenerationCommands.ts +++ b/src/commands/llmEnhancedCommands/queryGenerationCommands.ts @@ -3,15 +3,17 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { type Document } from 'mongodb'; import * as vscode from 'vscode'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { ext } from '../../extensionVariables'; import { CopilotService } from '../../services/copilotService'; import { PromptTemplateService } from '../../services/promptTemplateService'; import { generateSchemaDefinition, type SchemaDefinition } from '../../utils/schemaInference'; +import { guardBoundViewOperation, runBoundViewOperation } from '../../webviews/documentdb/boundViewOperations'; import { getQueryTypeConfig, type FilledPromptResult } from './promptTemplates'; /** @@ -26,8 +28,8 @@ export enum QueryGenerationType { * Context information needed for query generation */ export interface QueryGenerationContext { - // The cluster/connection ID - clusterId: string; + readonly binding: ConnectionBinding; + readonly signal: AbortSignal; // Database name databaseName: string; // Collection name (only for single-collection queries) @@ -174,6 +176,8 @@ export async function generateQuery( // Check if Copilot is available const copilotAvailable = await CopilotService.isAvailable(); + const assertCurrent = guardBoundViewOperation(queryContext.binding, queryContext.signal); + assertCurrent(); if (!copilotAvailable) { throw new Error( l10n.t( @@ -182,79 +186,96 @@ export async function generateQuery( ); } - // Get the MongoDB client const getClientStart = Date.now(); - const client = await ClustersClient.getClient(queryContext.clusterId); - context.telemetry.measurements.getClientDurationMs = Date.now() - getClientStart; + const schemas = await runBoundViewOperation( + queryContext.binding, + assertCurrent, + async (client) => { + context.telemetry.measurements.getClientDurationMs = Date.now() - getClientStart; + const schemas: Array = []; + const schemaGatheringStart = Date.now(); + try { + if (queryContext.generationType === QueryGenerationType.CrossCollection) { + // Get all collections in the database + const listCollectionsStart = Date.now(); + assertCurrent(); + const collections = await client.listCollections(queryContext.databaseName); + assertCurrent(); + context.telemetry.measurements.listCollectionsDurationMs = Date.now() - listCollectionsStart; + ext.outputChannel.trace( + l10n.t('[Query Generation] listCollections completed in {ms}ms ({count} collections)', { + ms: context.telemetry.measurements.listCollectionsDurationMs.toString(), + count: collections.length.toString(), + }), + ); - // Gather schema information - const schemas: Array = []; - const schemaGatheringStart = Date.now(); + let collectionIndex = 0; + for (const collection of collections) { + collectionIndex++; + const sampleDocsStart = Date.now(); + assertCurrent(); + const sampleDocs = await client.getSampleDocuments( + queryContext.databaseName, + collection.name, + 3, + ); + assertCurrent(); + const sampleDocsDuration = Date.now() - sampleDocsStart; + context.telemetry.measurements[`sampleDocs_${collectionIndex}_DurationMs`] = sampleDocsDuration; + ext.outputChannel.trace( + l10n.t('[Query Generation] Schema sampling for {collection} completed in {ms}ms', { + collection: collection.name, + ms: sampleDocsDuration.toString(), + }), + ); - try { - if (queryContext.generationType === QueryGenerationType.CrossCollection) { - // Get all collections in the database - const listCollectionsStart = Date.now(); - const collections = await client.listCollections(queryContext.databaseName); - context.telemetry.measurements.listCollectionsDurationMs = Date.now() - listCollectionsStart; - ext.outputChannel.trace( - l10n.t('[Query Generation] listCollections completed in {ms}ms ({count} collections)', { - ms: context.telemetry.measurements.listCollectionsDurationMs.toString(), - count: collections.length.toString(), - }), - ); + if (sampleDocs.length > 0) { + const schema = generateSchemaDefinition(sampleDocs, collection.name); + schemas.push(schema); + } else { + schemas.push({ collectionName: collection.name, fields: {} }); + } + } + } else { + if (!queryContext.collectionName) { + throw new Error(l10n.t('Collection name is required for single-collection query generation')); + } - let collectionIndex = 0; - for (const collection of collections) { - collectionIndex++; - const sampleDocsStart = Date.now(); - const sampleDocs = await client.getSampleDocuments(queryContext.databaseName, collection.name, 3); - const sampleDocsDuration = Date.now() - sampleDocsStart; - context.telemetry.measurements[`sampleDocs_${collectionIndex}_DurationMs`] = sampleDocsDuration; - ext.outputChannel.trace( - l10n.t('[Query Generation] Schema sampling for {collection} completed in {ms}ms', { - collection: collection.name, - ms: sampleDocsDuration.toString(), - }), - ); + const sampleDocsStart = Date.now(); + assertCurrent(); + const sampleDocs = await client.getSampleDocuments( + queryContext.databaseName, + queryContext.collectionName, + 10, + ); + assertCurrent(); + context.telemetry.measurements.sampleDocsDurationMs = Date.now() - sampleDocsStart; + ext.outputChannel.trace( + l10n.t('[Query Generation] Schema sampling completed in {ms}ms', { + ms: context.telemetry.measurements.sampleDocsDurationMs.toString(), + }), + ); - if (sampleDocs.length > 0) { - const schema = generateSchemaDefinition(sampleDocs, collection.name); + const schema = generateSchemaDefinition(sampleDocs, queryContext.collectionName); schemas.push(schema); - } else { - schemas.push({ collectionName: collection.name, fields: {} }); } + context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; + return schemas; + } catch (error) { + context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; + if (error instanceof ConnectionUnavailableError || error instanceof UserCancelledError) { + throw error; + } + throw new Error( + l10n.t('Failed to gather schema information: {message}', { + message: error instanceof Error ? error.message : String(error), + }), + { cause: error }, + ); } - } else { - if (!queryContext.collectionName) { - throw new Error(l10n.t('Collection name is required for single-collection query generation')); - } - - const sampleDocsStart = Date.now(); - const sampleDocs = await client.getSampleDocuments( - queryContext.databaseName, - queryContext.collectionName, - 10, - ); - context.telemetry.measurements.sampleDocsDurationMs = Date.now() - sampleDocsStart; - ext.outputChannel.trace( - l10n.t('[Query Generation] Schema sampling completed in {ms}ms', { - ms: context.telemetry.measurements.sampleDocsDurationMs.toString(), - }), - ); - - const schema = generateSchemaDefinition(sampleDocs, queryContext.collectionName); - schemas.push(schema); - } - context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; - } catch (error) { - context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; - throw new Error( - l10n.t('Failed to gather schema information: {message}', { - message: error instanceof Error ? error.message : String(error), - }), - ); - } + }, + { trigger: 'collectionView' }, + ); // Fill the prompt template const { craftedPrompt, userQuery, contextData } = await fillPromptTemplate( @@ -263,6 +284,9 @@ export async function generateQuery( schemas, ); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } ext.outputChannel.trace(l10n.t('[Query Generation] Calling Copilot...')); const response = await CopilotService.sendMessage( [ @@ -272,8 +296,12 @@ export async function generateQuery( ], { featureSource: 'queryGeneration', + signal: queryContext.signal, }, ); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } context.telemetry.measurements.llmCallDurationMs = response.durationMs; ext.outputChannel.trace( l10n.t('[Query Generation] Copilot response received in {ms}ms (model: {model})', { diff --git a/src/services/copilotService.test.ts b/src/services/copilotService.test.ts index 4719fe2e1..1bde76509 100644 --- a/src/services/copilotService.test.ts +++ b/src/services/copilotService.test.ts @@ -6,6 +6,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { type IActionContext, UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { getBindingLifetimeSignal, retireConnectionBindings } from '../documentdb/connectionBindingRetirement'; // Mock vscode-azext-utils — the real `callWithTelemetryAndErrorHandling` // returns `undefined` for unhandled errors; we simulate the success path and @@ -135,6 +136,56 @@ describe('CopilotService.streamMessage', () => { selectChatModelsMock.mockReset(); }); + describe('CopilotService.sendMessage cancellation during model selection', () => { + it.each(['request-abort', 'host-retirement', 'live-control'] as const)( + 'fences the actual model sendRequest across paused model selection: %s', + async (cancellation): Promise => { + selectChatModelsMock.mockReset(); + let releaseSelection!: (models: unknown[]) => void; + selectChatModelsMock.mockReturnValueOnce( + new Promise((resolve): void => { + releaseSelection = resolve; + }), + ); + const binding = { + clusterId: `copilot-model-selection-${cancellation}`, + fingerprint: 'original', + generation: 1, + }; + const controller = new AbortController(); + const signal = AbortSignal.any([getBindingLifetimeSignal(binding), controller.signal]); + const sendRequest = vi.fn().mockResolvedValue({ + text: (async function* (): AsyncGenerator { + yield 'Synthetic response'; + })(), + }); + const model = { ...(makeFakeModel([]) as object), sendRequest }; + const pending = CopilotService.sendMessage([makeUserMessage('Synthetic query context') as never], { + featureSource: 'queryGeneration', + signal, + }); + expect(selectChatModelsMock).toHaveBeenCalledExactlyOnceWith({ + vendor: 'copilot', + family: 'copilot-utility', + }); + if (cancellation === 'request-abort') { + controller.abort(); + } else if (cancellation === 'host-retirement') { + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + } + releaseSelection([model]); + + if (cancellation === 'live-control') { + await expect(pending).resolves.toMatchObject({ text: 'Synthetic response' }); + expect(sendRequest).toHaveBeenCalledOnce(); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sendRequest).not.toHaveBeenCalled(); + } + }, + ); + }); + it('yields fragments in order and resolves completion with the full text + usage', async () => { const fragments = ['Hello, ', 'world', '!']; selectChatModelsMock.mockResolvedValueOnce([makeFakeModel(fragments)]); diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts index 887c1fe25..3df49ac82 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts @@ -4,12 +4,22 @@ *--------------------------------------------------------------------------------------------*/ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import { + callWithTelemetryAndErrorHandling, + createTestActionContext, + UserCancelledError, + type IActionContext, +} from '@microsoft/vscode-azext-utils'; +import { MongoServerError } from 'mongodb'; import * as vscode from 'vscode'; +import { AuthMethodId } from '../../../documentdb/auth/AuthMethodId'; import { ClustersClient } from '../../../documentdb/ClustersClient'; +import { classifyConnectionFailure } from '../../../documentdb/connectionFailures'; import { retireConnectionBindings } from '../../../documentdb/connectionBindingRetirement'; import { ConnectionUnavailableError } from '../../../documentdb/ConnectionUnavailableError'; import { DocumentViewMode } from '../../../documentdb/DocumentViewMode'; import { API } from '../../../DocumentDBExperiences'; +import { CopilotService } from '../../../services/copilotService'; import { createCallerFactory } from '../../_integration/trpc'; import { collectionsViewRouter, type RouterContext } from './collectionViewRouter'; @@ -21,8 +31,22 @@ const mocks = vi.hoisted(() => ({ getSession: vi.fn(), findCollection: vi.fn(), updateGlobalState: vi.fn(), + generationAvailable: vi.fn(), + generationSend: vi.fn(), + generationTemplate: vi.fn(), + generationErrorNotice: vi.fn(), })); +vi.mock('../../../services/copilotService', () => ({ + CopilotService: { isAvailable: mocks.generationAvailable, sendMessage: mocks.generationSend }, +})); +vi.mock('../../../services/promptTemplateService', () => ({ + PromptTemplateService: { getQueryGenerationPromptTemplate: mocks.generationTemplate }, +})); +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + LanguageModelChatMessage: { User: vi.fn((content: string) => ({ role: 1, content })) }, +})); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal()), callWithTelemetryAndErrorHandling: vi.fn(async (): Promise => {}), @@ -154,6 +178,169 @@ it('captures the transfer binding before asynchronous collection lookup', async ); }); +let generationSequence = 0; + +async function generationFixture(signal?: AbortSignal): Promise<{ + readonly caller: ReturnType; + readonly origin: typeof binding; + readonly samples: ReturnType>; +}> { + const actionContext = await createTestActionContext(); + vi.mocked(callWithTelemetryAndErrorHandling).mockImplementation(async ( + _id: string, + callback: (context: IActionContext) => T | PromiseLike, + ): Promise => { + try { + return await callback(actionContext); + } catch (error) { + if (!(error instanceof UserCancelledError)) { + mocks.generationErrorNotice(error); + } + return undefined; + } + }); + const origin = { ...binding, clusterId: `collection-generation-${++generationSequence}` }; + const samples = vi.fn().mockResolvedValue([{ active: true }]); + const client = { binding: origin, getSampleDocuments: samples } as unknown as ClustersClient; + mocks.getBinding.mockReturnValue(origin); + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(origin); + vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(1); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockResolvedValue(client); + vi.spyOn(ClustersClient, 'reportFailure').mockImplementation((_binding, error) => + classifyConnectionFailure(error, AuthMethodId.NativeAuth).kind, + ); + mocks.generationAvailable.mockResolvedValue(true); + mocks.generationTemplate.mockResolvedValue('Fake prompt'); + mocks.generationSend.mockResolvedValue({ + text: JSON.stringify({ explanation: 'Generated', command: { filter: '{"active":true}' } }), + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + durationMs: 1, + }); + const context: RouterContext = { + dbExperience: API.DocumentDB, + webviewName: 'collectionView', + sessionId: 'generation-session', + clusterId: origin.clusterId, + clusterDisplayName: 'Cluster', + viewId: 'connectionsView', + databaseName: 'database', + collectionName: 'collection', + describeUnavailable, + recoverUnavailable: vi.fn(), + signal, + }; + return { caller: callCollectionView(context), origin, samples }; +} + +const generationInput = { + currentQuery: { filter: '{"draft":true}', project: '{"draft":1}', sort: '{"draft":1}', skip: 5, limit: 10 }, + prompt: 'Find active records', +}; + +it('generates once with the captured binding and preserves unspecified current query fields', async (): Promise => { + const { caller, samples } = await generationFixture(); + + await expect(caller.generateQuery(generationInput)).resolves.toEqual({ + ...generationInput.currentQuery, + filter: '{"active":true}', + }); + expect(mocks.getBinding).toHaveBeenCalledOnce(); + expect(samples).toHaveBeenCalledExactlyOnceWith('database', 'collection', 10); + expect(mocks.generationSend).toHaveBeenCalledOnce(); + expect(mocks.generationErrorNotice).not.toHaveBeenCalled(); +}); + +it.each(['userDisconnected', 'credentialsChanged', 'connectionRemoved'] as const)( + 'captures the origin before availability and cancels generation after %s without replacement samples', + async (reason): Promise => { + const { caller, origin } = await generationFixture(); + const replacementSamples = vi.fn().mockResolvedValue([]); + let releaseAvailability!: (available: boolean) => void; + mocks.generationAvailable.mockReturnValueOnce( + new Promise((resolve): void => { + releaseAvailability = resolve; + }), + ); + const pending = caller.generateQuery(generationInput); + await vi.waitFor(() => expect(mocks.generationAvailable).toHaveBeenCalledOnce()); + expect(mocks.getBinding).toHaveBeenCalledOnce(); + retireConnectionBindings(origin.clusterId, origin.generation, reason); + const replacement = { ...origin, fingerprint: 'replacement', generation: 2 }; + mocks.getBinding.mockReturnValue(replacement); + vi.mocked(ClustersClient.getBinding).mockReturnValue(replacement); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValue({ + binding: replacement, + getSampleDocuments: replacementSamples, + } as unknown as ClustersClient); + releaseAvailability(true); + + await expect(pending).rejects.toMatchObject({ cause: expect.any(UserCancelledError) }); + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); + expect(replacementSamples).not.toHaveBeenCalled(); + expect(mocks.generationSend).not.toHaveBeenCalled(); + expect(mocks.generationErrorNotice).not.toHaveBeenCalled(); + }, +); + +it('propagates request cancellation through generation without a generic failure or fallback', async (): Promise => { + const controller = new AbortController(); + const { caller, samples } = await generationFixture(controller.signal); + let releaseAvailability!: (available: boolean) => void; + mocks.generationAvailable.mockReturnValueOnce( + new Promise((resolve): void => { + releaseAvailability = resolve; + }), + ); + const pending = caller.generateQuery(generationInput); + await vi.waitFor(() => expect(mocks.generationAvailable).toHaveBeenCalledOnce()); + controller.abort(); + releaseAvailability(true); + + await expect(pending).rejects.toMatchObject({ cause: expect.any(UserCancelledError) }); + expect(samples).not.toHaveBeenCalled(); + expect(mocks.generationSend).not.toHaveBeenCalled(); + expect(mocks.generationErrorNotice).not.toHaveBeenCalled(); +}); + +it('returns described authentication unavailability before the telemetry wrapper can swallow it', async (): Promise => { + const { caller, origin, samples } = await generationFixture(); + const cause = new MongoServerError({ message: 'Synthetic authentication failure', code: 18 }); + samples.mockRejectedValueOnce(cause); + + await expect(caller.generateQuery(generationInput)).resolves.toEqual({ + unavailable: { + reason: 'credentialsRejected', + title: 'Connection unavailable', + detail: 'Close this view.', + action: 'close', + }, + }); + expect(ClustersClient.reportFailure).toHaveBeenCalledWith(origin, expect.objectContaining({ cause })); + expect(describeUnavailable).toHaveBeenCalledExactlyOnceWith('credentialsRejected'); + expect(mocks.generationSend).not.toHaveBeenCalled(); + expect(mocks.generationErrorNotice).not.toHaveBeenCalled(); +}); + +it('passes both host retirement and request cancellation to the model service', async (): Promise => { + const controller = new AbortController(); + const { caller, origin } = await generationFixture(controller.signal); + await caller.generateQuery(generationInput); + const options = vi.mocked(CopilotService.sendMessage).mock.calls[0][1]; + expect(options?.signal?.aborted).toBe(false); + retireConnectionBindings(origin.clusterId, origin.generation, 'userDisconnected'); + expect(options?.signal?.aborted).toBe(true); + + const next = await generationFixture(controller.signal); + await next.caller.generateQuery(generationInput); + const nextOptions = vi.mocked(CopilotService.sendMessage).mock.calls[1][1]; + expect(nextOptions?.signal?.aborted).toBe(false); + controller.abort(); + expect(nextOptions?.signal?.aborted).toBe(true); +}); + it.each(['userDisconnected', 'connectionRemoved', 'credentialsChanged'] as const)( 'preserves the old Collection query and blocks its RPC after %s; a fresh session queries once', async (reason): Promise => { diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.ts index eb938c049..fb7737011 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.ts @@ -4,7 +4,11 @@ *--------------------------------------------------------------------------------------------*/ import { type FieldEntry } from '@documentdb-js/schema-analyzer'; -import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { + callWithTelemetryAndErrorHandling, + UserCancelledError, + type IActionContext, +} from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { z } from 'zod'; import { ClusterSession } from '../../../documentdb/ClusterSession'; @@ -18,6 +22,7 @@ import { QueryGenerationType, type QueryGenerationContext, } from '../../../commands/llmEnhancedCommands/queryGenerationCommands'; +import { getBindingLifetimeSignal } from '../../../documentdb/connectionBindingRetirement'; import { showConfirmationAsInSettings } from '../../../utils/dialogs/showConfirmation'; import { @@ -511,72 +516,93 @@ export const collectionsViewRouter = router({ // handle generation request .query(async ({ input, ctx }) => { const generationCtx = ctx as RouterContext; + const binding = ClusterSession.getSession(generationCtx.sessionId).getBinding(); + const signal = AbortSignal.any([ + getBindingLifetimeSignal(binding), + ...(generationCtx.signal ? [generationCtx.signal] : []), + ]); + let cancellation: UserCancelledError | undefined; const result = await callWithTelemetryAndErrorHandling( 'vscode-documentdb.collectionView.generateQuery', async (context: IActionContext) => { - // Prepare query generation context - const queryContext: QueryGenerationContext = { - clusterId: generationCtx.clusterId, - databaseName: generationCtx.databaseName, - collectionName: generationCtx.collectionName, - // For now, only handle Find queries - targetQueryType: 'Find', - naturalLanguageQuery: input.prompt, - generationType: QueryGenerationType.SingleCollection, - }; - - // Generate query with LLM - const generationResult = await generateQuery(context, queryContext); - if (generationResult.generatedQuery === undefined) { - const errorExplanation = generationResult.explanation - ? generationResult.explanation.startsWith('Error:') - ? generationResult.explanation.slice(6).trim() - : generationResult.explanation - : 'No detailed error message provided.'; - context.telemetry.properties.generationError = errorExplanation; - throw new Error(l10n.t('Query generation failed with the error: {0}', errorExplanation)); - } - - // Parse the generated command - // For now we only support find query - let parsedCommand: { - filter?: string; - project?: string; - sort?: string; - skip?: number; - limit?: number; - }; - try { - parsedCommand = JSON.parse(generationResult.generatedQuery) as { + // Prepare query generation context + const queryContext: QueryGenerationContext = { + binding, + signal, + databaseName: generationCtx.databaseName, + collectionName: generationCtx.collectionName, + // For now, only handle Find queries + targetQueryType: 'Find', + naturalLanguageQuery: input.prompt, + generationType: QueryGenerationType.SingleCollection, + }; + + // Generate query with LLM + const generationResult = await generateQuery(context, queryContext); + if (generationResult.generatedQuery === undefined) { + const errorExplanation = generationResult.explanation + ? generationResult.explanation.startsWith('Error:') + ? generationResult.explanation.slice(6).trim() + : generationResult.explanation + : 'No detailed error message provided.'; + context.telemetry.properties.generationError = errorExplanation; + throw new Error(l10n.t('Query generation failed with the error: {0}', errorExplanation)); + } + + // Parse the generated command + // For now we only support find query + let parsedCommand: { filter?: string; project?: string; sort?: string; skip?: number; limit?: number; }; + + try { + parsedCommand = JSON.parse(generationResult.generatedQuery) as { + filter?: string; + project?: string; + sort?: string; + skip?: number; + limit?: number; + }; + } catch (error) { + // Add error details to telemetry + context.telemetry.properties.parseError = + error instanceof Error ? error.name : 'UnknownError'; + context.telemetry.properties.parseErrorMessage = + error instanceof Error ? error.message : String(error); + + throw new Error( + l10n.t('Failed to parse generated query. Query generation provided an invalid response.'), + ); + } + + return { + filter: parsedCommand.filter ?? input.currentQuery.filter, + project: parsedCommand.project ?? input.currentQuery.project ?? '{ }', + sort: parsedCommand.sort ?? input.currentQuery.sort ?? '{ }', + skip: parsedCommand.skip ?? input.currentQuery.skip ?? 0, + limit: parsedCommand.limit ?? input.currentQuery.limit ?? 0, + }; } catch (error) { - // Add error details to telemetry - context.telemetry.properties.parseError = error instanceof Error ? error.name : 'UnknownError'; - context.telemetry.properties.parseErrorMessage = - error instanceof Error ? error.message : String(error); - - throw new Error( - l10n.t('Failed to parse generated query. Query generation provided an invalid response.'), - ); + if (error instanceof ConnectionUnavailableError) { + return generationCtx.describeUnavailable(error.reason); + } + if (error instanceof UserCancelledError) { + cancellation = error; + } + throw error; } - - return { - filter: parsedCommand.filter ?? input.currentQuery.filter, - project: parsedCommand.project ?? input.currentQuery.project ?? '{ }', - sort: parsedCommand.sort ?? input.currentQuery.sort ?? '{ }', - skip: parsedCommand.skip ?? input.currentQuery.skip ?? 0, - limit: parsedCommand.limit ?? input.currentQuery.limit ?? 0, - }; }, ); + if (cancellation) { + throw cancellation; + } if (!result) { throw new Error(l10n.t('Query generation failed')); } diff --git a/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx b/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx index 76cbbfce3..abaa11439 100644 --- a/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx +++ b/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx @@ -25,6 +25,7 @@ import { ArrowResetRegular, SendRegular, SettingsFilled, SettingsRegular } from // eslint-disable-next-line import/no-internal-modules import { type editor } from 'monaco-editor/esm/vs/editor/editor.api'; import { normalizeCompletionCategory } from '../../../../../telemetry/completionCategories'; +import { isConnectionUnavailableResponse } from '../../../../_integration/connectionUnavailable'; import { useTrpcClient } from '../../../../_integration/useTrpcClient'; import { MonacoAutoHeight } from '../../../../components/MonacoAutoHeight'; import { CollectionViewContext } from '../../collectionViewContext'; @@ -475,29 +476,37 @@ export const QueryEditor = ({ onExecuteRequest }: QueryEditorProps): JSX.Element aiGenerationAbortControllerRef.current.abort(); } - // Create new AbortController for this request (used for client-side cancellation only) + // Create new AbortController for this request const abortController = new AbortController(); aiGenerationAbortControllerRef.current = abortController; setIsAiActive(true); try { - const result = await trpcClient.mongoClusters.collectionView.generateQuery.query({ - currentQuery: { - filter: filterValue, - project: projectValue, - sort: sortValue, - skip: skipValue, - limit: limitValue, + const result = await trpcClient.mongoClusters.collectionView.generateQuery.query( + { + currentQuery: { + filter: filterValue, + project: projectValue, + sort: sortValue, + skip: skipValue, + limit: limitValue, + }, + prompt: aiPromptValue, }, - prompt: aiPromptValue, - }); + { signal: abortController.signal }, + ); // Check if this request was aborted while waiting for response if (abortController.signal.aborted || !currentContext.lifecycle.isOperationCurrent(lifecycleRevision)) { return; // Ignore the response if we aborted } + if (isConnectionUnavailableResponse(result)) { + currentContext.lifecycle.showUnavailable(result.unavailable); + return; + } + // Update state with generated query setFilterValue(result.filter); setProjectValue(result.project); From 674ab9c414be1dbba373d33a2f31b82d522d3c9d Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 30 Nov 2026 14:44:35 +0000 Subject: [PATCH 18/62] fix: keep recovery live and frozen notices copy-only (WI-U1) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/verification/browser/scenarios.test.ts | 6 +- build/verification/browser/scenarios.ts | 210 +++++---- .../describeUnavailableConnection.test.ts | 18 +- .../describeUnavailableConnection.ts | 29 +- .../components/DisconnectedOverlay.test.tsx | 229 +++++----- .../components/DisconnectedOverlay.tsx | 36 +- .../clusterDashboard/ClusterDashboard.tsx | 32 +- .../collectionView/CollectionView.tsx | 11 +- .../documentView/documentView.test.tsx | 47 +- .../documentdb/documentView/documentView.tsx | 18 +- .../documentdb/useBoundViewRecovery.test.tsx | 415 ++++-------------- .../documentdb/useBoundViewRecovery.ts | 119 ++--- 12 files changed, 458 insertions(+), 712 deletions(-) diff --git a/build/verification/browser/scenarios.test.ts b/build/verification/browser/scenarios.test.ts index 0817b91d3..714139ecb 100644 --- a/build/verification/browser/scenarios.test.ts +++ b/build/verification/browser/scenarios.test.ts @@ -32,8 +32,8 @@ describe('L2-dev manifest and routes', (): void => { it('round-trips every scenario and theme, without duplicate routes', (): void => { const routes = scenarioRoutes(); - expect(routes).toHaveLength(186); - expect(new Set(routes.map((route): string => route.path)).size).toBe(186); + expect(routes).toHaveLength(189); + expect(new Set(routes.map((route): string => route.path)).size).toBe(189); for (const route of routes) expect(parseScenarioRoute(route.path)).toEqual(route); }); @@ -71,7 +71,7 @@ describe('L2-dev manifest and routes', (): void => { }); it('provides path-only all/view/theme helpers and rejects unknown subsets', (): void => { - expect(runnerRoutes('/scenarios/run-all.js')).toHaveLength(186); + expect(runnerRoutes('/scenarios/run-all.js')).toHaveLength(189); expect(runnerRoutes('/scenarios/run-all/connectionDiagnostics.js')).toHaveLength(84); expect(runnerRoutes('/scenarios/run-all/localQuickStart.js')).toHaveLength(75); expect(runnerRoutes('/scenarios/run-all/localQuickStart/dark.js')).toHaveLength(25); diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 6efcce13d..e9ab0dbe6 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -2435,8 +2435,9 @@ const saveDocumentPath = 'mongoClusters.documentView.saveDocument'; const disconnectedDocument = { reason: 'userDisconnected', title: 'Disconnected', - detail: 'Reconnect from the connection tree, then click Retry.', - action: 'retry', + detail: + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + action: 'close', } as const; const documentEditorName = 'Document Editor: Edit the document in JSON format'; const firstDocumentEdit = { @@ -2489,37 +2490,33 @@ const documentViewScenarios = { holdReply: true, results: [{ documentId: '"stage0-1"', documentStringified: '{"name":"Old save reply"}' }], }, + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, 'mongoClusters.documentView.recoverUnavailable': { type: 'mutation', - results: [{ recovered: { text: 'Reconnected' } }], + results: [], + undefinedResult: true, }, - 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, }, assertions: [ { kind: 'attribute', - name: 'recovery does not discard the editor', + name: 'a terminal notice preserves the editor and its draft', selector: '.disconnectedOverlayBackground', attribute: 'inert', expected: null, steps: [ firstDocumentEdit, saveDocumentStep, + { + ...firstDocumentEdit, + value: '{"_id":"stage0-1","name":"Newer unsaved edit"}', + }, { action: 'post', name: 'disable Document View', message: { type: 'documentView.connectionUnavailable', unavailable: disconnectedDocument }, }, - { action: 'click', role: 'button', name: 'Retry' }, - { - action: 'waitFor', - name: 'the editor to be enabled after reconnect', - selector: '.disconnectedOverlayBackground:not([inert])', - }, - { - ...firstDocumentEdit, - value: '{"_id":"stage0-1","name":"Newer unsaved edit"}', - }, + { action: 'click', role: 'button', name: 'Dismiss notice' }, ], }, { @@ -2530,10 +2527,26 @@ const documentViewScenarios = { }, { kind: 'attribute', - name: 'the newer edit stays dirty and can be saved', + name: 'the newer edit stays dirty and terminal Save stays disabled', selector: 'button[aria-label="Save to the database"]', attribute: 'disabled', - expected: null, + expected: '', + }, + { + kind: 'calls', + name: 'the terminal tab never calls recovery or submits the newer draft', + path: saveDocumentPath, + count: 1, + checkInput: false, + steps: [], + }, + { + kind: 'calls', + name: 'the terminal tab never calls the obsolete recovery RPC', + path: 'mongoClusters.documentView.recoverUnavailable', + count: 0, + checkInput: false, + steps: [], }, ], }, @@ -2541,7 +2554,67 @@ const documentViewScenarios = { const clusterDashboardBase = defaultScenario('clusterDashboard'); const clusterDashboardScenarios = { - default: clusterDashboardBase, + default: { + ...clusterDashboardBase, + assertions: [ + ...(clusterDashboardBase.assertions ?? []), + { + kind: 'text', + name: 'a healthy poll keeps the Dashboard connected', + selector: '.dashboardConnectionStatus', + includes: ['Connected'], + excludes: ['Disconnected'], + }, + ], + }, + 'recoverable-health-polls': { + ...clusterDashboardBase, + config: { ...fixtures.clusterDashboard.config, refreshIntervalMs: 25 }, + readiness: { ...clusterDashboardBase.readiness, content: ['Disconnected'] }, + rpc: { + ...clusterDashboardBase.rpc, + 'clusterDashboard.measureRtt': { + ...fixtures.clusterDashboard.rpc['clusterDashboard.measureRtt'], + afterFirst: { + results: [ + { + unavailable: { + reason: 'unreachable', + title: 'Connection lost', + detail: 'Check the network or server.', + action: 'retry', + }, + }, + ], + }, + }, + 'common.displayErrorMessage': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'text', + name: 'repeated failures are recorded in the connection status', + selector: '.dashboardConnectionStatus', + includes: ['Disconnected'], + excludes: [], + }, + { + kind: 'attribute', + name: 'recoverable poll failures do not show the terminal notice', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + }, + { + kind: 'calls', + name: 'background recoverable poll failures do not toast', + path: 'common.displayErrorMessage', + count: 0, + checkInput: false, + steps: [], + }, + ], + }, disconnected: { ...clusterDashboardBase, config: { ...fixtures.clusterDashboard.config, refreshIntervalMs: 2000 }, @@ -2552,10 +2625,7 @@ const clusterDashboardScenarios = { ...fixtures.clusterDashboard.rpc['clusterDashboard.measureRtt'], holdReply: true, }, - 'clusterDashboard.recoverUnavailable': { - type: 'mutation', - results: [{ recovered: { text: 'Reconnected' } }], - }, + 'clusterDashboard.recoverUnavailable': { type: 'mutation', results: [], undefinedResult: true }, }, assertions: [ { @@ -2601,25 +2671,21 @@ const clusterDashboardScenarios = { attribute: 'value', expected: 'stage0', }, + { + kind: 'attribute', + name: 'dismissing the notice exposes the retained inventory for copying only', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + steps: [{ action: 'click', role: 'button', name: 'Dismiss notice' }], + }, { kind: 'calls', - name: 'tree reconnect resumes the retained Dashboard through Retry', + name: 'the retained Dashboard never calls recovery after reconnect', path: 'clusterDashboard.recoverUnavailable', - count: 1, - checkInput: true, - input: { action: 'retry' }, - steps: [ - { - action: 'post', - name: 'reveal the Dashboard after reconnecting in the tree', - message: { type: 'clusterDashboard.retryAfterReconnect' }, - }, - { - action: 'waitFor', - name: 'Dashboard is enabled again', - selector: '.disconnectedOverlayBackground:not([inert])', - }, - ], + count: 0, + checkInput: false, + steps: [], }, ], }, @@ -2644,7 +2710,7 @@ const runCollectionQuery = { const collectionSignInRequired = { reason: 'signInRequired', title: 'Sign-in required', - detail: 'Sign in from the connection tree, then click Retry.', + detail: 'Sign in from the connection tree.', action: 'retry', } as const; const collectionViewScenarios = { @@ -2659,26 +2725,32 @@ const collectionViewScenarios = { }, 'mongoClusters.collectionView.recoverUnavailable': { type: 'mutation', - results: [{ recovered: { text: 'Reconnected' } }], + results: [], + undefinedResult: true, }, 'mongoClusters.collectionView.copyQueryToClipboard': { type: 'mutation', results: [null], }, 'common.confirm': { type: 'mutation', results: [{ confirmed: false }] }, + 'common.displayErrorMessage': { type: 'mutation', results: [], undefinedResult: true }, 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, }, assertions: [ { kind: 'attribute', - name: 'keeps the query and results mounted but disables their controls', + name: 'a recoverable failure keeps the same query and controls live', selector: '.disconnectedOverlayBackground', attribute: 'inert', - expected: '', + expected: null, steps: [ collectionFilter, runCollectionQuery, - { action: 'waitFor', name: 'sign-in overlay', selector: '.disconnectedOverlay' }, + { + action: 'waitFor', + name: 'actionable sign-in error reaches the host', + selector: '.collectionView', + }, ], }, { @@ -2688,28 +2760,18 @@ const collectionViewScenarios = { includes: ['"name":"Alpha"'], excludes: [], }, - { - kind: 'text', - name: 'offers Retry and Close view while sign-in stays in the tree', - selector: '.disconnectedOverlay', - includes: ['Sign-in required', 'Sign in from the connection tree, then click Retry.', 'Close view'], - excludes: ['Reconnect', 'Retry sign-in'], - }, { kind: 'calls', - name: 'the query shortcut while disconnected does not run another query', - path: collectionQueryPath, - count: 2, - checkInput: false, - steps: [{ action: 'press', role: 'button', name: 'Retry', key: 'Control+Enter' }], - }, - { - kind: 'attribute', - name: 'dismissing the dialog makes the existing view accessible', - selector: '.disconnectedOverlayBackground', - attribute: 'inert', - expected: null, - steps: [{ action: 'click', role: 'button', name: 'Dismiss dialog to access view contents' }], + name: 'the failed query surfaces one actionable repair error', + path: 'common.displayErrorMessage', + count: 1, + checkInput: true, + input: { + message: 'Sign in from the connection tree.', + modal: false, + cause: 'signInRequired', + }, + steps: [], }, { kind: 'text', @@ -2728,22 +2790,19 @@ const collectionViewScenarios = { }, { kind: 'calls', - name: 'Find Query after dismissal shows the dialog without submitting another query', + name: 'the next explicit query runs once in the same tab after repair', path: collectionQueryPath, - count: 2, + count: 3, checkInput: false, - steps: [ - runCollectionQuery, - { action: 'waitFor', name: 'sign-in overlay returns', selector: '.disconnectedOverlay' }, - ], + steps: [runCollectionQuery], }, { kind: 'calls', - name: 'Close view requests confirmation through the host', - path: 'common.confirm', - count: 1, + name: 'recoverable failures never call the obsolete recovery RPC', + path: 'mongoClusters.collectionView.recoverUnavailable', + count: 0, checkInput: false, - steps: [{ action: 'click', role: 'button', name: 'Close view' }], + steps: [], }, ], }, @@ -2791,7 +2850,10 @@ const collectionViewScenarios = { kind: 'text', name: 'the late reply does not change the displayed disconnect reason', selector: '.disconnectedOverlay', - includes: ['Disconnected', 'Retry'], + includes: [ + 'Disconnected', + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + ], excludes: ['Retry sign-in'], }, ], diff --git a/src/webviews/_integration/describeUnavailableConnection.test.ts b/src/webviews/_integration/describeUnavailableConnection.test.ts index 875b5b7ad..74bf7af19 100644 --- a/src/webviews/_integration/describeUnavailableConnection.test.ts +++ b/src/webviews/_integration/describeUnavailableConnection.test.ts @@ -6,18 +6,24 @@ import { expect, it } from 'vitest'; import { describeUnavailableConnection } from './describeUnavailableConnection'; -it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing'] as const)( - 'directs credential repair to the tree before retrying %s', +it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing', 'credentialsUpdating', 'unreachable'] as const)( + 'directs repair without a Retry workflow for %s', (reason): void => { const { unavailable } = describeUnavailableConnection(reason); expect(unavailable).toMatchObject({ reason, action: 'retry' }); - expect(unavailable.detail).toContain('tree'); + expect(unavailable.detail).not.toContain('then click Retry'); }, ); -it.each(['identityChanged', 'credentialsChanged', 'connectionRemoved'] as const)( - 'offers only Close view for %s', +it.each(['userDisconnected', 'identityChanged', 'credentialsChanged', 'connectionRemoved'] as const)( + 'permanently describes ended sessions for %s', (reason): void => { - expect(describeUnavailableConnection(reason).unavailable.action).toBe('close'); + expect(describeUnavailableConnection(reason).unavailable).toEqual({ + reason, + title: 'Disconnected', + detail: + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + action: 'close', + }); }, ); diff --git a/src/webviews/_integration/describeUnavailableConnection.ts b/src/webviews/_integration/describeUnavailableConnection.ts index f7491ad32..82d04bb4b 100644 --- a/src/webviews/_integration/describeUnavailableConnection.ts +++ b/src/webviews/_integration/describeUnavailableConnection.ts @@ -14,7 +14,7 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso unavailable: { reason, title: l10n.t('Sign-in required'), - detail: l10n.t('Sign in from the connection tree, then click Retry.'), + detail: l10n.t('Sign in from the connection tree.'), action: 'retry', }, }; @@ -23,20 +23,16 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso unavailable: { reason, title: l10n.t('Authentication failed'), - detail: l10n.t('Repair the connection in the tree, then click Retry.'), + detail: l10n.t('Repair the connection in the tree.'), action: 'retry', }, }; case 'credentialsMissing': - case 'userDisconnected': return { unavailable: { reason, title: l10n.t('Disconnected'), - detail: - reason === 'userDisconnected' - ? l10n.t('Reconnect from the connection tree, then click Retry.') - : l10n.t('Connect from the connection tree, then click Retry.'), + detail: l10n.t('Connect from the connection tree.'), action: 'retry', }, }; @@ -45,37 +41,30 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso unavailable: { reason, title: l10n.t('Connection update in progress'), - detail: l10n.t('Wait for the update to finish, then click Retry.'), + detail: l10n.t('Wait for the update to finish.'), action: 'retry', }, }; + case 'userDisconnected': case 'identityChanged': case 'credentialsChanged': + case 'connectionRemoved': return { unavailable: { reason, - title: l10n.t('Connection changed'), + title: l10n.t('Disconnected'), detail: l10n.t( - 'This view is tied to the previous connection settings. Close it and reopen it from the tree.', + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', ), action: 'close', }, }; - case 'connectionRemoved': - return { - unavailable: { - reason, - title: l10n.t('Connection removed'), - detail: l10n.t('This connection is no longer in the tree. Close this view.'), - action: 'close', - }, - }; case 'unreachable': return { unavailable: { reason, title: l10n.t('Connection lost'), - detail: l10n.t('Check the network or server, then click Retry.'), + detail: l10n.t('Check the network or server.'), action: 'retry', }, }; diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx index 099ad97c1..e0ba9fa99 100644 --- a/src/webviews/components/DisconnectedOverlay.test.tsx +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -18,74 +18,93 @@ vi.mock('../_integration/useTrpcClient', () => ({ useTrpcClient: () => ({ common: { confirm: { mutate: confirm } } }), })); +const unavailable: ConnectionUnavailableDetails = { + reason: 'userDisconnected', + title: 'Disconnected', + detail: + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + action: 'close', +}; + beforeEach((): void => { confirm.mockReset(); }); -it('dismisses without closing, and only closes a dirty view after confirmation', async (): Promise => { - const unavailable: ConnectionUnavailableDetails = { - reason: 'signInRequired', - title: 'Sign-in required', - detail: 'Sign in from the connection tree, then click Retry.', - action: 'retry', - }; +it('dismisses only the notice and never enables terminal content actions', async (): Promise => { const onAction = vi.fn(); const onDismiss = vi.fn(); - confirm.mockResolvedValueOnce({ confirmed: false }).mockResolvedValueOnce({ confirmed: true }); const host = document.createElement('div'); document.body.appendChild(host); const root = createRoot(host); + const render = async (failure?: ConnectionUnavailableDetails): Promise => { + await act(async () => + root.render( + +