diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 920feb2d3..4028f7081 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -3999,9 +3999,9 @@ const documentViewBase = defaultScenario('documentView'); const documentEditReadiness = { ...documentViewBase.readiness, content: ['Save'] }; const saveDocumentPath = 'mongoClusters.documentView.saveDocument'; const disconnectedDocument = { - reason: 'userDisconnected', - title: 'Disconnected', - detail: 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', } as const; const documentEditorName = 'Document Editor: Edit the document in JSON format'; const firstDocumentEdit = { @@ -4403,10 +4403,7 @@ const collectionViewLifecycleScenarios = { kind: 'text', name: 'the late reply does not change the displayed disconnect reason', selector: '.disconnectedOverlay', - includes: [ - 'Disconnected', - 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', - ], + includes: ['Session ended', 'Copy what you need and open a new tab.'], excludes: ['Retry sign-in'], }, ], diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index d22fbfc59..3cb783d10 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -127,6 +127,12 @@ entries are unpublished drafts and do not represent a shipped release. It never uses the failed saved authentication or shared authenticated metadata, and does not promise that anonymous commands are authorized. Normal context-menu Shell startup is unchanged. Pre-terminal failures use a tree modal; later failures stay in the terminal. + Extraction or a Connection Diagnostics panel entry is under evaluation, not approved (0036). +- **Obsolete recovery actions and ended sessions (0036):** one actionable explanation for a stale + explicit tree action, and one **Session ended** notice for a retired tab. The current connection + still reports its specific failure and repair steps. A single generation cutoff and the lifetime + abort signal keep old work from reaching a new session. Azure Discovery/ARM, retained views and + Show Connection Stats stay in scope. - **Disconnect and Remove Connection** share a teardown and a tab choice. Saving a change to connection details uses the disconnected edit flow (0026, 0030), subject to C01's accepted concurrency limitation (0033). A connected edit starts with **Disconnect and update**; preserve @@ -159,6 +165,7 @@ entries are unpublished drafts and do not represent a shipped release. | [iterations/02-pr1136-copilot-review.md](./iterations/02-pr1136-copilot-review.md) | review | | [iterations/03-complexity-reduction-analysis.md](./iterations/03-complexity-reduction-analysis.md) | analysis | | [iterations/03-pr1149-copilot-review.md](./iterations/03-pr1149-copilot-review.md) | review | +| [iterations/04-pr1136-scope-and-test-review.md](./iterations/04-pr1136-scope-and-test-review.md) | analysis | | [iterations/01-pr1136-final-review.md](./iterations/01-pr1136-final-review.md) | review | | [iterations/01-pr1136-ux-review.md](./iterations/01-pr1136-ux-review.md) | ux-review | @@ -189,7 +196,7 @@ See [decisions.md](./decisions.md): - 0021 key the in-memory connection fingerprint per extension host. - 0022 separately unauthenticated Shell entry from failure rows only. - 0023 retained-view Retry feedback (superseded by 0031). -- 0024 classify explicit stale recovery clicks without disturbing quiet background paths. +- 0024 classify explicit stale recovery clicks without disturbing quiet background paths; 0036 simplifies their feedback. - 0025 use modal feedback for tree-origin commands, leaving webview feedback unchanged; descendant expansion is deferred to #1143 until foreground attribution is supported. - 0026 Update Credentials and Update Connection String require a closed connection; Sign in again keeps the pin; A1 refusal replaced by A2 in 0030. @@ -203,6 +210,8 @@ See [decisions.md](./decisions.md): - 0033 approve the PR #1149 review dispositions: accept C01's concurrency edge, clear removed Playground selections for C06, leave C08's local editing unchanged, and require manual refresh after a stopped index-build poll for C10; C12 remains a no-code disposition. +- 0036 simplify obsolete actions and ended bindings, retain useful features and trim duplicate tests; + isolated Shell extraction and placement remain open. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index c55aa0ccb..3cb4d0d37 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -35,7 +35,7 @@ created: 2026-11-19 | 0021 | Key the in-memory connection fingerprint per extension host | Accepted | Operator: use HMAC and verify CodeQL without dismissing a remaining alert | 2026-11-26 | Yes; replaces unkeyed SHA-256 without changing identity rules | | 0022 | Offer a separately unauthenticated Shell from failure rows only | Accepted | Operator approved the bounded F1 policy in the iteration 2 lead run | 2026-11-27 | Modifies 0015 only for this explicit anonymous entry | | 0023 | Keep retained-view Retry failure feedback inside the unavailable dialog | Superseded by 0031 | D2 removes the retained-view Retry episode | 2026-11-27 | No automatic operation replay | -| 0024 | Classify explicit stale recovery clicks and explain only failed actions | Accepted | Operator selected F5 option C | 2026-11-27 | Cancellation, disposed work and obsolete replies remain quiet | +| 0024 | Classify explicit stale recovery clicks and explain only failed actions | Accepted (modified by 0036) | Operator selected F5 option C; 0036 simplifies stale-click feedback | 2026-11-27 | Cancellation, disposed work and obsolete replies remain quiet | | 0025 | Tree-origin failures use modals; webview-origin command feedback stays unchanged | Accepted | Operator confirmed F3 scope | 2026-11-27 | Shared command registrations must preserve origin | | 0026 | Update Credentials and Update Connection String require a closed connection; Sign in again keeps the pin | Accepted (modified by 0030) | Operator initially chose A1; 0030 replaces it with A2 | 2026-11-29 | Yes; removes the edit-while-connected path | | 0027 | Views kept open after Disconnect are permanently disabled; Disconnect still asks Close or Keep open | Accepted | Operator chose B2 over B1 (always close): "still ask the user" | 2026-11-29 | Yes; no rebinding or revival of retained views | @@ -47,6 +47,7 @@ created: 2026-11-19 | 0033 | Approve the PR1149 review dispositions with explicit complexity tradeoffs | Accepted | C01 option 3; C06 option 2 direction; C08 won't fix; C10 option 2 | 2026-12-01 | Nine code fixes; C01/C08/C12 are no-code dispositions | | 0034 | Keep manual Refresh as the only way to resume paused index polling after Create | Accepted | Document the workaround; no code change | 2026-12-01 | Clarifies 0033 for pre-review finding N01 | | 0035 | Keep Dashboard Connection Diagnostics available in disconnected views | Accepted | Not gated like the other tree-command actions | 2026-12-02 | Exception to 0031/0032: diagnosis opens a separate, read-only view | +| 0036 | Simplify obsolete actions and ended bindings without cutting useful features | Accepted | Operator accepted #2/#3 and duplicate-test trimming, not broad feature cuts | 2026-12-02 | Isolated Shell extraction or panel placement remains open | > Entries below are **semantically** immutable: append new entries rather than rewriting old ones, > and record reversals as a new entry plus a status change above. Heading text is frozen once @@ -606,6 +607,7 @@ rationale is inferred. ## 0024. Classify explicit stale recovery clicks and explain only failed actions **Accepted** by the operator on 2026-11-27: F5 option C. +The reason-specific modal copy below was superseded by [0036](#0036-simplify-obsolete-actions-and-ended-bindings-without-cutting-useful-features); the quiet paths still apply. Refresh current tree state and explain actually failed explicit clicks using their real reason: **This connection was removed. Choose another connection.** or @@ -919,3 +921,14 @@ procedure and button are therefore not bound to the view's connection lifetime; existing diagnose command against the current saved node. If the connection was removed, the missing-node error applies. This does not restore database access to a retained view, and the other Dashboard tree-command actions keep their guards. + +## 0036. Simplify obsolete actions and ended bindings without cutting useful features + +**Accepted direction, not implemented by this decision.** In the [#1136 scope review](./iterations/04-pr1136-scope-and-test-review.md), the operator agreed to proposals 2 and 3 and to trimming duplicate tests. Their criterion was to keep beneficial features that are cheap to maintain. + +- Use one actionable explanation for an obsolete explicit recovery action. Keep real repair instructions specific, and keep cancellation and obsolete background work quiet. +- An old binding need only say that its session ended, not preserve each historical reason. Keep the current connection's precise state, cancellation before side effects, dirty-data protection, and recovery after failed removal. No particular replacement data structure was approved. +- Consolidate repeated command-state and dismissal matrices. Retain tests that prove different safety boundaries: wrong identity, command replay, stale work or lost drafts. +- Keep Azure Discovery/ARM in #1136: the operator considers it a good solution already in place. Reject #4 (always closing views) as too aggressive; preserve Close/Keep/Cancel. Reject #5: Show Connection Stats stays because it is useful for debugging. + +**Open, not a reversal of 0022:** the operator asked to evaluate extracting the isolated Shell as future work and exposing it in Connection Diagnostics, either instead of or alongside the tree entry. They see diagnostic value but substantial cost for an edge case. No removal, additional entry point or deletion of isolation tests is approved. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/04-pr1136-scope-and-test-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/04-pr1136-scope-and-test-review.md new file mode 100644 index 000000000..56d55a10d --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/04-pr1136-scope-and-test-review.md @@ -0,0 +1,151 @@ +--- +feature: connection-lifecycle +kind: analysis +status: historical +prs: [1136] +created: 2026-12-02 +--- + +# PR #1136: what to cut from connection recovery + +**After operator review: simplify what happens to obsolete work; keep the useful features.** Accepted: one explanation for a stale user action (#2), one terminal “session ended” outcome for an old binding (#3), and trimming duplicate tests. Keep Azure Discovery/ARM **in this PR**, Close/Keep/Cancel for webviews, and Show Connection Stats for debugging. Do not cut ordinary Shell or Playground recovery. [Decision 0036](../decisions.md#0036-simplify-obsolete-actions-and-ended-bindings-without-cutting-useful-features) records the disposition; these changes have not been implemented by this review. + +**One open question: the isolated Shell.** The operator sees value in launching it from Connection Diagnostics, but considers it substantial work for an edge case. Extraction and placement are under evaluation, **not approved for removal or implementation**. Keep the current action and its isolation tests pending that decision. [Options and recommendation below](#isolated-shell-extract-the-feature-or-move-the-button). + +This is a review of [#1136](https://github.com/microsoft/vscode-documentdb/pull/1136), `feature/connection-lifecycle` at `7a1a7f5d2`, against its `main` merge base `c6b06e8ca`. [#1149](https://github.com/microsoft/vscode-documentdb/pull/1149) is already in that head. “80%” is a design criterion, not a measured usage share. + +## What users need, and what depends on what + +```mermaid +flowchart TD + A[Use an open tab, Shell or Playground] --> B{Can the same account continue?} + B -->|Yes| C[Silent token lookup or healthy replacement client] + C --> D([Next operation works; existing work stays]) + B -->|No| E([Actionable error; failed command is not replayed]) + E --> F[Explicit same-account repair; user runs the operation again] + E --> G[Failed tree row: Diagnose connection] + E --> H[Failed tree row today: separate anonymous Shell] + I[Disconnect, Remove or disconnect to edit] --> J{Active transfer or user cancels?} + J -->|Yes| K([Stop; do not tear down or edit]) + J -->|No| L[End old lifetime; stop workers and fence pending host work] + L --> M([Close views or retain copyable disabled views; dirty close requires consent]) + L --> N([Reconnect opens a new session; old work cannot target it]) +``` + +| Cluster | Dependency and user promise | Disposition | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Database Entra renewal | The [OIDC callback](../../../../../src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts#L233) asks VS Code silently for the pinned account on each driver lookup; it doesn't keep handing out the original token. The [driver contract](../../../../../src/documentdb/auth/driverOidcContract.test.ts#L63) shows the same driver workflow can repeat a rejected callback without invoking it again. | **Keep.** Fixing only the callback leaves users stuck after one failed refresh. No background sign-in prompt or extension-level replay of a failed write. | +| Client replacement and explicit tree repair | [Failure classification](../../../../../src/documentdb/connectionFailures.ts#L45) distinguishes a transient network failure, a closed/poisoned client, and rejected credentials. [Failure reporting](../../../../../src/documentdb/ClustersClient.ts#L1196) checks which physical client actually failed. A [bound operation](../../../../../src/documentdb/runWithClient.ts#L34) can use its replacement without moving to a different identity. | **Keep.** Not every network error calls for a new client. Do not silently redial rejected credentials. A late error on yesterday's client must not evict today's. | +| Disconnect, Remove and credential edits | One [teardown](../../../../../src/documentdb/connectionTeardown.ts#L111) coordinates tasks, views and workers. A connected edit first disconnects; a [save](../../../../../src/commands/saveConnectionEdit.ts#L53) excludes new startup and checks what persisted. [Secret and metadata writes](../../../../../src/services/storageService.ts#L356) are not atomic. | **Keep the boundary, not every branch.** Cancelling a dirty close must leave the edit unstarted. A partial save/delete must report failure and leave the surviving connection recoverable. A toast alone cannot establish either fact. | +| Collection, Document and Dashboard views | Collection has query/results state, Document has editor text, Dashboard can launch commands on a namespace. A [Dashboard → Collection handoff](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L298) and a [session check after an await](../../../../../src/documentdb/ClusterSession.ts#L82) protect work already running in the host, not just buttons in the panel. | **Keep live views through ordinary failure.** Preserve drafts/results and let the user retry the operation. Don't rebuild panels on every dropped socket. Explicit Disconnect/Remove is different; see the close-only alternative below. | +| Playground and ordinary integrated Shell | Both use the [host token relay](../../../../../src/documentdb/auth/WorkerTokenRelay.ts#L53) and worker protocol, not the extension host's database client. [Playground](../../../../../src/documentdb/playground/PlaygroundEvaluator.ts#L333) must not rerun a script after startup/repair; [Shell](../../../../../src/documentdb/shell/ShellSessionManager.ts#L223) has persistent session state. | **Keep both.** Removing renewal from one brings back the original defect on that surface without removing the relay for the other. On explicit Disconnect stop the worker; keep file text or scrollback, not a live session. | +| Azure Discovery / ARM | A separate token consumer: a subscription kept across expiry, the Azure SDK challenge path, listing/cache behavior and the host bundle. [The ARM regression](../../../../../src/utils/azureClients.test.ts#L66) uses one stored subscription for two operations; no Collection tab or worker is needed. | **Keep as-is in #1136.** The operator considers this a good solution already in place. Keep the SDK/lockfile, adapter/provider callers, ARM regression and [bundle verification](./01-pr2-azureauth-review.md#azure-esm-bundle-verification) together; no split. | + +### Expensive-looking features that are already gone + +There is **no** Retry-to-unlock step for a recoverable webview error; a retained view does **not** revive, even after reconnecting to the same account. Updating connection settings does **not** migrate live tabs to a new identity. A failed operation is not an invitation to replay it. These were consequential simplifications in [decisions 0031–0032](../decisions.md#0031-choose-package-p-a2-b2-c-balanced-d2-and-guarded-handoffs); don't count them again as future savings. A physical client replaced after expiry and a logical session ended by the user are still two different events. A single “connected” boolean cannot represent both safely. + +## Disposition of the five proposals + +1. **Open: evaluate extracting the isolated diagnostic Shell as future work.** On `main` the failed row offered ordinary **Open shell**. This branch [replaces that action](../../../../../src/tree/documentdb/ClusterItemBase.ts#L419) with an isolated mode. Neither moving it nor removing it has been approved. [Decision 0022](../decisions.md#0022-offer-a-separately-unauthenticated-shell-from-failure-rows-only) still applies. +2. **Collapse stale-action feedback; preserve actionable failures.** [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L90) repeats the refresh/removed-or-changed modal decision at entry, after a failed key read, after a successful key read, and after closing a client. [Disconnect/Reconnect](../../../../../src/commands/disconnect/disconnect.ts#L41) and [sign-in](../../../../../src/commands/signInAgain/signInAgain.ts#L88) have variants. For an explicit action that can no longer run, refresh the supported tree and say once: **“This connection is no longer available for that action. Refresh the tree and try again.”** Genuine user cancellation and obsolete background work stay quiet. Genuine provider changes, missing credentials and a rejected sign-in still get their specific repair instructions. **Tradeoff:** less precise copy on a race, fewer branches and test matrices; no change to whether stale work can run. This narrows [decision 0024](../decisions.md#0024-classify-explicit-stale-recovery-clicks-and-explain-only-failed-actions). +3. **Accepted: use a generic reason for an old binding.** The [retirement registry](../../../../../src/documentdb/connectionBindingRetirement.ts#L10) appends a generation/reason range and searches that history after later sessions start. A failed storage removal can [correct the last range and re-notify retained panels](../../../../../src/documentdb/connectionTeardown.ts#L318). A retained panel can instead say **“Session ended. Copy what you need and open a new tab.”** A monotonic cutoff plus the existing abort signal is a candidate implementation, not a requirement. Keep the _current_ connection's accurate latch, failed-removal ownership checks and the disconnected recovery path. Audit consumers before changing the typed reason; don't replace this small registry with another lifetime framework. +4. **Rejected: forcing webviews closed is too aggressive.** Keep the [open-tabs setting and choice](../../../../../src/documentdb/connectionTeardown.ts#L126), copyable retained contents and dirty-document consent. Closing everything would sacrifice results/drafts without eliminating guards for pending host work. +5. **Rejected: deferring Show Connection Stats.** Keep the [command](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L28) and [host snapshot](../../../../../src/documentdb/ClustersClient.ts#L427). The operator uses it for debugging; deleting a small, isolated formatter is a poor trade for losing visibility into expiry, pending startup and held connections. + +### Isolated Shell: extract the feature or move the button? + +| Option | What the user gains or loses | What it actually saves | +| --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Keep the existing tree entry; add nothing now | Direct access after a failed connection. No new UI to learn or maintain. | No reduction, but also no extraction or retesting cost. Lowest-risk default while demand is unknown. | +| Extract the **whole mode** to future work | For now the failed row offers Diagnose and repair, not an anonymous terminal. Ordinary Shell, normal NoAuth connections and Playground still work. | The only option that removes the anonymous worker/startup/isolation policy from this release. Move its specific tests with it; dropping only the tree row or hiding it behind a flag is not extraction. | +| Later, **panel only** | Users try the built-in checks first and explicitly launch a separate terminal if those checks cannot answer their question. One extra click from the failed row. | Better placement, **not** a cheaper Shell. One panel-to-host launch path replaces one tree entry; endpoint isolation and worker checks remain. | +| Later, **panel and tree** | Expert users retain the shortcut, and panel users can discover the tool. | No runtime simplification. Even with one shared launcher, there are two entry points to explain and test. | + +**Recommendation:** don't add a panel action in #1136. The [diagnostics panel already tests DNS, TCP, TLS and the unauthenticated server greeting](../../../../user-manual/diagnose-connection.md#what-the-checks-do). Revisit panel-only placement when support can name a task those checks cannot answer and an anonymous terminal can. Keep both entries only if the shortcut itself proves useful. If the goal is to take this edge case out of the release, extract only if its branches and tests can be removed cleanly without destabilizing the shared worker; otherwise keep the working tree entry rather than pay for a rewrite to make the diff smaller. + +**One design constraint if revisited:** launch a _separate terminal_ on an explicit click, never as a diagnostic step or embedded command runner. A [panel can be retargeted](../../../../../src/webviews/documentdb/connectionDiagnostics/connectionDiagnosticsController.ts#L29) while an old run keeps [its original subject](../../../../../src/webviews/documentdb/connectionDiagnostics/diagnosticsPanelSession.ts#L84). A report is not launch authority: the host must resolve the intended current target, reject a removed/changed/disconnected one and use the [isolated launch checks](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L106). Read-only diagnosis remains available from retained Dashboards under [0035](../decisions.md#0035-keep-dashboard-connection-diagnostics-available-in-disconnected-views); that exception must not authorize a Shell. Reuse the launcher, never saved credentials, authenticated completions or Playground state. + +## Test pruning: cut by contract, not by file size + +### Can consolidate now, without a product change + +| Group | Proposed reduction | What must still fail if the code regresses | +| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| [Update Credentials](../../../../../src/commands/updateCredentials/updateCredentials.test.ts#L518) and [Update Connection String](../../../../../src/commands/updateConnectionString/updateConnectionString.test.ts#L386) | Both run the **same five teardown outcomes and five initial states**: 20 expanded cases, 170 added lines in those four blocks. Exercise each matrix once at the shared boundary; keep one blocked/cancelled wiring test and the distinct successful persistence path for each command. | Neither wizard opens after a refused/failed disconnect. Keep secret-first partial-save coverage, the rejected-destination case, and the separate [work appears _during_ a wizard](../../../../../src/commands/saveConnectionEdit.test.ts#L489) check: that is not the initial-state matrix. | +| [Superseded sign-in dismissal](../../../../../src/commands/signInAgain/signInAgain.test.ts#L249) | Three stale reasons × two provider dismissal forms × tree/worker = **12 cases** for the same “no startup, no error UI” outcome. Cover both dismissal forms and both caller types across a small selection, not their product. Keep the distinct non-cancellation failure. | A real provider error is still surfaced; a dismissal never connects. A different account, tenant/provider drift and late publication after Disconnect are **not** dismissal variants. | +| [Collection controller](../../../../../src/webviews/documentdb/collectionView/collectionViewController.test.ts#L113) and [Document controller](../../../../../src/webviews/documentdb/documentView/documentsViewController.test.ts#L92) | Share the mock/setup for register → disable → dispose and avoid asserting the same notification plumbing in full everywhere. Keep a representative wiring check per view. This saves fixture maintenance, not a whole suite. | Document preserves its dirty draft; Collection removes the old session; Dashboard reuse can't route an old action to a new panel. Router authorization, controller disposal and rendered copy/dismiss behavior are different boundaries. | + +### Delete or rewrite **only with the corresponding feature cut** + +| Diagnostic Shell test group | Expanded cases | PR-added lines inside group | +| -------------------------------------------------------------------------------------------------------------------------------- | -------------: | --------------------------: | +| [Command: unauthenticated failure-row entry](../../../../../src/commands/openInteractiveShell/openInteractiveShell.test.ts#L182) | 24 | 262 | +| [PTY: unauthenticated isolation](../../../../../src/documentdb/shell/DocumentDBShellPty.test.ts#L288) | 8 | 149 | +| [Shell session manager: unauthenticated sessions](../../../../../src/documentdb/shell/ShellSessionManager.test.ts#L172) | 27 | 236 | +| [Shared worker manager: diagnostic Shell startup](../../../../../src/documentdb/playground/WorkerSessionManager.test.ts#L759) | 21 | 164 | +| [Standalone endpoint sanitization suite](../../../../../src/documentdb/shell/unauthenticatedEndpoint.test.ts) | 6 | 65 | +| **Named scope, not projected net deletion** | **86** | **876** | + +These are actual Vitest cases, counting parameterized rows, not 86 hand-written tests. **None are approved deletions just because the entry point is under discussion.** If the whole mode is extracted, move its specific coverage with it. Retain one regression that the ordinary worker flow cannot bypass a hold, plus the shared destination, credential-isolation and no-replay contracts wherever still applicable. Do **not** delete the four mixed-purpose test files or their existing Shell/Playground behavior contracts. + +- **If stale feedback is unified:** remove the removed/changed/disconnected **wording** cross-product from [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.test.ts#L445) and [sign-in](../../../../../src/commands/signInAgain/signInAgain.test.ts#L312). Keep tests at the actual race boundaries: a key read completes after removal, the startup returns after Disconnect, or a stale error arrives after a replacement. They must prove no publication or side effect, not merely assert a modal. +- **When historical reasons go:** replace the first-reason-per-range and reason-rewriting cases in [binding retirement](../../../../../src/documentdb/connectionBindingRetirement.test.ts#L48) with old/new cutoff, abort-once and no-revival cases. Keep [late client resolution](../../../../../src/documentdb/connectionBindingRetirement.test.ts#L123), [failed Remove](../../../../../src/documentdb/connectionTeardown.test.ts#L141), retained-view copy/dismiss and dirty cancel. +- **Keep with their features:** the [Show Connection Stats tests](../../../../../src/commands/showConnectionStats/showConnectionStats.test.ts), especially non-disclosure, and the real ARM SDK/transport regression. + +**Do not prune these to hit a size target:** a second token lookup returns a fresh token with no prompt; a poisoned client is replaced and a late failure cannot evict its replacement; a failed write/script is not replayed; a worker cannot switch identity or destination; a pending destructive command cannot cross Disconnect; a dirty discard can be cancelled; a failed storage write does not masquerade as success. Prefer one test at the boundary that can actually break. A mocked router cannot verify the driver callback contract, and a disabled button cannot verify that a pending host write was stopped. + +## Size, evidence and decision order + +`git diff --numstat c6b06e8ca...7a1a7f5d2` gives **307 files, +42,097 / −4,019** before this report. Categories below are disjoint; this is diff size, not executable complexity. + +| Changed files | Files | Added | Removed | +| ---------------------------------------------------------- | ----: | -----: | ------: | +| `*.test.*` anywhere | 95 | 18,433 | 570 | +| `docs/` | 30 | 12,179 | 8 | +| Other `src/` and `packages/` files | 158 | 10,429 | 3,014 | +| Other `build/` files (includes browser fixtures/scenarios) | 12 | 633 | 102 | +| Everything else | 12 | 423 | 325 | + +**73% of additions are named tests or docs.** The 16 historical iteration files alone add **10,421 lines**. For a smaller _review_, route those files to a documentation pass while keeping decisions and the user manual discoverable. Don't confuse moving history or splitting ARM into an earlier PR with deleting runtime complexity. Likewise, 876 test lines are a measured footprint, not 876 guaranteed net deletions after replacement tests. + +**Stopping point:** start with the duplicate edit and dismissal tests and #2's repeated stale-click feedback. Tackle #3 separately, alongside tests showing that old work still cannot write and a failed Remove still leaves the surviving connection recoverable. Stop after those accepted simplifications; don't wait on the Shell placement decision. In particular, keep in-place Shell/Playground sign-in: removing its UI would make people reopen or reconnect their working surface but would not remove the shared token relay. Beyond this point a live expiry, idle-wake and dirty-disconnect check buys more confidence than deleting another useful feature. + +**Verification (Case 1, not a release handoff):** `npm run build` passed. Two local focused Vitest runs at the stated head passed: **107/107** driver-contract, edit-command and sign-in cases; **375/375** across the five Shell/worker-related files above (**482 cases total**, including the 86, not in addition to them). Group line counts intersect the named test blocks with added diff lines. No full-suite, packaged-workbench, live Entra or live database run was performed for this report; no frequency estimates or release-readiness claim follow from these tests. + +## Implementation ledger + +### WI-1. Consolidate duplicate tests + +**Done (2026-12-02), commit `c5ac0403d`:** moved the edit refusals and initial-state coverage to `ensureDisconnectedForEdit`; kept one blocked-path wiring check and each command's distinct save path. The superseded sign-in cases now cover both dismissal forms and both caller types in two rows, with a separate genuine provider error test. Retained the partial-save, rejected destination, and mid-wizard guards. No runtime changes. + +- Decisions: scope accepted by the operator in 0036. Advised (`claude-opus-5.5`): use the existing teardown boundary (90%); do not share controller mocks, which would add setup rather than remove it. Recommended and actual coding model: `gpt-6.1-terra` for the bounded test-only change. +- Verification: 143/143 tests passed across the two edit commands, teardown, save and sign-in (166 before consolidation). Five teardown-outcome rows added at the shared boundary; the existing survivor and safe-idle rows exercise the same entry point. `npx tsc --noEmit -p .` and `git diff --check` passed. + +### WI-2. Unify feedback for stale explicit recovery actions + +**Done (2026-12-02), commit `0159d11dc`:** Retry, Reconnect, Disconnect and tree sign-in share one translated modal for obsolete actions. Kept each caller's existing refresh eligibility, refresh-before-feedback order, cancellation and worker/background silence, and specific guidance for real failures. No credential, startup or command fence moved. + +- Decisions: scope and wording accepted by the operator in 0036 and proposal 2. Advised (`claude-opus-5.5`): preserve each caller's view predicate, and centralize the text and eligibility without moving refresh. Advisor approved guard and ordering equivalence (85%). Kept one scenario for each distinct race instead of testing every wording permutation. Recommended and actual coding model: `gpt-6.1-sol` for cross-command lifecycle logic. +- Verification: 76/76 tests passed across Retry, Disconnect/Reconnect and sign-in after the review trims. Coverage includes an obsolete key read (success or failure), client close, deferred sign-in and startup, genuine errors, and unsupported or cancelled work. `npx tsc --noEmit -p .` (before the test-only trims) and `git diff --check` passed. + +### WI-3. Use one terminal outcome for retired bindings + +The operator approved a bundled `sessionEnded` reason, including the bounded `unavailableReason` telemetry value, with title **Session ended** and detail **Copy what you need and open a new tab.** Current-connection reasons and guidance remain unchanged. + +**Done (2026-12-02), commit `c99753dd8`:** replaced historical reason ranges with one generation cutoff and the existing lifetime abort signal. A failed storage removal can restore its own current disconnected latch, without rewriting history or notifying retained tabs a second time. Old tabs cannot run database work even after the same account reconnects. + +- Decisions: terminal copy and bounded telemetry value approved by the operator. Advised (`claude-opus-5.5`): cutoff equivalent to the ranges (95% in planning; 90% confidence in the reviewed implementation). Kept abort ordering and the epoch, latch and latest-retirement ownership checks. Recommended and actual coding model: `gpt-6.1-sol` for lifetime and cross-module behavior. Expanded test ownership only for the two edit-command interface pins; their exact call counts, ordering and cluster IDs are unchanged. +- Verification: targeted coverage distinguishes same-account physical replacement from explicit retirement and reconnect, fences a pending write and a late reply, and verifies that a failed Remove can recover the surviving connection without reviving old work. The generic reason is terminal in the webview and bounded in telemetry. Retained tabs can still be dismissed for copying or closed with dirty-draft protection. The worker's final focused run passed 435 tests, 80 browser scenario-definition tests and `npx tsc --noEmit -p .`. + +### Combined verification and delivery + +The operator chose local-only Case 1 delivery on a branch based on `feature/connection-lifecycle`. `npm run build` passed (~46s); the combined root Vitest run passed **518 tests in 28 files** (~11s), including all changed tests, the connection-surface suite and the OIDC driver contract. The dedicated browser scenario-definition run passed **80 tests** (~3s). No push, draft PR, CI, or Case 2; refresh the generated localization bundle with `npm run l10n` before the Case 2 localization check. + +**Not run in a live workbench:** same-account expiry or idle recovery in an open tab; **Keep open** with a dirty edit, notice dismissal/copy, then reconnect and open a fresh tab; stale tree actions during a real sign-in or Azure retry. Browser scenario-definition tests do not run those interactions. No decision or work on isolated Shell placement or extraction. + +### Case 2 follow-up (2026-12-02) + +The operator subsequently authorized publishing [draft #1169](https://github.com/microsoft/vscode-documentdb/pull/1169) against `feature/connection-lifecycle` before running Case 2. All eight checks passed: `npm run l10n`, `npm run prettier-fix`, `npm run l10n:check`, `npm run lint`, `npm run build`, `npm run typecheck:tests`, `npx vitest run` (**11,011 passed, 1 skipped; 473 files**) and `npm run package` (8.65 MB VSIX). Commit `868cfe934` regenerates the localization bundle, applies formatting and replaces two lint-rejected mock type annotations with Vitest's typed mock syntax. Repository-wide lint passed on retry; no production behavior changed. + +The PR remains in draft. Local checks do not replace the live workbench checks above or the formal AI pre-review and author decisions for #1169 required before requesting human review. diff --git a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md index f1674512a..a20410813 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/telemetry.md +++ b/docs/ai-and-plans/features/connection-lifecycle/telemetry.md @@ -119,7 +119,9 @@ Operations On `documentDB.rpc.*`, `unavailableReason` is set only for a valid connection-unavailable response. Its bounded values are `signInRequired`, `credentialsRejected`, `credentialsMissing`, `credentialsUpdating`, `credentialsChanged`, `identityChanged`, `userDisconnected`, -`connectionRemoved` and `unreachable`. It carries no error text or connection identifiers. +`connectionRemoved`, `unreachable` and `sessionEnded`. `sessionEnded` identifies a permanently +retired binding, regardless of how its session ended. It does not replace the current connection's +failure reason. The property carries no error text or connection identifiers. Check that CP-5 can see the property after exercising a typed unavailable response, and that an ordinary successful response does not get it. diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 4ede820ce..45b5b3cd0 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -28,6 +28,10 @@ The actions available depend on the connection and the failure: Retry is always last. These shorter labels apply to the recovery rows under a failed cluster; context-menu and Command Palette titles can differ. +If a recovery action can no longer act on the original connection, refresh the tree and choose +the action available for the current connection. Actual sign-in and credential failures still +show their specific repair instructions. + The normal context-menu Shell still uses the connection's saved authentication. The diagnostic Shell keeps local commands, methods, operators and history suggestions, but does not borrow database, collection or field suggestions from an authenticated shared client. If the endpoint is @@ -68,7 +72,8 @@ The setting can use `closeAll` or `keepOpenDisabled` as a default instead of sho time. It never bypasses the unsaved-document confirmation. **Delete Connection…** uses the same choice, but also removes the saved connection and its cached credentials. -A retained Collection View, Document View, or Cluster Dashboard shows a read-only notice: +A retained Collection View, Document View, or Cluster Dashboard shows **Session ended**. Copy what +you need and open a new tab to resume database work: - Use the **X** to dismiss the notice and inspect or copy the loaded contents. Database operations remain disabled. diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 6eefd1797..9dd06a052 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -931,6 +931,7 @@ "Copy the Public Key and Private Key from an API Key in MongoDB Atlas. We use them to sign in and show the clusters you can access.": "Copy the Public Key and Private Key from an API Key in MongoDB Atlas. We use them to sign in and show the clusters you can access.", "Copy the source collection's secondary index definitions. TTL and unique indexes must be pasted separately.": "Copy the source collection's secondary index definitions. TTL and unique indexes must be pasted separately.", "Copy this cluster’s connection string to the clipboard": "Copy this cluster’s connection string to the clipboard", + "Copy what you need and open a new tab.": "Copy what you need and open a new tab.", "Copy with password": "Copy with password", "Copy without password": "Copy without password", "Copy-and-Merge": "Copy-and-Merge", @@ -2714,6 +2715,7 @@ "Service Discovery for MongoDB Atlas": "Service Discovery for MongoDB Atlas", "Service record (SRV)": "Service record (SRV)", "Service-based fallback target": "Service-based fallback target", + "Session ended": "Session ended", "Session ID is required": "Session ID is required", "sessionId is required for query optimization": "sessionId is required for query optimization", "Set a display name for \"{0}\". The kubeconfig file is not modified. Leave empty to clear the alias.": "Set a display name for \"{0}\". The kubeconfig file is not modified. Leave empty to clear the alias.", @@ -3035,7 +3037,6 @@ "The connection succeeded, but the database-list request returned no databases visible to this user.": "The connection succeeded, but the database-list request returned no databases visible to this user.", "The connection succeeded, but the server denied the database-list request used by the extension.": "The connection succeeded, but the server denied the database-list request used by the extension.", "The connection update may be incomplete. Check the saved settings before reconnecting.": "The connection update may be incomplete. Check the saved settings before reconnecting.", - "The connection was closed while you were signing in.": "The connection was closed while you were signing in.", "The connection works, but these checks need attention:": "The connection works, but these checks need attention:", "The connections to remove changed. Refresh the tree and try again.": "The connections to remove changed. Refresh the tree and try again.", "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".": "The container and its data volume will be permanently removed. All data, logs, and the auto-generated credentials will be lost. This cannot be undone. You can recreate a fresh instance any time with \"Set up DocumentDB Local\".", @@ -3289,6 +3290,7 @@ "This connection is being updated. Run the script again when the update finishes.": "This connection is being updated. Run the script again when the update finishes.", "This connection is being updated. Run your command again when the update finishes.": "This connection is being updated. Run your command again when the update finishes.", "This connection is disconnected. Reconnect from the tree, then run the script again.": "This connection is disconnected. Reconnect from the tree, then run the script again.", + "This connection is no longer available for that action. Refresh the tree and try again.": "This connection is no longer available for that action. Refresh the tree and try again.", "This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.": "This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.", "This connection is unavailable.": "This connection is unavailable.", "This connection is unavailable. Reconnect from the tree, then run the script again.": "This connection is unavailable. Reconnect from the tree, then run the script again.", diff --git a/src/commands/disconnect/disconnect.test.ts b/src/commands/disconnect/disconnect.test.ts index 234f6b428..a50b7d8ac 100644 --- a/src/commands/disconnect/disconnect.test.ts +++ b/src/commands/disconnect/disconnect.test.ts @@ -27,7 +27,10 @@ vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegister 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() })); +vi.mock(import('../retryAuthentication/retryAuthentication'), async (importOriginal) => ({ + ...(await importOriginal()), + refreshAuthenticationNode: vi.fn(), +})); function actionContext(): IActionContext { return { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; @@ -52,34 +55,33 @@ describe('tree disconnect recovery', () => { vi.mocked(getRegisteredShellTerminals).mockReturnValue([]); }); - it.each([disconnect, connectDisconnected])( + it.each([ + [disconnect, 'connectionRemoved'], + [connectDisconnected, 'identityChanged'], + ] as const)( '%s rejects removed or changed stale actions after refreshing once', - async (command): Promise => { - 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(); - - command(context, node); - - expect(ClustersClient.getLatchReason).toHaveBeenCalledWith('stable-cluster'); - expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); - expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); - expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - reason === 'connectionRemoved' - ? 'This connection was removed. Choose another connection.' - : 'This connection changed. Refresh the tree and try again.', - { modal: true }, - ); - expect(context.errorHandling.suppressDisplay).toBe(true); - expect(teardownConnection).not.toHaveBeenCalled(); - expect(ClustersClient.unlatch).not.toHaveBeenCalled(); - expect(ext.state.notifyChildrenChanged).not.toHaveBeenCalled(); + async (command, reason): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + if (command === disconnect) { + vi.mocked(ClustersClient.exists).mockReturnValue(false); } + const context = actionContext(); + const node = clusterNode(); + + await command(context, node); + + expect(ClustersClient.getLatchReason).toHaveBeenCalledWith('stable-cluster'); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + expect(ext.state.notifyChildrenChanged).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); }, ); diff --git a/src/commands/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts index ea0c02eaa..46a7ccfba 100644 --- a/src/commands/disconnect/disconnect.ts +++ b/src/commands/disconnect/disconnect.ts @@ -4,7 +4,6 @@ *--------------------------------------------------------------------------------------------*/ 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'; @@ -14,7 +13,7 @@ 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'; +import { refreshAuthenticationNode, showObsoleteTreeAction } from '../retryAuthentication/retryAuthentication'; function isClusterNode(node: TreeElement | undefined): node is ClusterItemBase { return node instanceof ClusterItemBase; @@ -49,15 +48,7 @@ export async function disconnect(context: IActionContext, node?: TreeElement): P throw new UserCancelledError(); } refreshAuthenticationNode(node); - if (reason === 'connectionRemoved' || reason === 'credentialsChanged' || reason === 'identityChanged') { - context.errorHandling.suppressDisplay = true; - void window.showErrorMessage( - reason === 'connectionRemoved' - ? l10n.t('This connection was removed. Choose another connection.') - : l10n.t('This connection changed. Refresh the tree and try again.'), - { modal: true }, - ); - } + showObsoleteTreeAction(context, reason); return; } @@ -81,15 +72,7 @@ export function connectDisconnected(context: IActionContext, node?: TreeElement) return; } refreshAuthenticationNode(node); - if (reason === 'connectionRemoved' || reason === 'credentialsChanged' || reason === 'identityChanged') { - context.errorHandling.suppressDisplay = true; - void window.showErrorMessage( - reason === 'connectionRemoved' - ? l10n.t('This connection was removed. Choose another connection.') - : l10n.t('This connection changed. Refresh the tree and try again.'), - { modal: true }, - ); - } + showObsoleteTreeAction(context, reason); return; } diff --git a/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts index 5f7876887..afa37a256 100644 --- a/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts +++ b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts @@ -86,23 +86,20 @@ 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('does not sample a replacement after retirement during availability', async (): 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); + 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(); @@ -153,7 +150,7 @@ it('does not resolve or sample for a pre-aborted request with no cached client', it('does not sample or send for a retired binding with no cached client', async (): Promise => { vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); - retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + retireConnectionBindings(binding.clusterId, binding.generation); await expect(generateQuery(context, queryContext)).rejects.toBeInstanceOf(UserCancelledError); expect(sampleDocuments).not.toHaveBeenCalled(); @@ -217,7 +214,7 @@ it('does not sample after retirement during collection listing', async (): Promi listCollections.mockReturnValueOnce(listing.promise); const pending = generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }); await vi.waitFor(() => expect(listCollections).toHaveBeenCalledOnce()); - retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + retireConnectionBindings(binding.clusterId, binding.generation); listing.resolve([{ name: 'first' }]); await expect(pending).rejects.toBeInstanceOf(UserCancelledError); @@ -230,7 +227,7 @@ it('does not send after retirement during prompt preparation', async (): Promise 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'); + retireConnectionBindings(binding.clusterId, binding.generation); template.resolve('Fake prompt'); await expect(pending).rejects.toBeInstanceOf(UserCancelledError); @@ -267,7 +264,7 @@ it('cancels a model response after retirement even when the fake model ignores a 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'); + retireConnectionBindings(binding.clusterId, binding.generation); 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); diff --git a/src/commands/playground/newPlayground.test.ts b/src/commands/playground/newPlayground.test.ts index 17ccb453c..99c338dc2 100644 --- a/src/commands/playground/newPlayground.test.ts +++ b/src/commands/playground/newPlayground.test.ts @@ -156,7 +156,7 @@ describe('Playground origin handoffs', () => { clusterDisplayName: 'Cluster', databaseName: 'database', }); - retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + retireConnectionBindings(binding.clusterId, binding.generation); shellCurrent = false; vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); if (replacement === 'disconnect') { @@ -240,7 +240,7 @@ describe('Playground origin handoffs', () => { }); it('still permits an explicit connection re-pick after rejecting an old handoff', async (): Promise => { - retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + retireConnectionBindings(binding.clusterId, binding.generation); vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, fingerprint: 'replacement', diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index 34219bf61..32e580425 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -7,7 +7,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import type * as vscode from 'vscode'; -import { window } from 'vscode'; +import { commands, window } from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; @@ -459,7 +459,7 @@ describe('retryAuthentication', () => { }, ); - it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged', 'userDisconnected'] as const)( + it.each(['connectionRemoved', 'userDisconnected'] as const)( 'refreshes a stale Retry for %s without clearing another latch or doing auth work', async (reason): Promise => { const node = ruNode(); @@ -479,9 +479,7 @@ describe('retryAuthentication', () => { vi.mocked(window.showErrorMessage), ); expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - reason === 'connectionRemoved' - ? 'This connection was removed. Choose another connection.' - : 'This connection changed. Refresh the tree and try again.', + 'This connection is no longer available for that action. Refresh the tree and try again.', { modal: true }, ); expect(context.errorHandling.suppressDisplay).toBe(true); @@ -491,17 +489,20 @@ describe('retryAuthentication', () => { expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); }, ); - it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged', undefined] as const)( + it.each(['credentialsChanged', undefined] as const)( 'discards a replacement key when %s supersedes the read', async (reason): Promise => { const node = ruNode(); vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + vi.mocked(ext.discoveryBranchDataProvider.refresh).mockImplementationOnce(() => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + }); node.readReplacementKey.mockImplementationOnce(async () => { vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); return { connectionString: 'mongodb://test', availableAuthMethods: [AuthMethodId.NativeAuth], @@ -512,14 +513,12 @@ describe('retryAuthentication', () => { await retryAuthentication(actionContext as never, node); expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); - if (reason) { + if (reason === 'credentialsChanged') { expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledBefore( vi.mocked(window.showErrorMessage), ); expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - reason === 'connectionRemoved' - ? 'This connection was removed. Choose another connection.' - : 'This connection changed. Refresh the tree and try again.', + 'This connection is no longer available for that action. Refresh the tree and try again.', { modal: true }, ); } else { @@ -529,6 +528,7 @@ describe('retryAuthentication', () => { expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); expect(node.readReplacementKey).toHaveBeenCalledTimes(1); + expect(commands.executeCommand).not.toHaveBeenCalled(); }, ); @@ -549,47 +549,72 @@ describe('retryAuthentication', () => { if (cancelled) { expect(window.showErrorMessage).not.toHaveBeenCalled(); } else { + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledBefore( + vi.mocked(window.showErrorMessage), + ); expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - 'This connection was removed. Choose another connection.', + 'This connection is no longer available for that action. Refresh the tree and try again.', { modal: true }, ); } expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); }, ); - it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged'] as const)( - 'refreshes and explains %s after an obsolete client close without closing again', - async (reason): Promise => { - const node = { - id: 'connectionsView/folder/stale', - cluster: { clusterId: 'stale' }, - getTreeItem, - lastConnectionFailureKind: 'clientClosed' as const, + it('refreshes and explains an obsolete client close without closing again', async (): Promise => { + const node = { + id: 'connectionsView/folder/stale', + cluster: { clusterId: 'stale' }, + getTreeItem, + lastConnectionFailureKind: 'clientClosed' as const, + }; + vi.mocked(ClustersClient.hasReusableClient).mockReturnValueOnce(false); + vi.mocked(ClustersClient.deleteClient).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('identityChanged'); + }); + + await retryAuthentication(actionContext as never, node); + + expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stale'); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledBefore(vi.mocked(window.showErrorMessage)); + expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('discards a stale replacement key without feedback for an unsupported view', async (): Promise => { + const node = { ...ruNode(), id: 'azureWorkspaceView/ru' }; + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + node.readReplacementKey.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + return { + connectionString: 'mongodb://test', + availableAuthMethods: [AuthMethodId.NativeAuth], + nativeAuthConfig: { connectionUser: 'test', connectionPassword: 'replacement' }, }; - vi.mocked(ClustersClient.hasReusableClient).mockReturnValueOnce(false); - vi.mocked(ClustersClient.deleteClient).mockImplementationOnce(async () => { - vi.mocked(ClustersClient.getEpoch).mockReturnValueOnce(0).mockReturnValueOnce(1); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); - }); + }); - await retryAuthentication(actionContext as never, node); + await retryAuthentication(actionContext as never, node); - expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stale'); - expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); - expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledBefore( - vi.mocked(window.showErrorMessage), - ); - expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - reason === 'connectionRemoved' - ? 'This connection was removed. Choose another connection.' - : 'This connection changed. Refresh the tree and try again.', - { modal: true }, - ); - expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); - expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); - expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); - }, - ); + expect(node.readReplacementKey).toHaveBeenCalledOnce(); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.azureResourcesRUBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.azureResourcesVCoreBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(window.showErrorMessage).not.toHaveBeenCalled(); + expect(commands.executeCommand).not.toHaveBeenCalled(); + }); }); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index fce626367..b5d1b60c5 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -8,6 +8,7 @@ import { l10n, window } from 'vscode'; import { classifyResolutionFailure } from '../../connectionDiagnostics/checks/resolveTarget'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { addEstablishedConnectionContext, ClustersClient } from '../../documentdb/ClustersClient'; +import { type ConnectionUnavailableReason } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { inferViewIdFromTreeId, Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; @@ -67,6 +68,25 @@ function failedStartupCorrelationIdOf(node: RetryableTreeNode): string | undefin return typeof clusterId === 'string' ? ClustersClient.getLastFailedStartupCorrelationId(clusterId) : undefined; } +export function showObsoleteTreeAction( + context: IActionContext, + reason: ConnectionUnavailableReason | undefined, + includeDisconnected = false, +): void { + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' || + (includeDisconnected && reason === 'userDisconnected') + ) { + context.errorHandling.suppressDisplay = true; + void window.showErrorMessage( + l10n.t('This connection is no longer available for that action. Refresh the tree and try again.'), + { modal: true }, + ); + } +} + export async function retryAuthentication(context: IActionContext, node: RetryableTreeNode): Promise { if (!node?.id) { throw new Error(l10n.t('No node selected.')); @@ -86,23 +106,21 @@ export async function retryAuthentication(context: IActionContext, node: Retryab (viewId === Views.AzureResourcesView && (containsDelimited(node.contextValue, 'ruBranch') || containsDelimited(node.contextValue, 'documentDbBranch'))); - let epoch = ClustersClient.getEpoch(clusterId); - const latch = ClustersClient.getLatchReason(clusterId); - const kind = latch === 'credentialsRejected' ? latch : node.lastConnectionFailureKind; - if (latch && latch !== 'credentialsRejected') { + const reportObsolete = (reason?: ConnectionUnavailableReason, error?: unknown): void => { if (!supportsRefresh) { return; } refreshAuthenticationNode(node); - if (latch === 'connectionRemoved' || latch === 'credentialsChanged' || latch === 'identityChanged') { - context.errorHandling.suppressDisplay = true; - void window.showErrorMessage( - latch === 'connectionRemoved' - ? l10n.t('This connection was removed. Choose another connection.') - : l10n.t('This connection changed. Refresh the tree and try again.'), - { modal: true }, - ); + const currentReason = reason ?? ClustersClient.getLatchReason(clusterId); + if (!(error instanceof UserCancelledError)) { + showObsoleteTreeAction(context, currentReason); } + }; + let epoch = ClustersClient.getEpoch(clusterId); + const latch = ClustersClient.getLatchReason(clusterId); + const kind = latch === 'credentialsRejected' ? latch : node.lastConnectionFailureKind; + if (latch && latch !== 'credentialsRejected') { + reportObsolete(latch); return; } addEstablishedConnectionContext(context.telemetry, clusterId); @@ -128,25 +146,7 @@ export async function retryAuthentication(context: IActionContext, node: Retryab credentials = await node.readReplacementKey(context); } catch (error) { if (ClustersClient.getEpoch(clusterId) !== epoch) { - if (!supportsRefresh) { - return; - } - refreshAuthenticationNode(node); - const reason = ClustersClient.getLatchReason(clusterId); - if ( - !(error instanceof UserCancelledError) && - (reason === 'connectionRemoved' || - reason === 'credentialsChanged' || - reason === 'identityChanged') - ) { - context.errorHandling.suppressDisplay = true; - void window.showErrorMessage( - reason === 'connectionRemoved' - ? l10n.t('This connection was removed. Choose another connection.') - : l10n.t('This connection changed. Refresh the tree and try again.'), - { modal: true }, - ); - } + reportObsolete(undefined, error); return; } if (error instanceof UserCancelledError) { @@ -171,20 +171,7 @@ export async function retryAuthentication(context: IActionContext, node: Retryab throw error; } if (ClustersClient.getEpoch(clusterId) !== epoch) { - if (!supportsRefresh) { - return; - } - refreshAuthenticationNode(node); - const reason = ClustersClient.getLatchReason(clusterId); - if (reason === 'connectionRemoved' || reason === 'credentialsChanged' || reason === 'identityChanged') { - context.errorHandling.suppressDisplay = true; - void window.showErrorMessage( - reason === 'connectionRemoved' - ? l10n.t('This connection was removed. Choose another connection.') - : l10n.t('This connection changed. Refresh the tree and try again.'), - { modal: true }, - ); - } + reportObsolete(); return; } // One fresh ARM read per explicit click. A subsequent database rejection re-latches in @@ -210,20 +197,7 @@ export async function retryAuthentication(context: IActionContext, node: Retryab epoch = ClustersClient.getEpoch(clusterId); await closing; if (ClustersClient.getEpoch(clusterId) !== epoch) { - if (!supportsRefresh) { - return; - } - refreshAuthenticationNode(node); - const reason = ClustersClient.getLatchReason(clusterId); - if (reason === 'connectionRemoved' || reason === 'credentialsChanged' || reason === 'identityChanged') { - context.errorHandling.suppressDisplay = true; - void window.showErrorMessage( - reason === 'connectionRemoved' - ? l10n.t('This connection was removed. Choose another connection.') - : l10n.t('This connection changed. Refresh the tree and try again.'), - { modal: true }, - ); - } + reportObsolete(); return; } } diff --git a/src/commands/runBoundNamespaceCommand.test.ts b/src/commands/runBoundNamespaceCommand.test.ts index ea58caab2..9de2ef6fd 100644 --- a/src/commands/runBoundNamespaceCommand.test.ts +++ b/src/commands/runBoundNamespaceCommand.test.ts @@ -93,10 +93,10 @@ it.each(createEffects)('does not create a $name after its binding lifetime ends const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); expect(replacement[effect.method]).not.toHaveBeenCalled(); - retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + retireConnectionBindings(binding.clusterId, binding.generation); resolution.resolve(replacement.client); - await expect(pending).rejects.toMatchObject({ reason: 'credentialsChanged' }); + await expect(pending).rejects.toMatchObject({ reason: 'sessionEnded' }); expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); expect(replacement[effect.method]).not.toHaveBeenCalled(); expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); @@ -131,11 +131,11 @@ it.each(createEffects)('does not revive a retired $name binding when its teardow const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); ClustersClient.latch(binding.clusterId, 'credentialsChanged'); - retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + retireConnectionBindings(binding.clusterId, binding.generation); ClustersClient.unlatch(binding.clusterId); resolution.resolve(replacement.client); - await expect(pending).rejects.toMatchObject({ reason: 'credentialsChanged' }); + await expect(pending).rejects.toMatchObject({ reason: 'sessionEnded' }); expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); expect(replacement[effect.method]).not.toHaveBeenCalled(); expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); diff --git a/src/commands/saveConnectionEdit.test.ts b/src/commands/saveConnectionEdit.test.ts index f3e65d963..cf923a404 100644 --- a/src/commands/saveConnectionEdit.test.ts +++ b/src/commands/saveConnectionEdit.test.ts @@ -275,7 +275,7 @@ describe('disconnected connection edits', () => { }); expect(changed).toBe(true); - expect(getRetiredBindingReason(original.binding)).toBe('credentialsChanged'); + expect(getRetiredBindingReason(original.binding)).toBe('sessionEnded'); }); it('preserves an explicit Disconnect retirement when the edit boundary is reached', async (): Promise => { @@ -284,7 +284,7 @@ describe('disconnected connection edits', () => { await saveConnectionEdit(node, async (): Promise => false); - expect(getRetiredBindingReason(original.binding)).toBe('userDisconnected'); + expect(getRetiredBindingReason(original.binding)).toBe('sessionEnded'); }); it.each([ @@ -432,12 +432,12 @@ describe('disconnected connection edits', () => { expect(connected).not.toBe(original); expect(connected?.generation).toBeGreaterThan(original.generation); expect(driverConnect).toHaveBeenCalledTimes(2); - expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); 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', + reason: 'sessionEnded', }); if (!connected) { throw new Error('Expected refresh to open a fresh connection.'); diff --git a/src/commands/saveConnectionEdit.ts b/src/commands/saveConnectionEdit.ts index 0a81abaca..84d0dd6db 100644 --- a/src/commands/saveConnectionEdit.ts +++ b/src/commands/saveConnectionEdit.ts @@ -53,7 +53,7 @@ export async function saveConnectionEdit( throw new UserCancelledError(); } - ClustersClient.retireBoundViews(clusterId, 'credentialsChanged'); + ClustersClient.retireBoundViews(clusterId); const epoch = ClustersClient.getEpoch(clusterId); const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; let changed = false; diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index d75989a1f..1f391565b 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -60,7 +60,10 @@ vi.mock('../../documentdb/auth/MicrosoftEntraIDAuthHandler', () => ({ } }, })); -vi.mock('../retryAuthentication/retryAuthentication', () => ({ refreshAuthenticationNode: vi.fn() })); +vi.mock(import('../retryAuthentication/retryAuthentication'), async (importOriginal) => ({ + ...(await importOriginal()), + refreshAuthenticationNode: vi.fn(), +})); vi.mock('../../documentdb/showClusterConnectFailure', () => ({ showClusterConnectFailure: vi.fn() })); function actionContext(): IActionContext { @@ -246,57 +249,34 @@ describe('signInAgain', () => { } as ClusterItemBase; } - describe.each(['connectionRemoved', 'credentialsChanged', 'identityChanged'] as const)( - 'when %s supersedes a dismissed session acquisition', - (reason): void => { - it.each([undefined, new Error('User did not consent to login.')])( - 'keeps genuine tree dismissal quiet (%s)', - async (error): Promise => { - vi.mocked(getEntraSession).mockImplementationOnce(async () => { - vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); - if (error) { - throw error; - } - return undefined; - }); - - await expect(signInAgain(actionContext(), treeNode())).rejects.toBeInstanceOf(UserCancelledError); - - expect(getEntraSession).toHaveBeenCalledTimes(1); - expect(refreshAuthenticationNode).not.toHaveBeenCalled(); - expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); - expect(showClusterConnectFailure).not.toHaveBeenCalled(); - expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); - }, - ); + it.each([ + ['tree', undefined, 'connectionRemoved'], + ['worker', new Error('User did not consent to login.'), 'identityChanged'], + ] as const)('keeps a superseded %s dismissal quiet', async (caller, error, reason): Promise => { + if (caller === 'worker') { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + } + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + if (error) { + throw error; + } + return undefined; + }); - it.each([undefined, new Error('User did not consent to login.')])( - 'keeps genuine worker dismissal quiet (%s)', - async (error): Promise => { - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); - vi.mocked(getEntraSession).mockImplementationOnce(async () => { - vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); - if (error) { - throw error; - } - return undefined; - }); - - await expect(signInAgainForWorker(actionContext(), clusterId, pin)).rejects.toBeInstanceOf( - UserCancelledError, - ); - - expect(getEntraSession).toHaveBeenCalledTimes(1); - expect(refreshAuthenticationNode).not.toHaveBeenCalled(); - expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); - expect(showClusterConnectFailure).not.toHaveBeenCalled(); - expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); - }, - ); - }, - ); + const pending = + caller === 'tree' + ? signInAgain(actionContext(), treeNode()) + : signInAgainForWorker(actionContext(), clusterId, pin); + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + + expect(getEntraSession).toHaveBeenCalledTimes(1); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); it('preserves a noncancellation session acquisition error', async (): Promise => { const error = new Error('Session acquisition failed'); @@ -309,55 +289,115 @@ describe('signInAgain', () => { expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); }); - it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged'] as const)( - 'refreshes and explains an explicit stale tree sign-in for %s without auth work', - async (reason): Promise => { - const context = actionContext(); - const node = treeNode(); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + it('refreshes and explains an explicit stale tree sign-in without auth work', async (): Promise => { + const context = actionContext(); + const node = treeNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsChanged'); - await signInAgain(context, node); + await signInAgain(context, node); - expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); - expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); - expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - reason === 'connectionRemoved' - ? 'This connection was removed. Choose another connection.' - : 'This connection changed. Refresh the tree and try again.', - { modal: true }, - ); - expect(context.errorHandling.suppressDisplay).toBe(true); - expect(getEntraSession).not.toHaveBeenCalled(); - expect(mocks.configureAuth).not.toHaveBeenCalled(); - expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); - expect(showClusterConnectFailure).not.toHaveBeenCalled(); - }, - ); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(mocks.configureAuth).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); - it.each([ - ['connectionRemoved', 'This connection was removed. Choose another connection.'], - ['credentialsChanged', 'This connection changed. Refresh the tree and try again.'], - ['identityChanged', 'This connection changed. Refresh the tree and try again.'], - ['userDisconnected', 'The connection was closed while you were signing in.'], - ] as const)( - 'refreshes before the accurate modal when %s supersedes a pending tree sign-in', - async (reason, message): Promise => { - const node = treeNode(); - vi.mocked(getEntraSession).mockImplementationOnce(async () => { - vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); - return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; - }); + it('refreshes before feedback when Disconnect supersedes a pending tree sign-in', async (): Promise => { + const node = treeNode(); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); - await signInAgain(actionContext(), node); + await signInAgain(actionContext(), node); - expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); - expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); - expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(message, { modal: true }); - expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); - expect(showClusterConnectFailure).not.toHaveBeenCalled(); - }, - ); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('reports an obsolete provider failure instead of its superseded guidance', async (): Promise => { + const node = treeNode(); + mocks.configureAuth.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('identityChanged'); + throw new EntraSignInRequiredError('providerChanged'); + }); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('refreshes once when Disconnect supersedes sign-in startup', async (): Promise => { + const node = treeNode(); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); + vi.mocked(ClustersClient.startAfterSignIn).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + return undefined; + }); + + await signInAgain(actionContext(), node); + + expect(ClustersClient.startAfterSignIn).toHaveBeenCalledTimes(1); + expect(ClustersClient.getExistingClient).not.toHaveBeenCalled(); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is no longer available for that action. Refresh the tree and try again.', + { modal: true }, + ); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); + + it('stays quiet when synchronous stale refresh clears the reason', async (): Promise => { + const context = actionContext(); + const node = treeNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + vi.mocked(refreshAuthenticationNode).mockImplementationOnce(() => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + }); + + await signInAgain(context, node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).not.toBe(true); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(mocks.configureAuth).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); + }); it('refreshes an epoch-only stale tree sign-in quietly', async (): Promise => { const node = treeNode(); @@ -410,7 +450,7 @@ describe('signInAgain', () => { expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( - 'This connection was removed. Choose another connection.', + 'This connection is no longer available for that action. Refresh the tree and try again.', { modal: true }, ); expect(getEntraSession).not.toHaveBeenCalled(); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index f7be417d2..a49af136f 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -21,7 +21,7 @@ import { CredentialCache } from '../../documentdb/CredentialCache'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { Views } from '../../documentdb/Views'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; -import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; +import { refreshAuthenticationNode, showObsoleteTreeAction } from '../retryAuthentication/retryAuthentication'; interface WorkerSignInResult { readonly identity: VerifiedEntraIdentity; @@ -106,24 +106,7 @@ async function signInAgainInternal( refreshAuthenticationNode(node); } const currentReason = ClustersClient.getLatchReason(clusterId); - if ( - currentReason === 'connectionRemoved' || - currentReason === 'credentialsChanged' || - currentReason === 'identityChanged' - ) { - context.errorHandling.suppressDisplay = true; - void vscode.window.showErrorMessage( - currentReason === 'connectionRemoved' - ? vscode.l10n.t('This connection was removed. Choose another connection.') - : vscode.l10n.t('This connection changed. Refresh the tree and try again.'), - { modal: true }, - ); - } else if (currentReason === 'userDisconnected' && reason !== 'userDisconnected') { - context.errorHandling.suppressDisplay = true; - void vscode.window.showErrorMessage(vscode.l10n.t('The connection was closed while you were signing in.'), { - modal: true, - }); - } + showObsoleteTreeAction(context, currentReason, reason !== 'userDisconnected'); }; if (reason && reason !== 'credentialsRejected') { reportClosed(); diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 535c168ae..4ca0b26e7 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -9,14 +9,13 @@ import { type IActionContext, type callWithTelemetryAndErrorHandling, } from '@microsoft/vscode-azext-utils'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { API, DocumentDBExperience } from '../../DocumentDBExperiences'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; -import { registerConnectionSurface } from '../../documentdb/connectionSurfaces'; import { type AuthenticateWizardContext } from '../../documentdb/wizards/authenticate/AuthenticateWizardContext'; import { ChooseAuthMethodStep } from '../../documentdb/wizards/authenticate/ChooseAuthMethodStep'; import { ext } from '../../extensionVariables'; @@ -146,7 +145,6 @@ const showWarningMessage: ( ...items: string[] ) => Thenable = vscode.window.showWarningMessage; const showWarning = vi.mocked(showWarningMessage); -const registrations: vscode.Disposable[] = []; function makeContext(): IActionContext { return { @@ -237,12 +235,6 @@ 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], @@ -352,8 +344,8 @@ describe('updateConnectionString rejected-destination recovery', () => { expect(capturedContexts[0].connectionStringSaved).toBe(true); expect(storedConnection.secrets.connectionString).toBe(approvedUri); - expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(1, 'stable-id', 'userDisconnected'); - expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(2, 'stable-id', 'credentialsChanged'); + expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(1, 'stable-id'); + expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(2, 'stable-id'); expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { alreadyInvalidated: true }); expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(resetError).not.toHaveBeenCalled(); @@ -383,55 +375,17 @@ describe('updateConnectionString rejected-destination recovery', () => { ); }); - 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'), - ); - } + it('does not begin the wizard or save when Disconnect is declined', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + showWarning.mockResolvedValueOnce(undefined); - 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(); - }, - ); + await expect(updateConnectionString(makeContext(), item)).rejects.toBeInstanceOf(UserCancelledError); + + expect(capturedContexts).toHaveLength(0); + expect(showInputBox).not.toHaveBeenCalled(); + expect(ConnectionStorageService.get).not.toHaveBeenCalled(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + }); it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { vi.mocked(ClustersClient.exists).mockReturnValue(true); @@ -444,40 +398,4 @@ describe('updateConnectionString rejected-destination recovery', () => { 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/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index 87e5701b8..d7aa58e42 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -4,11 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import { UserCancelledError, type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { 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'; @@ -40,7 +39,6 @@ const showWarningMessage: ( ...items: string[] ) => Thenable = vscode.window.showWarningMessage; const showWarning = vi.mocked(showWarningMessage); -const registrations: vscode.Disposable[] = []; let epoch = 0; let latch: ReturnType; @@ -149,12 +147,6 @@ beforeEach(() => { capturedContexts.length = 0; }); -afterEach((): void => { - for (const registration of registrations.splice(0)) { - registration.dispose(); - } -}); - async function inferMethods( host: string, suffix?: string, @@ -317,8 +309,8 @@ 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).toHaveBeenNthCalledWith(1, node.cluster.clusterId, 'userDisconnected'); - expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId, 'credentialsChanged'); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId); expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { alreadyInvalidated: true }); expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); expect(mockDeleteClient).toHaveBeenCalledBefore(mockPrompt); @@ -340,8 +332,8 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); - expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId, 'userDisconnected'); - expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId, 'credentialsChanged'); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId); expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'userDisconnected'); if (saved) { expect(ClustersClient.unlatch).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); @@ -374,8 +366,8 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); expect(capturedContexts[0].credentialsSaved).not.toBe(true); - expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId, 'userDisconnected'); - expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId, 'credentialsChanged'); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId); expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( 'The connection update may be incomplete. Check the saved settings before reconnecting.', ); @@ -515,53 +507,17 @@ 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')); - } + it('does not begin the wizard or save when Disconnect is declined', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + showWarning.mockResolvedValueOnce(undefined); - 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(); - }, - ); + await expect(updateCredentials(context, node)).rejects.toBeInstanceOf(UserCancelledError); + + expect(capturedContexts).toHaveLength(0); + expect(mockPrompt).not.toHaveBeenCalled(); + expect(mockGet).not.toHaveBeenCalled(); + expect(mockSave).not.toHaveBeenCalled(); + }); it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { vi.mocked(ClustersClient.exists).mockReturnValue(true); @@ -575,46 +531,6 @@ describe('updateCredentials post-wizard updates', () => { 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++; diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index bfd079d48..c4389e57c 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -447,23 +447,31 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getBinding(clusterId)).toBe(current.binding); }); - it('does not let a retired view use a new client with the same fingerprint', async (): Promise => { + it('keeps a disconnected view retired after same-account reconnect while fresh work runs once', async (): Promise => { const old = await ClustersClient.connectInteractive(clusterId); const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); - ClustersClient.latch(clusterId, 'credentialsUpdating'); + ClustersClient.latch(clusterId, 'userDisconnected'); ClustersClient.retireBoundViews(clusterId); await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); ClustersClient.unlatch(clusterId); await expect(ClustersClient.resolveBoundClient(old.binding)).rejects.toMatchObject({ - reason: 'credentialsChanged', + reason: 'sessionEnded', }); expect(mockConnect).toHaveBeenCalledOnce(); const current = await ClustersClient.getClient(clusterId); expect(current.binding.fingerprint).toBe(old.binding.fingerprint); expect(current.generation).toBeGreaterThan(old.generation); - expect(() => session.assertAvailable()).toThrow(expect.objectContaining({ reason: 'credentialsChanged' })); + expect(() => session.assertAvailable()).toThrow(expect.objectContaining({ reason: 'sessionEnded' })); await expect(ClustersClient.resolveBoundClient(current.binding)).resolves.toBe(current); + const operation = vi.fn(async (client: ClustersClient): Promise => client); + await expect(runWithClient(old.binding, operation)).resolves.toEqual({ + unavailable: { reason: 'sessionEnded' }, + }); + expect(operation).not.toHaveBeenCalled(); + await expect(runWithClient(current.binding, operation)).resolves.toBe(current); + expect(operation).toHaveBeenCalledExactlyOnceWith(current); + expect(mockConnect).toHaveBeenCalledTimes(2); }); it.each([false, true])( @@ -476,7 +484,7 @@ describe('regular connection startup diagnostics', () => { await handshake.started; ClustersClient.latch(clusterId, 'userDisconnected'); - ClustersClient.retireBoundViews(clusterId, 'userDisconnected'); + ClustersClient.retireBoundViews(clusterId); await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); if (changedIdentity) { CredentialCache.setAuthCredentials( @@ -491,7 +499,7 @@ describe('regular connection startup diagnostics', () => { handshake.resolve(); await expect(opening).rejects.toMatchObject({ - reason: changedIdentity ? 'identityChanged' : 'userDisconnected', + reason: changedIdentity ? 'identityChanged' : 'sessionEnded', }); expect(ClusterSession._sessions.size).toBe(0); expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 78642b3a5..9a5fff1ed 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -54,11 +54,7 @@ import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; import { emitTokenRenewal } from './auth/tokenRenewalTelemetry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; -import { - getRetiredBindingReason, - retireConnectionBindings, - type EndedLifetimeReason, -} from './connectionBindingRetirement'; +import { getRetiredBindingReason, retireConnectionBindings } from './connectionBindingRetirement'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; @@ -917,9 +913,9 @@ export class ClustersClient { return client; } - public static retireBoundViews(clusterId: string, reason: EndedLifetimeReason = 'credentialsChanged'): number { + public static retireBoundViews(clusterId: string): number { const generation = ClustersClient._generations.get(clusterId) ?? 0; - retireConnectionBindings(clusterId, generation, reason); + retireConnectionBindings(clusterId, generation); return generation; } diff --git a/src/documentdb/ConnectionUnavailableError.ts b/src/documentdb/ConnectionUnavailableError.ts index 45c9fd6f3..4778e59a9 100644 --- a/src/documentdb/ConnectionUnavailableError.ts +++ b/src/documentdb/ConnectionUnavailableError.ts @@ -14,7 +14,8 @@ export type ConnectionUnavailableReason = | 'identityChanged' | 'userDisconnected' | 'connectionRemoved' - | 'unreachable'; + | 'unreachable' + | 'sessionEnded'; export function isDiagnosticAuthenticationHold(reason: ConnectionUnavailableReason | undefined): boolean { return reason === 'credentialsRejected' || reason === 'signInRequired' || reason === 'credentialsMissing'; diff --git a/src/documentdb/connectionBindingRetirement.test.ts b/src/documentdb/connectionBindingRetirement.test.ts index b1e446832..07367415e 100644 --- a/src/documentdb/connectionBindingRetirement.test.ts +++ b/src/documentdb/connectionBindingRetirement.test.ts @@ -7,9 +7,9 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { ClustersClient, type ConnectionBinding } from './ClustersClient'; import { - correctFailedRemovalRetirement, getBindingLifetimeSignal, getRetiredBindingReason, + isLatestRetirement, isRetiredConnectionBinding, retireConnectionBindings, } from './connectionBindingRetirement'; @@ -28,14 +28,18 @@ it('keeps same-account physical replacements in one lifetime and aborts it synch const binding = { clusterId: 'lifetime-signal', fingerprint: 'same-account', generation: 1 }; const replacement = { ...binding, generation: 2 }; const signal = getBindingLifetimeSignal(binding); - const abort = vi.fn(); + const abort = vi.fn((): void => { + expect(getRetiredBindingReason(replacement)).toBe('sessionEnded'); + expect(isLatestRetirement(binding.clusterId, replacement.generation)).toBe(true); + expect(getBindingLifetimeSignal({ ...binding, generation: 3 }).aborted).toBe(false); + }); 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'); + retireConnectionBindings(binding.clusterId, replacement.generation); expect(abort).toHaveBeenCalledOnce(); expect(signal.aborted).toBe(true); @@ -46,74 +50,80 @@ it('keeps same-account physical replacements in one lifetime and aborts it synch 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'); +it('keeps the cutoff monotonic without ending the fresh lifetime twice or reviving old bindings', (): void => { + const binding = { clusterId: 'lifetime-cutoff', fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 2); const freshSignal = getBindingLifetimeSignal({ ...binding, generation: 3 }); - retireConnectionBindings(binding.clusterId, 1, 'connectionRemoved'); - retireConnectionBindings(binding.clusterId, 2, 'credentialsChanged'); + const abort = vi.fn(); + freshSignal.addEventListener('abort', abort); + retireConnectionBindings(binding.clusterId, 1); + retireConnectionBindings(binding.clusterId, 2); expect(freshSignal.aborted).toBe(false); - expect(getRetiredBindingReason(binding)).toBe('userDisconnected'); + expect(abort).not.toHaveBeenCalled(); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); - retireConnectionBindings(binding.clusterId, 4, 'connectionRemoved'); + retireConnectionBindings(binding.clusterId, 4); expect(freshSignal.aborted).toBe(true); - expect(getRetiredBindingReason({ ...binding, generation: 2 })).toBe('userDisconnected'); - expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('connectionRemoved'); + expect(abort).toHaveBeenCalledOnce(); + expect(getRetiredBindingReason({ ...binding, generation: 2 })).toBe('sessionEnded'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('sessionEnded'); 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 }; +it('checks latest retirement ownership without reviving signals or affecting the next lifetime', (): void => { + const first = { clusterId: 'failed-removal-cutoff', fingerprint: 'same-account', generation: 1 }; const firstSignal = getBindingLifetimeSignal(first); - retireConnectionBindings(first.clusterId, 1, 'userDisconnected'); + retireConnectionBindings(first.clusterId, 1); const second = { ...first, generation: 2 }; const secondSignal = getBindingLifetimeSignal(second); - retireConnectionBindings(first.clusterId, 2, 'connectionRemoved'); + retireConnectionBindings(first.clusterId, 2); const freshSignal = getBindingLifetimeSignal({ ...first, generation: 3 }); - expect(correctFailedRemovalRetirement(first.clusterId, 2)).toBe(true); - expect(getRetiredBindingReason(first)).toBe('userDisconnected'); - expect(getRetiredBindingReason(second)).toBe('userDisconnected'); + expect(isLatestRetirement(first.clusterId, 2)).toBe(true); + expect(getRetiredBindingReason(first)).toBe('sessionEnded'); + expect(getRetiredBindingReason(second)).toBe('sessionEnded'); 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.objectContaining({ reason: 'sessionEnded' }), ); - expect(correctFailedRemovalRetirement(first.clusterId, 2)).toBe(true); + expect(isLatestRetirement(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('rejects ownership of a missing, wrong or superseded retirement generation', (): void => { + const binding = { clusterId: 'superseded-removal-cutoff', fingerprint: 'same-account', generation: 2 }; + expect(isLatestRetirement(binding.clusterId, 2)).toBe(false); + retireConnectionBindings(binding.clusterId, 2); + expect(isLatestRetirement(binding.clusterId, 1)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + retireConnectionBindings(binding.clusterId, 3); + expect(isLatestRetirement(binding.clusterId, 2)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('sessionEnded'); +}); + +it('retires generation zero while leaving a new lifetime active', (): void => { + const binding = { clusterId: 'generation-zero', fingerprint: 'same-account', generation: 0 }; + const signal = getBindingLifetimeSignal(binding); + expect(getRetiredBindingReason(binding)).toBeUndefined(); + expect(signal.aborted).toBe(false); + expect(isLatestRetirement(binding.clusterId, 0)).toBe(false); + retireConnectionBindings(binding.clusterId, 0); + expect(isLatestRetirement(binding.clusterId, 0)).toBe(true); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal({ ...binding, generation: 1 }).aborted).toBe(false); }); -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 => { +it('checks retirement 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'); + retireConnectionBindings(binding.clusterId, 1); vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue('credentialsRejected'); expect(() => ClustersClient.assertBindingActive(binding)).toThrow( - expect.objectContaining({ reason: 'userDisconnected' }), + expect.objectContaining({ reason: 'sessionEnded' }), ); expect(() => ClustersClient.assertBindingActive({ ...binding, generation: 2 })).toThrow( expect.objectContaining({ reason: 'credentialsRejected' }), @@ -132,9 +142,9 @@ it('rejects a client resolved across retirement before it can reach a driver ope const effect = vi.fn(); const operation = runWithClient(binding, effect); expect(acquisition).toHaveBeenCalledOnce(); - retireConnectionBindings(binding.clusterId, 1, 'connectionRemoved'); + retireConnectionBindings(binding.clusterId, 1); release({ binding: { ...binding, generation: 2 } } as ClustersClient); - await expect(operation).resolves.toEqual({ unavailable: { reason: 'connectionRemoved' } }); + await expect(operation).resolves.toEqual({ unavailable: { reason: 'sessionEnded' } }); expect(effect).not.toHaveBeenCalled(); }); @@ -150,7 +160,7 @@ it('never acquires, polls the database or prompts for an ended binding; a fresh .spyOn(ClustersClient as unknown as { acquireClient: () => Promise }, 'acquireClient') .mockResolvedValue(replacement); const database = vi.fn(async (): Promise => {}); - retireConnectionBindings(binding.clusterId, 1, 'userDisconnected'); + retireConnectionBindings(binding.clusterId, 1); const poll = vi.fn(async (): Promise => { await runWithClient(binding, database, { background: true }); }); diff --git a/src/documentdb/connectionBindingRetirement.ts b/src/documentdb/connectionBindingRetirement.ts index 46f778b63..dddad5cb6 100644 --- a/src/documentdb/connectionBindingRetirement.ts +++ b/src/documentdb/connectionBindingRetirement.ts @@ -5,42 +5,35 @@ import { type ConnectionBinding } from './ClustersClient'; -export type EndedLifetimeReason = 'userDisconnected' | 'connectionRemoved' | 'credentialsChanged'; - interface BindingLifetime { - readonly ended: { readonly generation: number; readonly reason: EndedLifetimeReason }[]; + retiredThrough: number; controller: AbortController; } 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)) { +export function retireConnectionBindings(clusterId: string, generation: number): void { + const lifetime: BindingLifetime = lifetimes.get(clusterId) ?? { + retiredThrough: -1, + controller: new AbortController(), + }; + if (generation <= lifetime.retiredThrough) { return; } - lifetime.ended.push({ generation, reason }); + lifetime.retiredThrough = generation; 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 getRetiredBindingReason({ clusterId, generation }: ConnectionBinding): 'sessionEnded' | undefined { + return generation <= (lifetimes.get(clusterId)?.retiredThrough ?? -1) ? 'sessionEnded' : undefined; } -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 isLatestRetirement(clusterId: string, generation: number): boolean { + return lifetimes.get(clusterId)?.retiredThrough === generation; } export function isRetiredConnectionBinding(binding: ConnectionBinding): boolean { @@ -53,7 +46,7 @@ export function getBindingLifetimeSignal(binding: ConnectionBinding): AbortSigna } let lifetime = lifetimes.get(binding.clusterId); if (!lifetime) { - lifetime = { ended: [], controller: new AbortController() }; + lifetime = { retiredThrough: -1, controller: new AbortController() }; lifetimes.set(binding.clusterId, lifetime); } return lifetime.controller.signal; diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts index 89945a27b..ec9b9add5 100644 --- a/src/documentdb/connectionTeardown.test.ts +++ b/src/documentdb/connectionTeardown.test.ts @@ -11,7 +11,6 @@ import { getBindingLifetimeSignal, getRetiredBindingReason, retireConnectionBindings, - type EndedLifetimeReason, } from './connectionBindingRetirement'; import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; import { @@ -154,8 +153,8 @@ describe('connection teardown', () => { 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); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, binding.generation); return binding.generation; }); const untouchedView = register('documentView', true, otherId); @@ -166,7 +165,7 @@ describe('connection teardown', () => { withConnectionRemoval([clusterId, otherId], async (remove) => { await remove(clusterId, async () => { expect(latches.get(otherId)).toBe('connectionRemoved'); - expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); fresh = register('collectionView'); throw failedDelete; }); @@ -174,8 +173,8 @@ describe('connection teardown', () => { ).rejects.toBe(failedDelete); expect(latches.get(clusterId)).toBe('userDisconnected'); - expect(vi.mocked(draft.disable).mock.calls).toEqual([['connectionRemoved'], ['userDisconnected']]); - expect(getRetiredBindingReason(binding)).toBe('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); expect(signal.aborted).toBe(true); expect(getBindingLifetimeSignal(binding).aborted).toBe(true); expect(getBindingLifetimeSignal({ ...binding, generation: 2 }).aborted).toBe(false); @@ -286,7 +285,7 @@ describe('connection teardown', () => { expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); for (const surface of surfaces) { expect(mocks.latch).toHaveBeenCalledBefore(vi.mocked(surface.disable)); - expect(surface.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(surface.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); expect(surface.dispose).not.toHaveBeenCalled(); } expect(unrelated.disable).not.toHaveBeenCalled(); @@ -343,14 +342,13 @@ describe('connection teardown', () => { if (alreadyLatched) { mocks.getLatchReason.mockReturnValue('connectionRemoved'); } - mocks.retireBoundViews.mockImplementation((id: string, reason: 'connectionRemoved'): number => { + mocks.retireBoundViews.mockImplementation((id: string): number => { expect(alreadyLatched || mocks.latch.mock.calls.length === 1).toBe(true); - retireConnectionBindings(id, 1, reason); + retireConnectionBindings(id, 1); return 1; }); - const onRetired = vi.fn((generation: number, surfaces: readonly ConnectionSurface[]): void => { + const onRetired = vi.fn((generation: number): void => { expect(generation).toBe(1); - expect(surfaces).toEqual([draft]); expect(signal.aborted).toBe(true); expect(getConnectionSurfaces(target)).toEqual([]); expect(draft.disable).not.toHaveBeenCalled(); @@ -379,12 +377,12 @@ describe('connection teardown', () => { refreshTree, }); expect(signal.aborted).toBe(true); - expect(onRetired).toHaveBeenCalledOnce(); + expect(onRetired).toHaveBeenCalledExactlyOnceWith(1); expect(disconnect).toHaveBeenCalledOnce(); expect(refreshTree).not.toHaveBeenCalled(); finishClose(); await expect(teardown).resolves.toBe('committed'); - expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(target); expect(draft.isDirty?.()).toBe(true); }, ); @@ -400,7 +398,7 @@ describe('connection teardown', () => { mocks.getSetting.mockReturnValue('closeAll'); await teardownConnection(clusterId, reason, refreshTree); - expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); expect(draft.isDirty?.()).toBe(true); expect(draft.dispose).not.toHaveBeenCalled(); expect(collection.dispose).not.toHaveBeenCalled(); @@ -414,10 +412,17 @@ describe('connection teardown', () => { ); it.each(['surface', 'startup', 'evaluator', 'shell', 'heldClient'] as const)( - 'tears down surviving %s even when the cached connection is absent or credentials are rejected', + 'requires Disconnect before editing with surviving %s', async (survivor): Promise => { + let epoch = 7; + let latch: ConnectionUnavailableReason | undefined = 'credentialsRejected'; mocks.exists.mockReturnValue(survivor === 'heldClient'); - mocks.getLatchReason.mockReturnValue('credentialsRejected'); + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); const draft = survivor === 'surface' ? register('documentView', true) : undefined; const disconnect = vi.fn(); mocks.hasPendingStartup.mockReturnValue(survivor === 'startup'); @@ -427,14 +432,28 @@ describe('connection teardown', () => { if (survivor === 'shell') { mocks.getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); } - await expect( - commitTeardown(clusterId, { reason: 'userDisconnected', choice: 'keepOpenDisabled', refreshTree }), - ).resolves.toBe('committed'); + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[1]); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).resolves.toBe(8); + + expect(showWarning).toHaveBeenNthCalledWith( + 1, + 'Disconnect?', + { + modal: true, + detail: 'You can only update credentials or the connection string while disconnected.', + }, + 'Disconnect and update', + ); expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); - expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); - expect(mocks.deleteClient).toHaveBeenCalledOnce(); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.deleteClient).toHaveBeenCalledExactlyOnceWith(clusterId, { alreadyInvalidated: true }); + expect(mocks.stopPlaygroundEvaluator).toHaveBeenCalledExactlyOnceWith(clusterId); if (draft) { - expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(draft.dispose).not.toHaveBeenCalled(); } if (survivor === 'shell') { expect(disconnect).toHaveBeenCalledOnce(); @@ -442,6 +461,57 @@ describe('connection teardown', () => { }, ); + it.each(['cancel offer', 'cancel tabs', 'active transfer', 'dirty close refusal', 'close failure'] as const)( + 'blocks editing after %s', + async (outcome): Promise => { + let latch: ConnectionUnavailableReason | undefined; + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + }); + const draft = register('documentView', true); + const task = { taskName: 'Copy orders', taskType: 'copy', cancel: vi.fn() }; + if (outcome === 'active transfer') { + mocks.getConflictingTasks.mockReturnValue([task]); + } else if (outcome !== 'cancel offer') { + showWarning.mockImplementationOnce(async (_message, _options, ...items) => items[0]); + if (outcome === 'dirty close refusal') { + showWarning.mockImplementationOnce(async (_message, _options, ...items) => items[0]); + } else if (outcome === 'close failure') { + showWarning.mockImplementationOnce(async (_message, _options, ...items) => items[1]); + mocks.deleteClient.mockRejectedValueOnce(new Error('private driver connection details')); + } + } + + const pending = ensureDisconnectedForEdit(clusterId, refreshTree); + if (outcome === 'close failure') { + await expect(pending).rejects.toThrow('Could not finish closing the connection.'); + expect(latch).toBe('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mocks.deleteClient).toHaveBeenCalledExactlyOnceWith(clusterId, { alreadyInvalidated: true }); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.retireBoundViews).not.toHaveBeenCalled(); + expect(draft.disable).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + expect(mocks.stopPlaygroundEvaluator).not.toHaveBeenCalled(); + expect(refreshTree).not.toHaveBeenCalled(); + } + const warningCount = { + 'cancel offer': 1, + 'cancel tabs': 2, + 'active transfer': 0, + 'dirty close refusal': 3, + 'close failure': 2, + }[outcome]; + expect(showWarning).toHaveBeenCalledTimes(warningCount); + expect(task.cancel).not.toHaveBeenCalled(); + }, + ); + it.each(['userDisconnected', 'connectionRemoved', 'credentialsUpdating', undefined] as const)( 'skips only terminal %s or a fully idle target', async (reason): Promise => { @@ -460,7 +530,7 @@ describe('connection teardown', () => { }, ); - it.each(['epoch', 'laterGeneration'] as const)( + it.each(['epoch', 'latch', 'laterGeneration'] as const)( 'does not correct a failed Remove superseded by %s during storage deletion', async (superseding): Promise => { const target = `superseded-removal-${superseding}`; @@ -474,8 +544,8 @@ describe('connection teardown', () => { latch = reason; epoch++; }); - mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { - retireConnectionBindings(id, old.generation, reason); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, old.generation); return old.generation; }); mocks.getSetting.mockReturnValue('keepOpenDisabled'); @@ -490,19 +560,22 @@ describe('connection teardown', () => { fresh = register('collectionView', false, target); if (superseding === 'epoch') { epoch++; + } else if (superseding === 'latch') { + latch = 'credentialsUpdating'; + } else { + retireConnectionBindings(target, later.generation); } - 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(latch).toBe(superseding === 'latch' ? 'credentialsUpdating' : 'connectionRemoved'); + expect(getRetiredBindingReason(old)).toBe('sessionEnded'); + expect(getRetiredBindingReason(later)).toBe(superseding === 'laterGeneration' ? 'sessionEnded' : undefined); expect(oldSignal.aborted).toBe(true); - expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); expect(fresh?.disable).not.toHaveBeenCalled(); expect(getConnectionSurfaces(target)).toEqual([fresh]); }, @@ -523,8 +596,8 @@ describe('connection teardown', () => { latch = reason; epoch++; }); - mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { - retireConnectionBindings(id, binding.generation, reason); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, binding.generation); return binding.generation; }); mocks.getSetting.mockReturnValue('keepOpenDisabled'); @@ -561,9 +634,7 @@ describe('connection teardown', () => { expect(deleteStored).toHaveBeenCalledOnce(); expect(latch).toBe('userDisconnected'); - expect(getRetiredBindingReason(binding)).toBe( - preceding === 'credentialsChanged' ? 'credentialsChanged' : 'userDisconnected', - ); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); expect(signal.aborted).toBe(true); expect(getBindingLifetimeSignal(binding).aborted).toBe(true); const currentNextSignal = getBindingLifetimeSignal({ ...binding, generation: 2 }); @@ -572,10 +643,7 @@ describe('connection teardown', () => { expect(currentNextSignal).toBe(nextSignal); } nextSignal = currentNextSignal; - expect(vi.mocked(captured.disable).mock.calls).toEqual([ - ['connectionRemoved'], - ['userDisconnected'], - ]); + expect(captured.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); expect(captured.isDirty?.()).toBe(true); expect(captured.dispose).not.toHaveBeenCalled(); expect(fresh.disable).not.toHaveBeenCalled(); @@ -586,11 +654,7 @@ describe('connection teardown', () => { } 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']], - ); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); }, ); @@ -604,12 +668,12 @@ describe('connection teardown', () => { 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); + mocks.retireBoundViews.mockImplementation((id: string): number => { + retireConnectionBindings(id, binding.generation); return binding.generation; }); const deleteStored = vi.fn(async (): Promise => { - expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); expect(signal.aborted).toBe(true); expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); }); @@ -618,8 +682,8 @@ describe('connection teardown', () => { }); expect(deleteStored).toHaveBeenCalledOnce(); - expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); - expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + expect(getRetiredBindingReason(binding)).toBe('sessionEnded'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); expect(mocks.clearRemovedPlaygroundConnections).toHaveBeenCalledExactlyOnceWith(target); }); @@ -678,7 +742,7 @@ describe('connection teardown', () => { void disconnecting.then(edited); await closingStarted; expect(edited).not.toHaveBeenCalled(); - expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('sessionEnded'); finishClose(); await expect(disconnecting).resolves.toBe(8); expect(showWarning).toHaveBeenNthCalledWith( @@ -696,9 +760,9 @@ describe('connection teardown', () => { }); it.each(['userDisconnected', 'credentialsRejected', undefined] as const)( - 'captures the safe-idle epoch without another teardown for %s', + 'captures the edit epoch without another teardown for %s', async (reason): Promise => { - mocks.exists.mockReturnValue(false); + mocks.exists.mockReturnValue(reason === 'userDisconnected'); mocks.getLatchReason.mockReturnValue(reason); mocks.getEpoch.mockReturnValue(7); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts index f6f2b86bf..36a5cb609 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -20,8 +20,8 @@ import { TaskService } from '../services/taskService/taskService'; import { settingsKeys } from '../settingsKeys'; import { clearEntraTokenFailure } from './auth/entraErrors/entraTokenFailures'; import { ClustersClient } from './ClustersClient'; -import { correctFailedRemovalRetirement } from './connectionBindingRetirement'; -import { getConnectionSurfaces, takeConnectionSurfaces, type ConnectionSurface } from './connectionSurfaces'; +import { isLatestRetirement } from './connectionBindingRetirement'; +import { getConnectionSurfaces, takeConnectionSurfaces } from './connectionSurfaces'; import { CredentialCache } from './CredentialCache'; import { getRegisteredShellTerminals } from './shell/ShellTerminalLinkProvider'; @@ -38,7 +38,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 onRetired?: (generation: number) => void; readonly refreshTree: () => void; } @@ -201,14 +201,14 @@ export async function commitTeardown( } try { - const generation = ClustersClient.retireBoundViews(clusterId, reason); + const generation = ClustersClient.retireBoundViews(clusterId); const surfaces = takeConnectionSurfaces(clusterId); - onRetired?.(generation, surfaces); + onRetired?.(generation); for (const surface of surfaces) { if (choice === 'close') { surface.dispose(); } else { - surface.disable(reason); + surface.disable('sessionEnded'); } } @@ -265,7 +265,6 @@ async function removeConnections( epoch: 0, started: false, generation: undefined as number | undefined, - surfaces: [] as readonly ConnectionSurface[], }, ]), ); @@ -301,9 +300,8 @@ async function removeConnections( choice: confirmed.choice, dropCredentials: true, alreadyLatched: true, - onRetired: (generation, surfaces): void => { + onRetired: (generation): void => { target.generation = generation; - target.surfaces = surfaces; }, refreshTree: () => {}, }); @@ -324,13 +322,8 @@ async function removeConnections( } if (target.started) { // A failed storage delete must not leave the surviving connection locked as removed. - if (target.generation !== undefined && correctFailedRemovalRetirement(id, target.generation)) { + if (target.generation !== undefined && isLatestRetirement(id, target.generation)) { ClustersClient.latch(id, 'userDisconnected'); - if (confirmed.choice === 'keepOpenDisabled') { - for (const surface of target.surfaces) { - surface.disable('userDisconnected'); - } - } } } else if (target.previous) { ClustersClient.latch(id, target.previous); diff --git a/src/services/copilotService.test.ts b/src/services/copilotService.test.ts index 1bde76509..cb1586de3 100644 --- a/src/services/copilotService.test.ts +++ b/src/services/copilotService.test.ts @@ -171,7 +171,7 @@ describe('CopilotService.streamMessage', () => { if (cancellation === 'request-abort') { controller.abort(); } else if (cancellation === 'host-retirement') { - retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + retireConnectionBindings(binding.clusterId, binding.generation); } releaseSelection([model]); diff --git a/src/webviews/_integration/connectionUnavailable.ts b/src/webviews/_integration/connectionUnavailable.ts index 3886337a2..70433b3d8 100644 --- a/src/webviews/_integration/connectionUnavailable.ts +++ b/src/webviews/_integration/connectionUnavailable.ts @@ -15,6 +15,7 @@ export const connectionUnavailableReasons = [ 'userDisconnected', 'connectionRemoved', 'unreachable', + 'sessionEnded', ] as const satisfies readonly ConnectionUnavailableReason[]; export const terminalUnavailableReasons = [ @@ -22,6 +23,7 @@ export const terminalUnavailableReasons = [ 'connectionRemoved', 'credentialsChanged', 'identityChanged', + 'sessionEnded', ] as const satisfies readonly ConnectionUnavailableReason[]; export interface ConnectionUnavailableDetails { diff --git a/src/webviews/_integration/describeUnavailableConnection.test.ts b/src/webviews/_integration/describeUnavailableConnection.test.ts index 84f4bff83..1f583c1dd 100644 --- a/src/webviews/_integration/describeUnavailableConnection.test.ts +++ b/src/webviews/_integration/describeUnavailableConnection.test.ts @@ -4,6 +4,11 @@ *--------------------------------------------------------------------------------------------*/ import { expect, it } from 'vitest'; +import { + isConnectionUnavailableMessage, + isConnectionUnavailableResponse, + isTerminalUnavailable, +} from './connectionUnavailable'; import { describeUnavailableConnection } from './describeUnavailableConnection'; it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing', 'credentialsUpdating', 'unreachable'] as const)( @@ -15,6 +20,23 @@ it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing', 'credent }, ); +it('describes a retired binding as terminal through both response and notification parsing', (): void => { + const response = describeUnavailableConnection('sessionEnded'); + expect(response.unavailable).toEqual({ + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', + }); + expect(isConnectionUnavailableResponse(response)).toBe(true); + expect( + isConnectionUnavailableMessage({ + type: 'documentView.connectionUnavailable', + ...response, + }), + ).toBe(true); + expect(isTerminalUnavailable(response.unavailable)).toBe(true); +}); + it.each(['userDisconnected', 'identityChanged', 'credentialsChanged', 'connectionRemoved'] as const)( 'permanently describes ended sessions for %s', (reason): void => { diff --git a/src/webviews/_integration/describeUnavailableConnection.ts b/src/webviews/_integration/describeUnavailableConnection.ts index a90f7c365..066ea3586 100644 --- a/src/webviews/_integration/describeUnavailableConnection.ts +++ b/src/webviews/_integration/describeUnavailableConnection.ts @@ -41,6 +41,14 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso detail: l10n.t('Wait for the update to finish.'), }, }; + case 'sessionEnded': + return { + unavailable: { + reason, + title: l10n.t('Session ended'), + detail: l10n.t('Copy what you need and open a new tab.'), + }, + }; case 'userDisconnected': case 'identityChanged': case 'credentialsChanged': diff --git a/src/webviews/_integration/trpc.test.ts b/src/webviews/_integration/trpc.test.ts index 3aeddab7c..f1de0f947 100644 --- a/src/webviews/_integration/trpc.test.ts +++ b/src/webviews/_integration/trpc.test.ts @@ -7,6 +7,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import { TRPCError } from '@trpc/server'; import { MongoServerError } from 'mongodb'; import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { describeUnavailableConnection } from './describeUnavailableConnection'; import { createCallerFactory, publicProcedureWithTelemetry, router } from './trpc'; const recordedContexts = vi.hoisted((): IActionContext[] => []); @@ -80,6 +81,7 @@ const unavailableResponse = { }, } as const; const ordinaryResponse = { value: 'loaded' } as const; +const endedResponse = describeUnavailableConnection('sessionEnded'); const malformedUnavailableResponse = { unavailable: { reason: 'tokenExpired', @@ -104,6 +106,7 @@ const testRouter = router({ throw new TRPCError({ code: 'BAD_REQUEST', message: 'rejected' }); }), unavailable: publicProcedureWithTelemetry.query(() => unavailableResponse), + ended: publicProcedureWithTelemetry.query(() => endedResponse), ordinary: publicProcedureWithTelemetry.query(() => ordinaryResponse), malformedUnavailable: publicProcedureWithTelemetry.query(() => malformedUnavailableResponse), }); @@ -154,6 +157,15 @@ describe('publicProcedureWithTelemetry', (): void => { }); }); + it('records sessionEnded through the existing safe reason pipeline without adding error fields', async (): Promise => { + await expect(caller().ended()).resolves.toBe(endedResponse); + expect(recordedContexts).toHaveLength(1); + expect(recordedContexts[0].telemetry.properties).toEqual({ + result: 'Succeeded', + unavailableReason: 'sessionEnded', + }); + }); + it.each([ ['ordinary', ordinaryResponse], ['malformed unavailable', malformedUnavailableResponse], diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx index fd5b007f0..e017653e5 100644 --- a/src/webviews/components/DisconnectedOverlay.test.tsx +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -19,9 +19,9 @@ vi.mock('../_integration/useTrpcClient', () => ({ })); 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.', + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', }; beforeEach((): void => { diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts index ca9c9b9ff..7d96ea2d6 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts @@ -166,20 +166,19 @@ describe('openClusterDashboardWebview panel lifecycle', () => { }); it.each([ - ['userDisconnected', binding, true], - ['userDisconnected', { ...binding, fingerprint: 'other-identity' }, true], - ['credentialsChanged', binding, true], - ['userDisconnected', binding, false], + [binding, true], + [{ ...binding, fingerprint: 'other-identity' }, true], + [binding, false], ] as const)( - 'opens fresh work without revealing or auto-retrying an ended Dashboard (%s, %j, %s)', - (reason, connectedBinding, autoOpen): void => { + 'opens fresh work without revealing or auto-retrying an ended Dashboard (%j, %s)', + (connectedBinding, autoOpen): void => { vi.clearAllMocks(); - const clusterId = `ended-dashboard-${reason}-${connectedBinding.fingerprint}-${autoOpen}`; + const clusterId = `ended-dashboard-${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); + retireConnectionBindings(clusterId, 1); + surface.disable('sessionEnded'); expect(getOpenClusterDashboardSessionId(clusterId)).toBeUndefined(); const fresh = openClusterDashboardWebview( @@ -195,7 +194,7 @@ describe('openClusterDashboardWebview panel lifecycle', () => { expect.objectContaining({ type: 'clusterDashboard.connectionUnavailable' }), ); const freshSession = getOpenClusterDashboardSessionId(clusterId); - surface.disable(reason); + surface.disable('sessionEnded'); expect(getOpenClusterDashboardSessionId(clusterId)).toBe(freshSession); const [freshSurface] = getConnectionSurfaces(clusterId); freshSurface.dispose(); @@ -233,11 +232,11 @@ describe('openClusterDashboardWebview panel lifecycle', () => { const [surface] = getConnectionSurfaces(CLUSTER); expect(surface).toMatchObject({ kind: 'clusterDashboard' }); - surface.disable('userDisconnected'); + surface.disable('sessionEnded'); expect(controller.panel.webview.postMessage).toHaveBeenCalledWith({ type: 'clusterDashboard.connectionUnavailable', unavailable: { - reason: 'userDisconnected', + reason: 'sessionEnded', title: expect.any(String), detail: expect.any(String), }, @@ -445,8 +444,8 @@ describe('cluster dashboard native context menu commands', () => { expect(vscode.commands.executeCommand).toHaveBeenCalledTimes(2); const [surface] = getConnectionSurfaces(clusterId); - retireConnectionBindings(clusterId, 1, 'userDisconnected'); - surface.disable('userDisconnected'); + retireConnectionBindings(clusterId, 1); + surface.disable('sessionEnded'); vi.mocked(resolveNamespaceNode).mockClear(); await exportRow?.(row); await handlers.get(CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.copyReference)?.(row); @@ -599,8 +598,8 @@ describe('cluster dashboard native context menu commands', () => { commandId === CLUSTER_DASHBOARD_CONTEXT_MENU_COMMANDS.deleteCollection ? 'orders' : undefined, }; const [surface] = getConnectionSurfaces(clusterId); - retireConnectionBindings(clusterId, 1, 'userDisconnected'); - surface.disable('userDisconnected'); + retireConnectionBindings(clusterId, 1); + surface.disable('sessionEnded'); const fresh = open(clusterId, 'sales', 2); const freshBinding = { ...binding, clusterId, generation: 2 }; vi.mocked(ClustersClient.getBinding).mockReturnValue(freshBinding); @@ -611,7 +610,7 @@ describe('cluster dashboard native context menu commands', () => { expect(database).not.toHaveBeenCalled(); expect(resolveNamespaceNode).not.toHaveBeenCalled(); expect(fresh.panel.webview.postMessage).not.toHaveBeenCalled(); - surface.disable('userDisconnected'); + surface.disable('sessionEnded'); const freshSession = getOpenClusterDashboardSessionId(clusterId, 'sales'); expect(freshSession).not.toBe(row.clusterDashboardSessionId); expect(freshSession).toBeDefined(); diff --git a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts index bc41235e5..d36adb768 100644 --- a/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts +++ b/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts @@ -112,13 +112,13 @@ function createContext( it('closes a retired dashboard without resolving a connection', async () => { const retiredBinding = { ...binding, clusterId: 'dashboard-close-retired' }; const context = createContext(undefined, undefined, retiredBinding); - retireConnectionBindings(retiredBinding.clusterId, retiredBinding.generation, 'userDisconnected'); + retireConnectionBindings(retiredBinding.clusterId, retiredBinding.generation); await createCallerFactory(clusterDashboardRouter)(context).closeView(); expect(context.closeView).toHaveBeenCalledOnce(); expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); - expect(getRetiredBindingReason(retiredBinding)).toBe('userDisconnected'); + expect(getRetiredBindingReason(retiredBinding)).toBe('sessionEnded'); }); describe('collectRawCommandReplies', () => { @@ -264,11 +264,11 @@ describe('clusterDashboardRouter create actions', () => { } as unknown as ClustersClient); vi.mocked(ClustersClient.resolveBoundClient).mockImplementation(actualClient.resolveBoundClient); vi.mocked(ClustersClient.getBinding).mockReturnValue(fresh); - retireConnectionBindings(old.clusterId, old.generation, 'userDisconnected'); + retireConnectionBindings(old.clusterId, old.generation); const frozen = createCallerFactory(clusterDashboardRouter)(createContext(undefined, undefined, old)); const poll = vi.fn(async (): Promise => { await expect(frozen.measureRtt()).resolves.toMatchObject({ - unavailable: { reason: 'userDisconnected' }, + unavailable: { reason: 'sessionEnded' }, }); }); vi.useFakeTimers(); @@ -305,12 +305,12 @@ describe('clusterDashboardRouter create actions', () => { vi.mocked(ClustersClient.getBinding).mockReturnValue(fresh); mockResolveClusterNode.mockResolvedValue({ id: 'cluster-tree-id' }); mockResolveNamespaceNode.mockResolvedValue({ id: 'database-tree-id' }); - retireConnectionBindings(old.clusterId, old.generation, 'userDisconnected'); + retireConnectionBindings(old.clusterId, old.generation); 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' } }); + ).resolves.toMatchObject({ unavailable: { reason: 'sessionEnded' } }); expect(mockResolveClusterNode).not.toHaveBeenCalled(); expect(mockResolveNamespaceNode).not.toHaveBeenCalled(); expect(vscode.commands.executeCommand).not.toHaveBeenCalled(); @@ -462,7 +462,7 @@ describe('clusterDashboardRouter create actions', () => { const clusterNode = { id: 'cluster-tree-id' }; mockResolveClusterNode.mockResolvedValue(clusterNode); const retiredBinding = { ...binding, clusterId: 'dashboard-diagnose-retired' }; - retireConnectionBindings(retiredBinding.clusterId, retiredBinding.generation, 'userDisconnected'); + retireConnectionBindings(retiredBinding.clusterId, retiredBinding.generation); await createCallerFactory(clusterDashboardRouter)( createContext(undefined, undefined, retiredBinding), diff --git a/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.test.tsx b/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.test.tsx index f584d15e4..0d48f69c3 100644 --- a/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.test.tsx +++ b/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.test.tsx @@ -75,9 +75,9 @@ const recoverable: ConnectionUnavailableDetails = { detail: 'Sign in from the connection tree.', }; const terminal: 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.', + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', }; interface TestState { diff --git a/src/webviews/documentdb/collectionView/collectionViewController.test.ts b/src/webviews/documentdb/collectionView/collectionViewController.test.ts index 00a62d335..8f88e6ad6 100644 --- a/src/webviews/documentdb/collectionView/collectionViewController.test.ts +++ b/src/webviews/documentdb/collectionView/collectionViewController.test.ts @@ -114,11 +114,11 @@ it('registers the Collection View and pushes a typed unavailable payload', (): v openPanel(); const [surface] = getConnectionSurfaces(clusterId); - surface.disable('userDisconnected'); + surface.disable('sessionEnded'); expect(mocks.postMessage).toHaveBeenCalledWith({ type: 'collectionView.connectionUnavailable', unavailable: { - reason: 'userDisconnected', + reason: 'sessionEnded', title: expect.any(String), detail: expect.any(String), }, @@ -132,7 +132,7 @@ it('detaches a kept Collection snapshot without disposing it or touching the nex openPanel(); const [snapshot] = getConnectionSurfaces(clusterId); const oldDispose = vi.spyOn(opened[0], 'dispose'); - snapshot.disable('userDisconnected'); + snapshot.disable('sessionEnded'); expect(getConnectionSurfaces(clusterId)).toEqual([]); expect(oldDispose).not.toHaveBeenCalled(); openPanel('fresh'); @@ -144,7 +144,7 @@ it('detaches a kept Collection snapshot without disposing it or touching the nex it('closes a retained view without resolving its session', (): void => { openPanel(); - context.describeUnavailable('userDisconnected'); + context.describeUnavailable('sessionEnded'); context.closeView(); diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts index a8f02c068..79edf422f 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.test.ts @@ -170,13 +170,13 @@ it('closes a retired view without resolving a connection', async (): Promise => { @@ -283,37 +283,34 @@ it('generates once with the captured binding and preserves unspecified current q 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('captures the origin before availability and cancels generation after retirement without replacement samples', async (): 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); + 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(); @@ -359,7 +356,7 @@ it('passes both host retirement and request cancellation to the model service', 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'); + retireConnectionBindings(origin.clusterId, origin.generation); expect(options?.signal?.aborted).toBe(true); const next = await generationFixture(controller.signal); @@ -462,7 +459,7 @@ describe('Collection View Playground handoff effects', () => { ).toHaveBeenCalledOnce(), ); if (replacement !== 'live') { - retireConnectionBindings(origin.clusterId, origin.generation, 'userDisconnected'); + retireConnectionBindings(origin.clusterId, origin.generation); } vi.mocked(ClustersClient.getBinding).mockReturnValue( replacement === 'disconnect' @@ -492,61 +489,58 @@ describe('Collection View Playground handoff effects', () => { ); }); -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); +it('preserves the old Collection query and blocks its retired RPC; a fresh session queries once', async (): Promise => { + const { ClusterSession } = await vi.importActual('../../../documentdb/ClusterSession'); + const old = { ...binding, clusterId: 'collection-ended' }; + 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); + 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: 'sessionEnded' }, + }); + await expect(snapshot.getFieldCompletionData()).resolves.toMatchObject({ + unavailable: { reason: 'sessionEnded' }, + }); + 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); - } + 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/collectionView/indexesTab/indexViewRouter.test.ts b/src/webviews/documentdb/collectionView/indexesTab/indexViewRouter.test.ts index 8470196ce..4c1868698 100644 --- a/src/webviews/documentdb/collectionView/indexesTab/indexViewRouter.test.ts +++ b/src/webviews/documentdb/collectionView/indexesTab/indexViewRouter.test.ts @@ -133,7 +133,7 @@ it.each([ ).toHaveBeenCalledOnce(), ); if (replacement !== 'live') { - retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + retireConnectionBindings(binding.clusterId, binding.generation); } vi.mocked(ClustersClient.getBinding).mockReturnValue( replacement === 'disconnect' diff --git a/src/webviews/documentdb/documentView/documentView.test.tsx b/src/webviews/documentdb/documentView/documentView.test.tsx index 7fbfd011b..072586071 100644 --- a/src/webviews/documentdb/documentView/documentView.test.tsx +++ b/src/webviews/documentdb/documentView/documentView.test.tsx @@ -236,9 +236,9 @@ it('ignores a load reply after disable and leaves an edit-mode placeholder unsav data: { type: 'documentView.connectionUnavailable', unavailable: { - reason: 'userDisconnected', - title: 'Disconnected', - detail: 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', }, }, }), @@ -248,7 +248,7 @@ it('ignores a load reply after disable and leaves an edit-mode placeholder unsav expect(host.querySelector('textarea')?.value).toBe('{"field":"preserved"}'); expect([...host.querySelectorAll('button')].find((button) => button.textContent === 'Save')?.disabled).toBe(true); - expect(document.querySelector('[role="dialog"] h2')?.textContent).toBe('Disconnected'); + expect(document.querySelector('[role="dialog"] h2')?.textContent).toBe('Session ended'); expect(document.querySelector('[role="dialog"]')?.textContent).toContain( 'Closing this view discards unsaved changes.', ); diff --git a/src/webviews/documentdb/documentView/documentsViewController.test.ts b/src/webviews/documentdb/documentView/documentsViewController.test.ts index 9a2ed8450..1240aea64 100644 --- a/src/webviews/documentdb/documentView/documentsViewController.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewController.test.ts @@ -106,11 +106,11 @@ it('registers the panel, sends typed disable payloads and unregisters on dispose const [surface] = getConnectionSurfaces(clusterId); expect(surface).toMatchObject({ kind: 'documentView' }); - surface.disable('userDisconnected'); + surface.disable('sessionEnded'); expect(mocks.postMessage).toHaveBeenCalledWith({ type: 'documentView.connectionUnavailable', unavailable: { - reason: 'userDisconnected', + reason: 'sessionEnded', title: expect.any(String), detail: expect.any(String), }, @@ -125,7 +125,7 @@ it('detaches a kept dirty Document snapshot without discarding its panel or the const oldContext = openPanel(originalBinding, 'add'); const [snapshot] = getConnectionSurfaces(clusterId); const oldDispose = vi.spyOn(opened[0], 'dispose'); - snapshot.disable('userDisconnected'); + snapshot.disable('sessionEnded'); expect(snapshot.isDirty?.()).toBe(true); expect(oldDispose).not.toHaveBeenCalled(); expect(getConnectionSurfaces(clusterId)).toEqual([]); @@ -139,7 +139,7 @@ it('detaches a kept dirty Document snapshot without discarding its panel or the it('closes a retained view without resolving its binding', (): void => { const context = openPanel(); - context.describeUnavailable('userDisconnected'); + context.describeUnavailable('sessionEnded'); context.closeView(); diff --git a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts index c95951e5f..e50afcfc9 100644 --- a/src/webviews/documentdb/documentView/documentsViewRouter.test.ts +++ b/src/webviews/documentdb/documentView/documentsViewRouter.test.ts @@ -9,8 +9,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type * as ClustersClientModule from '../../../documentdb/ClustersClient'; import { type ClustersClient, type ConnectionBinding } from '../../../documentdb/ClustersClient'; import { - correctFailedRemovalRetirement, getRetiredBindingReason, + isLatestRetirement, retireConnectionBindings, } from '../../../documentdb/connectionBindingRetirement'; import { ConnectionUnavailableError } from '../../../documentdb/ConnectionUnavailableError'; @@ -110,13 +110,13 @@ describe('Document View bound operations', () => { it('closes a retired view without resolving a connection', async () => { const retiredBinding = { ...binding, clusterId: 'document-close-retired' }; - retireConnectionBindings(retiredBinding.clusterId, retiredBinding.generation, 'userDisconnected'); + retireConnectionBindings(retiredBinding.clusterId, retiredBinding.generation); await createCaller(undefined, retiredBinding).closeView(); expect(closeView).toHaveBeenCalledOnce(); expect(mocks.resolveBoundClient).not.toHaveBeenCalled(); - expect(getRetiredBindingReason(retiredBinding)).toBe('userDisconnected'); + expect(getRetiredBindingReason(retiredBinding)).toBe('sessionEnded'); }); it('uses the captured identity and preserves the successful save and read shapes', async () => { @@ -257,43 +257,44 @@ describe('Document View bound operations', () => { 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( - '../../../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 => { + it('blocks an old retired Document RPC before acquisition or driver calls; a fresh panel saves once', async (): Promise => { + const { ClustersClient: actualClient } = await vi.importActual( + '../../../documentdb/ClustersClient', + ); + const old: ConnectionBinding = { ...binding, clusterId: 'document-ended' }; + 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); + + await expect(snapshot.saveDocument(input)).resolves.toMatchObject({ + unavailable: { reason: 'sessionEnded' }, + }); + await expect(snapshot.getDocumentById(serializedId)).resolves.toMatchObject({ + unavailable: { reason: 'sessionEnded' }, + }); + 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('keeps a failed Remove terminal through an old RPC without acquiring or writing to the replacement', async (): Promise => { const { ClustersClient: actualClient } = await vi.importActual( '../../../documentdb/ClustersClient', ); @@ -306,14 +307,14 @@ describe('Document View bound operations', () => { 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); + retireConnectionBindings(old.clusterId, old.generation); + expect(isLatestRetirement(old.clusterId, old.generation)).toBe(true); await expect(snapshot.saveDocument(input)).resolves.toMatchObject({ - unavailable: { reason: 'userDisconnected' }, + unavailable: { reason: 'sessionEnded' }, }); await expect(snapshot.getDocumentById(serializedId)).resolves.toMatchObject({ - unavailable: { reason: 'userDisconnected' }, + unavailable: { reason: 'sessionEnded' }, }); expect(acquisition).not.toHaveBeenCalled(); expect(upsertDocument).not.toHaveBeenCalled(); @@ -325,13 +326,13 @@ describe('Document View bound operations', () => { const old = { ...binding, clusterId: 'document-ended-save-reply' }; mocks.getBinding.mockReturnValue({ ...old, generation: 2 }); upsertDocument.mockImplementationOnce(async () => { - retireConnectionBindings(old.clusterId, old.generation, 'userDisconnected'); + retireConnectionBindings(old.clusterId, old.generation); return { documentId: id, document }; }); const caller = createCaller(undefined, old); await caller.reportDirty(true); await expect(caller.saveDocument(input)).resolves.toMatchObject({ - unavailable: { reason: 'userDisconnected' }, + unavailable: { reason: 'sessionEnded' }, }); expect(upsertDocument).toHaveBeenCalledOnce(); expect(setDirty).toHaveBeenCalledExactlyOnceWith(true); diff --git a/src/webviews/documentdb/useBoundViewRecovery.test.tsx b/src/webviews/documentdb/useBoundViewRecovery.test.tsx index 2e29e19f9..0399f934c 100644 --- a/src/webviews/documentdb/useBoundViewRecovery.test.tsx +++ b/src/webviews/documentdb/useBoundViewRecovery.test.tsx @@ -36,13 +36,12 @@ const reportEvent = vi.fn<(input: { eventName: string }) => Promise>(); const displayErrorMessage = vi.fn<(input: { message: string; modal: false; cause: string }) => Promise>(); const onShowUnavailable = vi.fn<() => void>(); const terminal: 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.', + reason: 'sessionEnded', + title: 'Session ended', + detail: 'Copy what you need and open a new tab.', }; const newerTerminal: ConnectionUnavailableDetails = { ...terminal, - reason: 'connectionRemoved', }; let state: ReturnType; @@ -111,11 +110,11 @@ it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing', 'credent }, ); -it.each(['userDisconnected', 'connectionRemoved', 'credentialsChanged', 'identityChanged'] as const)( +it.each(['sessionEnded', 'userDisconnected', 'connectionRemoved', 'credentialsChanged', 'identityChanged'] as const)( 'keeps a view permanently blocked for %s after its notice is dismissed', async (reason): Promise => { await render(); - const failure = { ...terminal, reason }; + const failure = describeUnavailableConnection(reason).unavailable; await act(async () => state.showUnavailable(failure)); const terminalRevision = state.revisionRef.current;