diff --git a/.github/skills/error-translation/SKILL.md b/.github/skills/error-translation/SKILL.md index 66577d14e..689b8531b 100644 --- a/.github/skills/error-translation/SKILL.md +++ b/.github/skills/error-translation/SKILL.md @@ -165,6 +165,11 @@ A cluster item's first-connect catch must render through `showClusterConnectFail it **before** evicting `CredentialCache` or deleting the client: the Entra and Atlas providers read the cached credentials. +The failure-row anonymous diagnostic Shell must not ask credential-backed explainers about a +different saved authentication context. Its pre-terminal failures use one modal directly at the +command call site; later driver failures stay in the terminal. Preserve the raw safe server +rejection, never reinterpret it as rejected saved credentials or fall back to saved authentication. + ### Do not call it from background paths Background work shows nothing, so translating there costs I/O for no benefit. Leave these alone: diff --git a/.github/skills/tree-cluster-architecture/SKILL.md b/.github/skills/tree-cluster-architecture/SKILL.md index 37642b9a4..02725fa12 100644 --- a/.github/skills/tree-cluster-architecture/SKILL.md +++ b/.github/skills/tree-cluster-architecture/SKILL.md @@ -78,6 +78,12 @@ router, shell, playground, task, or clipboard state. - Shell and playground workers may keep their own connection, but pin the originating identity and obey the same fingerprint and epoch checks when they respawn. +The failure-row **Open shell without authentication** entry is separate from normal authenticated +Shell startup. It binds to a sanitized endpoint and re-reads it with epoch/latch checks, without +`CredentialCache`, an authentication pin or a token relay. Only credential-rejection/sign-in/missing +credential holds may be bypassed; Disconnect, removal and updates still block it. Keep local +completion behavior, but exclude shared authenticated metadata and credential-backed explainers. + ## Design Rendering and Lookup Together When adding a cluster hierarchy or a tree/list mode, specify these four functions before coding: @@ -202,7 +208,7 @@ If a command is intentionally unavailable, gate it explicitly with context value The tree shows **actions, never error or information rows**. When expanding a cluster fails, the reason goes in a **modal** (`showErrorMessage(..., { modal: true, detail })`, translated through `ErrorExplanationService` where available). The children are only recovery actions: -"Diagnose connection…", "Open shell" (on every failure, so experts can debug +"Diagnose connection…", "Open shell without authentication" (on every failure, so experts can debug in the shell even when connecting or sign-in failed), and provider-owned actions such as "Update credentials…" via `errorRecoveryActions` (`ClusterItemBase.createErrorRecoveryChildren`). @@ -211,7 +217,7 @@ Keep a fixed relative order: configuration/targeted repairs, diagnosis/inspectio destructive recovery, and **Retry always last** (including "Retry setup…"). Providers prepend repairs; **Update connection string** precedes **Update credentials** when both exist. Then `ClusterItemBase` renders **Retry sign-in** when a verified Entra identity can recover, -followed by **Diagnose connection…** and **Open shell**. **Retry** is last. When **Retry sign-in** or +followed by **Diagnose connection…** and **Open shell without authentication**. **Retry** is last. When **Retry sign-in** or the stored-credential rejection action replaces Retry, do not add an ordinary Retry row too. Failure classification changes availability, never ordering. When healthy resources coexist with recovery actions, render the healthy resources first and the recovery block last. diff --git a/CHANGELOG.md b/CHANGELOG.md index 756d5c6d8..b6d3a3ddf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ ### New Features & Improvements - **Resilient Connections**: Renews Microsoft Entra ID tokens silently, refreshes Azure discovery credentials, and replaces closed or transient failed clients with the same binding on a later foreground operation. [#990](https://github.com/microsoft/vscode-documentdb/issues/990), [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) -- **Explicit Connection Teardown**: Adds Disconnect and Reconnect, a shared disconnect and deletion flow, a Close all or Keep open (disabled) choice, and protection for active copy, export, or import work. [#566](https://github.com/microsoft/vscode-documentdb/issues/566), [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) +- **Explicit Connection Teardown**: Adds Disconnect and Reconnect, a shared disconnect and deletion flow, a Close all or Keep open choice, and protection for active copy, export, or import work. [#566](https://github.com/microsoft/vscode-documentdb/issues/566), [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) - **Identity-Bound Open Views**: Keeps open views and editor state tied to the connection that created them. Expired sign-in or unavailable connections receive bounded recovery, while changed saved settings require a new view instead of changing identity behind it. [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) ## 1.1.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 71e803fc1..faa41e873 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -541,6 +541,7 @@ Case 2 is also where the AI pre-review in [§6](#6-ai-assisted-review-workflow) - **`npm run l10n`** regenerates the localization bundle from the strings passed to `vscode.l10n.t()`. **Never resolve a conflict in `l10n/bundle.l10n.json` by hand** — the file is generated. Take either side, or delete it, then re-run `npm run l10n` and commit the result. - **`npm run l10n:check`** validates localization against the source without regenerating files. Run it even when no strings changed, matching CI. - **`npm run prettier-fix`** covers Markdown as well as source, so documentation formatting does not drift whenever a file is touched. Fenced code blocks are left exactly as authored: they are often partial or illustrative, and reformatting them to the Markdown tab width would leave every example disagreeing with the code it documents. +- **`npm run lint`** checks the current checkout, including new source files, and skips nested Git worktrees and clones. To lint another worktree, run the command from that worktree. - **`npm run typecheck:tests`** checks every participating workspace's tests with its own TypeScript configuration, including strict checks that the root build and Vitest runtime do not cover. - **`npm run package`** catches Vite host and webview bundling issues and missing assets that unit tests alone will not surface. diff --git a/build/verification/browser/fixtures.ts b/build/verification/browser/fixtures.ts index dff59cf9b..fcd7a4089 100644 --- a/build/verification/browser/fixtures.ts +++ b/build/verification/browser/fixtures.ts @@ -541,6 +541,7 @@ export const fixtures = { ], rpc: { ...common, + 'mongoClusters.documentView.reportDirty': reply('mutation', null), 'mongoClusters.documentView.getDocumentById': reply< Outputs['mongoClusters']['documentView']['getDocumentById'] >('query', JSON.stringify({ _id: 'stage0-1', name: 'Stage 0 document payload', quantity: 7 }, null, 2)), diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 5be950f87..6efcce13d 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -2709,7 +2709,7 @@ const collectionViewScenarios = { selector: '.disconnectedOverlayBackground', attribute: 'inert', expected: null, - steps: [{ action: 'click', role: 'button', name: 'Dismiss dialog to copy view contents' }], + steps: [{ action: 'click', role: 'button', name: 'Dismiss dialog to access view contents' }], }, { kind: 'text', diff --git a/build/verification/eslint-worktrees.test.cjs b/build/verification/eslint-worktrees.test.cjs new file mode 100644 index 000000000..d4bf4ada2 --- /dev/null +++ b/build/verification/eslint-worktrees.test.cjs @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +const { deepStrictEqual } = require('node:assert/strict'); +const { mkdtempSync, mkdirSync, rmSync, writeFileSync } = require('node:fs'); +const { tmpdir } = require('node:os'); +const { join, resolve } = require('node:path'); +const { test } = require('node:test'); +const { ESLint } = require('eslint'); + +test('ESLint checks the current checkout but not nested Git checkouts', async (t) => { + const root = mkdtempSync(join(tmpdir(), 'documentdb-eslint-')); + t.after(() => rmSync(root, { recursive: true, force: true })); + + const source = join(root, 'src'); + const worktree = join(root, 'nested worktree'); + const clone = join(root, 'nested-clone'); + mkdirSync(join(root, '.git')); + mkdirSync(source); + mkdirSync(worktree); + mkdirSync(join(clone, '.git'), { recursive: true }); + writeFileSync(join(worktree, '.git'), 'gitdir: ../.git/worktrees/nested\n'); + const localFile = join(source, 'new.js'); + const worktreeFile = join(worktree, 'worktree.js'); + writeFileSync(localFile, ''); + writeFileSync(worktreeFile, ''); + writeFileSync(join(clone, 'clone.js'), ''); + + const overrideConfigFile = resolve(__dirname, '../../eslint.config.mjs'); + const lintPaths = async (cwd) => { + const eslint = new ESLint({ cwd, overrideConfigFile }); + return (await eslint.lintFiles(['.'])).map(({ filePath }) => filePath); + }; + + deepStrictEqual(await lintPaths(root), [localFile]); + deepStrictEqual(await lintPaths(worktree), [worktreeFile]); +}); diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index b70afc179..d8f7317df 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -87,6 +87,10 @@ entries are unpublished drafts and do not represent a shipped release. the available credentials. Credential repair stays in the tree. Dismissing the dialog with its **X** exposes the existing contents for copying without resuming database operations. Trying another operation shows the dialog again. **Close view** asks for confirmation. +- **Do not remove Retry during an unavailable episode once it has been offered.** A failed attempt + or a runtime reason change keeps the control, while the reason remains truthful and host guards + still reject unsafe recovery. Dismissing the dialog does not reset this choice. Successful + recovery ends the episode; a later initially Close-only episode does not inherit Retry. - After an explicit Disconnect, the tree offers **Reconnect**. If reconnecting automatically opens the existing Dashboard for the same identity, it retries that view without replaying an operation. Other retained views still require **Retry**. @@ -96,6 +100,10 @@ entries are unpublished drafts and do not represent a shipped release. - After a database rejects a verified Entra identity, discard the client but keep its in-memory connection settings for explicit sign-in. Do not retain the rejected token or retry silently. When the tree offers **Retry sign-in**, it does not also offer **Retry**. +- Failure rows offer **Open shell without authentication** as a separate diagnostic entry. + 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. - **Disconnect and Remove Connection** share a teardown and a tab choice. Saving a change to connection details (including a password-only change) in this window keeps old tabs open and copyable, but they cannot recover. Open new tabs from the tree. Unchanged settings still @@ -105,14 +113,16 @@ entries are unpublished drafts and do not represent a shipped release. ## Documents -| Document | Kind | -| ------------------------------------------------------------------------------ | --------- | -| [research-findings.md](./research-findings.md) | research | -| [decisions.md](./decisions.md) | decisions | -| [iterations/01-implementation-plan.md](./iterations/01-implementation-plan.md) | plan | -| [iterations/01-dev-plan.md](./iterations/01-dev-plan.md) | plan | -| [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 | +| Document | Kind | +| ------------------------------------------------------------------------------------ | --------- | +| [research-findings.md](./research-findings.md) | research | +| [decisions.md](./decisions.md) | decisions | +| [iterations/01-implementation-plan.md](./iterations/01-implementation-plan.md) | plan | +| [iterations/01-dev-plan.md](./iterations/01-dev-plan.md) | plan | +| [iterations/02-ux-implementation-plan.md](./iterations/02-ux-implementation-plan.md) | plan | +| [iterations/02-pr1146-copilot-review.md](./iterations/02-pr1146-copilot-review.md) | review | +| [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 | ## Decisions index @@ -139,6 +149,11 @@ See [decisions.md](./decisions.md): - 0019 require a fresh Dashboard delete after Disconnect and retain tree-only Paste. - 0020 defer the late-failure comparison across releases and retain descriptive telemetry. - 0021 key the in-memory connection fingerprint per extension host. +- 0022 separately unauthenticated Shell entry from failure rows only. +- 0023 keep failed retained-view Retry feedback inside the unavailable dialog. +- 0024 classify explicit stale recovery clicks without disturbing quiet background paths. +- 0025 use modal feedback for tree-origin commands, leaving webview feedback unchanged; + descendant expansion is deferred to #1143 until foreground attribution is supported. ## Timeline @@ -151,3 +166,4 @@ See [decisions.md](./decisions.md): | 2026-11-24 | WI-6 through WI-8 implement bound views, teardown and Dashboard behavior | | 2026-11-25 | WI-2 review fixes and WI-9 lifecycle measurements | | 2026-11-26 | WI-10 documentation draft, skill updates and unpublished 1.2.0 notes | +| 2026-11-27 | UX review findings organized into a draft implementation plan | diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 237b1b4b9..17130ce8a 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -26,13 +26,17 @@ created: 2026-11-19 | 0012 | Keep the lifecycle design minimal: no state machine, one epoch, no prompts in getClient, one-step teardown | Accepted | Operator: approved every proposed simplification | 2026-11-19 | — | | 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | | 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | -| 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | +| 0015 | Use the existing latch to block startup after authentication rejection | Accepted (modified by 0022) | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | | 0016 | Keep disconnected webviews open under a full-view overlay | Accepted (modified by 0017) | Operator chose a simple disabled state with explicit actions | 2026-11-24 | Yes; replaces the inline banner and single-action layout | | 0017 | Limit unavailable webview recovery to Retry and Close view | Accepted (modified by 0018) | Operator wants credential repair in the tree and no extra recovery workflow in a tab | 2026-11-24 | Yes; removes in-view credential repair | -| 0018 | Saved connection edits permanently lock existing views | Accepted | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | +| 0018 | Saved connection edits permanently lock existing views | Accepted (modified by 0023) | Operator prefers simple reconnect for unchanged settings over recovery after edits | 2026-11-24 | Yes; removes same-identity recovery after a saved edit | | 0019 | Require a fresh Dashboard delete after Disconnect and keep Paste Collection in the tree | Accepted | Operator: a lifecycle change cancels the pending delete and never replays it | 2026-11-24 | — | | 0020 | Defer the cross-release comparison of late failures | Accepted | Operator: keep descriptive telemetry and defer the comparison | 2026-11-26 | Yes; removes the WI-9 before/after comparison for 1.2.0 | | 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 | Accepted | Operator selected F4 option B and bounded failure copy | 2026-11-27 | No host modal or 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 | +| 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 | > 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 @@ -520,3 +524,109 @@ options may contain credentials and are not treated as sanitized data. Do not retain historical connection strings in an identity map or persist the HMAC key. Recheck [CodeQL alert 39](https://github.com/microsoft/vscode-documentdb/security/code-scanning/39). If it still reports the HMAC call, leave it open for review rather than suppressing it. + +## 0022. Offer a separately unauthenticated Shell from failure rows only + +**Accepted** by the operator on 2026-11-27 during +[iteration 2](./iterations/02-ux-implementation-plan.md). + +Replace the failure-row Shell action with **Open shell without authentication**. +Normal context-menu Shell startup remains authenticated. The anonymous entry may bypass +rejected or missing authentication holds, but must honor removal, credential-update and +explicit Disconnect guards. It does not clear a latch, use or modify `CredentialCache`, +change saved credentials or connection identity, or fall back to saved authentication. + +Use an available model or stored endpoint stripped of credentials and authentication +options. Do not fetch an endpoint from ARM on this path; report an unavailable endpoint +honestly. Retain the existing host-gated TLS and emulator rules. Opening the terminal +does not promise that anonymous database operations are authorized. + +This is the operator's explicit approval of the proposed policy, including its authentication +boundary. No additional rationale was supplied. Implementation remains subject to verifying +the endpoint and lifecycle contracts against the current source. + +**Execution clarification (2026-11-27):** the operator approved a code-only internal command, +the missing-endpoint message **Cannot open a shell without authentication for "{0}": its +endpoint is not available.**, and stripping database, proxy and client-certificate +authentication credentials while preserving server TLS validation. + +**Completion boundary (2026-11-27):** the operator questioned disabling already-working +suggestions, then agreed to metadata-only isolation for the new diagnostic anonymous path. +Normal Shell behavior remains unchanged. An internal `includeClusterMetadata` capability, +defaulting to the existing behavior, preserves local methods, commands, operators, history and +bracket suggestions while excluding shared-client database/collection/field/schema lookups in +anonymous sessions. Prewarming, schema feeds and credential-backed error explanations are also +excluded there. No fake cluster IDs or blanket suggestion disablement are authorized. +The completion provider and its existing tests are directly dependent owned files for WI-6. + +**Parse-error clarification (2026-11-27):** the operator selected **1.A**: show +**Invalid connection string.** when anonymous endpoint parsing fails and discard the +original parser error/cause completely. Dependency parser errors can contain the credential-bearing +URI or username, so retaining the unsafe cause is not permitted. The bounded replacement applies +only to constructor parsing, not arbitrary startup errors. + +## 0023. Keep retained-view Retry failure feedback inside the unavailable dialog + +**Accepted** by the operator on 2026-11-27: F4 option B. + +Keep the original unavailable reason distinct from the latest failed attempt. Use the bounded +copy **Unable to recover the connection. Try Retry again, or close this view.** for an +unclassified failure, without exposing a raw exception or stack. Announce the failure in-view +and restore Retry, Close view and X after the attempt. Do not add a host modal, change the +bound identity, or replay the failed database operation. No additional rationale was supplied. + +**Runtime-control clarification (2026-11-27):** after a review found that Retry can return +a new Close-only unavailable reason, the operator selected **2.A**, qualified by: +**when a user had a Retry button visible, it should never be gone after a retry**. +The displayed reason must remain truthful without removing an already-visible Retry control +because state changes at runtime. Identity and lifecycle guards +continue to reject unsafe attempts; keeping a control visible does not authorize rebinding. + +**Episode scope (2026-11-27):** the operator explicitly selected **1A**. An unavailable episode +persists while its dialog is dismissed and reopened, and ends when recovery succeeds. Once Retry +has been offered, runtime reason changes or a failed attempt do not remove it within that episode. +After success, a later initially Close-only episode does not inherit Retry. + +This qualifies 0018's visible **Close view**-only policy only for an already-unavailable episode +that previously offered Retry. Saved edits still permanently block database operations and old +views never rebind to changed settings. The explicit Retry remains a guarded attempt, not a promise +that the current reason can recover. This records the operator's qualified instruction; no new +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. + +Refresh current tree state and explain actually failed explicit clicks using their real reason: +**This connection was removed. Choose another connection.** or +**This connection changed. Refresh the tree and try again.** +Already-completed recovery refreshes or reveals current state without an error. +Cancellation, disposed work and obsolete background replies remain quiet. + +An explicit stale worker sign-in click uses its existing bounded worker surface when that +terminal or file still exists, not the tree's host-modal policy. Never connect another identity +or restart disposed work to make a stale action appear successful. No additional rationale +was supplied. + +## 0025. Tree-origin failures use modals; webview-origin command feedback stays unchanged + +**Accepted** by the operator on 2026-11-27. + +F3 covers explicit tree-origin actions, including tree expansion and commands, but does not +turn shared webview-origin command failures into host modals. One failed action gives one +modal with a translated heading and separate detail. Tree children remain recovery actions, +not error or information rows. Background replies and cancellations stay quiet. +No additional rationale was supplied. + +**Execution scope clarification (2026-11-27):** the operator selected descendant-expansion +alignment only for extension-owned Connections and Discovery TreeViews, leaving Azure Resources +unchanged. `getChildren` does not identify foreground versus background origin, and the Azure +Resources host owns its TreeView. The operator requested +[#1143](https://github.com/microsoft/vscode-documentdb/issues/1143) to investigate Azure support, +with motivating scenarios and the trade-offs of consistent feedback versus background modal +noise and host coordination. The own-view origin/event-order contract still needs verification. + +**Disposition (2026-11-27):** after the advisor found no documented expansion-event ordering, +the operator selected **Ship tree-command alignment now; defer descendant expansion to #1143 +until foreground attribution is supported**. This supersedes the earlier own-view-only +expansion scope for this iteration. No descendant-expansion modal change is authorized here. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md index 6c4be6c61..be8e49233 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-pr1136-ux-review.md @@ -37,11 +37,17 @@ removal, quoting the actual messages rather than only naming their surfaces. ## How this review was run -**Preparation only so far. No hands-on observations have been made in this review.** +**Preparation followed by the operator's first hands-on feedback on 2026-11-27.** The assistant read the manifest, command handlers, tree recovery paths, retained-view -components and controllers, worker recovery and Azure account flows. The six seeded -Flags describe confirmed code-path gaps or divergences; their severity and actual -runtime impact still need the operator's confirmation. +components and controllers, worker recovery and Azure account flows. The original six +Flags were code-derived seeds. Their bodies now distinguish the operator's observations, +accepted changes, remaining suggestions and version-uncertain reproduction requests. +No product fixes have been implemented in this review. + +Appendix C continues to quote **current source wording**, not pretend approved wording +has shipped. Decisions below and notes beside the relevant scenarios identify the +requested replacements. Operator transcripts omit the supplied server hostname; +that identifier is unnecessary to understand the observed behavior. During the live pass, the person drives the extension and dictates observations; the assistant verifies each observation against the source and updates this ledger and the @@ -68,12 +74,12 @@ No runtime tests ran because this preparation changes documentation only. ### Status -| Status | Meaning | -| ------------------ | ----------------------------------------------------------------------- | -| 🟠 **Open** | Recorded + analyzed; carries a recommendation but stays a _suggestion_ | +| Status | Meaning | +| ------------------ | ------------------------------------------------------------------------ | +| 🟠 **Open** | Recorded + analyzed; carries a recommendation but stays a _suggestion_ | | 🟡 **Open (soft)** | Open, but the recommendation depends on an investigation or is "as-is" | -| ✅ **Implemented** | A change was made on this branch and verified (Decision + commit link) | -| 🚫 **Closed** | Won't fix — with a mandatory one-line reason | +| ✅ **Implemented** | A change was made on this branch and verified (Decision + commit link) | +| 🚫 **Closed** | Won't fix — with a mandatory one-line reason | | 🔗 **Tracked** | Deferred to a repo issue (linked); dropped from the active priority list | > Anything unresolved carries forward to the next iteration. An item leaves the active @@ -184,33 +190,33 @@ The primary tree source is the command surface and gating are in [the manifest](../../../../../package.json#L1349) and [command registration](../../../../../src/documentdb/ClustersExtension.ts#L1014). -| # | User action / entry | Implementation reference | Terminal states / feedback | -| --- | --- | --- | --- | -| I1 | Expand cluster in Connections, Discovery or Azure Resources | [connect and expand](../../../../../src/tree/documentdb/ClusterItemBase.ts#L153) | Cancellable progress; databases; modal + repair rows; cancellation without an error dialog | -| I2 | Click Create Database / Create Collection in an empty tree | [cluster empty state](../../../../../src/tree/documentdb/ClusterItemBase.ts#L649), [database empty state](../../../../../src/tree/documentdb/DatabaseItem.ts#L97) | Creation wizard, result/refresh or command error; cancel leaves the empty state | -| I3 | Expand an existing database or Indexes node | [database](../../../../../src/tree/documentdb/DatabaseItem.ts#L72), [indexes](../../../../../src/tree/documentdb/IndexesItem.ts#L66) | Collections/indexes or provider error feedback; F3 | -| I4 | Refresh view/node or click Retry | [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L63) | Error cache reset and fresh expansion; some stale-state guards are silent, F5 | -| I5 | Click Retry for a rejected Azure RU key | [key replacement](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L92) | Explicit fresh ARM key read; reconnect on refresh; modal on key-read failure | -| I6 | Click Retry sign-in under failed Entra cluster | [sign-in](../../../../../src/commands/signInAgain/signInAgain.ts#L74) | Interactive authentication; tree refresh; translated failure modal; cancel/stale guard | -| I7 | Click Diagnose connection… or invoke Diagnose from the palette | [diagnose command](../../../../../src/commands/diagnoseConnection/diagnoseConnection.ts#L27) | Read-only diagnostics panel; palette first picks a stored cluster | -| I8 | Click Open shell in failure rows / cluster context menu | [shell command](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L45) | Terminal and connection banner, or missing-credentials notification with no terminal, F1 | -| I9 | Click Update connection string… / Update credentials… | [destination edit](../../../../../src/commands/updateConnectionString/updateConnectionString.ts#L77), [credential edit](../../../../../src/commands/updateCredentials/updateCredentials.ts#L147) | Wizard; save feedback; changed settings retire webviews; error-node credential wizard asks whether to reconnect | -| I10 | Respond to old-Shell-settings notice after an edit | [Shell choice](../../../../../src/commands/saveConnectionEdit.ts#L136) | Modal; Disconnect stops workers; dismissal keeps running workers on previous settings | -| I11 | Right-click connected cluster → Disconnect | [Disconnect](../../../../../src/commands/disconnect/disconnect.ts#L18), [tab choice](../../../../../src/documentdb/connectionTeardown.ts#L55) | Hidden from palette; connected-only menu; task block, tab choice, dirty warning, or teardown | -| I12 | Click Reconnect under a disconnected cluster | [Reconnect](../../../../../src/commands/disconnect/disconnect.ts#L32) | Unlatch and tree refresh; connection result follows expansion; stale guard is silent | -| I13 | Delete one/multiple saved connections or a folder | [connection removal](../../../../../src/commands/removeConnection/removeConnection.ts#L23), [folder removal](../../../../../src/commands/connections-view/deleteFolder/ExecuteStep.ts#L22) | Shared destructive confirmation + teardown; refresh; configured summary; failures surfaced | -| I14 | Collection View: run, page, refresh, manipulate documents | [Collection View](../../../../../src/webviews/documentdb/collectionView/CollectionView.tsx#L179) | Current results or typed unavailable dialog; stale replies ignored; failed operations not replayed | -| I15 | Collection View: Indexes and Query Insights actions | [Indexes tab](../../../../../src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx), [Query Insights tab](../../../../../src/webviews/documentdb/collectionView/queryInsightsTab/QueryInsightsTab.tsx) | Shared parent lifecycle blocking; results retained; repair through tree + Retry | -| I16 | Document View: edit, Save, Refresh | [Document View](../../../../../src/webviews/documentdb/documentView/documentView.tsx#L90) | Dirty draft tracked; server actions blocked when unavailable; close/discard confirmation | -| I17 | Dashboard: refresh, create/drop, open views, copy/export | [Dashboard](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx), [row commands](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L254) | Busy state and results; unavailable dialog; no pending delete replay; retained namespace reference can be copied | -| I18 | Unavailable webview: Retry / Close view / X | [overlay](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L37), [recovery hook](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L93) | Same-binding recovery without replay; typed reason remains in dialog; exception notification, F4; confirmed close; X permits copying | -| I19 | Import, export, copy/paste while attempting teardown/edit | [import lease](../../../../../src/commands/importDocuments/importDocuments.ts#L161), [export lease](../../../../../src/commands/exportDocuments/exportDocuments.ts#L57), [task guard](../../../../../src/services/taskService/resourceUsageHelper.ts#L19) | Registered task/lease blocks teardown in modal; running transfer is not interrupted | -| I20 | Retained Shell: run after disconnect/reconnect; Sign in again | [worker evaluation](../../../../../src/documentdb/shell/ShellSessionManager.ts#L340), [sign-in action](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L941) | Same-settings worker restart; bounded failure output; warning action; successful sign-in has a rerun cue; F2/F5 | -| I21 | Playground: Run All / Run Selected; unbound connect-on-run | [execution](../../../../../src/commands/playground/executePlaygroundCode.ts#L101) | Database picker if unbound; progress + result document; latch warning; cancellation without execution | -| I22 | Playground CodeLens/status connection choice; Sign in again | [connection picker](../../../../../src/commands/playground/connectDatabase.ts#L35), [recovery](../../../../../src/commands/playground/executePlaygroundCode.ts#L367) | Confirm switching; picker cancellation preserves binding; sign-in stops evaluator without replay or completion cue, F6 | -| I23 | Azure provider Refresh/Retry; Manage Accounts; Adjust Filters | [provider root](../../../../../src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts#L38), [listing](../../../../../src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts#L96) | Fresh listing; partial warning + Show Output; empty-state modal and actionable Retry | -| I24 | New/edit Entra connection: tenant, manual ID, Retry, Manage Azure Accounts | [new tenant picker](../../../../../src/commands/newConnection/PromptTenantStep.ts#L32), [edit tenant picker](../../../../../src/commands/updateCredentials/PromptTenantStep.ts) | Tenant selection/manual validation; recoverable lookup state; initial 5 s timeout and explicit retry up to 30 s | -| I25 | Show Connection Stats / Show Worker Stats during review | [connection stats](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L32) | Output channel; client state/generation and token expiry; worker stats are a separate surface | +| # | User action / entry | Implementation reference | Terminal states / feedback | +| --- | -------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| I1 | Expand cluster in Connections, Discovery or Azure Resources | [connect and expand](../../../../../src/tree/documentdb/ClusterItemBase.ts#L153) | Cancellable progress; databases; modal + repair rows; cancellation without an error dialog | +| I2 | Click Create Database / Create Collection in an empty tree | [cluster empty state](../../../../../src/tree/documentdb/ClusterItemBase.ts#L649), [database empty state](../../../../../src/tree/documentdb/DatabaseItem.ts#L97) | Creation wizard, result/refresh or command error; cancel leaves the empty state | +| I3 | Expand an existing database or Indexes node | [database](../../../../../src/tree/documentdb/DatabaseItem.ts#L72), [indexes](../../../../../src/tree/documentdb/IndexesItem.ts#L66) | Collections/indexes or provider error feedback; F3 | +| I4 | Refresh view/node or click Retry | [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L63) | Error cache reset and fresh expansion; some stale-state guards are silent, F5 | +| I5 | Click Retry for a rejected Azure RU key | [key replacement](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L92) | Explicit fresh ARM key read; reconnect on refresh; modal on key-read failure | +| I6 | Click Retry sign-in under failed Entra cluster | [sign-in](../../../../../src/commands/signInAgain/signInAgain.ts#L74) | Interactive authentication; tree refresh; translated failure modal; cancel/stale guard | +| I7 | Click Diagnose connection… or invoke Diagnose from the palette | [diagnose command](../../../../../src/commands/diagnoseConnection/diagnoseConnection.ts#L27) | Read-only diagnostics panel; palette first picks a stored cluster | +| I8 | Click Open shell in failure rows / cluster context menu | [shell command](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L45) | Terminal and connection banner, or missing-credentials notification with no terminal, F1 | +| I9 | Click Update connection string… / Update credentials… | [destination edit](../../../../../src/commands/updateConnectionString/updateConnectionString.ts#L77), [credential edit](../../../../../src/commands/updateCredentials/updateCredentials.ts#L147) | Wizard; save feedback; changed settings retire webviews; error-node credential wizard asks whether to reconnect | +| I10 | Respond to old-Shell-settings notice after an edit | [Shell choice](../../../../../src/commands/saveConnectionEdit.ts#L136) | Modal; Disconnect stops workers; dismissal keeps running workers on previous settings | +| I11 | Right-click connected cluster → Disconnect | [Disconnect](../../../../../src/commands/disconnect/disconnect.ts#L18), [tab choice](../../../../../src/documentdb/connectionTeardown.ts#L55) | Hidden from palette; connected-only menu; task block, tab choice, dirty warning, or teardown | +| I12 | Click Reconnect under a disconnected cluster | [Reconnect](../../../../../src/commands/disconnect/disconnect.ts#L32) | Unlatch and tree refresh; connection result follows expansion; stale guard is silent | +| I13 | Delete one/multiple saved connections or a folder | [connection removal](../../../../../src/commands/removeConnection/removeConnection.ts#L23), [folder removal](../../../../../src/commands/connections-view/deleteFolder/ExecuteStep.ts#L22) | Shared destructive confirmation + teardown; refresh; configured summary; failures surfaced | +| I14 | Collection View: run, page, refresh, manipulate documents | [Collection View](../../../../../src/webviews/documentdb/collectionView/CollectionView.tsx#L179) | Current results or typed unavailable dialog; stale replies ignored; failed operations not replayed | +| I15 | Collection View: Indexes and Query Insights actions | [Indexes tab](../../../../../src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx), [Query Insights tab](../../../../../src/webviews/documentdb/collectionView/queryInsightsTab/QueryInsightsTab.tsx) | Shared parent lifecycle blocking; results retained; repair through tree + Retry | +| I16 | Document View: edit, Save, Refresh | [Document View](../../../../../src/webviews/documentdb/documentView/documentView.tsx#L90) | Dirty draft tracked; server actions blocked when unavailable; close/discard confirmation | +| I17 | Dashboard: refresh, create/drop, open views, copy/export | [Dashboard](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx), [row commands](../../../../../src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L254) | Busy state and results; unavailable dialog; no pending delete replay; retained namespace reference can be copied | +| I18 | Unavailable webview: Retry / Close view / X | [overlay](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L37), [recovery hook](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L93) | Same-binding recovery without replay; typed reason remains in dialog; exception notification, F4; confirmed close; X permits copying | +| I19 | Import, export, copy/paste while attempting teardown/edit | [import lease](../../../../../src/commands/importDocuments/importDocuments.ts#L161), [export lease](../../../../../src/commands/exportDocuments/exportDocuments.ts#L57), [task guard](../../../../../src/services/taskService/resourceUsageHelper.ts#L19) | Registered task/lease blocks teardown in modal; running transfer is not interrupted | +| I20 | Retained Shell: run after disconnect/reconnect; Sign in again | [worker evaluation](../../../../../src/documentdb/shell/ShellSessionManager.ts#L340), [sign-in action](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L941) | Same-settings worker restart; bounded failure output; warning action; successful sign-in has a rerun cue; F2/F5 | +| I21 | Playground: Run All / Run Selected; unbound connect-on-run | [execution](../../../../../src/commands/playground/executePlaygroundCode.ts#L101) | Database picker if unbound; progress + result document; latch warning; cancellation without execution | +| I22 | Playground CodeLens/status connection choice; Sign in again | [connection picker](../../../../../src/commands/playground/connectDatabase.ts#L35), [recovery](../../../../../src/commands/playground/executePlaygroundCode.ts#L367) | Confirm switching; picker cancellation preserves binding; sign-in stops evaluator without replay or completion cue, F6 | +| I23 | Azure provider Refresh/Retry; Manage Accounts; Adjust Filters | [provider root](../../../../../src/plugins/service-azure-mongo-vcore/discovery-tree/AzureServiceRootItem.ts#L38), [listing](../../../../../src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts#L96) | Fresh listing; partial warning + Show Output; empty-state modal and actionable Retry | +| I24 | New/edit Entra connection: tenant, manual ID, Retry, Manage Azure Accounts | [new tenant picker](../../../../../src/commands/newConnection/PromptTenantStep.ts#L32), [edit tenant picker](../../../../../src/commands/updateCredentials/PromptTenantStep.ts) | Tenant selection/manual validation; recoverable lookup state; initial 5 s timeout and explicit retry up to 30 s | +| I25 | Show Connection Stats / Show Worker Stats during review | [connection stats](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L32) | Output channel; client state/generation and token expiry; worker stats are a separate surface | ### Failure and feedback surface matrix @@ -218,28 +224,28 @@ These are the lifecycle-relevant foreground failure branches, not every unrelate database-operation error. Silent background count/metadata failures and obsolete replies are intentionally not treated as user-action failures. -| Event | Current feedback / termination | Source | Assessment | -| --- | --- | --- | --- | -| First cluster startup failure | Output detail + translated modal; recovery rows | [first-connect helper](../../../../../src/documentdb/showClusterConnectFailure.ts#L36), [stored startup](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L273) | Expected baseline | -| Cached connect / listDatabases failure | Modal with explanation and detail; action-only children | [expansion failure](../../../../../src/tree/documentdb/ClusterItemBase.ts#L443) | Expected baseline | -| Explained database/index child-expansion failure | Non-modal error with cause appended | [provider catch](../../../../../src/tree/BaseExtendedTreeDataProvider.ts#L606) | F3: sibling tree divergence | -| Open shell after cache eviction | Non-modal “Not signed in”; no terminal | [credential guard](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L63) | F1: offered recovery can dead-end | -| Azure replacement-key read failure | Modal “Azure sign-in needed” or key-read failure | [key read](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L107) | Targeted recovery | -| Tree sign-in fails / cloud provider changed / connection closed mid-sign-in | Translated or dedicated modal | [sign-in flow](../../../../../src/commands/signInAgain/signInAgain.ts#L114) | Explicit action reports failure | -| Bound-view unavailable reason | In-view modal over retained content; Retry and/or Close view | [reason map](../../../../../src/webviews/_integration/describeUnavailableConnection.ts#L11) | Accepted design, not a passive tree row | -| Bound-view Retry throws an unclassified error | Host non-modal error; previous dialog remains | [recovery catch](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L125) | F4: feedback split | -| Close-view confirmation RPC fails | In-dialog alert; view remains open | [close confirmation](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L48) | Explicit failure with retry path | -| Worker sign-in expires | Shell bounded output or Playground result; non-modal Sign in again when safe | [Shell](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L907), [Playground](../../../../../src/commands/playground/executePlaygroundCode.ts#L313) | Deliberate worker surface; not automatically a modal inconsistency | -| Worker sign-in action fails | Bounded non-modal warning; original operation not replayed | [Shell action](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L979), [Playground action](../../../../../src/commands/playground/executePlaygroundCode.ts#L402) | Confirm actionable next-step wording | -| Run while user-disconnected / identity changed | Shell error output; Playground warning before run or result after failure | [Shell reason](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L895), [Playground latch](../../../../../src/commands/playground/executePlaygroundCode.ts#L127) | F2: unnecessary new-shell/re-pick guidance for unchanged settings | -| Save fails / persisted state uncertain | Save-error notification; possible incomplete-update warning; old views remain safely disabled | [save reconciliation](../../../../../src/commands/saveConnectionEdit.ts#L76), [credential save](../../../../../src/commands/updateCredentials/ExecuteStep.ts#L106) | Do not confuse “saved” with “usable” | -| Removal partly/all fails | Output details; partial-success summary respects summary setting; all-failed error is non-modal | [removal feedback](../../../../../src/commands/removeConnection/removeConnection.ts#L117) | Existing summary policy; confirm restored Reconnect state on storage failure | -| Transfer blocks disconnect/remove/edit | Modal lists conflicting tasks; nothing stopped | [task guard](../../../../../src/services/taskService/resourceUsageHelper.ts#L19) | Safety check | -| Azure partial listing | Successful subscriptions plus one warning with Show Output per listing | [partial listing](../../../../../src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts#L107) | Accepted partial-result policy | -| Azure empty listing | Informational modal with Manage Accounts / Adjust Filters; Retry child | [empty-state helper](../../../../../src/plugins/api-shared/azure/askToConfigureCredentials.ts#L26) | Actionable first-run state | -| Tenant lookup empty / error / timeout | Picker Retry row with reason, plus manual ID and account management | [tenant alternatives](../../../../../src/commands/newConnection/PromptTenantStep.ts#L76) | No wizard dead end | -| User cancellation | No error; no automatic operation replay | [connect cancellation](../../../../../src/tree/documentdb/ClusterItemBase.ts#L173) | Expected | -| Stale action becomes invalid before click | Some handlers return silently | [Reconnect](../../../../../src/commands/disconnect/disconnect.ts#L32), [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L85) | F5: distinguish safety guard from missing feedback | +| Event | Current feedback / termination | Source | Assessment | +| --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- | +| First cluster startup failure | Output detail + translated modal; recovery rows | [first-connect helper](../../../../../src/documentdb/showClusterConnectFailure.ts#L36), [stored startup](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L273) | Expected baseline | +| Cached connect / listDatabases failure | Modal with explanation and detail; action-only children | [expansion failure](../../../../../src/tree/documentdb/ClusterItemBase.ts#L443) | Expected baseline | +| Explained database/index child-expansion failure | Non-modal error with cause appended | [provider catch](../../../../../src/tree/BaseExtendedTreeDataProvider.ts#L606) | F3: sibling tree divergence | +| Open shell after cache eviction | Non-modal “Not signed in”; no terminal | [credential guard](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L63) | F1: offered recovery can dead-end | +| Azure replacement-key read failure | Modal “Azure sign-in needed” or key-read failure | [key read](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L107) | Targeted recovery | +| Tree sign-in fails / cloud provider changed / connection closed mid-sign-in | Translated or dedicated modal | [sign-in flow](../../../../../src/commands/signInAgain/signInAgain.ts#L114) | Explicit action reports failure | +| Bound-view unavailable reason | In-view modal over retained content; Retry and/or Close view | [reason map](../../../../../src/webviews/_integration/describeUnavailableConnection.ts#L11) | Accepted design, not a passive tree row | +| Bound-view Retry throws an unclassified error | Host non-modal error; previous dialog remains | [recovery catch](../../../../../src/webviews/documentdb/useBoundViewRecovery.ts#L125) | F4: feedback split | +| Close-view confirmation RPC fails | In-dialog alert; view remains open | [close confirmation](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L48) | Explicit failure with retry path | +| Worker sign-in expires | Shell bounded output or Playground result; non-modal Sign in again when safe | [Shell](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L907), [Playground](../../../../../src/commands/playground/executePlaygroundCode.ts#L313) | Deliberate worker surface; not automatically a modal inconsistency | +| Worker sign-in action fails | Bounded non-modal warning; original operation not replayed | [Shell action](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L979), [Playground action](../../../../../src/commands/playground/executePlaygroundCode.ts#L402) | Confirm actionable next-step wording | +| Run while user-disconnected / identity changed | Shell error output; Playground warning before run or result after failure | [Shell reason](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L895), [Playground latch](../../../../../src/commands/playground/executePlaygroundCode.ts#L127) | F2: unnecessary new-shell/re-pick guidance for unchanged settings | +| Save fails / persisted state uncertain | Save-error notification; possible incomplete-update warning; old views remain safely disabled | [save reconciliation](../../../../../src/commands/saveConnectionEdit.ts#L76), [credential save](../../../../../src/commands/updateCredentials/ExecuteStep.ts#L106) | Do not confuse “saved” with “usable” | +| Removal partly/all fails | Output details; partial-success summary respects summary setting; all-failed error is non-modal | [removal feedback](../../../../../src/commands/removeConnection/removeConnection.ts#L117) | Existing summary policy; confirm restored Reconnect state on storage failure | +| Transfer blocks disconnect/remove/edit | Modal lists conflicting tasks; nothing stopped | [task guard](../../../../../src/services/taskService/resourceUsageHelper.ts#L19) | Safety check | +| Azure partial listing | Successful subscriptions plus one warning with Show Output per listing | [partial listing](../../../../../src/plugins/api-shared/azure/AzureSubscriptionProviderWithFilters.ts#L107) | Accepted partial-result policy | +| Azure empty listing | Informational modal with Manage Accounts / Adjust Filters; Retry child | [empty-state helper](../../../../../src/plugins/api-shared/azure/askToConfigureCredentials.ts#L26) | Actionable first-run state | +| Tenant lookup empty / error / timeout | Picker Retry row with reason, plus manual ID and account management | [tenant alternatives](../../../../../src/commands/newConnection/PromptTenantStep.ts#L76) | No wizard dead end | +| User cancellation | No error; no automatic operation replay | [connect cancellation](../../../../../src/tree/documentdb/ClusterItemBase.ts#L173) | Expected | +| Stale action becomes invalid before click | Some handlers return silently | [Reconnect](../../../../../src/commands/disconnect/disconnect.ts#L32), [Retry](../../../../../src/commands/retryAuthentication/retryAuthentication.ts#L85) | F5: distinguish safety guard from missing feedback | --- @@ -249,24 +255,32 @@ The extension aims to recover silently when the connection identity has not chan and to preserve work rather than replay interrupted operations or silently change permissions. Explicit Disconnect offers a tab choice and a single tree Reconnect; changed saved settings permanently retire old webviews, while workers have separately -documented restart rules. The strongest suspected P1 gaps are an offered Shell recovery -that may not open, unnecessarily restrictive worker recovery wording, and inconsistent -feedback between cluster and descendant tree failures. Three P2 Flags cover Retry -feedback placement, stale-action silence, and Playground sign-in completion feedback. -None has yet been confirmed through hands-on use in this review. +documented restart rules. The live pass confirms that Shell and Playground can recover after tree Reconnect +without a new terminal or connection pick, despite their wording. The operator wants +unauthenticated Shell access from failure rows, modal errors for tree-originated actions, +simpler retained-view labels and readable, consistent debugging output. A missing +Disconnect menu item after credential repair still needs current-version reproduction; +Retry/stale-action feedback choices remain open. The lack of a dedicated Playground +sign-in completion message is accepted as-is. --- ## Priority index -| # | Priority | Item | Status | -| --- | --- | --- | --- | -| F1 | **P1** | Open shell recovery is offered when cache eviction can block opening | 🟠 Open | -| F2 | **P1** | Worker recovery wording requests unnecessary new Shell / connection pick | 🟠 Open | -| F3 | **P1** | Cluster and descendant tree failures use different feedback surfaces | 🟠 Open | -| F4 | **P2** | Retry exceptions appear outside the retained-view dialog | 🟠 Open | -| F5 | **P2** | State-drift guards silently terminate explicit recovery clicks | 🟠 Open | -| F6 | **P2** | Playground sign-in succeeds without a completion or rerun cue | 🟠 Open | +| # | Priority | Item | Status | +| --- | -------- | --------------------------------------------------------------------------------- | -------------- | +| F1 | **P1** | Offer unauthenticated Shell from failure rows; choose a clear label | 🟠 Open | +| F2 | **P1** | Worker recovery wording requests unnecessary new Shell / connection pick | 🟠 Open | +| F3 | **P1** | Use modal failure feedback for tree-originated actions | 🟠 Open | +| F7 | **P1** | Disconnect missing after credential repair; version uncertain | 🟡 Open (soft) | +| F4 | **P2** | Retry exceptions appear outside the retained-view dialog | 🟠 Open | +| F5 | **P2** | State-drift guards silently terminate explicit recovery clicks | 🟠 Open | +| F8 | **P2** | Shell Disconnected output looks like text entered at the prompt | 🟠 Open | +| F9 | **P2** | Shorten Keep open (disabled) to Keep open | 🟠 Open | +| F10 | **P2** | Explain that decoded-password confirmation saves the correctly formatted password | 🟠 Open | +| F11 | **P2** | X label should describe access, not only copying | 🟠 Open | +| F12 | **P2** | Unify connection/worker debug-stat format for human readability | 🟠 Open | +| F6 | **P2** | Playground sign-in succeeds without a completion or rerun cue | 🚫 Closed | ## P0 — Blocking (the user gets stuck) @@ -274,36 +288,78 @@ No P0 seeded. Promote an item only after confirming that no usable recovery path ## P1 — Broken / misleading, or consistency & safety -### F1. Open shell recovery can end before a terminal opens ⚠️ +### F1. Error-recovery Shell should not retry the failing authentication ⚠️ **Priority:** P1 · **Status:** 🟠 Open -**Observation:** Not yet observed live. Fail an initial stored Native-auth connection, -dismiss the modal, and click its Open shell recovery row. +**Observation (operator, 2026-11-27):** a No Authentication connection opened the Shell +and showed a prompt. An invalid key/password opened a Shell that attempted the saved +authentication and failed. Relevant output, with the host omitted: + +```text +Connected to: {test host} +Authentication: No Authentication | Database: test +Type "help" for available commands. +test> +``` + +```text +Failed to connect: Invalid key +Run a command to try connecting again, or close this terminal. +test> +``` + +> **TN leans towards always offering Shell without authentication from error rows.** +> The label should make that difference explicit; “Open shell (w/o auth)” was offered +> as a possible name, not a final wording decision. **Finding:** -- ⚠️ [Every cluster failure offers Open shell](../../../../../src/tree/documentdb/ClusterItemBase.ts#L431), - but [the Shell command refuses to open without cached credentials](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L63). +- ⚠️ [Every cluster failure offers Open shell](../../../../../src/tree/documentdb/ClusterItemBase.ts#L431). + The [current command uses ordinary Shell startup](../../../../../src/commands/openInteractiveShell/openInteractiveShell.ts#L60); + [the worker builds Native authentication from cached credentials](../../../../../src/documentdb/shell/ShellSessionManager.ts#L435), + rather than selecting an unauthenticated diagnostic session for failure rows. + This supports the reported NoAuth-versus-invalid-key behavior. - [Failed startup evicts non-recoverable credentials](../../../../../src/tree/documentdb/ClusterItemBase.ts#L324); [the stored connection calls that cleanup](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L386) before returning its recovery children. The user can therefore receive “Not signed in” - instead of the promised diagnostic terminal. + instead of the promised diagnostic terminal. This original pre-assessment branch + remains conditional; it does **not** mean every invalid-key click fails to open. + The operator's tested branch opened and then failed authentication instead. - 🔍 This conflicts with the stated intent that experts can open a Shell on every failure in the [tree architecture guidance](../../../../../.github/skills/tree-cluster-architecture/SKILL.md#failure-presentation-actions-only). It is a command precondition gap, not evidence that Shell automatically repairs authentication. -💡 **Suggestion:** Confirm the failed-auth and failed-network variants separately, then -make the offered action usable or accurately gate/explain it. Do not introduce automatic -sign-in or execution merely to make the row work. +💡 **Suggestion:** For error-row entry only, open a separately unauthenticated Shell +without changing saved credentials or the existing connection identity. Do not silently +fall back to saved credentials after a server rejects anonymous operations. A Shell +opening without authentication is not a promise that database commands are authorized. +Normal context-menu Open Shell should keep its existing authenticated behavior. + +| Name option | Pros | Cons | +| ------------------------------------- | ------------------------------------------------------ | ----------------------------------------------- | +| **Open shell without authentication** | Recommended; explicit, plain language, no abbreviation | Longer tree row | +| Open unauthenticated shell | Accurate and shorter | More technical vocabulary | +| Open shell (no authentication) | Consistent with the No Authentication method label | Parenthetical is less readable in a narrow tree | +| Open shell (w/o auth) | Short | Two abbreviations; least clear for non-experts | + +**Decision state:** operator's preferred recovery direction recorded; final label and +implementation are still open. No anonymous-startup behavior has been added. ### F2. Retained-worker guidance overstates when reopening or re-picking is required ⚠️ **Priority:** P1 · **Status:** 🟠 Open -**Observation:** Not yet observed live. Disconnect with unchanged settings, try the -retained Shell/Playground while disconnected, reconnect in the tree, then run again -without opening a new terminal or selecting a connection. +**Observation (operator, 2026-11-27):** the disconnected Shell requested a tree reconnect +and a new Shell, but after reconnecting the **same terminal** ran the query successfully. +The disconnected Playground warned: + +> This connection is unavailable. Reconnect from the tree, then re-pick it here. + +After tree Reconnect, running the retained Playground recovered without a connection +pick. The operator found “re-pick it here” difficult to interpret. The other two +observations reported with F2 are tracked separately as [F7](#f7-disconnect-menu-missing-after-credential-repair) +and [F8](#f8-disconnected-is-written-beside-the-active-shell-prompt). **Finding:** @@ -319,16 +375,28 @@ without opening a new terminal or selecting a connection. Source behavior supports that intent; the error wording is the mismatch. Identity or destination changes still require the stricter guidance. -💡 **Suggestion:** Separate unchanged-connection recovery wording from removed/changed -connection wording. Confirm worker-local variables/cursors are lost and interrupted -commands are not replayed; do not promise state preservation beyond text and scrollback. +> **Decision (Iteration 1):** for an unchanged disconnected connection, direct the person +> to reconnect from the tree and run the command/script again, not open a new Shell or +> re-pick the Playground. **Reason:** the operator verified in-place recovery; “re-pick +> it here” is not easy to follow. + +💡 **Proposed copy:** Shell: +**“Disconnected. Reconnect from the tree, then run your command again.”** +Playground: +**“This connection is disconnected. Reconnect from the tree, then run the script again.”** +These are proposed exact strings for the approved direction, not current source copy. +Preserve separate guidance when the connection was removed or its host/identity changed; +do not promise recovery or preservation of worker-local variables in those cases. ### F3. Sibling tree expansion failures use modal versus notification feedback ⚠️ **Priority:** P1 · **Status:** 🟠 Open -**Observation:** Not yet observed live. Compare expanding the cluster and an already -visible database/Indexes node after the same infrastructure failure. +**Observation / direction (operator, 2026-11-27):** +“yes, modal all the way please, that's our ux guideline.” +The later clarification is: **“I meant modals for tree actions.”** +This is a policy decision; the operator did not supply a new reproduction transcript +for each descendant failure. **Finding:** @@ -343,9 +411,37 @@ visible database/Indexes node after the same infrastructure failure. not a newly introduced renderer; code wins for current behavior, while the discrepancy should be resolved explicitly rather than silently treating the guidance as implemented. -💡 **Suggestion:** Confirm the practical recovery path at both hierarchy levels and choose -a consistent tree policy. Keep worker and database-command notification policy separate; -see [O1](#o1-which-failures-need-a-modal-versus-in-context-feedback-f3f4). +> **Decision (Iteration 1):** failures of tree-originated actions, including expansion +> and tree commands, use modal feedback. **Reason:** this is the operator's stated UX +> guideline. Keep tree children as recovery actions, not error paragraphs. + +This does **not** make every worker or webview failure a host modal. It supersedes the +earlier suggestion here to leave tree database-command notification policy separate. +Use a translated heading and separate error detail consistently; avoid two modals for +one action. [O1](#o1-tree-modal-policy-and-in-view-feedback-are-separate-f3f4) +records the same scoped decision. + +### F7. Disconnect menu missing after credential repair + +**Priority:** P1 · **Status:** 🟡 Open (soft) + +**Observation (operator, 2026-11-27):** failed connect → Update Credentials → allow +reconnect with fresh credentials → the cluster context menu did not offer Disconnect. +The operator explicitly questioned whether an older version was being tested. +After restart and a fresh healthy connection, Disconnect was available. + +**Finding:** + +- 🔍 [The manifest gates Disconnect](../../../../../package.json#L1355) on a cluster + tree item with the `connected` context tag and no multi-selection. +- [The tag is emitted when a cached client exists and no latch applies](../../../../../src/tree/documentdb/ClusterItemBase.ts#L689); + [the stored cluster uses that helper](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L484). +- [Credential repair resets error state when reconnect was chosen, then refreshes](../../../../../src/commands/updateCredentials/updateCredentials.ts#L183). + These are the current-code eligibility checks, **not a confirmed root cause**. + +💡 **Suggestion:** reproduce that exact sequence in the current build before changing +the menu. Capture client existence/latch and the refreshed tree context tag. Do not +claim the old-version possibility has been ruled out or mark the feature fixed by restart. ## P2 — Polish, expectation, or feature gap @@ -368,6 +464,11 @@ unreachable; compare a typed unavailable result and an unclassified thrown error failure should update the dialog or remain a notification. Preserve the translated reason and the ability to copy/close; never replay the failed operation. +**Operator request (Iteration 1):** provide options with pros/cons. Recommendation: +keep Retry failure **inside the existing in-view dialog**, without stacking a host modal. +[O2](#o2-where-should-a-failed-in-view-retry-be-explained-f4) gives the alternatives. +This remains a suggestion; F3's tree-modal decision does not decide F4 automatically. + ### F5. Stale recovery actions can be safely rejected without explaining why ⚠️ **Priority:** P2 · **Status:** 🟠 Open @@ -391,13 +492,20 @@ available, change the connection's state elsewhere, then invoke the old action. should stay quiet, from an explicit click on a still-visible stale action. Consider a refresh or brief bounded next-step notice only for the latter. +**Operator request (Iteration 1):** provide options with pros/cons. Recommendation: +re-check and refresh on explicit stale clicks; show an actionable **modal for a failed +tree-originated action**, but keep cancellation/background disposal quiet and do not +report an already-completed action as an error. See +[O3](#o3-how-should-an-explicit-stale-action-end-f5). Decision remains open. + ### F6. Playground sign-in has no equivalent of Shell's “run again” completion cue ⚠️ -**Priority:** P2 · **Status:** 🟠 Open +**Priority:** P2 · **Status:** 🚫 Closed -**Observation:** Not yet observed live. Let a Playground run fail because sign-in is -required, choose Sign in again, complete authentication, then inspect the retained result -and connection affordances without rerunning. +**Observation / comment (operator, 2026-11-27):** F6 is acceptable. The operator also did +not notice Shell's “Sign-in restored” line during testing, possibly because a `find()` +produced enough output to consume the visible scrollback. That explanation is a +possibility, not a verified cause. **Finding:** @@ -408,13 +516,145 @@ and connection affordances without rerunning. The authentication provider may show its own UI, but the Playground recovery handler supplies no equivalent completion/rerun cue. -💡 **Suggestion:** Confirm whether the surrounding VS Code UI is sufficient. If not, add -a small success/next-step signal rather than automatically executing the query. +> **Decision (Iteration 1):** leave the Playground completion behavior as-is. +> **Reason:** the operator accepts the lack of a dedicated completion/rerun cue. + +**Closed reason:** accepted as-is; no implementation change and no commit claimed. +Shell's line is emitted only after the explicit Shell Sign in again route succeeds +([source](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L962)); ordinary +tree Reconnect/worker restart is not evidence that the line must have appeared. +See [Q1](#q1-can-the-shell-scrollback-buffer-be-configured) for the buffer question. + +### F8. Disconnected is written beside the active Shell prompt + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation (operator, 2026-11-27):** + +```text +a11y-db> +a11y-db> Disconnected +a11y-db> +``` + +The system word looks like something the person entered at the prompt, rather than a +separate connection-state message. + +**Finding:** [disconnect writes Disconnected without first moving off the current line](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L274); +[writeLine appends only a trailing CRLF](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L1120), +and [showPrompt leaves the cursor after the prompt](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L1081). +This directly supports the reported rendering. + +> **Decision (Iteration 1):** render Disconnected on a separate system-output line +> before a fresh prompt. **Reason:** it must not look like user-entered input. + +💡 **Suggestion:** verify idle, partially typed and evaluating states when implementing; +preserve input intentionally rather than blindly adding a newline in every output path. + +### F9. Shorten the retained-tab choice + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** C0's host-modal option “Keep open (disabled)” is too complex; +the operator knows the state is disabled but finds the label unclear. + +**Finding:** [the teardown modal currently uses Keep open (disabled)](../../../../../src/documentdb/connectionTeardown.ts#L78). +The choice controls retained webviews; it does not close the Shell terminal or Playground +file. The later overlay can explain unavailable database operations. + +> **Decision (Iteration 1):** change the visible choice to **“Keep open”**, dropping +> “(disabled)”. **Reason:** the suffix is unclear and unnecessarily complex. + +Retain disabled-operation behavior; this is a label change, not permission to execute. + +### F10. Explain what the decoded-password save will store + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** after decoding succeeds, enhance +“Connected to "Orders" using the decoded password. Would you like to update your saved credentials?” +so it states that the saved credentials will receive the correctly formatted password. + +**Finding:** [the current successful-retry prompt](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L350) +offers “Update saved password” and saves the decoded password only on that explicit action. +It does not reveal the password in the prompt. + +**Requested change (Iteration 1):** explicitly describe saving the correctly formatted +password into the connection's saved credentials. The operator specified the information +to add; no separate rationale or final exact sentence was supplied. + +💡 **Proposed copy:** +**“Connected to "Orders" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?”** +Keep the existing “Update saved password” action and do not include the secret value. + +### F11. X should describe access to retained contents + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** C6's X accessible name should describe accessing contents, +not only copying them. + +**Finding:** [the overlay's current accessible name](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L105) +is “Dismiss dialog to copy view contents”; dismissal exposes the retained content while +database-operation guards remain in place. + +> **Decision (Iteration 1):** use **“Dismiss dialog to access view contents”**. +> **Reason:** dismissing enables access/inspection, not just the narrower act of copying. + +No change to recovery or close semantics is implied. + +### F12. Make connection and worker debugging output use one readable format + +**Priority:** P2 · **Status:** 🟠 Open + +**Observation / comment:** Show Connection Stats and Show Worker Stats use different +formats. The operator requests unification and authorizes selecting the better format, +emphasizing that humans also read this debugging output. + +**Finding:** [connection stats compress multiple fields onto one Client line](../../../../../src/commands/showConnectionStats/showConnectionStats.ts#L40); +[worker stats use ruled headings and one field per line](../../../../../src/commands/showWorkerStats/showWorkerStats.ts#L18). +These commands report different things: host cached clients versus worker/session state. + +> **Decision (Iteration 1):** unify presentation for human-readable debugging. +> **Reason:** the operator explicitly prioritizes readability for human investigation. + +**Selected format recommendation:** use the worker-style **multiline labeled record** +structure for both commands, with consistent indentation, headings and units; omit +decorative ruler lines. Do not flatten it into the host command's dense key/value line. +Preserve the separate facts and field availability. A cached client is not proof of a +live socket, and worker count is not necessarily connection count. +See [O4](#o4-shared-debug-stat-format-f12) for a concrete shape and trade-offs. ## P3 — Nice-to-have / cosmetic / acknowledged -No cosmetic items seeded. Inspect layout, wording, themes and focus during the live pass; -do not turn this preparation into a pixel-level review. +### Q1. Can the Shell scrollback buffer be configured? + +🔍 **Answered** + +**Observation:** the operator printed 50 documents and could not scroll back through +all output. Document count is not the same as terminal line count: multiline/wrapped +documents can consume many more lines. + +**Answer:** yes. The DocumentDB Shell uses a VS Code terminal; the live scrollback is +controlled by **`terminal.integrated.scrollback`**, whose documented default is **1000 +lines**. For example, in **user** settings: + +```json +{ + "terminal.integrated.scrollback": 10000 +} +``` + +This is a suggestion, not a setting changed by this review. Increase it before reproducing +the long-output case; output already discarded from scrollback is not recovered. +`terminal.integrated.persistentSessionScrollback` is a separate restored-session setting, +not the primary live-buffer control. The Shell's `clear` handling explicitly clears +scrollback, so increasing the limit does not preserve output across that action. + +Sources: [VS Code terminal buffer documentation](https://code.visualstudio.com/docs/terminal/basics#_navigating-the-buffer), +[persistent sessions](https://code.visualstudio.com/docs/terminal/advanced#_persistent-sessions), +[Shell clear](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L1002). +No new extension-specific scrollback setting is proposed. ## Implemented @@ -427,35 +667,154 @@ not relabeled as a fix from this pass. ### Preparation — before Iteration 1 -| # | Item | Decision (why) | Outcome | -| --- | --- | --- | --- | +| # | Item | Decision (why) | Outcome | +| ----- | ------------------------------------------------------------- | ------------------------------ | ------------------------------ | | F1–F3 | Recovery availability, worker guidance, sibling tree feedback | None; code-verified seeds only | 🟠 Open → hands-on Iteration 1 | -| F4–F6 | Retry feedback, stale clicks, Playground sign-in completion | None; code-verified seeds only | 🟠 Open → hands-on Iteration 1 | - -### Iteration 1 — hands-on pass pending - -Work one journey at a time using Appendix B. Record the operator's observation before -adjusting a Flag. Capture each approved choice and its reason before coding; commit fixes -individually and link verification. Everything unresolved carries to Iteration 2. +| F4–F6 | Retry feedback, stale clicks, Playground sign-in completion | None; code-verified seeds only | 🟠 Open → hands-on Iteration 1 | + +### Iteration 1 — operator feedback recorded, implementation pending + +| # | Operator outcome / reason | Current outcome | +| -------------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| F1 | Prefers anonymous Shell on error rows; invalid saved auth otherwise fails again | 🟠 Open; final label/implementation not decided | +| F2 | In-place worker recovery works; re-pick wording is unclear | 🟠 Open; rerun guidance approved | +| F3 / O1 | Modal errors for tree actions are the UX guideline | 🟠 Open; scoped policy approved | +| F4 / O2 | Wants guidance with pros/cons | 🟠 Open; recommendation recorded, no choice yet | +| F5 / O3 | Wants guidance with pros/cons | 🟠 Open; recommendation recorded, no choice yet | +| F6 | Acceptable as-is | 🚫 Closed; no code change | +| F7 | Possibly tested an older version | 🟡 Open (soft); current-build reproduction required | +| F8 | Disconnected must not look like entered input | 🟠 Open; separate output line approved | +| F9 | Disabled suffix is unclear/complex | 🟠 Open; Keep open approved | +| F10 | Wants the saved, correctly formatted password made explicit | 🟠 Open; proposed copy recorded | +| F11 | Access is broader than copying | 🟠 Open; accessible name approved | +| F12 | Debugging is also for humans; prioritize readability | 🟠 Open; shared multiline records recommended | +| Dashboard diagnostics link | Future work rather than widening this PR | 🔗 Tracked in [#1141](https://github.com/microsoft/vscode-documentdb/issues/1141) | +| Q1 | Asks how to increase Shell buffer capacity | 🔍 Answered; VS Code scrollback setting | + +No product changes were requested for execution in this recording pass. Open items stay +in the ledger and carry to the next fix iteration; code, tests, localization and shipped +documentation have not been changed to pretend these choices are already implemented. --- ## Open ideas — options, pros & cons -### O1. Which failures need a modal versus in-context feedback? (F3/F4) +### O1. Tree modal policy and in-view feedback are separate (F3/F4) Accepted design already places typed unavailable webview reasons in a modal and keeps -worker failures in bounded output/notifications. The open question is the *sibling -failure branches*, not whether every error in the extension should block the user. +worker failures in bounded output/notifications. The open question is the _sibling +failure branches_, not whether every error in the extension should block the user. + +| Option | Pros | Cons | +| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | +| **A. Keep current feedback boundaries** | Minimal change; preserves established command notifications | Sibling tree expansions and Retry outcomes remain asymmetric; guidance needs to describe this honestly | +| **B. Align tree-expansion errors; keep Retry failures inside their existing dialog** | One feedback location per journey; clearer relation between cause and recovery | Changes a shared tree boundary and needs explicit scope, accessibility and regression checks | +| **C. Make every lifecycle failure a host modal** | Prominent feedback everywhere | Can stack host/webview modals; disrupts workers and conflicts with deliberate surface-specific design | + +> **Decision (Iteration 1):** B's tree-alignment direction is accepted, with the +> operator's clarification **“I meant modals for tree actions.”** +> **Reason:** modal feedback for tree-originated failures is the UX guideline (F3). + +Tree-originated expansion and command failures should therefore be aligned to modal +feedback. This is not option C: do not impose host modals on all worker/webview errors. +The original B bundled tree alignment with in-dialog Retry feedback; F4 remains open +because the operator separately requests its pros/cons. O2 records that recommendation +without treating the tree decision as approval of a particular in-dialog implementation. + +### O2. Where should a failed in-view Retry be explained? (F4) + +| Option | Pros | Cons | +| -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| **A. Keep the current host notification** | Minimal implementation; existing error renderer and translated cause | May be missed while an old reason dialog remains; two feedback locations | +| **B. Show the Retry failure inside the existing unavailable dialog** | Recommended; keeps cause and actions together; no second modal; can announce the error once | Needs a clear distinction between the persistent unavailable reason and the failed attempt; detailed causes should not overwhelm the short explanation | +| **C. Open an additional host modal** | Prominent, hard to miss | Stacks host and webview modals; extra dismissal; does not follow from the tree-only modal policy | + +💡 **Suggested:** B. Keep the existing reason and add a concise failure explanation, +for example **“Could not reconnect. Check the network or server, then try Retry again.”** +only when that cause is supported; otherwise use a bounded **“Unable to recover the connection.”** +Keep translated technical detail available without replacing the user's next step with +a raw stack. Retry/Close/X become usable again after failure; no operation replay. +Use an alert/live announcement so a keyboard/screen-reader user notices the failed attempt. +Exact wording and detail disclosure remain proposals, not approved behavior. + +**Decision state:** awaiting the operator's choice. Modal **inside** the webview is +already the current unavailable presentation; the recommendation is to keep subsequent +failure feedback there, not open a new host modal. + +### O3. How should an explicit stale action end? (F5) + +| Option | Pros | Cons | +| ------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- | +| **A. Preserve every silent early return** | Least intrusive; no accidental startup or identity changes | Person can click an apparent action and see nothing happen | +| **B. Show a modal for every stale event** | Uniformly visible | Noisy for background replies, cancellation and already-completed actions; can show obsolete errors | +| **C. Classify the outcome of an explicit click, refresh, then explain only a failed user action** | Recommended; keeps safety guards; consistent with tree-modal guideline; silence remains appropriate for non-actions | Requires precise classification of missing/changed/already-completed state and foreground ownership | + +💡 **Suggested:** C, with these separate endings: + +- **Explicit tree click, removed/changed target:** refresh relevant tree state, then a + bounded modal with a next step; proposed examples: + **“This connection was removed. Choose another connection.”** or + **“This connection changed. Refresh the tree and try again.”** + Use the actual reason, not an inferred generic network failure. +- **Already healthy/completed:** refresh/reveal the current state; do not call a successful + or no-longer-needed recovery an error. Any completion acknowledgement is optional. +- **Worker Sign in again notification became stale:** explain only if the terminal/file + still exists and that person actually chose the action; use that worker's existing + bounded surface, not the tree's host-modal rule by accident. +- **User cancelled, view disposed, obsolete background reply:** remain silent. + +Do not auto-connect another identity or restart a disposed worker to make a stale click +look successful. **Decision state:** awaiting operator choice. + +### O4. Shared debug-stat format (F12) + +| Format | Pros | Cons | +| ---------------------------- | ---------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | +| **Multiline labeled blocks** | Recommended; scan and compare fields; explicit units; works in Output without column alignment | More vertical space | +| Dense key/value lines | Compact; easy to grep a whole record | Existing host format is harder for humans to scan | +| Aligned tables | Compact comparison for a small set of common columns | Long IDs wrap; host/worker fields differ; missing cells can look like real zero values | + +**Recommended shape**, illustrative rather than current output: + +```text +[Connection Stats] + Entries: 1 + Connection 1: + Source: Extension host + Client state: cached + Generation: 4 + Age (ms): 32000 + Auth method: NativeAuth + Startup ID: {startup ID} + +[Worker Stats] + Shell sessions: 1 + Shell 1: + Terminal: {terminal title} + Worker state: ready + Initialized: true + Evaluating: false + Database: test + Auth method: NativeAuth +``` -| Option | Pros | Cons | -| --- | --- | --- | -| **A. Keep current feedback boundaries** | Minimal change; preserves established command notifications | Sibling tree expansions and Retry outcomes remain asymmetric; guidance needs to describe this honestly | -| **B. Align tree-expansion errors; keep Retry failures inside their existing dialog** | One feedback location per journey; clearer relation between cause and recovery | Changes a shared tree boundary and needs explicit scope, accessibility and regression checks | -| **C. Make every lifecycle failure a host modal** | Prominent feedback everywhere | Can stack host/webview modals; disrupts workers and conflicts with deliberate surface-specific design | +Use the same record/field conventions for Playground workers, include the existing +counts, held/pending states, Entra expiry, session IDs and init-duration facts where +available, and choose one explicit missing-value representation. Preserve truthful +labels: client state `cached` is not equivalent to a successful ping; a pending startup +is not a live client. Keep existing redaction boundaries and do not add credential values. +This is the selected recommendation under the operator's request to choose a readable +format; no debug command has yet been changed. -> 💡 **Suggested:** B if the live pass confirms missed or confusing feedback. Preserve -> worker output and silent background recovery. This is not an approved design change. +### O5. Dashboard link to Connection Diagnostics + +**Status:** 🔗 Tracked in [#1141](https://github.com/microsoft/vscode-documentdb/issues/1141). + +The operator requested future work to make Connection Diagnostics reachable from the +Dashboard for its own connection. It is distinct from View Raw Diagnostics, which +exports different information. The issue asks for discoverable navigation and reuse +of the existing diagnostics flow, without silently selecting another connection. +It is not an active implementation item in #1136. --- @@ -518,15 +877,15 @@ Shell and a Playground against the same scratch connection. Keep token-expiry/ac checks separate from network failure checks; use the stats commands for observation, not as proof that renewal worked. -| Phase | Exercise | Confirm before moving on | -| --- | --- | --- | -| 1. First-run and entry parity | Expand; directly open Dashboard/Shell before expanding; empty DB/collection; cancel auth; fail initial auth; click each recovery row | Entries are actionable; no passive error rows; correct repair order; F1 and F3 | -| 2. Normal and silent recovery | Read/query in tree, views, Shell and Playground after idle/token expiry; observe Dashboard/background work | No surprise sign-in; same identity; actual operations still succeed; no interrupted write replay | -| 3. Explicit authentication repair | Tree Retry sign-in; worker Sign in again; cancel; wrong identity; Azure key Retry; stale notification | Failure explanation and next step; F5/F6; identity remains pinned where required | -| 4. Disconnect and retained work | `ask`, `closeAll`, `keepOpenDisabled`; dirty discard/cancel; X-copy and repeated blocked actions; reconnect and Retry | Modal choices match settings; no data loss on cancel; F2/F4; workers restart only on a new run; Dashboard exception is legible | -| 5. Saved edits | Cancel, unchanged save, password-only change, destination/account change; Shell keep/disconnect choice | Old webviews never resume after a changed save; unchanged save does not permanently lock them; copied drafts preserved; workers obey the documented distinction | -| 6. Transfers and destructive actions | Start scratch import/export/copy; attempt disconnect/remove/folder delete; later remove with retained views; cancel pending Dashboard delete across disconnect | Conflicting transfer continues; shared confirmation respected; no old delete replay; removal is distinct from Disconnect | -| 7. Discovery and accessibility | No accounts; filters hide results; partial listing; tenant lookup retry/manual ID; keyboard-only modal use in light/dark/high contrast | Account/filter exits work; Show Output is reachable; modal title/detail announced; focus and X-copy route usable | +| Phase | Exercise | Confirm before moving on | +| ------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1. First-run and entry parity | Expand; directly open Dashboard/Shell before expanding; empty DB/collection; cancel auth; fail initial auth; click each recovery row | Entries are actionable; no passive error rows; correct repair order; F1 and F3 | +| 2. Normal and silent recovery | Read/query in tree, views, Shell and Playground after idle/token expiry; observe Dashboard/background work | No surprise sign-in; same identity; actual operations still succeed; no interrupted write replay | +| 3. Explicit authentication repair | Tree Retry sign-in; worker Sign in again; cancel; wrong identity; Azure key Retry; stale notification | Failure explanation and next step; F5/F6; identity remains pinned where required | +| 4. Disconnect and retained work | `ask`, `closeAll`, `keepOpenDisabled`; dirty discard/cancel; X-copy and repeated blocked actions; reconnect and Retry | Modal choices match settings; no data loss on cancel; F2/F4; workers restart only on a new run; Dashboard exception is legible | +| 5. Saved edits | Cancel, unchanged save, password-only change, destination/account change; Shell keep/disconnect choice | Old webviews never resume after a changed save; unchanged save does not permanently lock them; copied drafts preserved; workers obey the documented distinction | +| 6. Transfers and destructive actions | Start scratch import/export/copy; attempt disconnect/remove/folder delete; later remove with retained views; cancel pending Dashboard delete across disconnect | Conflicting transfer continues; shared confirmation respected; no old delete replay; removal is distinct from Disconnect | +| 7. Discovery and accessibility | No accounts; filters hide results; partial listing; tenant lookup retry/manual ID; keyboard-only modal use in light/dark/high contrast | Account/filter exits work; Show Output is reachable; modal title/detail announced; focus and X-copy route usable | During Phase 4, also check whether long Retry waits have a perceivable busy signal: [the overlay disables actions while recovering](../../../../../src/webviews/components/DisconnectedOverlay.tsx#L115), @@ -549,7 +908,9 @@ pre-merge review so this snapshot is not mistaken for current behavior. ## Appendix C — message walkthrough: what the user sees, and when -This is a **script for the hands-on review, not a record of runtime results**. +This is the **source-based script for the hands-on review**; runtime observations and +decisions from Iteration 1 are recorded in the F-items above, not retroactively substituted +for the current source wording here. The source snapshot is unchanged from the preparation above. Quoted wording is the English source wording; `Orders`, `inventory` and `reviews` are fictional display names used to instantiate templates. `{error}`, `{host}` and similar placeholders @@ -564,26 +925,30 @@ Links identify the renderer or caller that selects each message. ### C0. Know which surface you are reviewing -| Surface | What the person experiences | Example in this walkthrough | -| --- | --- | --- | -| Notification | VS Code information/warning/error message; does not block the whole window | “Could not sign in again. Open a new shell from the tree.” | -| Progress notification | Cancellable progress, possibly delayed; not a success or error toast | `Connecting to "Orders"…` | -| Host modal | A VS Code dialog with a heading, optional detail and buttons; interrupts the window | “Disconnect?” / “Close all” / “Keep open (disabled)” | -| Tree recovery action | Clickable child under a failed/disconnected node; not a paragraph explaining the failure | “Retry sign-in”, “Diagnose connection…”, “Reconnect” | -| In-view overlay/dialog | Modal **inside** a Collection, Document or Dashboard webview; existing contents stay mounted behind it | “Connection changed” with “Close view” | -| Persistent inline message | MessageBar or panel error that stays in the view, rather than a transient notification | “Failed to read cluster information: {error}” with “Retry” | -| Picker/input validation | Quick Pick title, row, detail or input validation inside an ongoing wizard | “Retry loading tenants” / “Loading tenants timed out after 5 seconds.” | -| Terminal output | Shell scrollback, connection banner, prompt and spinner; separate from host notifications | “Sign-in restored. Run your command again.” | -| Playground result document | Read-only execution output next to the source file; survives a dismissed notification | “Error executing query” plus a bounded recovery message | -| Badge, CodeLens, tooltip or accessible name | Smaller state and action cues; some are read aloud rather than shown as prose | “Disconnected”, “Running…”, “Dismiss dialog to copy view contents” | -| Screen-reader announcement | Live-region message; **not** necessarily visible text or a toast | “Reconnected”, “Lost connection to the cluster.” | -| Output channel only | Detail is available if the person opens Output; not an acknowledgement on its own | “Skipped an Azure tenant because its subscriptions could not be listed.” | -| Deliberate silence | No new message on successful silent renewal, cancellation or obsolete replies | A successful operation simply continues after token renewal | +| Surface | What the person experiences | Example in this walkthrough | +| ------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------ | +| Notification | VS Code information/warning/error message; does not block the whole window | “Could not sign in again. Open a new shell from the tree.” | +| Progress notification | Cancellable progress, possibly delayed; not a success or error toast | `Connecting to "Orders"…` | +| Host modal | A VS Code dialog with a heading, optional detail and buttons; interrupts the window | “Disconnect?” / “Close all” / “Keep open (disabled)” | +| Tree recovery action | Clickable child under a failed/disconnected node; not a paragraph explaining the failure | “Retry sign-in”, “Diagnose connection…”, “Reconnect” | +| In-view overlay/dialog | Modal **inside** a Collection, Document or Dashboard webview; existing contents stay mounted behind it | “Connection changed” with “Close view” | +| Persistent inline message | MessageBar or panel error that stays in the view, rather than a transient notification | “Failed to read cluster information: {error}” with “Retry” | +| Picker/input validation | Quick Pick title, row, detail or input validation inside an ongoing wizard | “Retry loading tenants” / “Loading tenants timed out after 5 seconds.” | +| Terminal output | Shell scrollback, connection banner, prompt and spinner; separate from host notifications | “Sign-in restored. Run your command again.” | +| Playground result document | Read-only execution output next to the source file; survives a dismissed notification | “Error executing query” plus a bounded recovery message | +| Badge, CodeLens, tooltip or accessible name | Smaller state and action cues; some are read aloud rather than shown as prose | “Disconnected”, “Running…”, “Dismiss dialog to copy view contents” | +| Screen-reader announcement | Live-region message; **not** necessarily visible text or a toast | “Reconnected”, “Lost connection to the cluster.” | +| Output channel only | Detail is available if the person opens Output; not an acknowledgement on its own | “Skipped an Azure tenant because its subscriptions could not be listed.” | +| Deliberate silence | No new message on successful silent renewal, cancellation or obsolete replies | A successful operation simply continues after token renewal | “Error nodes” in the lifecycle tree are the action rows above, sometimes internally tagged `error`. They are **not** passive error-summary rows. Read the failure modal first, then review whether the surviving action labels are enough to guide recovery. +**Iteration 1 wording decision:** the host-modal choice quoted above is still the current +**“Keep open (disabled)”**; the approved replacement is **“Keep open”** ([F9](#f9-shorten-the-retained-tab-choice)). +The retained-view behavior stays unavailable for database operations. + ### C1. “I expand Orders and connect for the first time” Start with a saved scratch connection. Expand it, then repeat with a connection slow @@ -598,6 +963,7 @@ enough to expose progress. Finally repeat with an empty server. error dialog just to report the cancellation. Sources: [tree progress](../../../../../src/tree/documentdb/ClusterItemBase.ts#L263) and [delay helper](../../../../../src/utils/withProgress.ts#L8). + 2. **When it succeeds:** the tree shows databases. If none exist, the child is **“Create Database…”**, not “No databases found”. Inside an empty database the equivalent action is **“Create Collection…”**. Those entries start creation @@ -610,6 +976,7 @@ enough to expose progress. Finally repeat with an empty server. The initial successful connection does not have a dedicated lifecycle “Connected successfully” toast. Tree contents, the optional Dashboard and its badge are the visible completion. + 4. **If the person checks Output:** examples include `Loading cluster details for "Orders"`, `Reusing active connection for "Orders".` and `Could not connect to "Orders".` These are Output messages, not three separate @@ -660,12 +1027,12 @@ Sources: [modal composition](../../../../../src/documentdb/showClusterConnectFai **After dismissing the modal, review the action rows.** Examples: -| Failed state | Example children, in order | Important absence | -| --- | --- | --- | -| Stored Native credentials rejected | “Update connection string…”, “Update credentials…”, “Diagnose connection…”, “Open shell” | No ordinary Retry while the stored-credential rejection latch requires editing | -| Recoverable verified Entra sign-in failure on a stored connection | Provider repair rows when applicable, then “Retry sign-in”, “Diagnose connection…”, “Open shell” | No ordinary Retry beside Retry sign-in | -| Ordinary retryable failure | Provider repair rows when applicable, then “Diagnose connection…”, “Open shell”, “Retry” | No passive row containing the full driver error | -| Explicit user Disconnect | “Reconnect” | Not the failed-authentication repair block | +| Failed state | Example children, in order | Important absence | +| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | +| Stored Native credentials rejected | “Update connection string…”, “Update credentials…”, “Diagnose connection…”, “Open shell” | No ordinary Retry while the stored-credential rejection latch requires editing | +| Recoverable verified Entra sign-in failure on a stored connection | Provider repair rows when applicable, then “Retry sign-in”, “Diagnose connection…”, “Open shell” | No ordinary Retry beside Retry sign-in | +| Ordinary retryable failure | Provider repair rows when applicable, then “Diagnose connection…”, “Open shell”, “Retry” | No passive row containing the full driver error | +| Explicit user Disconnect | “Reconnect” | Not the failed-authentication repair block | Sources: [base recovery rows](../../../../../src/tree/documentdb/ClusterItemBase.ts#L402), [stored repair rows](../../../../../src/tree/connections-view/ConnectionsBranchDataProvider.ts#L124), @@ -674,13 +1041,13 @@ Sources: [base recovery rows](../../../../../src/tree/documentdb/ClusterItemBase For an already-unavailable acquisition, the expansion modal can use a bounded detail instead of the raw rejection: -| Condition | Detail text | -| --- | --- | -| Sign-in required | “Sign in again to continue using this connection.” | -| Verified Entra credentials rejected | “The database rejected the credentials. Choose Retry sign-in to continue.” | -| Azure replacement-key path | “The database rejected the key. Choose Retry to read the key from Azure again.” | -| Stored credentials need editing | “The database rejected the credentials. Choose Update credentials to continue.” | -| Other reloadable credentials | “The database rejected the credentials. Choose Retry to reload them.” | +| Condition | Detail text | +| ----------------------------------- | ------------------------------------------------------------------------------- | +| Sign-in required | “Sign in again to continue using this connection.” | +| Verified Entra credentials rejected | “The database rejected the credentials. Choose Retry sign-in to continue.” | +| Azure replacement-key path | “The database rejected the key. Choose Retry to read the key from Azure again.” | +| Stored credentials need editing | “The database rejected the credentials. Choose Update credentials to continue.” | +| Other reloadable credentials | “The database rejected the credentials. Choose Retry to reload them.” | Source: [credential rejection wording](../../../../../src/tree/documentdb/ClusterItemBase.ts#L374). These details are conditional branches, not five messages shown in succession. @@ -704,6 +1071,11 @@ The action is **“Update saved password”**. Sources: [decoding offer](../../../../../src/documentdb/auth/urlEncodedPassword.ts#L101), [successful retry](../../../../../src/tree/connections-view/DocumentDBClusterItem.ts#L350). +**Iteration 1 comment:** make this explicit about storing the correctly formatted +password. [F10](#f10-explain-what-the-decoded-password-save-will-store) proposes: +**“Connected to "Orders" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?”** +The source sentence above remains unchanged until implementation. + **Review checkpoint:** read the modal, dismiss it, and explain the next step using only the remaining rows. Compare a cluster failure with a database/Indexes expansion failure: the latter's explained failure is a **notification**, formatted as @@ -717,13 +1089,13 @@ message appears and the operation continues; or **interactive recovery is needed the person gets a surface-specific message. Authentication/browser consent UI comes from VS Code's configured provider; its precise wording is not owned by this extension. -| Where the failure is encountered | Exact extension wording | Where / next action | -| --- | --- | --- | -| Tree, typed expired sign-in explanation | “Your Microsoft sign-in for this connection expired. Sign in again to continue.” | Explanation heading in failure modal; tree offers “Retry sign-in” when the verified identity can recover | -| Tree, unexpected identity returned | “A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.” | Explanation heading in failure modal | -| Existing webview | “Sign-in required” / “Sign in from the connection tree, then click Retry.” | In-view dialog, not a Sign in again button; repair is in the tree | -| Shell, explicit worker recovery available | “Microsoft sign-in expired for this shell. Sign in again to continue.” | Terminal error **and** warning notification with “Sign in again” | -| Playground, explicit worker recovery available | “Microsoft sign-in expired for this playground. Sign in again to continue.” | Failed result document **and** warning notification with “Sign in again” | +| Where the failure is encountered | Exact extension wording | Where / next action | +| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| Tree, typed expired sign-in explanation | “Your Microsoft sign-in for this connection expired. Sign in again to continue.” | Explanation heading in failure modal; tree offers “Retry sign-in” when the verified identity can recover | +| Tree, unexpected identity returned | “A different Microsoft account was returned for this connection. Sign in with the account you originally used for this connection, then try again.” | Explanation heading in failure modal | +| Existing webview | “Sign-in required” / “Sign in from the connection tree, then click Retry.” | In-view dialog, not a Sign in again button; repair is in the tree | +| Shell, explicit worker recovery available | “Microsoft sign-in expired for this shell. Sign in again to continue.” | Terminal error **and** warning notification with “Sign in again” | +| Playground, explicit worker recovery available | “Microsoft sign-in expired for this playground. Sign in again to continue.” | Failed result document **and** warning notification with “Sign in again” | Sources: [typed Entra explanation](../../../../../src/documentdb/auth/entraErrors/EntraSignInRequiredErrorExplainer.ts#L24), [Shell auth feedback](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L907), @@ -754,12 +1126,12 @@ Sources: [tree action](../../../../../src/commands/signInAgain/signInAgain.ts#L1 alternatives selected by the failure reason, not extra generic driver errors appended to every failure: -| Reason | Shell terminal message | Playground result message | -| --- | --- | --- | -| Expired, no safe in-place sign-in action | “Microsoft sign-in expired for this shell. Open a new shell from the tree.” | “Microsoft sign-in expired for this playground. Re-pick its connection from the tree.” | -| Different account | “This shell is bound to a different Microsoft account. Open a new shell from the tree.” | “This playground is bound to a different Microsoft account. Re-pick its connection from the tree.” | -| Destination not trusted | “This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.” | “This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.” | -| Token refresh failed for another reason | “The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.” | “The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.” | +| Reason | Shell terminal message | Playground result message | +| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| Expired, no safe in-place sign-in action | “Microsoft sign-in expired for this shell. Open a new shell from the tree.” | “Microsoft sign-in expired for this playground. Re-pick its connection from the tree.” | +| Different account | “This shell is bound to a different Microsoft account. Open a new shell from the tree.” | “This playground is bound to a different Microsoft account. Re-pick its connection from the tree.” | +| Destination not trusted | “This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.” | “This connection is not allowed for Microsoft sign-in. Review the trusted server settings, then re-pick the playground connection.” | +| Token refresh failed for another reason | “The sign-in token could not be refreshed. Run the next command to reconnect with the same connection.” | “The sign-in token could not be refreshed. Run the query again to reconnect with the same connection.” | Two **tree sign-in modal exceptions** are worth a separate read: @@ -819,13 +1191,13 @@ Sources: [Shell ordinary startup failure](../../../../../src/documentdb/shell/Do **The Dashboard has additional, non-overlay ways to say something is wrong:** -| When | Message / affordance | Where it remains | -| --- | --- | --- | -| Periodic health samples fail | Badge becomes “Disconnected” after two consecutive failed samples; one failed sample does not immediately switch it to Disconnected | Header; screen-reader announcement “Lost connection to the cluster.” | -| Initial cluster-information read fails ordinarily | “Failed to read cluster information: {error}” with “Retry” | Persistent inline MessageBar | -| Storage read fails but previous database rows exist | “Failed to read storage statistics: {error}” with “Retry” | Persistent inline MessageBar above retained inventory | -| Manual storage refresh throws | “Failed to read storage statistics.” plus the cause | Non-modal host error; also an accessible failure announcement | -| Another Dashboard action throws | For example “Failed to open the interactive shell.”, “Failed to copy the connection string.” or “Failed to export diagnostics.”, plus cause | Non-modal host error | +| When | Message / affordance | Where it remains | +| --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- | +| Periodic health samples fail | Badge becomes “Disconnected” after two consecutive failed samples; one failed sample does not immediately switch it to Disconnected | Header; screen-reader announcement “Lost connection to the cluster.” | +| Initial cluster-information read fails ordinarily | “Failed to read cluster information: {error}” with “Retry” | Persistent inline MessageBar | +| Storage read fails but previous database rows exist | “Failed to read storage statistics: {error}” with “Retry” | Persistent inline MessageBar above retained inventory | +| Manual storage refresh throws | “Failed to read storage statistics.” plus the cause | Non-modal host error; also an accessible failure announcement | +| Another Dashboard action throws | For example “Failed to open the interactive shell.”, “Failed to copy the connection string.” or “Failed to export diagnostics.”, plus cause | Non-modal host error | Sources: [health polling](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L348), [threshold](../../../../../src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L62), @@ -855,6 +1227,7 @@ and Playground open. Right-click the connected cluster and choose **“Disconnec Choices: **“Close all”**, **“Keep open (disabled)”**, or VS Code's dismissal/cancel. With a configured `closeAll` or `keepOpenDisabled` default, this question is skipped. With no registered views, there is no tab-choice question even if workers exist. + 3. **Choose Close all while a Document View is dirty:** a second warning modal: > **Discard unsaved document changes?** @@ -863,6 +1236,7 @@ and Playground open. Right-click the connected cluster and choose **“Disconnec Explicit action: **“Discard changes”**. Cancelling leaves the teardown uncommitted. The configured tab default does **not** bypass this warning. + 4. **Choose Keep open (disabled) instead:** each retained webview gets C6's **“Disconnected”** dialog. The tree's child becomes **“Reconnect”**. Shell prints **“Disconnected”** and keeps its terminal; the Playground file remains @@ -888,17 +1262,17 @@ This is the shared **in-view** modal for Collection View, Document View and Dash It is not a host notification. It shades/blocks the mounted contents while open. Here is the complete reason-to-copy inventory, including repeated titles: -| Trigger / reason | Title | Detail | Footer buttons | -| --- | --- | --- | --- | -| Sign-in must be repaired | “Sign-in required” | “Sign in from the connection tree, then click Retry.” | Retry; Close view | -| Database rejected credentials | “Authentication failed” | “Repair the connection in the tree, then click Retry.” | Retry; Close view | -| Credentials are unavailable | “Disconnected” | “Connect from the connection tree, then click Retry.” | Retry; Close view | -| Person explicitly disconnected | “Disconnected” | “Reconnect from the connection tree, then click Retry.” | Retry; Close view | -| Connection edit is in progress | “Connection update in progress” | “Wait for the update to finish, then click Retry.” | Retry; Close view | -| Saved settings changed | “Connection changed” | “This view is tied to the previous connection settings. Close it and reopen it from the tree.” | Close view | -| Bound identity changed | “Connection changed” | “This view is tied to the previous connection settings. Close it and reopen it from the tree.” | Close view | -| Saved connection was removed | “Connection removed” | “This connection is no longer in the tree. Close this view.” | Close view | -| Bound connection is unreachable | “Connection lost” | “Check the network or server, then click Retry.” | Retry; Close view | +| Trigger / reason | Title | Detail | Footer buttons | +| ------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------- | +| Sign-in must be repaired | “Sign-in required” | “Sign in from the connection tree, then click Retry.” | Retry; Close view | +| Database rejected credentials | “Authentication failed” | “Repair the connection in the tree, then click Retry.” | Retry; Close view | +| Credentials are unavailable | “Disconnected” | “Connect from the connection tree, then click Retry.” | Retry; Close view | +| Person explicitly disconnected | “Disconnected” | “Reconnect from the connection tree, then click Retry.” | Retry; Close view | +| Connection edit is in progress | “Connection update in progress” | “Wait for the update to finish, then click Retry.” | Retry; Close view | +| Saved settings changed | “Connection changed” | “This view is tied to the previous connection settings. Close it and reopen it from the tree.” | Close view | +| Bound identity changed | “Connection changed” | “This view is tied to the previous connection settings. Close it and reopen it from the tree.” | Close view | +| Saved connection was removed | “Connection removed” | “This connection is no longer in the tree. Close this view.” | Close view | +| Bound connection is unreachable | “Connection lost” | “Check the network or server, then click Retry.” | Retry; Close view | Source: [all mapped titles/details](../../../../../src/webviews/_integration/describeUnavailableConnection.ts#L11). These are available mappings, not a promise that each reason can be reproduced by @@ -910,6 +1284,8 @@ every surface or that every low-level error is mapped. is not reconnecting. The contents become accessible for copying; attempting another database operation reveals the reason again. Confirm this distinction without assuming a visible disabled toolbar persists after dismissal. + **Iteration 1 approved replacement:** **“Dismiss dialog to access view contents”**, + because access/inspection is broader than copying ([F11](#f11-x-should-describe-access-to-retained-contents)). - **Retry:** while pending, Retry, Close view and the X are disabled/focusable. Their labels do not change to “Retrying…” and this component adds no recovery spinner. On success the overlay disappears and a live region announces **“Reconnected”**; @@ -962,6 +1338,7 @@ unchanged values, a password-only edit, and changed destination/identity. Its explicit action is **“Disconnect”**. Dismissing it leaves those workers running on their previous settings. Accepting it prints **“Disconnected”** in the terminals. + 5. An unchanged/cancelled edit does not permanently retire existing views. Distinguish transient “Connection update in progress” from permanent “Connection changed”. @@ -973,15 +1350,15 @@ Sources: [authentication picker](../../../../../src/commands/updateCredentials/P **Failure and special-case copy to read on this journey:** -| Condition | Exact message | Surface | -| --- | --- | --- | -| Cannot read original saved connection | “The connection could not be read from storage.” | Error notification | -| Credential save fails | “Failed to save credentials.” | Error notification; technical detail goes to Output | -| Connection-string save fails | “Failed to update the connection.” | Error notification; technical detail goes to Output | -| Cannot verify what persisted | “Could not verify the saved connection settings.” | Output warning only | -| Persisted settings differ but save is incomplete/unverified | “The connection update may be incomplete. Check the saved settings before reconnecting.” | Warning notification; old views may still be disabled for safety | +| Condition | Exact message | Surface | +| ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | +| Cannot read original saved connection | “The connection could not be read from storage.” | Error notification | +| Credential save fails | “Failed to save credentials.” | Error notification; technical detail goes to Output | +| Connection-string save fails | “Failed to update the connection.” | Error notification; technical detail goes to Output | +| Cannot verify what persisted | “Could not verify the saved connection settings.” | Output warning only | +| Persisted settings differ but save is incomplete/unverified | “The connection update may be incomplete. Check the saved settings before reconnecting.” | Warning notification; old views may still be disabled for safety | | New destination no longer supports the selected Entra method | “Connection updated. Microsoft Entra ID isn't available for the new server, so choose another method when you connect.” | Information notification instead of the ordinary string-update summary | -| Concurrent edit/removal already owns the connection | “A connection is already being updated or removed. Try again when it finishes.” | Thrown error, reported by caller/command handling | +| Concurrent edit/removal already owns the connection | “A connection is already being updated or removed. Try again when it finishes.” | Thrown error, reported by caller/command handling | **Review checkpoint:** can “updated successfully” be mistaken for “old tabs are usable”? Does the later Shell modal explain why Shell and webviews differ? Save success, reconnect @@ -1006,11 +1383,11 @@ Source: [Shell banner/spinner](../../../../../src/documentdb/shell/DocumentDBShe **Then disconnect and type before reconnecting.** The bounded terminal messages are: -| State when the command is attempted | Shell terminal wording | -| --- | --- | -| Explicitly disconnected | “Disconnected. Reconnect from the tree, then open a new shell.” | +| State when the command is attempted | Shell terminal wording | +| ----------------------------------- | --------------------------------------------------------------------------------- | +| Explicitly disconnected | “Disconnected. Reconnect from the tree, then open a new shell.” | | Different identity/settings binding | “This shell is bound to the previous connection. Open a new shell from the tree.” | -| Other typed unavailable state | “This connection is unavailable. Reconnect from the tree, then open a new shell.” | +| Other typed unavailable state | “This connection is unavailable. Reconnect from the tree, then open a new shell.” | Source: [lifecycle worker failure](../../../../../src/documentdb/shell/DocumentDBShellPty.ts#L889). These are output lines, not full-view overlays or necessarily host toasts. C3 lists @@ -1043,6 +1420,7 @@ worker restart distinguishable in scrollback? Action: **“Connect to a different database…”**. Cancelling the following picker preserves the original binding. + 4. **Run:** a cancellable **“Query Playground”** progress notification reports **“Initializing…”**, **“Authenticating…”**, **“Running query…”** as the evaluator reaches those phases. The CodeLens changes from **“Run All”** / **“Run”** to @@ -1069,6 +1447,7 @@ worker restart distinguishable in scrollback? **“Sign in again”**. Other bounded result messages include: **“This playground is bound to the previous connection. Re-pick its connection from the tree.”** and **“This connection is unavailable. Reconnect from the tree, then re-pick it here.”** + 6. **If it is already latched as unavailable before the run starts**, the bounded message is a **warning notification**, and that early exit does not create the execution-error result document. This matters when comparing seemingly identical @@ -1275,15 +1654,17 @@ they are not normal end-user lifecycle notifications For each scenario, dictate a short sequence using this review card: -| Question | What to record | -| --- | --- | -| What did I click / what changed externally? | Entry point, connection type, open views/workers, relevant setting | -| What appeared first, second, and after dismissal? | Exact title/detail/action labels; notification vs modal vs inline vs Output | -| Did two surfaces disagree? | For example, a bound Playground CodeLens, a failed old result and a current sign-in warning | -| Could I explain the next action without opening docs? | Which button/row I expected to use, and what it actually did | -| How did I know it finished? | View enabled, result changed, live announcement, tree refreshed, or no visible completion | -| What was preserved or lost? | Draft, result, query text, scrollback, worker variables; whether anything unexpectedly replayed | -| Is this observed or only inferred? | Runtime evidence versus a source-only branch; link an existing F-item where applicable | - -The six seeded Flags remain suggestions pending this walkthrough. No new UX decisions, -runtime findings or implementation fixes are implied by adding this message inventory. +| Question | What to record | +| ----------------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| What did I click / what changed externally? | Entry point, connection type, open views/workers, relevant setting | +| What appeared first, second, and after dismissal? | Exact title/detail/action labels; notification vs modal vs inline vs Output | +| Did two surfaces disagree? | For example, a bound Playground CodeLens, a failed old result and a current sign-in warning | +| Could I explain the next action without opening docs? | Which button/row I expected to use, and what it actually did | +| How did I know it finished? | View enabled, result changed, live announcement, tree refreshed, or no visible completion | +| What was preserved or lost? | Draft, result, query text, scrollback, worker variables; whether anything unexpectedly replayed | +| Is this observed or only inferred? | Runtime evidence versus a source-only branch; link an existing F-item where applicable | + +This appendix preserves the message inventory from the source snapshot. Iteration 1 +decisions and observations are explicit in the ledger above; unresolved suggestions +remain open, F6 is closed as accepted, and none of the requested fixes has shipped merely +because it was recorded here. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md new file mode 100644 index 000000000..cee58db4a --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1146-copilot-review.md @@ -0,0 +1,887 @@ +--- +feature: connection-lifecycle +kind: review +status: active +prs: [1146] +created: 2026-11-27 +verified: 2026-11-27 +--- + +# PR #1146: Copilot comment validation + +## Scope and review policy + +Reviewed [the refinement PR](https://github.com/microsoft/vscode-documentdb/pull/1146) at +`dec9ac64cbdb18f295fb0f05a7ebe12955703c47`, against `feature/connection-lifecycle`. +The [Copilot review](https://github.com/microsoft/vscode-documentdb/pull/1146#pullrequestreview-6090776593) +contains 12 inline comments; all 12 were unresolved and current when retrieved. +The PR is now non-draft; that is an externally changed status, not a readiness decision made here. + +The leader verified the claims against source and focused behavioral probes, then consulted +**Claude Opus 5.5** as the read-only advisor. The operator selected the actions recorded below on +2026-11-27. The initial validation pass made no production changes, commits, pushes, GitHub replies, +or thread resolutions. The lead implementation run is recorded separately below. + +The operator's priorities for this review: + +- Standard workflows should work without elaborate machinery for implausible races. +- Edge cases must not permit data loss, wrong-target execution, or automatic replay. +- A **won't fix** recommendation is legitimate when safety is preserved and the benefit is small. +- Separate a real behavior defect from an overstated severity or unnecessarily broad solution. + +Severity: **High** breaks a central supported workflow; **Medium** materially disrupts routine +actions or has a concrete wrong-target/input/write-outcome risk; **Low** is bounded feedback or +ergonomic degradation. Severity and disposition are separate: a low-frequency wrong-target defect +still warrants a fix. None of these findings proves that database data was actually lost. + +## Operator-selected disposition + +The operator directed **"c10, ignore/wont fix."** and selected the recommended actions for every +other item. This selects nine fixes and three won't-fix/defer outcomes (C05, C10, C12). +No additional rationale was supplied; the review's option analysis is preserved below rather +than attributing new reasoning to the operator. Selection is not implementation. + +| Item | Copilot severity | Validity | Assessed severity | Selected action | +| ---------------------------------------------------------------------- | ---------------- | ------------------------------------- | --------------------------------- | ---------------------------------------------------------- | +| [C01](#c01-diagnostic-worker-startup-rejects-authentication-holds) | High | Confirmed | High | Fix: explicit diagnostic startup capability | +| [C02](#c02-vm-diagnostic-shell-can-use-the-wrong-port) | High | Confirmed | Medium | Fix: retain attempted endpoint; fail closed when unknown | +| [C03](#c03-stale-diagnostic-shell-click-has-generic-feedback) | Medium | Confirmed, stale-node claim qualified | Low | Fix: supported-view refresh and typed stale feedback | +| [C04](#c04-old-playground-sign-in-can-warn-a-new-connection) | Medium | Confirmed | Low | Fix: two connection-ownership checks | +| [C05](#c05-completed-edit-can-silently-supersede-tree-sign-in) | Medium | Confirmed | Low | Won't fix / defer richer change attribution | +| [C06](#c06-genuine-sign-in-dismissal-can-show-a-stale-modal) | Medium | Confirmed | Low | Fix: distinguish genuine dismissal from stale cancellation | +| [C07](#c07-disconnect-restores-text-but-not-the-cursor) | Medium | Confirmed | Low | Fix with C09: restore text and cursor | +| [C08](#c08-anonymous-startup-failure-also-notifies-the-host) | Medium | Confirmed | Low | Fix: anonymous-only notification guard | +| [C09](#c09-late-shell-sign-in-output-corrupts-the-visible-prompt) | Medium | Confirmed | Medium | Fix: bounded asynchronous output handling | +| [C10](#c10-anonymous-command-result-is-discarded-on-host-client-churn) | Medium | Confirmed; guard is intentional | Medium for write-outcome feedback | Won't fix: operator override; no guard or message changes | +| [C11](#c11-index-failures-can-show-two-tree-modals) | Medium | Confirmed | Medium | Fix: explicit feedback ownership, not suppressDisplay | +| [C12](#c12-host-side-stale-retry-cancellation-becomes-an-alert) | Medium | Confirmed | Low | Won't fix / defer typed cancellation outcome | + +Suggested implementation order for this run: C01, C02, C11; then the shared C07/C09 input work; +then cheap C04/C08/C06/C03 feedback refinements. C05 and C12 need no new architecture this round. +C10 is excluded from implementation. The operator withdrew the initial C01/C02 deferral. +All nine accepted fixes are in scope for this run; all remain unimplemented at intake. + +### Lead run intake (2026-11-27, 17:17 UTC) + +The operator requested committing this plan and implementing it as a lead with an advisor, +initially with **"we skip work items 1 and 2 for now."** Before coding, the operator corrected +this as a different-project instruction: **"here we don't skip 1 and 2"**, then confirmed +**"we work on all decided/accepted work items."** C01 and C02 are included; the initial +deferral is superseded. C05, C10 and C12 retain their selected won't-fix/defer outcomes. + +The operator confirmed the model assignments: **claude-opus-5.5** advisor; +**mai-code-2** for smaller coding items, **gpt-6.1-sol** for lifecycle/concurrency work; +**mai-code-2-flash** for checks. The advisor supplies the implementation mapping and technical +decisions within the accepted scope before coding. + +Endpoint: local implementation and separate item commits, with Case 1 build and focused tests. +No push, PR-status change, or thread resolution is authorized by this run. Full Case 2 is not +part of this ongoing-work endpoint. + +The operator authorized a summary **in each item's Copilot review thread**, explaining what +changed and why, with a commit reference when available: **"always in the thread, no one +multi-comment."** Do not post an omnibus PR comment. Any local-only commit reference must be +identified as not yet pushed rather than linked as though available on GitHub. + +### Advisor implementation mapping + +**Advised (claude-opus-5.5, 2026-11-27):** all nine selected fixes fit the existing code. +No new user-facing strings or changed authentication identity rules are planned. Each item gets +its own code commit; C07 precedes C09, and C01 precedes C03. Items sharing the PTY run sequentially. +Tests use the root Vitest configuration with `--maxWorkers=2`. + +| Item | Advisor-recommended / assigned model | Owned implementation and test scope | Confidence | +| ---- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------ | ---------------------------------- | +| C01 | gpt-6.1-sol | ConnectionUnavailableError; WorkerSessionManager; ShellSessionManager; openInteractiveShell; dependent tests | 85% | +| C02 | gpt-6.1-sol | AzureVMResourceItem and its focused new test | 80% | +| C03 | mai-code-2 | openInteractiveShell and its test, after C01 | 85% | +| C04 | mai-code-2 | executePlaygroundCode and its test | 95% | +| C06 | gpt-6.1-sol | signInAgain and its test; final cross-surface checks after other edits | 80% | +| C07 | mai-code-2 | ShellInputHandler and DocumentDBShellPty with their tests, after C08 | 90% | +| C08 | mai-code-2 | DocumentDBShellPty and its test | 95% | +| C09 | gpt-6.1-sol | DocumentDBShellPty and tests, using C07's input restore method | 90% after render-origin refinement | +| C11 | mai-code-2 | commandErrorHandling; three index callbacks; wrapper and focused index tests | 90% | + +Approved implementation interfaces supplied by the advisor: + +- C01: `isDiagnosticAuthenticationHold(reason: ConnectionUnavailableReason | undefined): boolean`, + with an explicit host-only `allowDiagnosticAuthenticationHold = false` startup parameter passed + through worker startup. Shell passes it only for the separate diagnostic path; no wire-message flag. +- C07: `ShellInputHandler.restoreLine(text: string, cursor: number): void`, clamping the cursor + and using the existing renderer without clearing multiline/history state or firing buffer callbacks. +- C09: private PTY `writeAsyncFeedback(line: string): void`, with queued feedback during evaluation + or disabled input, flushed at the next safe prompt. Disconnect clears obsolete queued feedback. +- C11: `markCommandErrorPresented(context: IActionContext, error: unknown): void`, with exact + invocation/error ownership. Skip only additional tree UI, preserving webview behavior, explanation + telemetry and presentation for a different cleanup error. + +The leader accepts this mapping within the already approved solutions; material deviations still +return to the advisor/operator. Existing exact-output tests may change only where the accepted +cursor restoration changes their actual behavior, not merely to make a failing test pass. +Live checks remain pending: C09 installed-terminal redraw and C02 provider node lifetime/refresh. + +## C01. Diagnostic worker startup rejects authentication holds + +**Comment:** [Copilot C01](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515405). + +**Evidence and impact.** The command and +[Shell latch filter](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/ShellSessionManager.ts#L462) +allow diagnostic startup through three authentication holds. However, +[WorkerSessionManager's startup assertion](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/playground/WorkerSessionManager.ts#L351) +rejects every latch. Its repeated checks include the boundary before worker construction. +A real ShellSessionManager calling the real WorkerSessionManager rejected all three probe cases +before spawning, while leaving the latch intact. + +The existing Shell tests mock WorkerSessionManager, so their passing bypass tests do not verify +this integration. `credentialsRejected` is a concrete production path; the other two cases also +test the intended capability boundary. This fails safely, but defeats the recovery action precisely +when rejected authentication made it useful. **High; fix.** + +**Options.** + +- **Recommended:** pass a host-only diagnostic capability into worker startup and share the narrow + authentication-hold predicate. **Pros:** fixes the actual boundary; preserves shared state; + ordinary Shell/Playground checks stay strict. **Cons:** one startup API change and dependent tests. +- Infer the bypass from `authMechanism === 'NoAuth'`. **Pros:** fewer parameters. + **Cons:** also affects ordinary saved NoAuth sessions; rejected. +- Won't fix. **Pros:** no changes. **Cons:** leaves the accepted diagnostic workflow broken; not recommended. + +**Acceptance:** real Shell-to-worker startup under each allowed hold; ordinary NoAuth remains +blocked; Disconnect, removal, updates, aborts and superseding epochs remain blocked. No credentials, +token relay, shared-client mutation, or automatic authenticated fallback. + +**Author decision (2026-11-27):** selected the recommended explicit diagnostic startup capability +and shared narrow authentication-hold predicate. + +**Deferred by operator (2026-11-27):** skip C01 for this lead run. The accepted fix remains pending. + +**Deferral withdrawn by operator (2026-11-27):** the skip instruction was for a different +project. C01's accepted fix is included in this lead run. + +**Done (2026-11-27), commit `476e65176` (local, not pushed):** gpt-6.1-sol passed the explicit +diagnostic capability through worker startup and shared the exact three-hold predicate across +the command, Shell and Worker. Ordinary NoAuth, all other holds, abort and epoch fences stay strict; +no credentials, relay, wire flag or hold clearing. Added 21 focused cases; four targeted files: +224 passed. The extra startup argument assertion preserves the existing isolation assertions. +Advised (claude-opus-5.5): approved at 90% confidence after checking startup and worker ownership. +Final batch build remains pending. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722230665). + +## C02. VM diagnostic Shell can use the wrong port + +**Comment:** [Copilot C02](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515477). + +**Evidence and impact.** +[VM discovery](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/plugins/service-azure-vm/discovery-tree/AzureSubscriptionItem.ts#L105) +seeds `host:27017`. +[The VM credentials path](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts#L123) +asks for a port and builds a different URI without updating that model. +The inherited diagnostic endpoint still returns the model URI. Credential-cache recovery is both +unreliable after failure and forbidden on this anonymous path. + +Default-port users are unaffected. Custom-port users usually get a misleading refusal; if another +anonymous-capable server listens at 27017, arbitrary Shell commands can target it instead. +The banner exposes the port, but that is not an adequate correctness guard. **Medium; fix required.** +There is no evidence that a destructive command was actually executed against another server. + +**Options.** + +- **Recommended:** retain the credential-free endpoint actually attempted on that VM node and + override its endpoint reader. Record it on the connection-attempt path, not from a diagnostics-only + port prompt. **Pros:** preserves the feature and correct port, with small node-local state. + **Cons:** a recreated node has no trustworthy attempted endpoint and must report unavailable. + Re-reading must observe a later attempt with a different port rather than returning a frozen URI. +- Always return unavailable for VM diagnostic endpoints. **Pros:** smallest fail-closed fix; + eliminates wrong-target risk. **Cons:** loses the diagnostic Shell even for default-port VMs. +- Prompt or fetch credentials during endpoint re-read. **Pros:** can recover the port. + **Cons:** violates the approved no-authentication/no-ARM path and can repeatedly prompt; rejected. + +**Acceptance:** failed attempts on default and custom ports, cache eviction, another attempt on a +different port, and node recreation. Unknown endpoint must never silently fall back to 27017. + +**Author decision (2026-11-27):** selected retaining the credential-free attempted VM endpoint +with an overridden reader that fails closed when the endpoint is unknown. + +**Deferred by operator (2026-11-27):** skip C02 for this lead run. The accepted fix remains pending. + +**Deferral withdrawn by operator (2026-11-27):** the skip instruction was for a different +project. C02's accepted fix is included in this lead run. + +**Done (2026-11-27), commit `e3bd77b21` (local, not pushed):** gpt-6.1-sol retains the sanitized +actually attempted VM endpoint, including its selected port. Unknown/recreated nodes fail closed; +later attempts update the reader; cache eviction and diagnostics-only reads do not redirect it. +Added eight focused cases; three targeted files: 69 passed. Advised (claude-opus-5.5): final revision +approved with high confidence. The leader rejected the first revision's silent sanitizer catch; +the advisor confirmed that the already-parsed input can use normal outer failure handling. +The revised new test verifies cleared endpoint, no client startup and bounded failure presentation +instead of silent diagnostic failure. No pre-existing or TDD test was weakened. +Real VM/provider node-lifetime checks and final batch build remain pending. +[Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722266137). + +## C03. Stale diagnostic Shell click has generic feedback + +**Comment:** [Copilot C03](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515571). + +**Evidence and impact.** +[The command](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/openInteractiveShell/openInteractiveShell.ts#L105) +correctly blocks lifecycle holds, but its catch shows a generic modal without the supported-node +refresh used by other recovery commands. A bare epoch mismatch also maps to `credentialsChanged`. +Removal or update may already refresh the provider, so "leaves the old node visible" is not universal. +No unsafe connection starts. **Low.** + +**Options.** + +- **Recommended cheap fix:** reuse supported-view refresh routing and existing removed/changed + wording only when the current typed latch proves that cause. **Pros:** consistent actionable UX. + **Cons:** a few routing guards; unsupported Workspace branches must remain unchanged. +- Won't fix. **Pros:** safe existing behavior and narrow stale-click window. + **Cons:** less useful explanation and possibly stale recovery rows. + +Do not infer an actual settings change from an epoch mismatch alone, or create a new provenance +tracker just for this command. **Acceptance:** removed/changed supported nodes, unsupported nodes, +cancelled work, and epoch-only supersession without a false "connection changed" claim. + +**Author decision (2026-11-27):** selected the recommended supported-view refresh and typed +removed/changed feedback, without speculative epoch attribution. + +**Done (2026-11-27), commit `c952e9624` (local, not pushed):** mai-code-2 refreshes supported +nodes and selects existing actionable copy only from the current removed/changed latch. +Unknown, epoch-only and unsupported-view failures retain generic feedback; cancellation stays quiet +and the original error is preserved. Added five focused cases; 34 passed. +Advised (claude-opus-5.5): approved at 85% confidence after checking routing and reason attribution. +Final batch build remains pending. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722266186). + +## C04. Old Playground sign-in can warn a new connection + +**Comment:** [Copilot C04](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515627). + +**Evidence and impact.** +[Both stale-feedback branches](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/playground/executePlaygroundCode.ts#L414) +check that the document is open but omit its current connection ownership. +Probes re-picked A to healthy B and then removed A, before the click and during sign-in: +both produced A's removal warning against the document now using B. The newer evaluator was +not disposed and no operation was replayed. Existing "re-picked healthy" tests omit A's removal +latch, which is why they miss this combination. **Low; cheap fix.** + +**Options.** + +- **Recommended:** require `service.getConnection(documentUri) === connection` in both feedback + branches. **Pros:** two local checks; preserves legitimate removal feedback for the same document. + **Cons:** requires focused race tests. +- Reuse the whole `stillOwnsAction()` predicate. **Pros:** existing helper. + **Cons:** suppresses legitimate feedback when removal has disposed the old evaluator; rejected. +- Won't fix. **Pros:** state remains safe. **Cons:** a straightforward ownership defect remains. + +**Author decision (2026-11-27):** selected the two document-connection ownership checks in the +stale-feedback branches, not the full evaluator-ownership predicate. + +**Done (2026-11-27), commit `1fdcfd43d` (local, not pushed):** mai-code-2 added both ownership +guards and four stale-feedback race cases. Same-document feedback and evaluator state are preserved; +no reset or replay. Advised (claude-opus-5.5): approved at 90% confidence after verifying the stored +connection object identity and both async branches. Focused Playground suite: 38 passed. +Final batch build remains pending. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722213773). + +## C05. Completed edit can silently supersede tree sign-in + +**Comment:** [Copilot C05](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515692). + +**Evidence and impact.** +[The save helper](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/saveConnectionEdit.ts#L120) +can clear the update latch after the changed settings persist. +[The sign-in currentness check](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/signInAgain/signInAgain.ts#L146) +still rejects the old epoch/credentials, but `reportClosed()` then has no typed change reason. +A probe replacing credentials and clearing the latch during acquisition confirmed refresh without +a modal or client startup. This probe models the completed-edit outcome, not a real storage write. +Safety is intact; only feedback is missing in a two-action overlap. **Low.** + +**Options.** + +- **Recommended won't fix / defer:** keep quiet supersession and refreshed tree state. + **Pros:** no new history, storage reads, secret comparisons or ambiguous attribution. + **Cons:** the older sign-in action can end without explaining why. +- Capture authoritative saved settings and compare later. **Pros:** can identify some completed edits. + **Cons:** asynchronous storage/error handling and sensitive in-memory comparison for a small benefit; + cache object inequality or epoch alone is not proof of an edit. +- Add a bounded change-version token. **Pros:** precise if lifecycle-wide semantics are well-defined. + **Cons:** new state and call-site responsibilities; disproportionate for this round. + +Do not relax the stale credential/epoch guard. A future fix must distinguish real edits from Retry, +Disconnect/reconnect, and concurrent successful sign-in without guessing. + +**Author decision (2026-11-27):** selected the recommended won't-fix/defer outcome: retain quiet +supersession and refreshed tree state; do not add richer completed-edit attribution this round. + +**No-code outcome recorded (2026-11-27):** no implementation change; the selected safe +supersession behavior remains. [Individual thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722321228) +records the tradeoff. The thread was not resolved. + +## C06. Genuine sign-in dismissal can show a stale modal + +**Comment:** [Copilot C06](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515749). + +**Evidence and impact.** +[The catch order](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/signInAgain/signInAgain.ts#L211) +checks stale acquisition before genuine dismissal. A probe rejecting acquisition with +`User did not consent to login.` after removal showed a modal and started no client. +Internal stale-acquisition checks also use UserCancelledError, so blindly moving the cancellation +check first loses intentional feedback for genuine stale actions. **Low.** + +**Options.** + +- **Recommended bounded fix:** distinguish actual dismissal at the session-acquisition boundary + from internally generated stale cancellation, then keep genuine dismissal quiet. + **Pros:** matches the approved cancellation UX with local control flow. + **Cons:** needs two clearly distinguished outcomes and tests; avoid broad message heuristics. +- Won't fix / defer. **Pros:** the modal is truthful and only appears in the overlapping tree path. + **Cons:** contradicts the quiet-user-cancellation policy. + +**Acceptance:** dismissal after removal/update is quiet; accepted sign-in superseded by removal +still explains; worker-origin recovery remains quiet; no client starts for either stale case. + +**Author decision (2026-11-27):** selected distinguishing actual session-acquisition dismissal +from internally generated stale cancellation, keeping genuine dismissal quiet. + +**Done (2026-11-27), commit `2688f86ca` (local, not pushed):** gpt-6.1-sol captures genuine +acquisition dismissal and handles it before stale-action presentation. Successful stale acquisition, +worker quietness and identity/provider/epoch guards are preserved. Added 13 focused cases; +sign-in suite: 41 passed. Advised (claude-opus-5.5): approved at 90% confidence, including exact +error identity through the acquisition handler. Final batch build remains pending. +[Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722213722). + +## C07. Disconnect restores text but not the cursor + +**Comment:** [Copilot C07](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515827). + +**Evidence and impact.** +[Disconnect](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L282) +captures the partial buffer, moves to End, and restores text with the cursor at its end. +The actual PTY probe typed `abcdef`, moved to position 2, disconnected, inserted `X`, and submitted: +evaluation received `abcdefX`, not `abXcdef`. +Nothing executes automatically, and the relocated cursor is visible. **Low**, rather than +claiming this alone causes database loss; nonetheless preserve editing intent with a small fix. + +**Options.** + +- **Recommended with C09:** capture logical cursor position and use an input-handler + text-and-cursor restore operation backed by the existing wrap-aware renderer. + **Pros:** predictable editing; reusable for asynchronous feedback. + **Cons:** a small input API addition and wrapped-line tests. +- Won't fix. **Pros:** visible End placement is understandable after explicit Disconnect. + **Cons:** breaks the "keep typing where I was" expectation for retained drafts. +- Restore through repeated synthetic arrow keys. **Pros:** no new method. + **Cons:** couples to escape parsing, Unicode movement and repeated rendering; not recommended. + +Do not change the separately approved behavior that drops incomplete multiline/queued executing +input on Disconnect. No reconnect or replay is part of this restoration. + +**Author decision (2026-11-27):** selected restoring the partial input's logical cursor together +with its text through the wrap-aware renderer, shared with C09. + +**Done (2026-11-27), commit `ce2cf8d8b` (local, not pushed):** mai-code-2 added `restoreLine` +and captures the idle single-line cursor before Disconnect moves to End. The next edit submits +the intended command; multiline/evaluating discard and C08's notification guard are unchanged. +Added five focused cases; input/PTY suites: 228 passed. The wrapped Home exact-output expectation +was updated for the selected cursor restoration; the End-position assertion stays unchanged. +Advised (claude-opus-5.5): approved at 90% confidence after checking wrap-row tracking and no replay. +The leader requested a C09 render-origin refinement before dispatch, because a newly emitted prompt +must not inherit the old wrapped cursor row. Final batch build and live terminal checks remain pending. +[Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722303779). + +## C08. Anonymous startup failure also notifies the host + +**Comment:** [Copilot C08](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515913). + +**Evidence and impact.** +[The ordinary startup catch](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L673) +skips the credential-backed explanation for anonymous sessions but still sends the host notification. +A probe confirmed terminal output plus `showErrorMessage`. **Low; trivial policy fix.** + +**Options.** + +- **Recommended:** guard only the host notification with `!this._unauthenticated`. + **Pros:** matches the diagnostic terminal-only policy; no normal Shell behavior change. + **Cons:** a background diagnostic terminal will not additionally notify the host. +- Won't fix and explicitly change the policy. **Pros:** retains normal Shell's background visibility. + **Cons:** conflicts with [current feature intent](../README.md#intent) and + [the error-translation skill](../../../../../.github/skills/error-translation/SKILL.md). + +**Advisor disagreement:** the advisor considered the existing notification a reasonable won't-fix +and said no decision required quiet feedback. The leader did not adopt that conclusion: +current feature intent expressly says later failures stay in the terminal. Do not silently +reinterpret the approved boundary just because normal Shells deliberately notify. + +**Author decision (2026-11-27):** selected the anonymous-only host-notification guard, retaining +normal Shell notifications and terminal feedback. + +**Done (2026-11-27), commit `bd70e3298` (local, not pushed):** mai-code-2 guarded only the +anonymous startup host notification. Terminal output, safe logging and retained retry prompt stay +unchanged; normal Shell failures still notify. Added assertions to two existing tests rather than +new suites; all 134 PTY tests passed. Advised design (claude-opus-5.5): 95% confidence; the leader's +mechanical diff review confirmed the exact guard and retained behaviors at 95% confidence. +Final batch build remains pending. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722276450). + +## C09. Late Shell sign-in output corrupts the visible prompt + +**Comment:** [Copilot C09](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721515975). + +**Evidence and impact.** +[Late sign-in feedback](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L1007) +calls `handleWorkerFailure()` at the live cursor without separating output or redrawing input. +The success text has the same pattern. The PTY probe typed a partial command, moved Home, +then accepted a stale notification: output was only the error plus CRLF, with no prompt/input redraw. +[writeLine](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/DocumentDBShellPty.ts#L1200) +does not manage input state. + +The logical buffer is retained, but the displayed command can be overwritten or split across +incorrect rows. Later edits/Enter may operate on text the user cannot accurately see. +No automatic replay or database loss was observed. **Medium** because visual/logical command +divergence has a plausible destructive-command consequence, not just a missing empty prompt. + +**Options.** + +- **Recommended:** one bounded asynchronous-output helper using C07's restore primitive. + When idle, move past the rendered input, separate the message, and redraw the current prompt, + current line and cursor. Preserve accumulated multiline state; do not call `showPrompt()` + and erase it. When evaluating, defer the message to the next safe prompt boundary instead + of injecting a second prompt. Apply to failure and success callbacks. + **Pros:** correct visible command; shared fix for realistic asynchronous arrivals. + **Cons:** a small queued-feedback path plus idle/evaluating/multiline tests. +- Queue every message until the user submits. **Pros:** simpler live-rendering handling. + **Cons:** hides explicit recovery feedback indefinitely while an idle user waits. +- Won't fix. **Pros:** no input changes. + **Cons:** invisible buffered command text is an avoidable safety/UX defect; not recommended. + +**Advisor disagreement:** Opus rated this upper-Low because empty prompts are common and the +buffer remains intact. The leader retains Medium for the populated-prompt consequence. +The advisor's suggested `showPrompt()`-then-restore must be qualified: that method resets +multiline state. The helper must preserve it, not reconstruct only the current line. + +**Acceptance:** empty prompt, populated mid-line and wrapped cursor, continuation/multiline state, +evaluation in progress, delayed success, delayed failure, and closed/disconnected terminals. +Assert both visible redraw and the exact next submitted command, with no automatic evaluation. + +**Author decision (2026-11-27):** selected the bounded asynchronous-output helper using C07's +restore primitive, preserving multiline state and deferring output during evaluation to a safe +prompt boundary. Apply to delayed success and failure feedback. + +**Implementation refinement (advised claude-opus-5.5, 2026-11-27, 90% confidence):** the existing +`setPromptWidth` already resets only the physical render-origin row, preserving logical input, +multiline and history state. No additional input API is needed. First move to End using the old +origin, separate/write the message, then call `setPromptWidth(terminalDisplayWidth(prompt))` +at the new prompt row before emitting the prompt and restoring text/cursor. Do not call +`showPrompt` or `resetLine` for idle asynchronous feedback. Queue while evaluating or input-disabled; +flush at the next safe `showPrompt` boundary and discard queued feedback on Disconnect. +This answers the C07 review's wrapped-row concern without expanding the accepted scope. + +**Done (2026-11-27), commit `b32d0a0dc` (local, not pushed):** gpt-6.1-sol separates late +sign-in feedback from the live prompt, restores its input/cursor without clearing multiline/history +state, and queues feedback while evaluation or disabled input owns the terminal. Disconnect/close +discard obsolete queued messages. Existing identity/lifecycle guards, synchronous messages and +C10 behavior remain unchanged. Added 21 focused cases; input/PTY suites: 249 passed. +Six existing late-failure assertions now include the deliberately redrawn prompt while retaining +the original message and no-reset/no-replay assertions. Advised (claude-opus-5.5): exact revision +approved at 90% confidence. Final Case 1 build and all 652 targeted tests passed. +Bounded residual: feedback queued during a paste-choice dialog dismissed without a new prompt +appears at the next prompt. This timing edge was noted by the advisor as non-blocking, not expanded +into additional handling. Real-terminal visual checks remain pending. +[Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722358367). + +## C10. Anonymous command result is discarded on host-client churn + +**Comment:** [Copilot C10](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721516027). + +**Evidence and impact.** +[Anonymous evaluation](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/shell/ShellSessionManager.ts#L399) +maps any intervening epoch change to `credentialsChanged`, after awaiting the worker response. +[Host client deletion](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/ClustersClient.ts#L1252) +advances that epoch even when the diagnostic endpoint has not changed. +Initialization also checks this conservative fence. + +The important distinction: a submitted command **may already have completed on the server** +before its reply is rejected. The extension does not replay it, but "open a new Shell" is not +an accurate account of benign client churn and can encourage a manual rerun. +**Medium for post-command outcome messaging; Low for the rare concurrency inconvenience.** +No mutation was executed during this review. + +**Options.** + +- **Recommended:** keep epoch/latch guards, but distinguish an epoch-only stale _evaluation reply_ + from a proven settings change when presenting it. Proposed bounded copy: + **"This command may have completed, but its result is no longer current. Check the database + before running it again."** + Do not use this completion warning for startup, which has not evaluated a command. + **Pros:** honest outcome and less rerun risk; no safety relaxation. + **Cons:** a small host-local outcome distinction and dependent PTY tests/localization. +- Won't fix epoch tolerance. **Pros:** preserves the existing conservative fence. + **Cons:** benign host churn can still discard a useful reply; acceptable alongside the message fix. +- Accept replies whenever the current endpoint matches. **Pros:** fewer discarded results. + **Cons:** cannot rule out Disconnect/update that occurred and cleared during the operation; + equality now is not lifecycle history. Rejected without a justified stronger invariant. + +Do not add a second epoch/state machine for this edge case, replay any operation, claim rollback, +or treat a warm worker's current model URI as proof that a previous reply is safe. + +**Author decision (2026-11-27):** **won't fix / ignore**, overriding the message-change +recommendation. Operator instruction: **"c10, ignore/wont fix."** No C10 guard, classification, +or message changes are selected. The existing behavior and safety fences remain unchanged. +No additional rationale was supplied. + +**No-code outcome recorded (2026-11-27):** the operator's override is retained without changing +guards or wording. [Individual thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722321276) +records the selected outcome, not an implemented fix. The thread was not resolved. + +## C11. Index failures can show two tree modals + +**Comment:** [Copilot C11](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721516084). + +**Evidence and impact.** +[hideIndex](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/index.hideIndex/hideIndex.ts#L74) +and its drop/unhide peers show a modal, set `suppressDisplay`, and rethrow. +[Their registration](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/documentdb/ClustersExtension.ts#L1087) +uses the diagnostics wrapper, which then shows another modal. +A callback-owned-modal probe confirmed two presentations with the same original error. +**Medium; fix this routine failure regression.** + +**Important correction:** `suppressDisplay` is **not** an "already presented" flag. +[rethrowBoundCommandUnavailable](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/commands/rethrowBoundCommandUnavailable.ts#L9) +sets it without showing anything. Honoring it blindly would make other tree failures silent. + +**Options.** + +- **Recommended:** explicitly mark feedback ownership for the particular error/invocation when + an index catch actually presents it; the tree wrapper skips additional UI only for that marker. + Use a narrow shared helper rather than mutating/wrapping errors or changing the SDK flag's meaning. + **Pros:** preserves original errors, telemetry, early validation failures and webview behavior. + **Cons:** small ownership bookkeeping at the three existing catches and the wrapper. + Unknown/non-Error throws must still work; a different error thrown by cleanup must not be + hidden merely because an earlier error was presented. No extra explanation notification. +- Consolidate tree index feedback into the wrapper while retaining callback feedback for webview + invocations. **Pros:** one owner and no sidecar marker. + **Cons:** requires reliable invocation-origin plumbing and preserving index-specific headings. +- Declare the entire index callback presentation-owned at registration. **Pros:** simple option. + **Cons:** validation errors thrown before the callback's catch have no owner; unsafe unless those + paths are also covered. +- Won't fix. **Pros:** errors remain visible. **Cons:** two modal interruptions for normal failures; + not recommended. + +The advisor correctly identified the `suppressDisplay` counterexample. Its error-marker idea is +useful, but restoring an additional explanation notification would still duplicate feedback; +the final proposal keeps one presentation. **Acceptance:** exactly one modal for each index action, +early validation still visible, suppression-only bound errors still visible, original error +identity/telemetry retained, and webview behavior unchanged. + +**Author decision (2026-11-27):** selected explicit feedback ownership for the particular +error/invocation when an index catch presents it, with one presentation and no generic +`suppressDisplay` shortcut. + +**Done (2026-11-27), commit `61f09ffcd` (local, not pushed):** mai-code-2 added exact +invocation/error ownership markers at the three index catches and gated only additional tree +modals. Suppression-only errors, early validation, primitives and replacement cleanup errors remain +visible; original errors, explanation telemetry and webview behavior are unchanged. Added 12 +focused cases, including real callback/wrapper integration; 26 passed. Advised (claude-opus-5.5): +approved with high confidence after checking context lifetime and original error identity. +Final batch build remains pending. [Thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722240271). + +## C12. Host-side stale Retry cancellation becomes an alert + +**Comment:** [Copilot C12](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4721516133). + +**Evidence and impact.** +[The bound-view guard](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/webviews/documentdb/boundViewOperations.ts#L55) +can throw `UserCancelledError('staleBoundViewOperation')` without a new unavailable event. +[The Retry catch](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/webviews/documentdb/useBoundViewRecovery.ts#L150) +shows a generic failure when its local revision has not changed. +[The telemetry runner](https://github.com/microsoft/vscode-documentdb/blob/dec9ac64cbdb18f295fb0f05a7ebe12955703c47/src/webviews/_integration/trpc.ts#L149) +recognizes cancellation, but does not provide a client-side cancellation discriminator. +The transport wraps errors; frontend `instanceof UserCancelledError` is not a reliable solution. + +A client-shaped stale rejection probe confirmed the alert, with Retry retained and recovery reset. +This was a hook probe plus source tracing, **not an end-to-end transport reproduction**. +Normal successful Retry is unaffected; concurrent epoch changes are required. +The view stays blocked, its contents remain, and no database operation is replayed. **Low.** + +**Options.** + +- **Recommended won't fix / defer:** keep the bounded "Try Retry again" feedback. + **Pros:** safe and actionable; no cross-router protocol work for a rare superseded attempt. + **Cons:** an obsolete host attempt is announced as a failure rather than staying quiet. + This is an explicit tradeoff for the author, not a claim that cancellation is already filtered. +- Add a distinct typed cancellation result to bound-view recovery and consume it in the shared hook. + **Pros:** precise quiet handling without raw error inspection. + **Cons:** host result contract, three bound-view integrations and transport tests must stay aligned. +- Match cancellation strings or treat every INTERNAL_SERVER_ERROR as cancellation. + **Pros:** little code. **Cons:** hides genuine failures and depends on transport details; rejected. + +If the author prioritizes exact quiet-obsolete-attempt semantics, select the typed option. +Do not return a recovered/success-shaped result for cancelled work or remove the episode's Retry. + +**Author decision (2026-11-27):** selected the recommended won't-fix/defer outcome: retain the +bounded Retry-failure feedback and do not introduce a typed cancellation protocol this round. + +**No-code outcome recorded (2026-11-27):** no protocol or UI change; retained-view safety guards +and bounded Retry feedback remain. [Individual thread reply](https://github.com/microsoft/vscode-documentdb/pull/1146#discussion_r4722321308) +records the tradeoff. The thread was not resolved. + +## Verification and outcome + +- GitHub REST and GraphQL retrieval confirmed the same HEAD and all 12 current unresolved threads; + there was no additional human review request or substantive timeline feedback to assess. + The active-PR tool returned an unrelated cached merged PR, so this review used explicit #1146 + retrieval rather than that cached result. +- Source/control-flow verification covered all 12 comments. A narrow advisor sweep also checked + feedback-ownership counterexamples and unavailable provider endpoints; this was not a broad audit. +- **Run 1:** nine focused existing test files, **428 tests passed**, including **8 temporary probes**. + Run by MAI Code 2 Flash. +- **Run 2:** three of those files after four further probes, **72 tests passed**. + Counts overlap; they are not 500 unique tests. Across the runs there were **12 distinct probes**. +- No TDD-prefixed contract failed. The probes intentionally asserted observed defective behavior + to establish evidence; their passing does **not** mean the proposed fixes exist. +- Temporary probe edits were removed. The deliverable is this report only; proposed permanent + regression coverage is listed with the relevant findings. + +Commands used: + +```bash +npx vitest run \ + src/documentdb/playground/WorkerSessionManager.test.ts \ + src/documentdb/shell/ShellSessionManager.test.ts \ + src/documentdb/shell/DocumentDBShellPty.test.ts \ + src/commands/signInAgain/signInAgain.test.ts \ + src/commands/playground/executePlaygroundCode.test.ts \ + src/commands/openInteractiveShell/openInteractiveShell.test.ts \ + src/utils/commandErrorHandling.test.ts \ + src/webviews/documentdb/useBoundViewRecovery.test.tsx \ + src/webviews/documentdb/documentView/documentsViewRouter.test.ts \ + --maxWorkers=2 + +npx vitest run \ + src/utils/commandErrorHandling.test.ts \ + src/webviews/documentdb/useBoundViewRecovery.test.tsx \ + src/commands/playground/executePlaygroundCode.test.ts \ + --maxWorkers=2 +``` + +Not verified here: actual server mutations, real VM custom-port connectivity, installed-workbench +terminal rendering, live account dialogs, screen-reader behavior, or complete RPC transport +cancellation. No shared accounts, services or database contents were altered. +Build, lint, packaging and the full Case 2 suite were not rerun for this documentation-only review. + +This is comment validation with an advisor, not a completed replacement for every +[CONTRIBUTING section 6 stage](../../../../../CONTRIBUTING.md#6-ai-assisted-review-workflow). +Author decisions are recorded inline above. At lead-run intake the nine selected fixes were +unimplemented; all nine are in scope after the operator's correction. Subsequent commits and +verification belong in the corresponding item's progress note. No GitHub thread was resolved +by recording these selections. + +## Lead outcome (2026-11-27, 17:53 UTC snapshot) + +### Unverified live checks first + +- **C02:** on a real Azure VM node, fail a connection on a custom port, then open the diagnostic + Shell and verify its banner/target uses that port. Refresh/recreate the node and verify an unknown + attempted endpoint reports unavailable rather than using 27017. Do not run destructive commands. +- **C07/C09:** in the installed terminal, check idle/mid-line/wrapped cursor restoration on Disconnect; + check delayed sign-in success/failure with partially typed and multiline input, and while evaluating. + Verify visible text and the next submitted read-only command agree. +- Unit tests exercised PTY output and mocked VM attempts, not a running workbench, live authentication + or real VM networking. Try these checks before pushing. + +### Endpoint and completed work + +**Local implementation complete:** all nine accepted fixes have separate code commits and passed +the final Case 1 checks. The source plan was committed before coding; progress notes were committed +separately from code. No push, PR-status change, thread resolution, or Case 2 handoff was performed. +The remote PR head remains `dec9ac64c`; the new code is local. + +| Item | Code commit (local) | Actual coding model | Outcome | +| ---- | ------------------- | ------------------- | ------------------------------------------------------------- | +| C01 | `476e65176` | gpt-6.1-sol | Diagnostic startup capability across the worker boundary | +| C02 | `e3bd77b21` | gpt-6.1-sol | Sanitized attempted VM endpoint, unknown fails closed | +| C03 | `c952e9624` | mai-code-2 | Current-state stale diagnostic feedback and supported refresh | +| C04 | `1fdcfd43d` | mai-code-2 | Playground document-connection feedback ownership | +| C06 | `2688f86ca` | gpt-6.1-sol | Genuine dismissal separated from internal stale acquisition | +| C07 | `ce2cf8d8b` | mai-code-2 | Retained input cursor restored with wrap-aware rendering | +| C08 | `bd70e3298` | mai-code-2 | Anonymous errors stay terminal-only | +| C09 | `b32d0a0dc` | gpt-6.1-sol | Asynchronous feedback preserves input and defers safely | +| C11 | `61f09ffcd` | mai-code-2 | Exact callback error-presentation ownership | + +C05, C10 and C12 retain their operator-selected no-code outcomes. +**All 12 comments received individual replies in their own Copilot review threads**; links are +recorded inline. No omnibus PR comment was posted. Earlier replies and done notes stating that +the batch build was pending describe their posting-time snapshot; this final verification supersedes +that pending status for all nine code commits. + +Models match the advisor recommendations; no substitutions or unavailable-model retries occurred. +The C08/C07 same-file chain reused one MAI Code 2 agent with a commit between items. +Technical decisions are recorded inline: operator selections; advisor-approved interfaces and logic; +the leader's C08 mechanical review; C02's rejected silent catch and revised new test; and C09's use of +the existing render-origin reset rather than a new API. No unresolved technical question was parked. +The operator's initial C01/C02 skip was withdrawn before coding. + +Advisor work: two planning consultations plus ten logic-review consultations across nine advisor +contexts, including the C02 follow-ups. C08's one-line guard had the advisor-approved design and a +leader mechanical review. All final logic revisions received approval; C02's initial approval was +not treated as sufficient after the leader found the silent catch. C07's Home-output assertion and +C09's redrawn-prompt assertions changed only to match selected behavior, not to weaken contracts. + +### Final verification + +- `npm run build`: **passed**, exit 0. +- One focused Vitest run: **13 files, 652 tests passed, 0 skipped, 0 failures**, exit 0; + Vitest duration **17.58 seconds**. +- Build ran before the root tests. Combined build/test tool span was about **1m04s**; + build elapsed time was not separately reported. +- No TDD-prefixed contract failed. No dependencies were installed or changed. +- Source user-facing localization keys were unchanged; generation, formatting, lint, strict + package-test checks, full Vitest and packaging were not run for this Case 1 endpoint. +- The feature README and user manual still describe the selected recovery behavior; the README + now links this review/progress record. No documentation drift sweep was performed. +- Tracked worktree was clean at verification. Only the two pre-existing untracked + `.copilot-connection-*` directories remained, untouched. + +Final command: + +```bash +npx vitest run \ + src/documentdb/playground/WorkerSessionManager.test.ts \ + src/documentdb/shell/ShellSessionManager.test.ts \ + src/documentdb/playground/PlaygroundEvaluator.test.ts \ + src/commands/openInteractiveShell/openInteractiveShell.test.ts \ + src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.test.ts \ + src/tree/documentdb/diagnosticCredentialRead.test.ts \ + src/tree/documentdb/ClusterItemBase.test.ts \ + src/commands/playground/executePlaygroundCode.test.ts \ + src/commands/signInAgain/signInAgain.test.ts \ + src/documentdb/shell/ShellInputHandler.test.ts \ + src/documentdb/shell/DocumentDBShellPty.test.ts \ + src/utils/commandErrorHandling.test.ts \ + src/commands/index.shared/indexCommandFeedback.test.ts \ + --maxWorkers=2 +``` + +Full Case 2 remains for an explicit review handoff. This run does not claim completion of all +CONTRIBUTING section 6 initial-review/validation/sweep requirements or the pending live checks. + +### Usage snapshot + +Window: **2026-11-27T17:17:00.522Z through the host's 17:53 UTC snapshot** (about 36 minutes). +This is the current lead run only, not the earlier implementation/review sessions. +The final response and subsequent report-persistence operations are excluded. +AIU are usage units, not dollars. Model-request spans overlap and are not wall-clock elapsed time. + +| Model | Role | Requests | Summed model time | AIU | AIU share | +| ---------------- | ------- | -------: | ----------------: | ----: | --------: | +| claude-opus-5.5 | advisor | 106 | 11m09s | 522.2 | 56.9% | +| gpt-6.1-sol | leader | 73 | 21m07s | 249.0 | 27.1% | +| gpt-6.1-sol | coding | 52 | 8m19s | 102.1 | 11.1% | +| mai-code-2 | coding | 66 | 10m23s | 43.8 | 4.8% | +| mai-code-2-flash | checks | 3 | 12s | 0.1 | 0.0% | + +| Role | Requests | Summed model time | AIU | AIU share | +| ------- | -------: | ----------------: | ----: | --------: | +| leader | 73 | 21m07s | 249.0 | 27.1% | +| coding | 118 | 18m42s | 145.8 | 15.9% | +| advisor | 106 | 11m09s | 522.2 | 56.9% | +| checks | 3 | 12s | 0.1 | 0.0% | + +**Totals:** leader **249.0 AIU**, subagents **668.2 AIU**, run **917.2 AIU**. +Rounding individual rows can differ from these host totals. + +| Model | Role | Input | Output | Cache read | Cache write | Reasoning | +| ---------------- | ------- | ---------: | -----: | ---------: | ----------: | --------: | +| claude-opus-5.5 | advisor | 7,417,828 | 66,866 | 6,917,519 | 500,069 | 32,299 | +| gpt-6.1-sol | leader | 16,168,987 | 62,617 | 16,066,066 | 102,702 | 27,412 | +| gpt-6.1-sol | coding | 2,599,223 | 29,702 | 2,405,939 | 193,128 | 9,412 | +| mai-code-2 | coding | 3,261,276 | 35,323 | 2,697,728 | 0 | 17,143 | +| mai-code-2-flash | checks | 49,634 | 798 | 31,744 | 0 | 310 | + +Cache and reasoning fields may overlap input/output; they must not be added into a purported +token total. Figures are copied from the host session-log helper with explicit agent roles. +The helper's multi-turn elapsed summaries are not used as per-item wall-clock measurements. + +**Optimization note:** advising was the largest measured category (56.9%), followed by leading +(27.1%). The planning context alone accounted for 334.5 AIU, including its late C09 follow-up. +Future runs could use a smaller planning packet and a fresh, narrowly scoped context for late +interface questions instead of rehydrating a large planning context. C02 needed one bounded +implementation rework and a final re-review; no coding model was silently downgraded to reduce cost. + +## Case 2 pre-push verification (2026-11-27, 18:24 UTC snapshot) + +The operator expanded the endpoint: **"run case 2 checks, address issues, then push."** +The earlier local-only endpoint and deferred Case 2 notes are historical. This snapshot was +recorded after all local checks passed and before the authorized push; the delivered head and CI +state are reported in the handoff. No PR-status change or thread resolution is part of this request. + +### All eight commands passed + +| Command | Result | +| ------------------------- | --------------------------------------------------------------- | +| `npm run l10n` | Passed; generated bundle unchanged | +| `npm run prettier-fix` | Passed; nine tracked files formatted | +| `npm run l10n:check` | Passed | +| `npm run lint` | Passed on full rerun after fixture corrections | +| `npm run build` | Passed | +| `npm run typecheck:tests` | Passed; exact strict workspace-test script | +| `npx vitest run` | Passed: 451 files, 10,294 passed, 1 skipped; 118.89s | +| `npm run package` | Passed: `vscode-documentdb-1.1.1-alpha.4.vsix`, 9,268,165 bytes | + +Formatting was committed separately as `e33bb7bb1`. +The full runtime suite passed before the two test-only fixture corrections; afterwards the +two relevant suites passed **26/26**, and full lint passed. Those 26 tests are not additional +unique tests. Production source did not change after the successful build, strict package-test +checks and package run. No TDD-prefixed contract failed, no dependencies were changed or installed, +and no larger-heap or worktree-ignore workaround was needed. + +### C11 fixture correction + +**Commit `2589ec75d`:** the primitive-error fixture now uses a typed +`vi.fn<() => Promise>().mockRejectedValue(error)` instead of a direct primitive throw. +The cleanup fixture calls a typed throwing cleanup function from `finally`. +Error/primitive identity, marked-feedback modal counts, explanation telemetry, cleanup precedence +and the exact replacement-error assertions remain unchanged. No lint rule was disabled. + +The first attempt used `Promise.reject(error)`, which triggered a second production-style rule, +`prefer-promise-reject-errors`. Advised (claude-opus-5.5): use the existing typed rejection-mock +pattern; the advisor verified its `unknown` rejection input and awaited-wrapper equivalence. +MAI Code 2 applied the final fixture changes and passed targeted Prettier, ESLint and Vitest. +This is test setup, not a production behavior change or a weakened contract. + +### Publishing and remaining checks + +The verified commits and this record are to be pushed together to +`dev/tnaum/connection-lifecycle-ux`, targeting `feature/connection-lifecycle` in PR #1146. +The milestone remains 1.2.0. Individual thread updates will reference published commits; +no omnibus PR comment or automatic thread resolution is requested. + +C05/C10/C12 retain their selected no-code outcomes. Real VM node-lifetime/custom-port and installed +terminal visual checks remain unperformed, as listed above. All CONTRIBUTING section 6 +initial-review/validation/sweep requirements are not claimed complete merely because Case 2 passed. + +### Case 2 follow-up usage + +Window: **2026-11-27T17:59:57.853Z through the host's 18:24 UTC snapshot**. +These figures are separate from the earlier lead snapshot; publication, subsequent report +persistence and the final response are excluded. AIU are not dollars. + +| Model | Role | Requests | Summed model time | AIU | AIU share | +| ---------------- | ------- | -------: | ----------------: | ----: | --------: | +| claude-opus-5.5 | advisor | 3 | 14s | 25.5 | 7.0% | +| gpt-6.1-sol | leader | 20 | 17m02s | 336.1 | 92.2% | +| mai-code-2 | coding | 9 | 49s | 2.6 | 0.7% | +| mai-code-2-flash | checks | 13 | 46s | 0.5 | 0.1% | + +**Role totals:** leader 336.1 AIU; coding 2.6; advisor 25.5; checks 0.5. +**Host totals:** leader 336.1 AIU, subagents 28.6 AIU, follow-up run 364.7 AIU. +Rounded rows may differ from the host total. + +| Model | Role | Input | Output | Cache read | Cache write | Reasoning | +| ---------------- | ------- | --------: | -----: | ---------: | ----------: | --------: | +| claude-opus-5.5 | advisor | 122,674 | 1,445 | 80,680 | 41,986 | 400 | +| gpt-6.1-sol | leader | 6,087,797 | 42,590 | 5,774,418 | 313,319 | 37,441 | +| mai-code-2 | coding | 218,487 | 2,089 | 186,368 | 0 | 699 | +| mai-code-2-flash | checks | 254,047 | 1,913 | 179,200 | 0 | 901 | + +Cache/reasoning fields overlap input/output and are not a token total. Request spans are not +wall-clock elapsed time. The full-suite agent's initial tool span was about 8m31s; per-step +durations other than the runtime suite were not reported. Leading was the largest measured +follow-up cost; a fresh, smaller-context session for long verification/publishing rounds would +reduce coordination overhead. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/02-ux-implementation-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-ux-implementation-plan.md new file mode 100644 index 000000000..2c02f1659 --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-ux-implementation-plan.md @@ -0,0 +1,721 @@ +--- +feature: connection-lifecycle +kind: plan +status: draft +created: 2026-11-27 +code: + - src/tree/documentdb/ClusterItemBase.ts + - src/tree/documentdb/DatabaseItem.ts + - src/tree/documentdb/IndexesItem.ts + - src/tree/BaseExtendedTreeDataProvider.ts + - src/commands/openInteractiveShell/openInteractiveShell.ts + - src/documentdb/shell/ShellSessionManager.ts + - src/documentdb/shell/DocumentDBShellPty.ts + - src/commands/playground/executePlaygroundCode.ts + - src/webviews/documentdb/useBoundViewRecovery.ts + - src/webviews/components/DisconnectedOverlay.tsx + - src/documentdb/connectionTeardown.ts + - src/tree/connections-view/DocumentDBClusterItem.ts + - src/commands/showConnectionStats/showConnectionStats.ts + - src/commands/showWorkerStats/showWorkerStats.ts +--- + +# Iteration 2: implement the connection-lifecycle UX review findings + +> **Purpose:** translate the open findings in the +> [PR #1136 UX review](./01-pr1136-ux-review.md) into bounded implementation work for +> review, then execution by the `lead` skill. This plan is not approval to implement +> unresolved recommendations. + +**Source of truth:** the review records the observed behavior, operator decisions, +recommendations and remaining uncertainty. Existing feature intent and accepted +constraints remain in the [feature overview](../README.md) and +[decisions](../decisions.md). If current code differs from the review's cited snapshot, +verify the current behavior before changing it; do not treat snapshot references as proof +that a reported issue still reproduces. + +## Goal and scope + +Implement the review's open, actionable user-experience findings while preserving the +connection-lifecycle safety rules: never change the identity bound to a retained view, +never replay a failed database operation, retain action-only tree recovery rows, and keep +worker/webview feedback on its intended surface. + +In scope: F1–F5 and F7–F12 from the review. F6 is closed as accepted-as-is; Q1 is answered +without an extension change; the Dashboard diagnostics link is tracked in #1141. Do not +expand this work into broader network resilience, account sign-out handling, telemetry +redesign, or unrelated error-message cleanup. + +## Authority and decision gates + +1. Approved directions in the UX review are constraints: F2's rerun guidance, F3's + tree-action modal policy, F8's separate Shell system-output line, F9's “Keep open” + label, F10's explicit saved-password explanation, F11's accessible name, and F12's + human-readable shared debug format. +2. The review's recommendations for F1, F4 and F5 are **not all final decisions**. + Before implementing each item, confirm its unresolved behavior or exact wording with + the operator. In particular: + - F1 leans toward an unauthenticated Shell from error rows, but final label and + behavior are still open. + - F4's recommended in-dialog Retry failure treatment is not approved. + - F5's recommended stale-explicit-click handling is not approved. +3. F7 is a reproduction gate, not a confirmed regression. Reproduce the exact credential + repair sequence on the current build before changing menu eligibility. If it does not + reproduce, record the evidence and close it without a speculative code change. +4. Do not append a decision to `decisions.md` for a recommendation merely because this + plan records it. Once the operator confirms a significant new behavior, record that + decision with their rationale before or alongside implementation. +5. Recheck affected source, related tests, and current localization patterns at execution + time. Keep changes in the existing command/tree/webview surfaces; avoid new lifecycle + abstractions unless current code demonstrates they are necessary. + +### Execution authorization (2026-11-27) + +The operator invoked `/lead` to process this plan, then explicitly approved the item/model +mapping and the remaining F1/F4/F5/F3 choices. The endpoint is **local work and commits**: +no push, external edits or Case 2 handoff was requested. + +- Advisor: `claude-opus-5.5`. +- WI-1 expansion, WI-2, WI-3 and WI-5: `mai-code-2`, substituted for the advisor's + `gpt-6.1-terra` recommendations at the operator's request. +- WI-4: `gpt-6-luna`, the advisor's mechanical-copy recommendation. +- WI-1 stale recovery and WI-6: `gpt-6.1-sol`, retained for lifecycle/authentication logic. +- Tests, builds and other tool-running agents: `mai-code-2-flash`. +- F1: replace the error-row action with **Open shell without authentication**, using the + bounded authentication/endpoint policy in [decision 0022](../decisions.md#0022-offer-a-separately-unauthenticated-shell-from-failure-rows-only). +- F4: option B, with the bounded copy and in-view announcement in + [decision 0023](../decisions.md#0023-keep-retained-view-retry-failure-feedback-inside-the-unavailable-dialog). +- F5: option C, with the explicit-click and quiet-background policy in + [decision 0024](../decisions.md#0024-classify-explicit-stale-recovery-clicks-and-explain-only-failed-actions). +- F3: explicit tree-origin commands are included; webview-origin feedback is unchanged + ([decision 0025](../decisions.md#0025-tree-origin-failures-use-modals-webview-origin-command-feedback-stays-unchanged)). +- WI-2: the operator requested proposed copy for other unavailable reasons before editing; + the subsequent reason-specific Shell/Playground proposals were approved. Changed + identity/settings and sign-in messages remain unchanged. Single-line partial Shell input + is preserved; partial multi-line and queued evaluation input are cleared, as approved. +- WI-4: F10 changes explanatory copy only; the opt-in credential-save branch is unchanged. + The final approved wording retains the cluster and successful decoded-password context: + **Connected to "{cluster}" using the decoded password. Would you like to update your + saved credentials with the correctly formatted password?** +- F3 expansion: the operator selected extension-owned TreeViews only. Azure Resources + remains unchanged, with enhancement [#1143](https://github.com/microsoft/vscode-documentdb/issues/1143) + created at their request. Foreground-origin/event-order verification is still required + before implementing owned-view expansion. +- F7: current source inspection has not established a defect. A live reproduction is + still pending; no speculative menu change is authorized. + +Unrelated untracked `.copilot-connection-relays/` and `.copilot-connection-telemetry/` +directories were present at intake and are left untouched. + +## Workstream order and dependencies + +```text +WI-0: Revalidate findings and settle gates + ├── WI-1: Tree feedback and explicit stale tree actions (F3; F5 decision-gated) + ├── WI-2: Worker recovery wording and Shell output line (F2, F8) + ├── WI-3: Retained-view Retry failure feedback (F4) + ├── WI-4: Teardown, decoded-password, and overlay wording (F9–F11) + ├── WI-5: Human-readable connection and worker stats (F12) + ├── WI-6: Unauthenticated Shell from connection failure rows (F1) + └── WI-7: Investigate F7 only if it reproduces +``` + +WI-1 through WI-6 are independent after WI-0 except: + +- WI-1's stale-action behavior depends on the operator choosing an F5 option. +- WI-3 depends on the operator choosing an F4 option. +- WI-6 depends on the operator confirming F1's behavior and label. +- F7 is included in WI-0; only a reproducible defect creates a small implementation + follow-up, which must be reviewed as a separate scoped change. + +Workstreams may be grouped into reviewable PRs by surface, but keep distinct behavior +changes and their tests independently reviewable. Do not combine unrelated changes just +to reduce the number of PRs. + +## WI-0: Revalidate findings and settle decision gates + +**Review items:** F1, F4, F5, F7 +**Depends on:** none +**Deliverable:** verified current-code baseline and explicit operator answers for the +behavior gates. + +1. Check the current branch/build against the review's evidence; inspect the current + implementations and tests named in the relevant F sections. +2. Reproduce F7 in the current build: failed connection → Update Credentials → choose + reconnect with fresh credentials → inspect the cluster context menu after refresh. + Capture whether a client exists, whether a latch applies, and the refreshed tree + context tag. Do not infer the cause from a restart. +3. Present the operator the options and trade-offs in O2 and O3 and ask for a decision + before coding F4 or F5. +4. Confirm F1's error-row Shell behavior and user-facing label. Keep normal context-menu + Shell startup authenticated unless explicitly changed by a decision. +5. Record what was confirmed, rejected, or not reproducible in the progress notes for + this plan. No code change is required for a non-reproducible F7. + +**Done when:** current behavior is verified; F4/F5/F1 are either explicitly decided or +marked blocked; F7 has reproduction evidence and a disposition. Do not silently resolve +any of these gates in implementation. + +> **Baseline verified; live evidence pending (2026-11-27):** advisor +> `claude-opus-5.5` revalidated the relevant current source against `dd11ca7d3`. +> The operator explicitly decided F1/F4/F5 and approved the model mapping. +> The connected context tag still requires a cached client without a lifecycle hold; +> credential-save completion releases the update hold. Source inspection did not +> establish an F7 defect and is not a reproduction. The operator selected **Leave +> pending for operator testing; no speculative fix**. WI-0 is not claimed fully +> verified until that live evidence is supplied. + +## WI-1: Align tree-action failures and stale explicit recovery (F3, F5) + +**Depends on:** WI-0 for F5; F3's tree-modal direction is already approved. +**Likely areas:** `BaseExtendedTreeDataProvider`, database/index expansion providers, +tree recovery commands, and their existing tests. + +- Use modal feedback for failures caused by tree actions, including descendant tree + expansion and explicit tree commands, consistent with the cluster-expansion pattern + and error-translation guidance. +- Present a translated heading and separate error detail. Avoid duplicate modals for one + action, raw error paragraphs in tree children, or changing recovery children from + actions into status text. +- Apply the chosen F5 policy only to an explicit click on a still-visible stale action: + re-check state, refresh/reveal current tree state where appropriate, and explain an + actually failed action using the selected behavior. Keep cancellation, disposed work, + obsolete background replies, and already-completed recovery quiet. +- Never connect a different identity or restart work for a removed/disposed target just + to make the stale action appear successful. + +**Acceptance:** + +- A failed database or index expansion gives one modal with the actionable explanation; + no second notification/modal is emitted for the same failure. +- Tree items still expose recovery actions only. +- An explicit stale action follows the operator-approved outcome; cancellation and stale + background work remain silent. +- The result does not bypass existing identity, epoch, or latch guards. + +**Tests:** focused provider/command tests for modal feedback, one-error/one-feedback +behavior, current-state refresh, and quiet cancellation/background paths. Use existing +tree/error-translation helpers and assert the translated-message contract rather than +duplicating framework behavior. + +> **Deferred, escalated (2026-11-27), WI-1a/F3 descendant expansion:** the advisor +> (`claude-opus-5.5`, 40% confidence in origin attribution) found no documented ordering +> between `onDidExpandElement` and the first failing `getChildren`. Options were modals +> for all owned-view failures including background refresh, a workbench event-order probe +> without an API guarantee, or deferral. The operator explicitly chose to ship +> tree-command alignment and defer descendant expansion to +> [#1143](https://github.com/microsoft/vscode-documentdb/issues/1143) until foreground +> attribution is supported. No expansion code was changed. The issue records Azure +> scenarios, benefits, background-noise risks and host-coordination trade-offs. + +> **Done (2026-11-27), WI-1b commit `57f96b23b`:** explicit cluster-associated +> tree-command failures use one modal with an explained/localized heading and separate +> error detail. The Diagnostics wrapper was changed in place; command registrations and +> webview/no-cluster feedback are unchanged. Decisions: operator, explicit tree-origin +> policy; advised (`claude-opus-5.5`), 90% approval of the exact implementation after +> checking callers, cancellation, original error identity and single-feedback ownership. +> The worker (`gpt-6.1-sol`, as recommended) verified the installed azext runtime at +> 99% confidence. Fourteen focused tests were added and passed. Batch 1 +> `npm run build` passed; seven touched test files passed (67 tests). No Case 2 checks ran. +> The initial wrapper-selection blocker was resolved by preserving registrations and +> changing Diagnostics itself; no public argument contract changed. F5/WI-1c remains open. + +> **Done (2026-11-27), WI-1c-tree commit `c77ba2115`:** supported explicit stale recovery +> actions refresh first, then show one accurate removed/changed modal. Other stale states +> refresh quietly; a connection disconnected during sign-in retains the existing closed +> explanation. Worker sign-in entry points, identity checks, key/latch mutations and unsupported +> Azure Workspace guards are unchanged. Decisions: operator, explicit F5 option C; advised +> (`claude-opus-5.5`), 85% approval of the exact revision. Actual/recommended model: +> `gpt-6.1-sol`; the worker verified preserved invariants at 97%. Forty-four focused cases +> were added across the three command test files; 73 tests passed. Epoch-only presentation +> assertions intentionally became quiet, retaining no-auth-start assertions. No helper export +> or helper expansion was added. Worker notification handling remains a separate follow-up. + +> **Done (2026-11-27), WI-1c-worker commit `0a01a24e4`:** an explicit stale sign-in click +> gets existing Shell/Playground-specific removed/changed guidance only when the terminal/file +> still exists and the current typed latch proves that failure. Cancellation, closed work, +> already-reported revisions, epoch-only and no-latch cases stay quiet. No worker is reset, +> stopped, restarted or rebound by these stale callbacks. Decisions: operator, explicit F5 +> worker-surface policy; advised (`claude-opus-5.5`), 85% approval; actual/recommended +> `gpt-6.1-sol`. The leader's initial helper-name error was corrected before edits to reuse +> `handleWorkerFailure` and `getPlaygroundRecovery`. Thirty-eight focused cases were added; +> 163 tests passed. Existing ownership assertions are unchanged; the telemetry mock suppresses +> only the production fire-and-forget sign-in action. Final batch verification remains pending. + +## WI-2: Correct worker recovery guidance and Shell status output (F2, F8) + +**Depends on:** none. +**Likely areas:** `DocumentDBShellPty`, `executePlaygroundCode`, their tests, and the +connection-lifecycle user manual. + +- For an unchanged disconnected connection, tell the user to reconnect from the tree and + run the command/script again in the existing Shell/Playground. Do not request a new + Shell or a new connection pick when the retained binding can recover in place. +- Preserve stricter guidance for a removed connection or changed host/identity. Do not + promise worker-local variables survive when a worker must restart. +- Emit Shell “Disconnected” as system output on a separate line from the interactive + prompt. Handle idle, partially typed, and evaluating states deliberately; preserve + user input when possible rather than applying a newline blindly. +- Localize changed/new user-facing copy and update the manual's disconnect/reconnect + guidance so it matches the implemented behavior. + +**Acceptance:** + +- Same-identity Disconnect → Reconnect guidance allows a retained Shell and Playground + to retry without reopening/re-picking. +- Changed or removed bindings retain their accurate non-recovery guidance. +- “Disconnected” cannot be mistaken for text typed at the Shell prompt, including when + emitted during partial input or evaluation. + +**Tests:** focused Shell output tests for idle/partial/evaluating states; Playground +message tests for unchanged versus changed/removed bindings; relevant manual link/content +check if available. + +> **Execution split (2026-11-27):** WI-2a implements the approved, unit-testable F2 guidance +> first (`mai-code-2`, substituted for the advisor's Terra recommendation). WI-2b implements +> F8 system-output/input handling last, after other Shell changes, because terminal timing +> also needs a live workbench check. This is a coordination split, not additional scope; +> the accepted work-item count remains seven, plus conditional WI-7. No Shell-writing workers +> run concurrently. + +> **Done (2026-11-27), WI-2a commit `a2eba522a`:** Shell and Playground now give the approved +> reason-specific recovery guidance. Unchanged Disconnect asks for tree reconnect and a new +> run in the existing terminal/file; removed and changed bindings keep their stricter guidance. +> Decisions: operator, explicit approval of the reason-specific copy; leader, 99% confidence +> after reviewing the message-selector diff and direct-latch reuse that execution guards and +> no-replay behavior are unchanged. Advised (`claude-opus-5.5`); recommended Terra, actual +> `mai-code-2` per the approved substitution. Eighteen focused cases were added across the +> existing two tests, retaining no-start/no-replay assertions; 118 tests passed. The new +> asynchronous Shell assertions use `vi.waitFor`, not a fixed sleep. Batch build/localization +> remain pending. WI-2b/F8 output is not implemented. + +> **Done (2026-11-27), WI-2b commit `9d434732d`:** Disconnected is system output on its own +> line. Idle single-line input is preserved and visibly restored; partial multiline and queued +> evaluating input are cleared as approved. Wrapped input moves its caret to the end before the +> newline, preventing old input tails from appearing beside the status. Decisions: operator, +> explicit input-state policy; advised (`claude-opus-5.5`), 88% final approval. Recommended +> Terra, actual `mai-code-2` per the approved substitution. Five focused output cases were added; +> 134 Shell tests passed. Final build passed after the wrapped-cursor fix. Real terminal behavior +> still needs the operator check below; no live workbench verification is claimed. + +## WI-3: Keep failed retained-view Retry feedback in context (F4) + +**Depends on:** WI-0 operator decision. +**Likely areas:** `useBoundViewRecovery`, `DisconnectedOverlay`, and the three retained +view recovery tests/scenarios. + +Implement only the operator-selected O2 option. If the recommended in-dialog option is +selected: + +- Keep the persistent unavailable reason distinct from the latest Retry failure. +- Show a concise, bounded failure explanation in the existing dialog; do not replace the + original reason with unsupported network/server assumptions or expose a raw stack. +- Make Retry, Close view, and X behavior available again after failure. Ensure an + assistive-technology user is notified of the new failure. +- Do not add a host modal, replay the failed database operation, or change the retained + content/copy behavior. + +**Acceptance:** a typed unavailable result and an unclassified thrown exception both +leave the user with one coherent in-view explanation and usable recovery/close controls; +failure does not execute the original operation again. + +**Tests:** focused hook/component tests for typed and thrown Retry failures, restored +controls, announcement, and no operation replay. Exercise Collection View, Document View, +and Dashboard if their shared integration wiring differs. + +> **Review correction pending (2026-11-27):** the first `mai-code-2` implementation passed +> 19 focused tests and type-checking, but advisor `claude-opus-5.5` (80%) found that a Retry +> reply can disclose a new irrecoverable reason. Keeping the old reason hides actual +> removal/settings/identity state. The operator selected adopting truthful current reasons, +> with the explicit constraint that an already-visible Retry button must not disappear after +> Retry or runtime state changes. This is not permission to change identity or bypass a hold. +> The corrected UI contract is pending; the initial implementation is not marked done. + +> **Scope confirmed (2026-11-27):** the operator selected **1A**: retained Retry availability +> lasts for the current unavailable episode, including dialog dismissal/reopening. Successful +> recovery ends the episode; a later initially Close-only episode does not inherit Retry. +> New terminal reasons remain truthful, but cannot remove Retry already offered in that episode. + +> **Done (2026-11-27), commit `6d2e10715`:** failed Retry feedback stays in the existing dialog. +> The current unavailable reason updates when the host reports a different reason/action; a +> separate bounded alert announces every failed attempt. Retry, once offered, remains through +> failures, runtime updates and dismissal/reopening of the same unavailable episode. Successful +> recovery resets availability for a later episode. Retained Retry explicitly dispatches `retry`, +> never `close`, and no original operation is replayed. Decisions: operator, explicit 2.A +> qualification and 1A episode scope; advised (`claude-opus-5.5`), 88% approval of the exact +> corrected revision. Recommended Terra, actual `mai-code-2` per the approved substitution. +> Eight focused tests were added across the two existing files; 23 tests passed. The interim +> type-check encountered concurrent WI-6 edits; WI-6 subsequently reported a successful root +> type-check. Final batch build and browser scenarios remain pending. + +> **Browser fixture follow-up (2026-11-27), commit `039c1cbd8`:** real Document View lifecycle +> scenarios failed because the existing fixture did not acknowledge the void `reportDirty` +> mutation. The shared fixture now returns transport-compatible `null`; application code and +> scenario behavior are unchanged. Model `mai-code-2`; leader, 99% confidence after checking +> the actual host/link void-result contract. Static browser scenario tests passed (47). +> The nine Document View routes are being rerun; the earlier Collection View/Dashboard runs +> passed. This is a required validation-fixture repair, not a new product behavior. + +> **Browser verification update (2026-11-27):** all 24 unique source routes passed: +> Collection View 9, Document View 9 and Dashboard 6, across dark, light and high contrast. +> No page/CSP/unknown-RPC or assertion failures remained. The `reportDirty` mutation was +> exercised successfully. Static scenario tests passed (47). Only owned watch servers were +> started/stopped; no background verification server was left running. These are source +> browser checks, not a live extension-host or screen-reader verification. + +## WI-4: Clarify teardown and retained-content wording (F9–F11) + +**Depends on:** none. +**Likely areas:** `connectionTeardown`, `DocumentDBClusterItem`, `DisconnectedOverlay`, +related tests, and localization. + +- Change the retained-view choice label from “Keep open (disabled)” to “Keep open”. + Preserve the disabled-operation behavior and existing help that explains the resulting + state. +- In the decoded-password confirmation, say that the correctly formatted password will + be saved into the connection's saved credentials. Preserve the existing explicit + opt-in action and never include the secret value. +- Change the overlay X accessible name to “Dismiss dialog to access view contents”. + Preserve the existing behavior: dismissing exposes retained contents for inspection + and copying but does not restore database operations. +- Update localized strings using the repository localization workflow when implementing. + +**Acceptance:** + +- The teardown option is “Keep open” and does not change teardown semantics. +- The password confirmation communicates what is saved without revealing the password + or changing the save action. +- The accessible name describes content access, and dismissing still leaves database + operations blocked. + +**Tests:** focused existing component/command tests for the rendered label, confirmation +copy and action, accessible name, and blocked-operation behavior. + +> **Done (2026-11-27), commit `5d00558cb`:** F9 now says **Keep open**; F10 retains the +> successful decoded-password/cluster context and explicitly names the correctly formatted +> password saved in credentials; F11 names access to retained contents. The save branch, +> teardown settings and blocked-operation behavior are unchanged. Decisions: operator, +> explicit approval of the exact copy; leader, 99% confidence after reviewing the +> mechanical source diff that the action/save semantics were preserved. Advised +> (`claude-opus-5.5`) during WI-0; its `gpt-6-luna` recommendation was used. One added +> decoded-password workflow test proves dismissal does not save. The three focused +> Vitest files passed (26 tests), including after the operator-driven F10 correction. +> The original generic F10 prompt was a leader error, corrected before commit. +> Batch build/localization and live workbench presentation checks remain pending. + +> **Verification update (2026-11-27):** Batch 1 build and focused tests passed. Localization +> generation will run once after all string-changing items. Live presentation remains pending. + +## WI-5: Unify human-readable debug-stat formatting (F12) + +**Depends on:** none. +**Likely areas:** `showConnectionStats`, `showWorkerStats`, their tests. + +- Use multiline labeled records for both commands, with consistent headings, indentation, + units, and a single explicit missing-value convention. Do not use decorative rulers. +- Preserve each command's existing facts and availability, including worker/session + counts, held/pending states, Entra expiry, session identifiers, and init-duration facts + where currently available. +- Keep state descriptions truthful: a cached client is not a successful ping; pending + startup is not a live connection. Preserve redaction boundaries and do not add + credential values or new identifying information. +- Keep host-client and worker/session data distinct; formatting consistency does not + imply they measure the same thing. + +**Acceptance:** both commands use the same readable record conventions without losing +existing fields, inventing values, or disclosing sensitive data. + +**Tests:** focused output tests for headings, field labels/units, missing values, and +redaction-safe output. Assert representative formatting without overfitting whitespace +that is not user-visible. + +> **Done (2026-11-27), commit `e4a6ad337`:** both stats commands now use labeled +> multiline records, explicit units and **(not available)** for missing values, preserving +> existing host-client, pending/held, worker/session, expiry and username facts. +> Decisions: operator, explicit F12/model approval; leader, 99% confidence after comparing +> the mechanical output diff that existing values/redaction boundaries were retained. +> Advised (`claude-opus-5.5`); recommended `gpt-6.1-terra`, actual `mai-code-2` per the +> approved substitution. Five tests were added across the two stats test files; all +> nine focused tests passed. Review replaced an `as never` evaluator fixture with a real, +> typed evaluator using a mocked worker. Batch build remains pending. + +> **Verification update (2026-11-27):** Batch 1 `npm run build` passed; both stats files were +> included in the seven-file focused test run (67 tests total). + +## WI-6: Offer an unauthenticated Shell from connection failure rows (F1) + +**Depends on:** WI-0 operator confirmation of behavior and label. +**Likely areas:** `ClusterItemBase`, `openInteractiveShell`, Shell startup options, and +focused command/tree tests. + +- Add a distinct error-row entry path that starts a Shell without attempting the failed + saved authentication. Do not change ordinary authenticated Shell startup from the + cluster context menu. +- Keep saved credentials, `CredentialCache`, connection identity, and existing clients + unchanged. Do not silently fall back to saved authentication after anonymous database + operations are rejected. +- Make clear in the final, operator-approved label that this Shell starts without + authentication. Opening it does not promise that database commands are authorized. +- Preserve existing error-row recovery behavior and action ordering. + +**Acceptance:** + +- Error-row Shell startup does not read/use cached credentials or make an authenticated + startup attempt. +- Normal context-menu Shell startup remains authenticated and unchanged. +- Anonymous command failure is surfaced honestly; no credential state is modified. + +**Tests:** focused command tests contrasting error-row and normal entry, proving no +credential use or mutation on the former and preserving the latter's existing startup +path. Test the anonymous command failure feedback. + +> **Gate resolved (2026-11-27):** the worker stopped before edits because URI parser errors +> can contain credentials. Advisor `claude-opus-5.5` approved a constructor-only bounded +> replacement at 90%, and removing every mixed-case credential-key spelling at 95%. +> The operator selected **1.A**: **Invalid connection string.**, with the unsafe parser +> error/cause discarded entirely. WI-6 implementation resumed with the previously approved +> zero-cache, endpoint, trust and lifecycle constraints. + +> **Completion scope approved (2026-11-27):** the operator questioned blanket removal of +> working suggestions, then agreed to an internal `includeClusterMetadata` flag that preserves +> local completion/ghost behavior but excludes authenticated shared metadata from the new +> anonymous diagnostic path. The completion provider and its existing tests are directly +> dependent owned files. Normal Shell behavior is unchanged; no fake IDs, new setting or +> blanket completion disablement is authorized. Implementation is in progress, not complete. + +> **Done (2026-11-27), commit `aea08108a`:** the failure-row Shell is a separate NoAuth entry +> with a sanitized, re-read endpoint and epoch/latch guards. It does not read `CredentialCache`, +> alter saved credentials/clients, use shared authenticated metadata, pin an authenticated +> identity, create a token relay, fall back to saved authentication or replay operations. +> Local completion/history/bracket behavior and normal Shell startup are preserved. Constructor +> parser errors become the approved bounded message without an unsafe cause. Pre-terminal +> failures use one modal; later driver failures stay in the terminal. +> Decisions: operator, explicit F1 authentication/endpoint/parser/metadata boundaries; advised +> (`claude-opus-5.5`), 88% full-path approval and 90% approval of the final pre-terminal hunk. +> Actual/recommended model: `gpt-6.1-sol`. Seventy-two cases were added across the existing/new +> test files; the initial eight-suite run passed 392 tests without TDD failures, the final +> command suite passed 29 and the strengthened Shell suite passed 111. Root type-check passed; +> final build/localization remain pending. No public command contract or manifest entry was added. + +## WI-7: Investigate F7 only if WI-0 reproduces it + +**Depends on:** WI-0 evidence. +**Likely areas if confirmed:** credential repair refresh path, connected context-tag +calculation, Disconnect menu condition. + +Do not pre-emptively alter command visibility. If reproduced, identify and fix the +smallest stale-state or refresh defect supported by evidence; preserve the rule that +Disconnect is available only for a currently connected eligible tree item. If not +reproduced, record the tested build and state checks in this plan and close the finding +without a code change. + +**Acceptance if fixed:** after successful credential repair and reconnect, the refreshed +connected cluster item exposes Disconnect; disconnected/error items do not. + +**Tests if fixed:** regression test the exact state transition and ensure the menu remains +hidden when no connected client is present or a latch applies. + +> **Deferred, escalated (2026-11-27), operator decision:** leave F7 pending live testing +> with no speculative implementation. On the current build, try failed saved-password +> connection → Update Credentials → **Yes, reconnect now** → databases appear → +> right-click the refreshed cluster. Capture whether **Disconnect** is present, the cached +> client/held state from **Show Connection Stats**, and whether collapse/expand or Refresh +> changes the menu. Record the actual build/commit and state; do not label a source-only +> check **not reproducible**. + +## Cross-workstream verification + +For code changes, follow the repository's Case 1 checks while implementation is in +progress: `npm run build` and `npx vitest run `. Run `npm run l10n` +only if localized strings change. Do not claim the full handoff suite passed unless it +was actually run; if this work is later prepared for review, follow the repository's +Case 2 requirements. + +Before calling this iteration complete: + +- Verify all new/changed strings use `vscode.l10n.t()` where required and generated + localization output is current. +- Verify tree recovery remains action-only and connection/view identity safety is + unchanged. +- Run the focused regression tests for every implemented workstream; run relevant webview + scenarios for changed retained-view behavior. +- Update the user manual only where the implemented recovery guidance changes. +- Record each operator decision, deviation, test result, and any non-reproduced finding + in the corresponding workstream progress record. Do not mark an unimplemented finding + fixed. + +## Progress + +| WI | Status | Outcome / decision / verification | +| ---- | ----------------------------------------------------------- | ----------------------------------------------------------------- | +| WI-0 | Gates approved; F7 live evidence pending | Current-code baseline checked; no live reproduction claim | +| WI-1 | Implemented and locally verified; expansion deferred | `57f96b23b`, `c77ba2115`, `0a01a24e4`; F3 expansion follows #1143 | +| WI-2 | Implemented and locally verified; terminal check pending | `a2eba522a`, `9d434732d`; final Shell suite 134 passed | +| WI-3 | Implemented and locally verified | `6d2e10715`, fixture `039c1cbd8`; 24 source routes passed | +| WI-4 | Implemented and locally verified; live presentation pending | `5d00558cb`; generated localization current | +| WI-5 | Implemented and locally verified | `e4a6ad337`; Batch 1 build/tests passed | +| WI-6 | Implemented and locally verified | `aea08108a`; full-path approval 88%, final hunk 90% | +| WI-7 | Deferred pending operator reproduction | No speculative code change; exact live sequence recorded | + +## Outcome + +**Endpoint: local work, committed and Case 1 verified.** No push or review handoff was requested. +The only external edit was the operator-requested enhancement issue +[#1143](https://github.com/microsoft/vscode-documentdb/issues/1143). No CI run for a pushed head +is claimed. Case 2 (including `prettier-fix`, lint, strict package-test type-check, full runtime +suite and packaging) was not run and remains deferred until review handoff. + +### Unverified workbench checks + +1. **Shell output:** disconnect while idle, with partial single-line input, with a long wrapped + input whose caret was moved Home, in multiline mode and while evaluating. Verify a separate + system status line, preserved visible single-line input, cleared multiline/queued input and + no stale output or replay. Try this before pushing. +2. **F7:** run the recorded failed-password → Update Credentials → reconnect → refreshed + Disconnect-menu sequence on the current build. Capture client/held state; do not infer a + regression from source or label it not reproducible without the live run. +3. **Presentation/accessibility:** inspect the Keep open/decoded-password/X copy in the workbench + and verify a real screen reader notices each failed Retry. Source browser and ARIA tests are + not a screen-reader or installed-extension check. + +### Verification + +- `npm run l10n`: passed; generated bundle committed separately as `6959c70f5`. +- `npm run build`: passed in the final batch and again after the last wrapped-cursor fix. +- Focused runtime batch: **18 files, 583 tests passed** (11.33 s). +- After the last added regression: the unchanged earlier files retain that result; the final + Shell suite was rerun separately and **134 tests passed** (11.36 s). No combined 584-test + invocation is claimed. +- Browser manifest/route tests: **47 passed** with the browser-specific Vitest config. +- Real source browser helpers: **24 unique routes ready** across all three themes: + Collection View 9, Document View 9, Dashboard 6. A missing void-mutation fixture caused six + initial Document View failures and was repaired in `039c1cbd8`; the rerun passed. +- No TDD contract failures. One interim root type-check saw concurrent unfinished NoAuth edits; + the later root type-check and final builds passed. +- All owned browser/watch helpers were stopped. No dependency installation was required. +- Unrelated untracked `.copilot-connection-relays/` and `.copilot-connection-telemetry/` were + left untouched. + +### Decisions, review and model plan + +Operator decisions are recorded in 0022–0025 and inline above. Retry availability is sticky only +within its unavailable episode; successful recovery resets it. The anonymous path isolates +authenticated metadata while preserving local completion behavior. Descendant expansion is +explicitly deferred to #1143, and F7 is pending operator evidence. No identity/latch guard was +weakened. The unsupported/no-latch cases stay quiet instead of receiving speculative explanations. + +Thirty substantive advisory packets ran across six `claude-opus-5.5` agents. Exact code revisions +received their required logic reviews. The operator's sticky Retry direction superseded the initial +remove-Retry recommendation, and metadata isolation replaced the rejected blanket-completion and +fake-ID proposals. The leader's F10-copy and worker-helper-name mistakes were corrected before their +code commits. There were no coding-model authorization substitutions; Terra recommendations used +`mai-code-2`, mechanical WI-4 used `gpt-6-luna`, lifecycle/authentication used `gpt-6.1-sol`, and +checks used `mai-code-2-flash`, as approved. + +### Usage: cumulative run + +Start **2026-11-27 11:06:38 UTC**, snapshot **14:23 UTC**: approximately 196 minutes wall-clock. +Model-request spans below sum to 162m20s; overlapping model/tool/check spans are not additive. +Build and localization durations were not separately reported. The final response and subsequent +progress-record writes are excluded from this snapshot. AIU are not dollars. + +| Model | Role | Requests | Summed model time | AIU | Share | +| ---------------- | ------- | -------: | ----------------: | -----: | ----: | +| claude-opus-5.5 | advisor | 146 | 21m16s | 1277.8 | 47.6% | +| gpt-6-luna | coding | 13 | 1m13s | 2.0 | 0.1% | +| gpt-6.1-sol | leader | 135 | 95m58s | 1019.3 | 37.9% | +| gpt-6.1-sol | coding | 123 | 23m46s | 321.0 | 11.9% | +| mai-code-2 | coding | 89 | 16m13s | 64.5 | 2.4% | +| mai-code-2-flash | checks | 41 | 3m54s | 1.7 | 0.1% | + +| Role | Requests | Summed model time | AIU | Share | +| ------- | -------: | ----------------: | -----: | ----: | +| leader | 135 | 95m58s | 1019.3 | 37.9% | +| coding | 225 | 41m12s | 387.5 | 14.4% | +| advisor | 146 | 21m16s | 1277.8 | 47.6% | +| checks | 41 | 3m54s | 1.7 | 0.1% | + +**Totals:** leader 1019.3 AIU; subagents 1667.0 AIU; run 2686.3 AIU. + +| Model / role | Input | Output | Cache read | Cache write | Reasoning | +| ------------------------- | ---------: | ------: | ---------: | ----------: | --------: | +| claude-opus-5.5 / advisor | 11,507,254 | 125,393 | 9,846,990 | 1,659,908 | 66,048 | +| gpt-6-luna / coding | 723,017 | 9,623 | 653,250 | 69,728 | 6,183 | +| gpt-6.1-sol / leader | 30,887,461 | 244,993 | 30,106,530 | 780,526 | 174,956 | +| gpt-6.1-sol / coding | 10,009,918 | 77,779 | 9,413,490 | 596,059 | 27,223 | +| mai-code-2 / coding | 5,329,087 | 47,245 | 4,499,968 | 0 | 20,975 | +| mai-code-2-flash / checks | 923,922 | 9,468 | 708,096 | 0 | 4,554 | + +Cache/reasoning fields may overlap input/output; do not sum them into a purported token total. + +### Usage: resumed work + +Separate window **12:37:15–14:24 UTC**, approximately 107 minutes wall-clock, following the +operator-reported authentication restoration. The original blocked edit succeeded on retry; +no alternative access route was used while it was denied. This window is a subset of the +cumulative run, not an additional charge to add to it. + +| Model | Role | Requests | Summed model time | AIU | Share | +| ---------------- | ------- | -------: | ----------------: | ----: | ----: | +| claude-opus-5.5 | advisor | 47 | 6m25s | 503.8 | 30.8% | +| gpt-6.1-sol | leader | 72 | 72m44s | 849.7 | 52.0% | +| gpt-6.1-sol | coding | 89 | 18m37s | 250.9 | 15.4% | +| mai-code-2 | coding | 45 | 6m34s | 28.6 | 1.7% | +| mai-code-2-flash | checks | 36 | 3m36s | 1.4 | 0.1% | + +| Role | Requests | Summed model time | AIU | Share | +| ------- | -------: | ----------------: | ----: | ----: | +| leader | 72 | 72m44s | 849.7 | 52.0% | +| coding | 134 | 25m11s | 279.5 | 17.1% | +| advisor | 47 | 6m25s | 503.8 | 30.8% | +| checks | 36 | 3m36s | 1.4 | 0.1% | + +**Resumed totals:** leader 849.7 AIU; subagents 784.7 AIU; run 1634.4 AIU. + +| Model / role | Input | Output | Cache read | Cache write | Reasoning | +| ------------------------- | ---------: | ------: | ---------: | ----------: | --------: | +| claude-opus-5.5 / advisor | 3,209,592 | 37,413 | 2,449,519 | 759,947 | 19,439 | +| gpt-6.1-sol / leader | 23,416,229 | 178,087 | 22,779,798 | 636,215 | 147,875 | +| gpt-6.1-sol / coding | 7,974,254 | 62,647 | 7,521,903 | 452,084 | 21,678 | +| mai-code-2 / coding | 2,962,098 | 17,172 | 2,607,104 | 0 | 7,978 | +| mai-code-2-flash / checks | 836,803 | 9,122 | 674,304 | 0 | 4,476 | + +**Optimization:** advising was the largest cumulative category (47.6%); leading was the largest +resumed category (52.0%). Repeated contract clarification, broad initial reading and long leader +turns were substantial overhead compared with coding/checks. For a future run, consolidate UX and +ownership gates into one compact packet, correct exact interfaces before dispatch, and keep leader +handoffs short. Preserve the approved model plan; these unlike tasks do not establish a model-quality +ranking. + +## Case 2 follow-up (2026-11-27) + +The operator requested committing the work, running the full Case 2 list, addressing failures, +then pushing once. A dedicated draft head, `dev/tnaum/connection-lifecycle-ux`, targets +`feature/connection-lifecycle`; the milestone is 1.2.0. The earlier local-only outcome above is +the record of the preceding endpoint, not the current publishing authorization. + +| Command | Result | +| ------------------------- | ----------------------------------------------------- | +| `npm run l10n` | Passed | +| `npm run prettier-fix` | Passed; 18 formatted files committed as `6a8ad8756` | +| `npm run l10n:check` | Passed | +| `npm run lint` | Passed with the default heap after the fixes below | +| `npm run build` | Passed; rerun after the scoped lint fixes | +| `npm run typecheck:tests` | Passed (exact strict package-test script) | +| `npx vitest run` | 449 files passed; 10,205 tests passed, 1 skipped | +| `npm run package` | Passed; rerun after fixes, producing the current VSIX | + +The first lint run exhausted the default Node heap. The operator identified the main-branch +worktree exclusion fix, which was ported from `f38e0282f` as `9553a3810`, without merging unrelated +main changes. Its regression test passed, and lint no longer required an increased heap. +The now-completing lint run exposed 20 diagnostics in seven changed files; `mai-code-2` corrected +only type-visible comparisons, mock/error typing, synchronous awaits and log inspection. +All existing assertions, unknown-error coverage, error identity, view identifiers and redaction +coverage were retained. Those fixes are committed as `feb640c3f`; targeted lint and 63 focused +tests passed. Final default-heap lint, build and packaging passed after targeted formatting. +The added worktree regression passed; its three ported files passed the formatting check. + +Readiness remains separate from publishing: there is no committed Section 6 AI pre-review file +for this UX round. The dedicated PR stays draft. The live workbench/F7/screen-reader checks and +the explicit #1143 deferral remain as recorded above; no human-review readiness is claimed. +No unrelated untracked `.copilot-connection-*` directories were changed. diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md index 24aa55459..adbc0ce77 100644 --- a/docs/release-notes/1.2.md +++ b/docs/release-notes/1.2.md @@ -36,7 +36,7 @@ See [Keep connections usable](https://microsoft.github.io/vscode-documentdb/user ### ⭐ Disconnect, Reconnect, and Keep Your Place Connected clusters gain a **Disconnect** action. Before ending live work, the extension asks what to -do with open view tabs: **Close all** or **Keep open (disabled)**. A setting can choose either +do with open view tabs: **Close all** or **Keep open**. A setting can choose either behavior in advance, while unsaved document changes still require explicit confirmation. Retained Collection View, Document View, and Cluster Dashboard contents stay available for diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index bbb754b92..1de0d385f 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -21,12 +21,18 @@ The actions available depend on the connection and the failure: 1. **Update connection string…**, when offered, corrects the saved destination before you change credentials. 2. **Update credentials…**, when offered, lets you review the saved authentication. 3. **Diagnose connection…** opens [step-by-step connection diagnostics](./diagnose-connection). -4. **Open shell** opens the Interactive Shell for further investigation. +4. **Open shell without authentication** opens a diagnostic Interactive Shell without using the + failed saved login. The server can still reject database commands that require authentication. 5. **Retry** tries the connection again after you have corrected or investigated the problem. Retry is always last. These shorter labels apply to the recovery rows under a failed cluster; context-menu and Command Palette titles can differ. +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 +not available, the action explains that instead of retrying the saved authentication. + ## Keep connections usable The extension normally recovers from an expired Microsoft Entra ID token or an idle connection @@ -48,7 +54,7 @@ When open connection views exist and the setting `documentDB.connections.openTab - **Close all**, which closes open connection views. Closing a dirty Document View first asks whether to **Discard changes**. -- **Keep open (disabled)**, which keeps view contents but prevents database operations. +- **Keep open**, which keeps view contents but prevents database operations. This choice applies to Collection View, Document View, and Cluster Dashboard tabs. It does not close the Interactive Shell terminal or the Query Playground file; Disconnect stops their database @@ -64,9 +70,14 @@ why it is unavailable: - Select **Retry** after repairing or reconnecting the connection. Retry checks the binding and does not replay the operation that failed. - Select **Close view** to close the tab. A dirty Document View warns before closing. -- Use the **X** to dismiss the dialog when you need to copy from the view. Database operations stay +- Use the **X** to dismiss the dialog when you need to inspect or copy view contents. Database operations stay disabled, and the next operation shows the dialog again. +Once **Retry** is offered, it remains available while that connection problem is unresolved, +even if the reason changes or you dismiss and reopen the dialog. Attempts still check the original +binding and cannot bypass a blocked connection or switch identity. After successful recovery, +a later problem can offer **Close view** only. + Use the cluster's **Reconnect** action in the tree to restore the same connection. If reconnect automatically opens the retained Dashboard for that connection, it retries on its own. If it stays disabled, select **Retry**, as you would in other retained webviews. diff --git a/docs/user-manual/diagnose-connection.md b/docs/user-manual/diagnose-connection.md index af3ff0f2d..23c23bec7 100644 --- a/docs/user-manual/diagnose-connection.md +++ b/docs/user-manual/diagnose-connection.md @@ -38,7 +38,7 @@ There are three ways to open it: - **From a failed connection.** When a cluster fails to connect, the tree shows recovery items under it. Select **Diagnose connection…**. Configuration repairs appear before diagnosis and - **Open shell**, with **Retry** last; see [connection recovery](./connecting-to-databases#recover-from-a-failed-connection). + **Open shell without authentication**, with **Retry** last; see [connection recovery](./connecting-to-databases#recover-from-a-failed-connection). - **From any cluster.** Right-click a cluster in the Connections, Discovery or Azure view and select **Diagnose Connection…**. This works whether or not the cluster is connected. It is not offered on the Local Quick Start instance node. diff --git a/eslint.config.mjs b/eslint.config.mjs index 752782725..e4edb3259 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -10,6 +10,8 @@ import licenseHeader from 'eslint-plugin-license-header'; import react from 'eslint-plugin-react'; import reactHooks from 'eslint-plugin-react-hooks'; import globals from 'globals'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; import ts from 'typescript-eslint'; export default ts.config( @@ -24,6 +26,8 @@ export default ts.config( '**/out', '**/node_modules', '**/*.d.ts', + // A nested checkout is a separate workspace, even when it has no ESLint ignore pattern. + (filePath) => existsSync(join(filePath, '.git')), ], }, { diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 0c2e205fc..701333347 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -584,6 +584,7 @@ "Cannot copy TTL or unique indexes with documents": "Cannot copy TTL or unique indexes with documents", "Cannot delete folder \"{0}\". The following {1} task(s) are using connections within this folder:": "Cannot delete folder \"{0}\". The following {1} task(s) are using connections within this folder:", "Cannot move {0} {1}. The following {2} task(s) are using connections being moved:": "Cannot move {0} {1}. The following {2} task(s) are using connections being moved:", + "Cannot open a shell without authentication for \"{0}\": its endpoint is not available.": "Cannot open a shell without authentication for \"{0}\": its endpoint is not available.", "Cannot start task in state: {0}": "Cannot start task in state: {0}", "Capabilities": "Capabilities", "Certificate": "Certificate", @@ -820,7 +821,7 @@ "Connect without a username or password": "Connect without a username or password", "Connected": "Connected", "Connected to": "Connected to", - "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials?": "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials?", + "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?": "Connected to \"{cluster}\" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?", "Connected to {0}": "Connected to {0}", "Connected to the cluster \"{cluster}\" using decoded password.": "Connected to the cluster \"{cluster}\" using decoded password.", "Connected to the cluster \"{cluster}\".": "Connected to the cluster \"{cluster}\".", @@ -1124,13 +1125,13 @@ "disconnect this connection": "disconnect this connection", "Disconnect?": "Disconnect?", "Disconnected": "Disconnected", - "Disconnected. Reconnect from the tree, then open a new shell.": "Disconnected. Reconnect from the tree, then open a new shell.", + "Disconnected. Reconnect from the tree, then run your command again.": "Disconnected. Reconnect from the tree, then run your command again.", "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.": "Discovery plugin error: clusterId \"{0}\" must start with provider ID \"{1}\". Plugin \"{2}\" must prefix clusterId with its provider ID.", "Discovery Plugins: {0}": "Discovery Plugins: {0}", "Discovery view": "Discovery view", "DiskANN": "DiskANN", "Dismiss": "Dismiss", - "Dismiss dialog to copy view contents": "Dismiss dialog to copy view contents", + "Dismiss dialog to access view contents": "Dismiss dialog to access view contents", "Dismiss the connection dialog instead if you need to copy anything from the view.": "Dismiss the connection dialog instead if you need to copy anything from the view.", "Dissatisfied": "Dissatisfied", "DNS connection options invalid": "DNS connection options invalid", @@ -1736,6 +1737,7 @@ "Invalid conflict resolution strategy selected.": "Invalid conflict resolution strategy selected.", "Invalid connection string format. It should start with \"mongodb://\" or \"mongodb+srv://\".": "Invalid connection string format. It should start with \"mongodb://\" or \"mongodb+srv://\".", "Invalid Connection String: {error}": "Invalid Connection String: {error}", + "Invalid connection string.": "Invalid connection string.", "Invalid connection type selected.": "Invalid connection type selected.", "Invalid filter syntax: {0}. Please use valid JSON or a DocumentDB API expression, for example: { name: \"value\" }": "Invalid filter syntax: {0}. Please use valid JSON or a DocumentDB API expression, for example: { name: \"value\" }", "Invalid folder type.": "Invalid folder type.", @@ -1771,7 +1773,7 @@ "JSON results view: Read-only display of query results in JSON format": "JSON results view: Read-only display of query results in JSON format", "JSON View": "JSON View", "Keep one tls option with the value required by your cluster.": "Keep one tls option with the value required by your cluster.", - "Keep open (disabled)": "Keep open (disabled)", + "Keep open": "Keep open", "Keep the existing data": "Keep the existing data", "Keep validation on": "Keep validation on", "Keep-alive timeout exceeded": "Keep-alive timeout exceeded", @@ -2213,8 +2215,8 @@ "Open setting: {0}": "Open setting: {0}", "Open settings to change the default behavior.": "Open settings to change the default behavior.", "Open setup": "Open setup", - "Open shell": "Open shell", "Open Shell": "Open Shell", + "Open shell without authentication": "Open shell without authentication", "Open shells are still using the previous connection settings.": "Open shells are still using the previous connection settings.", "Open the VS Code Marketplace to learn more about \"{0}\"": "Open the VS Code Marketplace to learn more about \"{0}\"", "Open this query in Collection View": "Open this query in Collection View", @@ -3007,6 +3009,8 @@ "The connection details could not be read.": "The connection details could not be read.", "The connection did not finish in time. You can increase the timeout in Settings:": "The connection did not finish in time. You can increase the timeout in Settings:", "The connection is unavailable.": "The connection is unavailable.", + "The connection is unavailable. Check the server or network, then run the script again.": "The connection is unavailable. Check the server or network, then run the script again.", + "The connection is unavailable. Check the server or network, then run your command again.": "The connection is unavailable. Check the server or network, then run your command again.", "The connection on this computer was accepted, then closed during the secure handshake, before a certificate arrived.": "The connection on this computer was accepted, then closed during the secure handshake, before a certificate arrived.", "The connection option {0} is deprecated. This does not establish that the driver ignores it.": "The connection option {0} is deprecated. This does not establish that the driver ignores it.", "The connection requests {0}, but the extension cannot use it.": "The connection requests {0}, but the extension cannot use it.", @@ -3168,6 +3172,8 @@ "The requested managed identity is not assigned to this machine.": "The requested managed identity is not assigned to this machine.", "The requested Microsoft Entra sign-in resource does not appear to be valid for this cloud. If \"documentDB.customEnvironment.ossrdbmsEndpoint\" is set, check its value with your cloud administrator. Otherwise, report this on GitHub so the extension maintainers can investigate. See {link}": "The requested Microsoft Entra sign-in resource does not appear to be valid for this cloud. If \"documentDB.customEnvironment.ossrdbmsEndpoint\" is set, check its value with your cloud administrator. Otherwise, report this on GitHub so the extension maintainers can investigate. See {link}", "The requested sign-in resource does not appear to be valid for this cloud.": "The requested sign-in resource does not appear to be valid for this cloud.", + "The saved credentials were rejected. Update them from the tree, then run the script again.": "The saved credentials were rejected. Update them from the tree, then run the script again.", + "The saved credentials were rejected. Update them from the tree, then run your command again.": "The saved credentials were rejected. Update them from the tree, then run your command again.", "The selected {0} index is not supported by Copy/Paste Indexes.": "The selected {0} index is not supported by Copy/Paste Indexes.", "The selected authentication mechanism does not match what the server offers.": "The selected authentication mechanism does not match what the server offers.", "The selected authentication method is not supported.": "The selected authentication method is not supported.", @@ -3267,15 +3273,22 @@ "This cluster is paused. Resume it in MongoDB Atlas before connecting.": "This cluster is paused. Resume it in MongoDB Atlas before connecting.", "This ClusterIP service requires port-forwarding. Confirm or change the local port to forward to {0}/{1}:{2}.": "This ClusterIP service requires port-forwarding. Confirm or change the local port to forward to {0}/{1}:{2}.", "This Codespaces environment": "This Codespaces environment", + "This connection changed. Refresh the tree and try again.": "This connection changed. Refresh the tree and try again.", "This connection has no connection string.": "This connection has no connection string.", + "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 in the tree. Close this view.": "This connection is no longer in the tree. Close this view.", "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 open a new shell.": "This connection is unavailable. Reconnect from the tree, then open a new shell.", - "This connection is unavailable. Reconnect from the tree, then re-pick it here.": "This connection is unavailable. Reconnect from the tree, then re-pick it here.", + "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.", + "This connection is unavailable. Reconnect from the tree, then run your command again.": "This connection is unavailable. Reconnect from the tree, then run your command again.", "This connection no longer exists. It may have been removed.": "This connection no longer exists. It may have been removed.", "This connection string asked for Microsoft Entra ID": "This connection string asked for Microsoft Entra ID", "This connection targets a local or private network host. TLS certificate validation:": "This connection targets a local or private network host. TLS certificate validation:", + "This connection was removed. Choose another connection for this playground.": "This connection was removed. Choose another connection for this playground.", + "This connection was removed. Choose another connection.": "This connection was removed. Choose another connection.", + "This connection was removed. Open a shell from another connection.": "This connection was removed. Open a shell from another connection.", "This credential no longer exists": "This credential no longer exists", "This deletes the container named {0} and its data volume, then creates a new one. Everything stored in DocumentDB Local is erased.": "This deletes the container named {0} and its data volume, then creates a new one. Everything stored in DocumentDB Local is erased.", "This deletes the DocumentDB Local container and its data volume in {0}, then creates a new instance. All data in the existing instance is permanently erased.": "This deletes the DocumentDB Local container and its data volume in {0}, then creates a new instance. All data in the existing instance is permanently erased.", @@ -3395,12 +3408,14 @@ "Type \"it\" for more": "Type \"it\" for more", "Type a username that is not in this list": "Type a username that is not in this list", "TypeScript-powered completions are unavailable on this read-only extension install. Click to retry.": "TypeScript-powered completions are unavailable on this read-only extension install. Click to retry.", + "Unable to complete this tree action.": "Unable to complete this tree action.", "Unable to confirm closing the view. Try again.": "Unable to confirm closing the view. Try again.", "Unable to connect to the local database instance. Make sure it is started correctly. See {link} for tips.": "Unable to connect to the local database instance. Make sure it is started correctly. See {link} for tips.", "Unable to connect to the local instance. Make sure it is started correctly. See {link} for tips.": "Unable to connect to the local instance. Make sure it is started correctly. See {link} for tips.", "Unable to load tenants. See the DocumentDB output for details.": "Unable to load tenants. See the DocumentDB output for details.", "Unable to parse the document _id. See the output channel for details.": "Unable to parse the document _id. See the output channel for details.", "Unable to recover the connection": "Unable to recover the connection", + "Unable to recover the connection. Try Retry again, or close this view.": "Unable to recover the connection. Try Retry again, or close this view.", "Unable to retrieve credentials for cluster \"{cluster}\".": "Unable to retrieve credentials for cluster \"{cluster}\".", "Unable to retrieve credentials for the selected cluster.": "Unable to retrieve credentials for the selected cluster.", "Uncertainty": "Uncertainty", diff --git a/src/commands/disconnect/disconnect.test.ts b/src/commands/disconnect/disconnect.test.ts new file mode 100644 index 000000000..3b1bfcc65 --- /dev/null +++ b/src/commands/disconnect/disconnect.test.ts @@ -0,0 +1,157 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { Views } from '../../documentdb/Views'; +import { ext } from '../../extensionVariables'; +import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; +import { connectDisconnected, disconnect } from './disconnect'; + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { exists: vi.fn(), getLatchReason: vi.fn(), unlatch: vi.fn() }, +})); +vi.mock('../../documentdb/connectionTeardown', () => ({ teardownConnection: vi.fn() })); +vi.mock('../../extensionVariables', () => ({ ext: { state: { notifyChildrenChanged: vi.fn() } } })); +vi.mock('../../tree/documentdb/ClusterItemBase', () => ({ ClusterItemBase: class {} })); +vi.mock('../retryAuthentication/retryAuthentication', () => ({ refreshAuthenticationNode: vi.fn() })); + +function actionContext(): IActionContext { + return { telemetry: { properties: {}, measurements: {} }, errorHandling: {} } as IActionContext; +} + +function clusterNode(viewId: Views = Views.ConnectionsView): ClusterItemBase { + return Object.assign(Object.create(ClusterItemBase.prototype) as ClusterItemBase, { + id: `${viewId}/folder/cluster`, + contextValue: `${viewId};treeItem_documentdbcluster`, + cluster: { clusterId: 'stable-cluster', treeId: `${viewId}/folder/cluster`, viewId }, + }); +} + +describe('tree disconnect recovery', () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.mocked(ClustersClient.exists).mockReturnValue(true); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + }); + + it.each([disconnect, connectDisconnected])( + '%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); + 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(); + } + }, + ); + + it.each([undefined, 'credentialsRejected', 'userDisconnected'] as const)( + 'refreshes an obsolete Disconnect quietly for %s', + async (reason): Promise => { + const node = clusterNode(); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + await disconnect(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }, + ); + + it.each([undefined, 'credentialsRejected'] as const)( + 'refreshes an already completed or superseded Reconnect quietly for %s', + (reason): void => { + const node = clusterNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + connectDisconnected(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + expect(ext.state.notifyChildrenChanged).not.toHaveBeenCalled(); + }, + ); + + it('disconnects the stable identity and delegates its single refresh to teardown', async (): Promise => { + const node = clusterNode(); + vi.mocked(teardownConnection).mockImplementationOnce(async (_clusterId, _reason, refresh): Promise => { + refresh?.(); + }); + + await disconnect(actionContext(), node); + + expect(teardownConnection).toHaveBeenCalledExactlyOnceWith( + 'stable-cluster', + 'userDisconnected', + expect.any(Function), + ); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('only clears the current user-disconnected latch when reconnecting', (): void => { + const node = clusterNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + + connectDisconnected(actionContext(), node); + + expect(ClustersClient.unlatch).toHaveBeenCalledExactlyOnceWith('stable-cluster'); + expect(ext.state.notifyChildrenChanged).toHaveBeenCalledExactlyOnceWith(node.id); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it.each([disconnect, connectDisconnected])( + '%s leaves unsupported stale Workspace nodes untouched', + async (command): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + + if (command === disconnect) { + await expect(command(actionContext(), clusterNode(Views.AzureWorkspaceView))).rejects.toBeInstanceOf( + UserCancelledError, + ); + } else { + command(actionContext(), clusterNode(Views.AzureWorkspaceView)); + } + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }, + ); + + it('keeps an absent Disconnect selection cancelled without UI', async (): Promise => { + await expect(disconnect(actionContext())).rejects.toBeInstanceOf(UserCancelledError); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); +}); diff --git a/src/commands/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts index 38673118d..08296041a 100644 --- a/src/commands/disconnect/disconnect.ts +++ b/src/commands/disconnect/disconnect.ts @@ -4,8 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { l10n, window } from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { type TreeElement } from '../../tree/TreeElement'; @@ -22,15 +24,60 @@ export async function disconnect(context: IActionContext, node?: TreeElement): P } const { clusterId } = node.cluster; - if (!ClustersClient.exists(clusterId) || ClustersClient.getLatchReason(clusterId)) { - throw new UserCancelledError(); + const reason = ClustersClient.getLatchReason(clusterId); + if (!ClustersClient.exists(clusterId) || reason) { + if ( + node.cluster.viewId !== String(Views.ConnectionsView) && + node.cluster.viewId !== String(Views.DiscoveryView) && + !( + node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue) + ) + ) { + 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 }, + ); + } + return; } await teardownConnection(clusterId, 'userDisconnected', () => refreshAuthenticationNode(node)); } -export function connectDisconnected(_context: IActionContext, node?: TreeElement): void { - if (!isClusterNode(node) || ClustersClient.getLatchReason(node.cluster.clusterId) !== 'userDisconnected') { +export function connectDisconnected(context: IActionContext, node?: TreeElement): void { + if (!isClusterNode(node)) { + return; + } + const reason = ClustersClient.getLatchReason(node.cluster.clusterId); + if (reason !== 'userDisconnected') { + if ( + node.cluster.viewId !== String(Views.ConnectionsView) && + node.cluster.viewId !== String(Views.DiscoveryView) && + !( + node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue) + ) + ) { + 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 }, + ); + } return; } diff --git a/src/commands/index.dropIndex/dropIndex.ts b/src/commands/index.dropIndex/dropIndex.ts index 62eb3dc05..c11a7a085 100644 --- a/src/commands/index.dropIndex/dropIndex.ts +++ b/src/commands/index.dropIndex/dropIndex.ts @@ -9,6 +9,7 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { markCommandErrorPresented } from '../../utils/commandErrorHandling'; import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { getIndexConfirmationStats } from '../index.shared/getIndexConfirmationStats'; @@ -72,6 +73,7 @@ export async function dropIndex(context: IActionContext, node: IndexItem): Promi // error, then rethrow so telemetry still records the failure. const detail = error instanceof Error ? error.message : String(error); context.errorHandling.suppressDisplay = true; + markCommandErrorPresented(context, error); void vscode.window.showErrorMessage(l10n.t('Failed to delete index "{indexName}".', { indexName }), { modal: true, detail, diff --git a/src/commands/index.hideIndex/hideIndex.ts b/src/commands/index.hideIndex/hideIndex.ts index a50ad35f9..d5b6f7ad7 100644 --- a/src/commands/index.hideIndex/hideIndex.ts +++ b/src/commands/index.hideIndex/hideIndex.ts @@ -9,6 +9,7 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { markCommandErrorPresented } from '../../utils/commandErrorHandling'; import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { getIndexConfirmationStats } from '../index.shared/getIndexConfirmationStats'; @@ -76,6 +77,7 @@ export async function hideIndex(context: IActionContext, node: IndexItem): Promi // azext's default non-modal error and rethrow for telemetry. const detail = error instanceof Error ? error.message : String(error); context.errorHandling.suppressDisplay = true; + markCommandErrorPresented(context, error); void vscode.window.showErrorMessage(l10n.t('Failed to hide index "{indexName}".', { indexName }), { modal: true, detail, diff --git a/src/commands/index.shared/indexCommandFeedback.test.ts b/src/commands/index.shared/indexCommandFeedback.test.ts new file mode 100644 index 000000000..3dc0f7650 --- /dev/null +++ b/src/commands/index.shared/indexCommandFeedback.test.ts @@ -0,0 +1,229 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { + createTestActionContext, + registerCommand, + type IActionContext, + type TreeNodeCommandCallback, +} from '@microsoft/vscode-azext-utils'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ext } from '../../extensionVariables'; +import { ErrorExplanationService } from '../../services/errorExplanationService'; +import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { registerCommandWithTreeNodeUnwrappingAndDiagnostics } from '../../utils/commandErrorHandling'; +import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; +import { dropIndex } from '../index.dropIndex/dropIndex'; +import { hideIndex } from '../index.hideIndex/hideIndex'; +import { unhideIndex } from '../index.unhideIndex/unhideIndex'; +import { getIndexConfirmationStats } from './getIndexConfirmationStats'; + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => { + const actual = await importOriginal>(); + return { ...actual, registerCommand: vi.fn() }; +}); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal & { default: Record }>(); + class CancellationError extends Error {} + actual.default.CancellationError = CancellationError; + return { ...actual, CancellationError }; +}); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { getClient: vi.fn() }, +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { + state: { + runWithTemporaryDescription: vi.fn( + async (_id: string, _description: string, callback: () => Promise) => callback(), + ), + showDeleting: vi.fn(async (_id: string, callback: () => Promise) => callback()), + notifyChildrenChanged: vi.fn(), + }, + }, +})); + +vi.mock('../../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn() }, +})); + +vi.mock('../../utils/dialogs/confirmIndexAction', () => ({ + confirmIndexAction: vi.fn(), +})); + +vi.mock('../../utils/dialogs/showConfirmation', () => ({ + showConfirmationAsInSettings: vi.fn(), +})); + +vi.mock('./getIndexConfirmationStats', () => ({ + getIndexConfirmationStats: vi.fn(), +})); + +const explanation = { providerId: 'test-provider', message: 'Check the connection infrastructure.' }; + +function createIndexNode(overrides: Partial = {}): IndexItem { + return { + id: 'folder/cluster/database/collection/indexes/example_1', + cluster: { clusterId: 'stable-cluster' }, + databaseInfo: { name: 'database' }, + collectionInfo: { name: 'collection' }, + indexInfo: { name: 'example_1', type: 'traditional', key: { example: 1 }, ...overrides }, + experience: { api: 'documentdb' }, + } as unknown as IndexItem; +} + +function registerHandler( + handler: TreeNodeCommandCallback, +): (context: IActionContext, ...args: unknown[]) => unknown { + registerCommandWithTreeNodeUnwrappingAndDiagnostics('test.indexAction', handler); + const callback = vi.mocked(registerCommand).mock.calls.at(-1)?.[1]; + if (!callback) { + throw new Error('Command was not registered.'); + } + return callback; +} + +interface ActionCase { + readonly name: string; + readonly callback: TreeNodeCommandCallback; + readonly method: 'dropIndex' | 'hideIndex' | 'unhideIndex'; + readonly telemetryAction: 'drop' | 'hide' | 'unhide'; + readonly heading: string; + readonly error: unknown; + readonly node?: IndexItem; +} + +const actionCases: ActionCase[] = [ + { + name: 'hide', + callback: hideIndex, + method: 'hideIndex', + telemetryAction: 'hide', + heading: 'Failed to hide index "example_1".', + error: new Error('Hide failure'), + }, + { + name: 'unhide', + callback: unhideIndex, + method: 'unhideIndex', + telemetryAction: 'unhide', + heading: 'Failed to unhide index "example_1".', + error: 'Unhide primitive failure', + node: createIndexNode({ hidden: true }), + }, + { + name: 'delete', + callback: dropIndex, + method: 'dropIndex', + telemetryAction: 'drop', + heading: 'Failed to delete index "example_1".', + error: Object.freeze(new Error('Delete failure')), + }, +]; + +describe('tree index command feedback', () => { + let context: IActionContext; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.mocked(confirmIndexAction).mockResolvedValue(true); + vi.mocked(getIndexConfirmationStats).mockResolvedValue({}); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + vi.mocked(vscode.window.showErrorMessage).mockResolvedValue(undefined); + context = await createTestActionContext(); + context.errorHandling.rethrow = true; + context.errorHandling.suppressDisplay = false; + }); + + it.each(actionCases)('shows exactly one callback modal for a failed $name action', async (action) => { + const operation = vi.fn().mockRejectedValue(action.error); + vi.mocked(ClustersClient.getClient).mockResolvedValue({ + [action.method]: operation, + } as unknown as ClustersClient); + const command = registerHandler(action.callback); + const node = action.node ?? createIndexNode(); + + await expect(command(context, node, [node])).rejects.toBe(action.error); + + expect(operation).toHaveBeenCalledExactlyOnceWith('database', 'collection', 'example_1'); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(action.heading, { + modal: true, + detail: String(action.error instanceof Error ? action.error.message : action.error), + }); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: 'stable-cluster', + error: action.error, + }); + expect(context.telemetry.properties).toMatchObject({ + experience: 'documentdb', + actionType: action.telemetryAction, + userCancelled: 'false', + explanationProviderId: explanation.providerId, + }); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.errorHandling.rethrow).toBe(true); + }); + + it.each([ + { + name: 'hide', + callback: hideIndex, + node: createIndexNode({ name: '_id_', key: { _id: 1 } }), + message: 'The "_id_" index cannot be hidden.', + }, + { + name: 'unhide', + callback: unhideIndex, + node: createIndexNode({ hidden: false }), + message: 'Index "example_1" is not hidden.', + }, + { + name: 'delete', + callback: dropIndex, + node: createIndexNode({ name: '_id_', key: { _id: 1 } }), + message: 'The "_id_" index cannot be deleted.', + }, + ] as const)('keeps $name validation failures on the wrapper display path', async ({ callback, node, message }) => { + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + const command = registerHandler(callback); + + const result = command(context, node, [node]); + + await expect(result).rejects.toThrow(message); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail: message, + }); + expect(confirmIndexAction).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(true); + }); + + it('shows a different refresh error after the operation modal was presented', async () => { + const operationError = new Error('Hide failure'); + const refreshError = new Error('Refresh failure'); + vi.mocked(ClustersClient.getClient).mockResolvedValue({ + hideIndex: vi.fn().mockRejectedValue(operationError), + } as unknown as ClustersClient); + vi.mocked(ext.state.notifyChildrenChanged).mockImplementationOnce(() => { + throw refreshError; + }); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + const command = registerHandler(hideIndex); + const node = createIndexNode(); + + await expect(command(context, node, [node])).rejects.toBe(refreshError); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(2); + expect(vscode.window.showErrorMessage).toHaveBeenNthCalledWith(2, 'Unable to complete this tree action.', { + modal: true, + detail: refreshError.message, + }); + }); +}); diff --git a/src/commands/index.unhideIndex/unhideIndex.ts b/src/commands/index.unhideIndex/unhideIndex.ts index 093491d71..6dc7bcd4c 100644 --- a/src/commands/index.unhideIndex/unhideIndex.ts +++ b/src/commands/index.unhideIndex/unhideIndex.ts @@ -9,6 +9,7 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { ext } from '../../extensionVariables'; import { type IndexItem } from '../../tree/documentdb/IndexItem'; +import { markCommandErrorPresented } from '../../utils/commandErrorHandling'; import { confirmIndexAction } from '../../utils/dialogs/confirmIndexAction'; import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { getIndexConfirmationStats } from '../index.shared/getIndexConfirmationStats'; @@ -71,6 +72,7 @@ export async function unhideIndex(context: IActionContext, node: IndexItem): Pro // azext's default non-modal error and rethrow for telemetry. const detail = error instanceof Error ? error.message : String(error); context.errorHandling.suppressDisplay = true; + markCommandErrorPresented(context, error); void vscode.window.showErrorMessage(l10n.t('Failed to unhide index "{indexName}".', { indexName }), { modal: true, detail, diff --git a/src/commands/openInteractiveShell/openInteractiveShell.test.ts b/src/commands/openInteractiveShell/openInteractiveShell.test.ts index 457a82fe6..caf8f3ca6 100644 --- a/src/commands/openInteractiveShell/openInteractiveShell.test.ts +++ b/src/commands/openInteractiveShell/openInteractiveShell.test.ts @@ -5,9 +5,43 @@ import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockInstance } from 'vitest'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; -import { openInteractiveShell } from './openInteractiveShell'; +import { Views } from '../../documentdb/Views'; +import { DocumentDBShellPty, type DocumentDBShellPtyOptions } from '../../documentdb/shell/DocumentDBShellPty'; +import { registerShellTerminal } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import * as unauthenticatedEndpoint from '../../documentdb/shell/unauthenticatedEndpoint'; +import { ErrorExplanationService } from '../../services/errorExplanationService'; +import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; +import { openInteractiveShell, openUnauthenticatedShell } from './openInteractiveShell'; + +vi.mock('../../documentdb/ClustersClient', () => { + const latches = new Map(); + return { + ClustersClient: { + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn((clusterId: string) => latches.get(clusterId)), + latch: vi.fn((clusterId: string, reason: string): void => { + latches.set(clusterId, reason); + }), + unlatch: vi.fn((clusterId: string): void => { + latches.delete(clusterId); + }), + }, + }; +}); + +vi.mock('../../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn() }, +})); + +vi.mock('../retryAuthentication/retryAuthentication', () => ({ + refreshAuthenticationNode: vi.fn(), +})); // Mock DocumentDBShellPty vi.mock('../../documentdb/shell/DocumentDBShellPty', () => ({ @@ -22,6 +56,7 @@ vi.mock('../../documentdb/shell/DocumentDBShellPty', () => ({ handleInput: vi.fn(), setTerminal: vi.fn(), getTerminalInfo: vi.fn().mockReturnValue({ clusterId: 'test-cluster-id' }), + disconnect: vi.fn(), }; }), })); @@ -36,6 +71,7 @@ vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ vi.mock('../../documentdb/CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn().mockReturnValue(true), + getCredentials: vi.fn(), }, })); @@ -50,7 +86,7 @@ describe('openInteractiveShell', () => { properties: {} as Record, measurements: {}, }, - errorHandling: {}, + errorHandling: {} as { suppressDisplay?: boolean }, ui: {}, valuesToMask: [], }; @@ -64,6 +100,7 @@ describe('openInteractiveShell', () => { mockShowInformationMessage = vi.spyOn(vscode.window, 'showInformationMessage').mockResolvedValue(undefined); mockShowErrorMessage = vi.spyOn(vscode.window, 'showErrorMessage').mockResolvedValue(undefined); mockContext.telemetry.properties = {}; + mockContext.errorHandling = {}; (CredentialCache.hasCredentials as Mock).mockReturnValue(true); }); @@ -97,14 +134,17 @@ describe('openInteractiveShell', () => { overrides?: Partial<{ clusterId: string; clusterName: string; + viewId: string; + contextValue: string; }>, ): unknown { return { + contextValue: overrides?.contextValue ?? 'connectionsView;treeItem_documentdbcluster', cluster: { clusterId: overrides?.clusterId ?? 'test-cluster-id', name: overrides?.clusterName ?? 'TestCluster', treeId: 'treeId-test', - viewId: 'connectionsView', + viewId: overrides?.viewId ?? 'connectionsView', dbExperience: { api: 'documentDB' }, }, experience: { api: 'documentDB' }, @@ -139,6 +179,269 @@ describe('openInteractiveShell', () => { }); }); + describe('unauthenticated failure-row entry', () => { + function expectPreTerminalModal(detail: string): void { + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail, + }); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(mockContext.errorHandling.suppressDisplay).toBe(true); + } + + function makeAnonymousNode( + overrides?: Partial<{ + viewId: string; + contextValue: string; + }>, + ): ClusterItemBase { + return { + ...(makeClusterNode(overrides) as object), + getUnauthenticatedEndpoint: vi.fn().mockResolvedValue('mongodb://user:secret@host/?authSource=admin'), + getCredentials: vi.fn(), + getCredentialsForDiagnostics: vi.fn(), + } as unknown as ClusterItemBase; + } + + it('opens with an evicted cache and rereads sanitized endpoints without fetching credentials', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(CredentialCache.hasCredentials).mockReturnValue(false); + await openUnauthenticatedShell(mockContext as never, node); + const options = vi.mocked(DocumentDBShellPty).mock.calls[0][0]; + expect(options.unauthenticated?.connectionString).toBe('mongodb://host/'); + expect(await options.unauthenticated?.reread()).toBe('mongodb://host/'); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(node.getCredentials).not.toHaveBeenCalled(); + expect(node.getCredentialsForDiagnostics).not.toHaveBeenCalled(); + expect(registerShellTerminal).toHaveBeenCalledWith( + expect.anything(), + expect.any(Function), + expect.any(Function), + ); + expect(mockShowTerminal).toHaveBeenCalledOnce(); + }); + + it('keeps the normal command on its authenticated startup options', async (): Promise => { + await openInteractiveShell(mockContext as never, makeClusterNode() as never); + expect(CredentialCache.hasCredentials).toHaveBeenCalledWith('test-cluster-id'); + const options: DocumentDBShellPtyOptions = vi.mocked(DocumentDBShellPty).mock.calls[0][0]; + expect(options.unauthenticated).toBeUndefined(); + }); + + it('reports an unavailable endpoint without opening a terminal', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(node.getUnauthenticatedEndpoint).mockResolvedValue(undefined); + await openUnauthenticatedShell(mockContext as never, node); + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'Cannot open a shell without authentication for "TestCluster": its endpoint is not available.', + { modal: true }, + ); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + }); + + it('propagates only bounded parser errors without creating a terminal', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(node.getUnauthenticatedEndpoint).mockResolvedValue('mongodb://user:private@'); + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + message: 'Invalid connection string.', + }); + expectPreTerminalModal('Invalid connection string.'); + }); + + it.each(['credentialsRejected', 'signInRequired', 'credentialsMissing'] as const)( + 'allows the %s hold without clearing it', + async (reason): Promise => { + const node = makeAnonymousNode(); + ClustersClient.latch(node.cluster.clusterId, reason); + try { + await openUnauthenticatedShell(mockContext as never, node); + expect(mockShowTerminal).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(node.cluster.clusterId)).toBe(reason); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it.each([ + [Views.ConnectionsView, 'connectionsView;treeItem_documentdbcluster', 'connectionRemoved'], + [Views.DiscoveryView, 'discoveryView;treeItem_documentdbcluster', 'credentialsChanged'], + [Views.AzureResourcesView, 'azureResourcesView;ruBranch;treeItem_documentdbcluster', 'identityChanged'], + [ + Views.AzureResourcesView, + 'azureResourcesView;documentDbBranch;treeItem_documentdbcluster', + 'connectionRemoved', + ], + ] as const)( + 'refreshes and explains %s stale nodes with routing tag %s for %s', + async (viewId, contextValue, reason): Promise => { + const node = makeAnonymousNode({ viewId, contextValue }); + ClustersClient.latch(node.cluster.clusterId, reason); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason, + }); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith( + reason === 'connectionRemoved' + ? 'This connection was removed. Choose another connection.' + : 'This connection changed. Refresh the tree and try again.', + { modal: true }, + ); + expect(node.getUnauthenticatedEndpoint).not.toHaveBeenCalled(); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(mockContext.errorHandling.suppressDisplay).toBe(true); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it.each(['userDisconnected', 'credentialsUpdating', 'unreachable'] as const)( + 'uses the generic modal for the %s hold before reading an endpoint', + async (reason): Promise => { + const node = makeAnonymousNode(); + ClustersClient.latch(node.cluster.clusterId, reason); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason, + }); + expect(node.getUnauthenticatedEndpoint).not.toHaveBeenCalled(); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expectPreTerminalModal('The connection is unavailable.'); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it.each([ + [Views.AzureWorkspaceView, 'azureWorkspaceView;treeItem_documentdbcluster'], + [Views.AzureResourcesView, 'azureResourcesView;otherBranch;treeItem_documentdbcluster'], + ] as const)( + 'keeps typed stale feedback generic for unsupported %s node', + async (viewId, contextValue): Promise => { + const node = makeAnonymousNode({ viewId, contextValue }); + ClustersClient.latch(node.cluster.clusterId, 'connectionRemoved'); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason: 'connectionRemoved', + }); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expectPreTerminalModal('The connection is unavailable.'); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }, + ); + + it('rethrows the same unavailability error with generic feedback when no current latch exists', async (): Promise => { + const node = makeAnonymousNode(); + const error = new ConnectionUnavailableError('credentialsChanged'); + vi.mocked(node.getUnauthenticatedEndpoint).mockRejectedValueOnce(error); + + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(error); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expectPreTerminalModal(error.message); + }); + + it('uses the current latch rather than the unavailable error reason', async (): Promise => { + const node = makeAnonymousNode(); + const error = new ConnectionUnavailableError('credentialsChanged'); + vi.mocked(node.getUnauthenticatedEndpoint).mockImplementationOnce(async (): Promise => { + ClustersClient.latch(node.cluster.clusterId, 'connectionRemoved'); + throw error; + }); + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(error); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(mockShowErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection was removed. Choose another connection.', + { modal: true }, + ); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }); + + it('honors Disconnect during the endpoint read', async (): Promise => { + const node = makeAnonymousNode(); + vi.mocked(node.getUnauthenticatedEndpoint).mockImplementation(async (): Promise => { + ClustersClient.latch(node.cluster.clusterId, 'userDisconnected'); + return 'mongodb://host/'; + }); + + try { + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + expectPreTerminalModal('The connection is unavailable.'); + } finally { + ClustersClient.unlatch(node.cluster.clusterId); + } + }); + + it('honors an epoch change during the endpoint read before opening a terminal', async (): Promise => { + const node = makeAnonymousNode(); + let epoch = 0; + vi.mocked(ClustersClient.getEpoch).mockImplementation(() => epoch); + vi.mocked(node.getUnauthenticatedEndpoint).mockImplementation(async (): Promise => { + epoch++; + return 'mongodb://host/'; + }); + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toMatchObject({ + reason: 'credentialsChanged', + }); + expectPreTerminalModal('The connection is unavailable.'); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(0); + }); + + it.each(['endpoint', 'sanitization', 'pty'] as const)( + 'shows one modal and rethrows the same safe %s failure', + async (phase): Promise => { + const node = makeAnonymousNode(); + const error = new Error('Safe startup failure'); + if (phase === 'endpoint') { + vi.mocked(node.getUnauthenticatedEndpoint).mockRejectedValueOnce(error); + } else if (phase === 'sanitization') { + vi.spyOn(unauthenticatedEndpoint, 'toUnauthenticatedConnectionString').mockImplementationOnce( + (): never => { + throw error; + }, + ); + } else { + vi.mocked(DocumentDBShellPty).mockImplementationOnce(function (): never { + throw error; + }); + } + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(error); + expectPreTerminalModal(error.message); + }, + ); + + it('keeps endpoint-read cancellation quiet and rethrows the same cancellation', async (): Promise => { + const node = makeAnonymousNode(); + const cancellation = new UserCancelledError(); + vi.mocked(node.getUnauthenticatedEndpoint).mockRejectedValueOnce(cancellation); + await expect(openUnauthenticatedShell(mockContext as never, node)).rejects.toBe(cancellation); + expect(mockShowErrorMessage).not.toHaveBeenCalled(); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(mockCreateTerminal).not.toHaveBeenCalled(); + expect(mockContext.errorHandling.suppressDisplay).toBeUndefined(); + expect(CredentialCache.hasCredentials).not.toHaveBeenCalled(); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + }); + }); + describe('when invoked from a database node', () => { it('should create terminal with correct name', async () => { await openInteractiveShell(mockContext as never, makeDatabaseNode() as never); diff --git a/src/commands/openInteractiveShell/openInteractiveShell.ts b/src/commands/openInteractiveShell/openInteractiveShell.ts index 7e367b0bc..48ccb16bc 100644 --- a/src/commands/openInteractiveShell/openInteractiveShell.ts +++ b/src/commands/openInteractiveShell/openInteractiveShell.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import * as vscode from 'vscode'; import { @@ -11,13 +11,22 @@ import { type DeepLinkOpenOptions, type DeepLinkOpenResult, } from '../../deepLinks/deepLinkTelemetry'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { + ConnectionUnavailableError, + isDiagnosticAuthenticationHold, +} from '../../documentdb/ConnectionUnavailableError'; import { CredentialCache } from '../../documentdb/CredentialCache'; +import { Views } from '../../documentdb/Views'; import { DocumentDBShellPty } from '../../documentdb/shell/DocumentDBShellPty'; import { type ShellConnectionInfo } from '../../documentdb/shell/ShellSessionManager'; import { registerShellTerminal } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import { toUnauthenticatedConnectionString } from '../../documentdb/shell/unauthenticatedEndpoint'; +import { type ConnectionClusterModel } from '../../tree/connections-view/models/ConnectionClusterModel'; import { type ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; import { type DatabaseItem } from '../../tree/documentdb/DatabaseItem'; +import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; /** * Parameters for opening an interactive shell with pre-formatted content. @@ -94,6 +103,98 @@ export async function openInteractiveShell( return { opened: true, shellSessionId: pty.shellSessionId }; } +export async function openUnauthenticatedShell(context: IActionContext, node?: ClusterItemBase): Promise { + if (!node) { + return; + } + const connectionInfo = extractConnectionInfo(node); + let pty: DocumentDBShellPty; + try { + const { clusterId } = node.cluster; + const assertAvailable = (): void => { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason && !isDiagnosticAuthenticationHold(reason)) { + throw new ConnectionUnavailableError(reason); + } + }; + assertAvailable(); + const epoch = ClustersClient.getEpoch(clusterId); + const endpoint = await node.getUnauthenticatedEndpoint(); + assertAvailable(); + if (epoch !== ClustersClient.getEpoch(clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (!endpoint) { + await vscode.window.showErrorMessage( + vscode.l10n.t( + 'Cannot open a shell without authentication for "{0}": its endpoint is not available.', + node.cluster.name, + ), + { modal: true }, + ); + return; + } + const connectionString = toUnauthenticatedConnectionString(endpoint); + pty = new DocumentDBShellPty({ + connectionInfo, + unauthenticated: { + connectionString, + emulatorConfiguration: (node.cluster as Partial).emulatorConfiguration, + reread: async (): Promise => { + const current = await node.getUnauthenticatedEndpoint(); + return current ? toUnauthenticatedConnectionString(current) : undefined; + }, + }, + }); + } catch (error) { + if (error instanceof UserCancelledError) { + throw error; + } + context.errorHandling.suppressDisplay = true; + if ( + error instanceof ConnectionUnavailableError && + (node.cluster.viewId === String(Views.ConnectionsView) || + node.cluster.viewId === String(Views.DiscoveryView) || + (node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue))) + ) { + const currentReason = ClustersClient.getLatchReason(node.cluster.clusterId); + refreshAuthenticationNode(node); + if ( + currentReason === 'connectionRemoved' || + currentReason === 'credentialsChanged' || + currentReason === 'identityChanged' + ) { + await vscode.window.showErrorMessage( + currentReason === 'connectionRemoved' + ? l10n.t('This connection was removed. Choose another connection.') + : l10n.t('This connection changed. Refresh the tree and try again.'), + { modal: true }, + ); + throw error; + } + } + await vscode.window.showErrorMessage(l10n.t('Unable to complete this tree action.'), { + modal: true, + detail: error instanceof Error ? error.message : String(error), + }); + throw error; + } + context.telemetry.properties.shellSessionId = pty.shellSessionId; + const terminal = vscode.window.createTerminal({ + name: l10n.t('DocumentDB: {0}/{1}', connectionInfo.clusterDisplayName, connectionInfo.databaseName), + pty, + iconPath: new vscode.ThemeIcon('terminal'), + }); + pty.setTerminal(terminal); + registerShellTerminal( + terminal, + () => pty.getTerminalInfo(), + () => pty.disconnect(), + ); + terminal.show(); +} + /** * Opens an interactive shell with explicit connection info and optional pre-filled input. * diff --git a/src/commands/playground/executePlaygroundCode.test.ts b/src/commands/playground/executePlaygroundCode.test.ts index 2a61da142..55527ccdc 100644 --- a/src/commands/playground/executePlaygroundCode.test.ts +++ b/src/commands/playground/executePlaygroundCode.test.ts @@ -4,23 +4,39 @@ *--------------------------------------------------------------------------------------------*/ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest'; import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CredentialCache } from '../../documentdb/CredentialCache'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { executePlaygroundCode, stopPlaygroundEvaluator } from './executePlaygroundCode'; -const { evaluate, dispose, setExecuting, showResult, getConnection, getEpoch, canRecover, recover, contexts } = - vi.hoisted(() => ({ - evaluate: vi.fn(), - dispose: vi.fn(), - setExecuting: vi.fn(), - showResult: vi.fn(), - getConnection: vi.fn<() => PlaygroundConnection | undefined>(), - getEpoch: vi.fn<() => number>(), - canRecover: vi.fn(), - recover: vi.fn(), - contexts: new Map(), - })); +const { + evaluate, + dispose, + setExecuting, + showResult, + getConnection, + getLatchReason, + getEpoch, + canRecover, + recover, + contexts, + createEvaluator, +} = vi.hoisted(() => ({ + evaluate: vi.fn(), + dispose: vi.fn(), + setExecuting: vi.fn(), + showResult: vi.fn(), + getConnection: vi.fn<() => PlaygroundConnection | undefined>(), + getLatchReason: vi.fn(), + getEpoch: vi.fn<() => number>(), + canRecover: vi.fn(), + recover: vi.fn(), + contexts: new Map(), + createEvaluator: vi.fn(), +})); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ UserCancelledError: typeof UserCancelledError }>()), @@ -30,12 +46,26 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ): Promise => { const context = { errorHandling: {}, telemetry: { measurements: {}, properties: {} } } as IActionContext; contexts.set(name, context); - return run(context); + const result = run(context); + // Fire-and-forget recovery uses the real telemetry wrapper's default error suppression. + return name === 'playground.signInAgain' ? result.catch((): undefined => undefined) : result; }, })); vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { getLatchReason: vi.fn(), getExistingClient: vi.fn(), getEpoch }, + ClustersClient: { + getLatchReason, + getExistingClient: vi.fn(), + getEpoch, + getLastVerifiedIdentity: vi.fn(), + clearLastVerifiedIdentity: vi.fn(), + getClient: vi.fn(), + startAfterSignIn: vi.fn(), + deleteClient: vi.fn(), + latch: vi.fn(), + unlatch: vi.fn(), + invalidate: vi.fn(), + }, })); vi.mock('../signInAgain/signInAgain', () => ({ @@ -45,6 +75,9 @@ vi.mock('../signInAgain/signInAgain', () => ({ vi.mock('../../documentdb/playground/PlaygroundEvaluator', () => ({ PlaygroundEvaluator: class { + constructor() { + createEvaluator(); + } evaluate = evaluate; dispose = dispose; sessionDomainProperties = { domainInfo_isAzure: 'true' }; @@ -74,6 +107,58 @@ describe('executePlaygroundCode', () => { canRecover.mockReturnValue(false); }); + it.each([ + ['userDisconnected', 'This connection is disconnected. Reconnect from the tree, then run the script again.'], + ['unreachable', 'The connection is unavailable. Check the server or network, then run the script again.'], + [ + 'credentialsRejected', + 'The saved credentials were rejected. Update them from the tree, then run the script again.', + ], + ['credentialsUpdating', 'This connection is being updated. Run the script again when the update finishes.'], + ['connectionRemoved', 'This connection was removed. Choose another connection for this playground.'], + [ + 'credentialsChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'identityChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + ['credentialsMissing', 'This connection is unavailable. Reconnect from the tree, then run the script again.'], + ['signInRequired', 'This connection is unavailable. Reconnect from the tree, then run the script again.'], + ] as const)('uses %s guidance for latch and worker failures', async (reason, message) => { + getLatchReason.mockReturnValueOnce(reason); + const showWarning = vi.spyOn(vscode.window, 'showWarningMessage'); + const progress = vi + .spyOn(vscode.window, 'withProgress') + .mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); + + try { + const uri = vscode.Uri.file('test.documentdb.js'); + await executePlaygroundCode('db.stats()', 'runAll', uri); + expect(showWarning).toHaveBeenCalledExactlyOnceWith(message); + expect(evaluate).not.toHaveBeenCalled(); + expect(setExecuting).not.toHaveBeenCalled(); + + showWarning.mockClear(); + const failure = new ConnectionUnavailableError(reason); + evaluate.mockRejectedValueOnce(failure); + + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + expect(showResult).toHaveBeenCalledExactlyOnceWith(expect.anything(), expect.stringContaining(message)); + expect(evaluate).toHaveBeenCalledOnce(); + expect(showWarning).not.toHaveBeenCalled(); + } finally { + progress.mockRestore(); + showWarning.mockRestore(); + stopPlaygroundEvaluator('cluster'); + } + }); + it('cancels a stopped worker without replacing the retained result or showing an error', async () => { let stopEvaluation: (error: Error) => void = () => {}; evaluate.mockImplementation( @@ -218,4 +303,222 @@ describe('executePlaygroundCode', () => { stopPlaygroundEvaluator('cluster'); } }); + + describe('stale sign-in notifications', () => { + const uri = vscode.Uri.file('test.documentdb.js'); + let connection: PlaygroundConnection; + let chooseAction: (choice: vscode.MessageItem | undefined) => void; + let warning: MockInstance; + let modal: MockInstance; + let openDocuments: vscode.TextDocument[]; + let connectionStateCalls: MockInstance[]; + + beforeEach(async (): Promise => { + connection = { + clusterId: 'cluster', + clusterDisplayName: 'Cluster', + databaseName: 'test', + entraIdentity: { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }, + }; + getConnection.mockReturnValue(connection); + getLatchReason.mockReturnValue(undefined); + canRecover.mockReturnValue(true); + openDocuments = vscode.workspace.textDocuments as vscode.TextDocument[]; + openDocuments.push({ uri: vscode.Uri.parse(uri.toString()) } as vscode.TextDocument); + warning = vi.spyOn(vscode.window, 'showWarningMessage').mockImplementationOnce( + () => + new Promise((resolve) => { + chooseAction = resolve; + }), + ); + modal = vi.spyOn(vscode.window, 'showErrorMessage'); + vi.spyOn(vscode.window, 'withProgress').mockImplementation((_options, task) => + Promise.resolve( + task({ report: vi.fn() }, { isCancellationRequested: false, onCancellationRequested: vi.fn() }), + ), + ); + const failure = Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }); + evaluate.mockRejectedValueOnce(failure); + await expect(executePlaygroundCode('db.stats()', 'runAll', uri)).rejects.toBe(failure); + connectionStateCalls = [ + vi.spyOn(CredentialCache, 'getCredentials'), + vi.spyOn(CredentialCache, 'setCredentials'), + vi.spyOn(CredentialCache, 'deleteCredentials'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'clearLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'getClient'), + vi.spyOn(ClustersClient, 'startAfterSignIn'), + vi.spyOn(ClustersClient, 'deleteClient'), + vi.spyOn(ClustersClient, 'latch'), + vi.spyOn(ClustersClient, 'unlatch'), + vi.spyOn(ClustersClient, 'invalidate'), + ]; + }); + + afterEach((): void => { + stopPlaygroundEvaluator('cluster'); + openDocuments.splice(0); + vi.restoreAllMocks(); + }); + + it.each([ + [ + 'before click', + 'connectionRemoved', + 'This connection was removed. Choose another connection for this playground.', + ], + [ + 'before click', + 'credentialsChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'before click', + 'identityChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'during sign-in', + 'connectionRemoved', + 'This connection was removed. Choose another connection for this playground.', + ], + [ + 'during sign-in', + 'credentialsChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + [ + 'during sign-in', + 'identityChanged', + 'This playground is bound to the previous connection. Re-pick its connection from the tree.', + ], + ] as const)('explains %s %s for the existing document only', async (stage, reason, message): Promise => { + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue(reason); + } else { + recover.mockImplementationOnce(async (): Promise => { + getLatchReason.mockReturnValue(reason); + return undefined; + }); + } + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(warning).toHaveBeenCalledTimes(2)); + + expect(warning).toHaveBeenNthCalledWith( + 1, + 'Microsoft sign-in expired for this playground. Sign in again to continue.', + 'Sign in again', + ); + expect(warning).toHaveBeenNthCalledWith(2, message); + expect(modal).not.toHaveBeenCalled(); + expect(recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(evaluate).toHaveBeenCalledOnce(); + expect(createEvaluator).toHaveBeenCalledOnce(); + expect(dispose).not.toHaveBeenCalled(); + expect(showResult).toHaveBeenCalledOnce(); + expect(getConnection()).toBe(connection); + expect(canRecover).toHaveBeenCalledTimes(2); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + }); + + it.each([ + ['before click', 'cancelled'], + ['before click', 'closed'], + ['before click', 'disposed'], + ['before click', 'epoch only'], + ['before click', 'unproven no latch'], + ['before click', 're-picked healthy'], + ['before click', 're-picked removed'], + ['before click', 're-picked changed'], + ['before click', 'already completed'], + ['during sign-in', 'cancelled'], + ['during sign-in', 'closed'], + ['during sign-in', 'disposed'], + ['during sign-in', 'epoch only'], + ['during sign-in', 'unproven no latch'], + ['during sign-in', 're-picked healthy'], + ['during sign-in', 're-picked removed'], + ['during sign-in', 're-picked changed'], + ['during sign-in', 'already completed'], + ] as const)( + 'keeps %s %s quiet without replacing the worker or result', + async (stage, outcome): Promise => { + const supersede = (): void => { + if (outcome === 'closed' || outcome === 'disposed') { + openDocuments.splice(0); + openDocuments.push({ uri: vscode.Uri.file('another.documentdb.js') } as vscode.TextDocument); + } + if (outcome === 'disposed') { + stopPlaygroundEvaluator('cluster'); + dispose.mockClear(); + } + if ( + outcome === 're-picked healthy' || + outcome === 're-picked removed' || + outcome === 're-picked changed' || + outcome === 'unproven no latch' + ) { + getConnection.mockReturnValue({ + ...connection, + clusterId: 'healthy-cluster', + entraIdentity: undefined, + }); + } + getEpoch.mockReturnValue(2); + getLatchReason.mockReturnValue( + outcome === 'closed' || + outcome === 'disposed' || + outcome === 'cancelled' || + outcome === 're-picked removed' + ? 'connectionRemoved' + : outcome === 're-picked changed' + ? 'credentialsChanged' + : undefined, + ); + }; + if (stage === 'before click') { + supersede(); + } else { + recover.mockImplementationOnce(async () => { + supersede(); + if (outcome === 'cancelled') { + throw new UserCancelledError('playground.signInAgain'); + } + return outcome === 'unproven no latch' + ? undefined + : { identity: connection.entraIdentity, epoch: 1 }; + }); + } + + chooseAction( + stage === 'before click' && outcome === 'cancelled' + ? undefined + : ('Sign in again' as unknown as vscode.MessageItem), + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(warning).toHaveBeenCalledOnce(); + expect(modal).not.toHaveBeenCalled(); + expect(recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(evaluate).toHaveBeenCalledOnce(); + expect(createEvaluator).toHaveBeenCalledOnce(); + expect(dispose).not.toHaveBeenCalled(); + expect(showResult).toHaveBeenCalledOnce(); + expect(canRecover).toHaveBeenCalledTimes(2); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + }, + ); + }); }); diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index 497cd58c8..d150879a9 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -359,8 +359,35 @@ function getPlaygroundRecovery(error: unknown, connection: PlaygroundConnection) ), }; } + if (error.reason === 'userDisconnected') { + return { + message: l10n.t('This connection is disconnected. Reconnect from the tree, then run the script again.'), + }; + } + if (error.reason === 'unreachable') { + return { + message: l10n.t('The connection is unavailable. Check the server or network, then run the script again.'), + }; + } + if (error.reason === 'credentialsRejected') { + return { + message: l10n.t( + 'The saved credentials were rejected. Update them from the tree, then run the script again.', + ), + }; + } + if (error.reason === 'credentialsUpdating') { + return { + message: l10n.t('This connection is being updated. Run the script again when the update finishes.'), + }; + } + if (error.reason === 'connectionRemoved') { + return { + message: l10n.t('This connection was removed. Choose another connection for this playground.'), + }; + } return { - message: l10n.t('This connection is unavailable. Reconnect from the tree, then re-pick it here.'), + message: l10n.t('This connection is unavailable. Reconnect from the tree, then run the script again.'), }; } @@ -388,6 +415,19 @@ function offerPlaygroundRecovery( const action = l10n.t('Sign in again'); void vscode.window.showWarningMessage(recovery.message, action).then(async (choice) => { if (choice !== action || ClustersClient.getEpoch(clusterId) !== epoch || !stillOwnsAction()) { + if ( + choice === action && + service.getConnection(documentUri) === connection && + vscode.workspace.textDocuments.some((d) => d.uri.toString() === documentUri.toString()) + ) { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason === 'connectionRemoved' || reason === 'credentialsChanged' || reason === 'identityChanged') { + const currentRecovery = getPlaygroundRecovery(new ConnectionUnavailableError(reason), connection); + if (currentRecovery) { + void vscode.window.showWarningMessage(currentRecovery.message); + } + } + } return; } await callWithTelemetryAndErrorHandling('playground.signInAgain', async (context) => { @@ -396,6 +436,25 @@ function offerPlaygroundRecovery( try { const result = await signInAgainForWorker(context, clusterId, identity); if (!result || ClustersClient.getEpoch(clusterId) !== result.epoch || !stillOwnsAction()) { + if ( + service.getConnection(documentUri) === connection && + vscode.workspace.textDocuments.some((d) => d.uri.toString() === documentUri.toString()) + ) { + const reason = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' + ) { + const currentRecovery = getPlaygroundRecovery( + new ConnectionUnavailableError(reason), + connection, + ); + if (currentRecovery) { + void vscode.window.showWarningMessage(currentRecovery.message); + } + } + } return; } stopPlaygroundEvaluator(clusterId); diff --git a/src/commands/retryAuthentication/retryAuthentication.test.ts b/src/commands/retryAuthentication/retryAuthentication.test.ts index 1eb8a91da..34219bf61 100644 --- a/src/commands/retryAuthentication/retryAuthentication.test.ts +++ b/src/commands/retryAuthentication/retryAuthentication.test.ts @@ -85,6 +85,8 @@ describe('retryAuthentication', () => { beforeEach(() => { vi.clearAllMocks(); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(0); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); vi.mocked(CredentialCache.getCredentials).mockReset(); }); @@ -404,7 +406,8 @@ describe('retryAuthentication', () => { await retryAuthentication(actionContext as never, node); expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); - expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(window.showErrorMessage).not.toHaveBeenCalled(); }); it('refreshes without closing a healthy client that replaced the one that failed', async (): Promise => { @@ -422,7 +425,7 @@ describe('retryAuthentication', () => { expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); }); - it('does not refresh an old Retry after the client was replaced while its close was pending', async (): Promise => { + it('refreshes an old Retry quietly after the client was replaced while its close was pending', async (): Promise => { const node = { id: 'connectionsView/stale', cluster: { clusterId: 'stale' }, @@ -435,7 +438,8 @@ describe('retryAuthentication', () => { await retryAuthentication(actionContext as never, node); expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stale'); - expect(ext.connectionsBranchDataProvider.refresh).not.toHaveBeenCalled(); + expect(ext.connectionsBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + expect(window.showErrorMessage).not.toHaveBeenCalled(); }); it.each([new UserCancelledError(), Object.assign(new Error('ARM rejected access'), { statusCode: 401 })])( @@ -454,4 +458,138 @@ describe('retryAuthentication', () => { expect(ext.discoveryBranchDataProvider.refresh).not.toHaveBeenCalled(); }, ); + + it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged', 'userDisconnected'] as const)( + 'refreshes a stale Retry for %s without clearing another latch or doing auth work', + async (reason): Promise => { + const node = ruNode(); + const context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: { suppressDisplay: false }, + }; + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + await retryAuthentication(context as never, node); + + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + if (reason === 'userDisconnected') { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } else { + 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.', + { modal: true }, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + } + expect(node.readReplacementKey).not.toHaveBeenCalled(); + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + }, + ); + + it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged', undefined] as const)( + 'discards a replacement key when %s supersedes the read', + async (reason): Promise => { + const node = ruNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + node.readReplacementKey.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + return { + connectionString: 'mongodb://test', + availableAuthMethods: [AuthMethodId.NativeAuth], + nativeAuthConfig: { connectionUser: 'test', connectionPassword: 'replacement' }, + }; + }); + + await retryAuthentication(actionContext as never, node); + + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + if (reason) { + 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.', + { modal: true }, + ); + } else { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.deleteCredentials).toHaveBeenCalledExactlyOnceWith('ru'); + expect(node.readReplacementKey).toHaveBeenCalledTimes(1); + }, + ); + + it.each([false, true])( + 'refreshes a superseded failed key read with cancellation kept quiet (%s)', + async (cancelled): Promise => { + const node = ruNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValueOnce('credentialsRejected'); + node.readReplacementKey.mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + throw cancelled ? new UserCancelledError() : new Error('obsolete ARM failure'); + }); + + await retryAuthentication(actionContext as never, node); + + expect(ext.discoveryBranchDataProvider.refresh).toHaveBeenCalledExactlyOnceWith(node); + if (cancelled) { + expect(window.showErrorMessage).not.toHaveBeenCalled(); + } else { + expect(window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection was removed. Choose another connection.', + { modal: true }, + ); + } + expect(ClustersClient.clearCredentialRejection).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).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, + }; + 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); + + 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(); + }, + ); }); diff --git a/src/commands/retryAuthentication/retryAuthentication.ts b/src/commands/retryAuthentication/retryAuthentication.ts index 13487c1b0..fce626367 100644 --- a/src/commands/retryAuthentication/retryAuthentication.ts +++ b/src/commands/retryAuthentication/retryAuthentication.ts @@ -79,10 +79,30 @@ export async function retryAuthentication(context: IActionContext, node: Retryab const clusterId = node.cluster?.clusterId; if (clusterId) { + const viewId = getViewId(node); + const supportsRefresh = + viewId === Views.ConnectionsView || + viewId === Views.DiscoveryView || + (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') { + 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 }, + ); + } return; } addEstablishedConnectionContext(context.telemetry, clusterId); @@ -108,6 +128,25 @@ 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 }, + ); + } return; } if (error instanceof UserCancelledError) { @@ -132,6 +171,20 @@ 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 }, + ); + } return; } // One fresh ARM read per explicit click. A subsequent database rejection re-latches in @@ -157,6 +210,20 @@ 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 }, + ); + } return; } } diff --git a/src/commands/showConnectionStats/showConnectionStats.test.ts b/src/commands/showConnectionStats/showConnectionStats.test.ts index fe1a2161f..9b6b32b90 100644 --- a/src/commands/showConnectionStats/showConnectionStats.test.ts +++ b/src/commands/showConnectionStats/showConnectionStats.test.ts @@ -26,7 +26,7 @@ it.each([ ['2026-11-24T19:02:03.000Z', '2026-11-24T19:02:03.000Z (in 25:02:03)'], ['2026-11-23T18:00:00.001Z', '2026-11-23T18:00:00.001Z (in 00:00:01)'], ['2026-11-23T18:00:00.000Z', '2026-11-23T18:00:00.000Z (expired)'], - [undefined, 'unknown'], + [undefined, '(not available)'], ])('prints the UTC expiry with remaining time or status for %s', (expiry, expected): void => { vi.useFakeTimers({ now: new Date('2026-11-23T18:00:00.000Z') }); vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce([ @@ -44,5 +44,67 @@ it.each([ showConnectionStats({} as IActionContext); - expect(ext.outputChannel.appendLog).toHaveBeenCalledWith(` lastEntraTokenExpiresAt=${expected}`); + expect(ext.outputChannel.appendLog).toHaveBeenCalledWith(` Last Entra token expires at: ${expected}`); +}); + +it('formats host records with units, availability, and lifecycle facts', (): void => { + vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce([ + { + client: { + generation: 4, + ageMs: 32000, + authMethod: AuthMethodId.NativeAuth, + startupId: undefined, + state: 'cached', + socketTrace: false, + }, + pending: { startupId: 'pending-startup', superseded: true }, + held: 'credentialsUpdating', + lastFailedStartupId: 'failed-startup', + }, + ]); + + showConnectionStats({} as IActionContext); + + const output = vi.mocked(ext.outputChannel.appendLog).mock.calls.map(([line]) => line); + expect(output).toEqual( + expect.arrayContaining([ + '[Connection Stats]', + ' Entries: 1', + ' Connection 1:', + ' Client state: cached', + ' Generation: 4', + ' Age (ms): 32000', + ' Startup ID: (not available)', + ' Socket trace: false', + ' Pending state: superseded', + ' Pending startup ID: pending-startup', + ' Held reason: credentialsUpdating', + ' Last failed startup ID: failed-startup', + ]), + ); +}); + +it('does not expose values outside the diagnostics fields', (): void => { + const snapshot = [ + { + client: { + generation: 1, + ageMs: 10, + authMethod: AuthMethodId.NativeAuth, + state: 'cached' as const, + socketTrace: true, + connectionString: 'mongodb://user:password@example.test/', + accessToken: 'secret-access-token', + }, + }, + ]; + vi.mocked(ClustersClient.getDiagnosticsSnapshot).mockReturnValueOnce(snapshot); + + showConnectionStats({} as IActionContext); + + const output = JSON.stringify(vi.mocked(ext.outputChannel.appendLog).mock.calls); + expect(output).not.toContain('password'); + expect(output).not.toContain('secret-access-token'); + expect(output).not.toContain('mongodb://'); }); diff --git a/src/commands/showConnectionStats/showConnectionStats.ts b/src/commands/showConnectionStats/showConnectionStats.ts index 2685115f3..0a2555622 100644 --- a/src/commands/showConnectionStats/showConnectionStats.ts +++ b/src/commands/showConnectionStats/showConnectionStats.ts @@ -10,7 +10,7 @@ import { ext } from '../../extensionVariables'; function formatEntraExpiry(expiresAt: string | undefined, now: number): string { if (expiresAt === undefined) { - return 'unknown'; + return '(not available)'; } const remainingMs = Date.parse(expiresAt) - now; @@ -28,32 +28,36 @@ function formatEntraExpiry(expiresAt: string | undefined, now: number): string { export function showConnectionStats(_context: IActionContext): void { const snapshot = ClustersClient.getDiagnosticsSnapshot(); const now = Date.now(); - ext.outputChannel.appendLog(`[Connection Stats] Extension-host cache entries: ${String(snapshot.length)}`); + ext.outputChannel.appendLog('[Connection Stats]'); + ext.outputChannel.appendLog(` Entries: ${String(snapshot.length)}`); + ext.outputChannel.appendLog(' Source: Extension host'); ext.outputChannel.appendLog( - 'Each cached client can own multiple sockets. Socket counts are not tracked here. For Shell and Playground, use Show Worker Stats.', + ' Socket counts: (not available); each cached client can own multiple sockets. For Shell and Playground, use Show Worker Stats.', ); for (const [index, { client, pending, held, lastFailedStartupId }] of snapshot.entries()) { ext.outputChannel.appendLog(` Connection ${String(index + 1)}:`); - ext.outputChannel.appendLog( - client - ? ` Client: ${client.state} generation=${String(client.generation)} ageMs=${String(client.ageMs)} auth=${client.authMethod ?? 'unknown'} startup=${client.startupId ?? 'none'} socketTrace=${String(client.socketTrace)}` - : ' Client: none', - ); + ext.outputChannel.appendLog(` Client state: ${client?.state ?? '(not available)'}`); + if (client) { + ext.outputChannel.appendLog(` Generation: ${String(client.generation)}`); + ext.outputChannel.appendLog(` Age (ms): ${String(client.ageMs)}`); + ext.outputChannel.appendLog(` Auth method: ${client.authMethod ?? '(not available)'}`); + ext.outputChannel.appendLog(` Startup ID: ${client.startupId ?? '(not available)'}`); + ext.outputChannel.appendLog(` Socket trace: ${String(client.socketTrace)}`); + } if (client?.authMethod === AuthMethodId.MicrosoftEntraID) { ext.outputChannel.appendLog( - ` lastEntraTokenExpiresAt=${formatEntraExpiry(client.lastEntraTokenExpiresAt, now)}`, + ` Last Entra token expires at: ${formatEntraExpiry(client.lastEntraTokenExpiresAt, now)}`, ); } if (pending) { - ext.outputChannel.appendLog( - ` Pending: ${pending.superseded ? 'superseded' : 'current'} startup=${pending.startupId}`, - ); + ext.outputChannel.appendLog(` Pending state: ${pending.superseded ? 'superseded' : 'current'}`); + ext.outputChannel.appendLog(` Pending startup ID: ${pending.startupId}`); } if (held) { - ext.outputChannel.appendLog(` Held: ${held}`); + ext.outputChannel.appendLog(` Held reason: ${held}`); } if (lastFailedStartupId) { - ext.outputChannel.appendLog(` Last failed startup: ${lastFailedStartupId}`); + ext.outputChannel.appendLog(` Last failed startup ID: ${lastFailedStartupId}`); } } ext.outputChannel.show(); diff --git a/src/commands/showWorkerStats/showWorkerStats.test.ts b/src/commands/showWorkerStats/showWorkerStats.test.ts new file mode 100644 index 000000000..e18f57e55 --- /dev/null +++ b/src/commands/showWorkerStats/showWorkerStats.test.ts @@ -0,0 +1,127 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { beforeEach, expect, it, vi } from 'vitest'; +import { PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; +import { ext } from '../../extensionVariables'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; +import { showWorkerStats } from './showWorkerStats'; + +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals: vi.fn(), +})); + +vi.mock('../playground/executePlaygroundCode', () => ({ + getPlaygroundEvaluators: vi.fn(), +})); + +vi.mock('../../documentdb/playground/WorkerSessionManager', () => ({ + WorkerSessionManager: vi.fn().mockImplementation(function () { + return { + get workerState(): string { + return 'idle'; + }, + get isAlive(): boolean { + return false; + }, + get workerClusterId(): string | undefined { + return undefined; + }, + }; + }), +})); + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { appendLog: vi.fn(), show: vi.fn() } }, +})); + +beforeEach(() => { + vi.mocked(getRegisteredShellTerminals).mockReset(); + vi.mocked(getPlaygroundEvaluators).mockReset(); + vi.mocked(ext.outputChannel.appendLog).mockReset(); + vi.mocked(ext.outputChannel.show).mockReset(); + vi.mocked(getRegisteredShellTerminals).mockReturnValue([]); + vi.mocked(getPlaygroundEvaluators).mockReturnValue(new Map()); +}); + +it('prints explicit zero counts and shared record headings', (): void => { + showWorkerStats({} as IActionContext); + + const output = vi.mocked(ext.outputChannel.appendLog).mock.calls.map(([line]) => line); + expect(output).toEqual(['[Worker Stats]', ' Shell sessions: 0', ' Playground sessions: 0']); +}); + +it('distinguishes shell and playground worker state from missing session values', (): void => { + vi.mocked(getRegisteredShellTerminals).mockReturnValueOnce([ + { + terminal: { name: 'DocumentDB Shell' } as ReturnType< + typeof getRegisteredShellTerminals + >[number]['terminal'], + info: { + clusterId: 'shell-cluster', + clusterDisplayName: 'Shell Cluster', + activeDatabase: 'test', + isInitialized: false, + isEvaluating: false, + workerState: 'spawning', + authMethod: undefined, + username: undefined, + }, + }, + ]); + const evaluator = new PlaygroundEvaluator(); + vi.spyOn(evaluator, 'workerState', 'get').mockReturnValue('idle'); + vi.spyOn(evaluator, 'isAlive', 'get').mockReturnValue(false); + vi.mocked(getPlaygroundEvaluators).mockReturnValueOnce(new Map([['playground-cluster', evaluator]])); + + showWorkerStats({} as IActionContext); + + const output = vi.mocked(ext.outputChannel.appendLog).mock.calls.map(([line]) => line); + expect(output).toEqual( + expect.arrayContaining([ + ' Shell sessions: 1', + ' Playground sessions: 1', + ' Shell 1:', + ' Initialized: false', + ' Worker state: spawning', + ' Auth method: (not available)', + ' Username: (not available)', + ' Playground 1:', + ' Worker alive: false', + ' Worker state: idle', + ' Session ID: (not available)', + ' Last init duration (ms): 0', + ]), + ); +}); + +it('does not print identifying or credential values that are not worker fields', (): void => { + const shell = { + terminal: { name: 'Safe terminal' } as ReturnType[number]['terminal'], + info: { + clusterId: 'visible-cluster-id', + clusterDisplayName: 'Visible Cluster', + activeDatabase: 'test', + isInitialized: true, + isEvaluating: false, + workerState: 'ready' as const, + authMethod: 'NativeAuth' as const, + username: 'existing-username', + connectionString: 'mongodb://user:password@example.test/', + accessToken: 'secret-access-token', + }, + }; + vi.mocked(getRegisteredShellTerminals).mockReturnValueOnce([shell]); + + showWorkerStats({} as IActionContext); + + const output = JSON.stringify(vi.mocked(ext.outputChannel.appendLog).mock.calls); + expect(output).toContain('Username: existing-username'); + expect(output).not.toContain('password'); + expect(output).not.toContain('secret-access-token'); + expect(output).not.toContain('mongodb://'); +}); diff --git a/src/commands/showWorkerStats/showWorkerStats.ts b/src/commands/showWorkerStats/showWorkerStats.ts index e8954d123..850137de8 100644 --- a/src/commands/showWorkerStats/showWorkerStats.ts +++ b/src/commands/showWorkerStats/showWorkerStats.ts @@ -14,53 +14,36 @@ import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; */ export function showWorkerStats(_context: IActionContext): void { const log = (msg: string): void => ext.outputChannel.appendLog(msg); - - log('──────────────────────────────────────'); - log('[Worker Task Manager] Worker Stats'); - log('──────────────────────────────────────'); - - // ── Playground Workers ─────────────────────────────────────────────── - log(''); - log(' Playground Workers:'); - const evaluators = getPlaygroundEvaluators(); - if (evaluators.size === 0) { - log(' (no playground workers — no playground run yet)'); - } else { - log(` Active workers: ${String(evaluators.size)}`); - for (const [clusterId, evaluator] of evaluators) { - log(` ─ Cluster: ${clusterId}`); - log(` Status: ${evaluator.isAlive ? 'alive' : 'not running'}`); - log(` Worker state: ${evaluator.workerState}`); - log(` Session ID: ${evaluator.sessionId ?? '(none)'}`); - log(` Eval count (session): ${String(evaluator.sessionEvalCount)}`); - log(` Auth method: ${evaluator.sessionAuthMethod ?? '(none)'}`); - log(` Last init duration: ${String(evaluator.lastInitDurationMs)}ms`); - } - } - // ── Interactive Shell Workers ──────────────────────────────────────── - log(''); - log(' Interactive Shell Workers:'); - const shellTerminals = getRegisteredShellTerminals(); - if (shellTerminals.length === 0) { - log(' (no active shell sessions)'); - } else { - log(` Active sessions: ${String(shellTerminals.length)}`); - for (const { terminal, info } of shellTerminals) { - log(` ─ Terminal: "${terminal.name}"`); - log(` Cluster: ${info.clusterDisplayName} (${info.clusterId})`); - log(` Database: ${info.activeDatabase}`); - log(` Initialized: ${String(info.isInitialized)}`); - log(` Worker state: ${info.workerState}`); - log(` Evaluating: ${String(info.isEvaluating)}`); - log(` Auth method: ${info.authMethod ?? '(not yet initialized)'}`); - log(` Username: ${info.username ?? '(n/a)'}`); - } + + log('[Worker Stats]'); + log(` Shell sessions: ${String(shellTerminals.length)}`); + log(` Playground sessions: ${String(evaluators.size)}`); + + for (const [index, { terminal, info }] of shellTerminals.entries()) { + log(` Shell ${String(index + 1)}:`); + log(` Terminal: ${terminal.name}`); + log(` Cluster: ${info.clusterDisplayName}`); + log(` Cluster ID: ${info.clusterId}`); + log(` Database: ${info.activeDatabase || '(not available)'}`); + log(` Worker state: ${info.workerState}`); + log(` Initialized: ${String(info.isInitialized)}`); + log(` Evaluating: ${String(info.isEvaluating)}`); + log(` Auth method: ${info.authMethod ?? '(not available)'}`); + log(` Username: ${info.username ?? '(not available)'}`); } - log(''); - log('──────────────────────────────────────'); + for (const [index, [clusterId, evaluator]] of Array.from(evaluators).entries()) { + log(` Playground ${String(index + 1)}:`); + log(` Cluster ID: ${clusterId}`); + log(` Worker alive: ${String(evaluator.isAlive)}`); + log(` Worker state: ${evaluator.workerState}`); + log(` Session ID: ${evaluator.sessionId ?? '(not available)'}`); + log(` Eval count (session): ${String(evaluator.sessionEvalCount)}`); + log(` Auth method: ${evaluator.sessionAuthMethod ?? '(not available)'}`); + log(` Last init duration (ms): ${String(evaluator.lastInitDurationMs)}`); + } ext.outputChannel.show(); } diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index b6bffabc0..d5c465bcd 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -16,6 +16,9 @@ import { getEntraSession } from '../../documentdb/auth/entraSession'; import { ClustersClient } from '../../documentdb/ClustersClient'; 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 { signInAgain, signInAgainForWorker } from './signInAgain'; const pin = { @@ -67,6 +70,9 @@ function actionContext(): IActionContext { describe('signInAgain', () => { beforeEach(() => { vi.clearAllMocks(); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + vi.mocked(ClustersClient.getLastVerifiedIdentity).mockReturnValue(pin); mocks.configureAuth.mockImplementation( async (_timings: undefined, _trace: undefined, acquire: typeof getEntraSession): Promise => { const session = await acquire({ @@ -158,10 +164,7 @@ describe('signInAgain', () => { }); await signInAgain(actionContext(), { clusterId }); expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); - expect(vscode.window.showErrorMessage).toHaveBeenCalledWith( - 'The connection was closed while you were signing in.', - { modal: true }, - ); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); }); @@ -205,4 +208,233 @@ describe('signInAgain', () => { expect(getEntraSession).not.toHaveBeenCalled(); expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); }); + + function treeNode(viewId: Views = Views.ConnectionsView): ClusterItemBase { + return { + id: `${viewId}/folder/cluster`, + contextValue: `${viewId};treeItem_documentdbcluster`, + cluster: { clusterId, treeId: `${viewId}/folder/cluster`, viewId, name: 'test' }, + } 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([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(); + }, + ); + }, + ); + + it('preserves a noncancellation session acquisition error', async (): Promise => { + const error = new Error('Session acquisition failed'); + vi.mocked(getEntraSession).mockRejectedValueOnce(error); + + await expect(signInAgain(actionContext(), treeNode())).rejects.toBe(error); + + expect(showClusterConnectFailure).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ error })); + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + 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); + + 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(); + }, + ); + + 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; + }); + + 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(); + }, + ); + + it('refreshes an epoch-only stale tree sign-in quietly', async (): Promise => { + const node = treeNode(); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); + + it('refreshes an already disconnected tree sign-in quietly', async (): Promise => { + const node = treeNode(); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('userDisconnected'); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(getEntraSession).not.toHaveBeenCalled(); + }); + + it('does not refresh or show a stale modal for an unsupported Workspace node', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + + await signInAgain(actionContext(), treeNode(Views.AzureWorkspaceView)); + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(getEntraSession).not.toHaveBeenCalled(); + }); + + it.each([ + [Views.DiscoveryView, 'discoveryView;treeItem_documentdbcluster'], + [Views.AzureResourcesView, 'azureResourcesView;ruBranch;treeItem_documentdbcluster'], + [Views.AzureResourcesView, 'azureResourcesView;documentDbBranch;treeItem_documentdbcluster'], + ] as const)( + 'refreshes eligible stale nodes using their existing %s routing tags (%s)', + async (viewId, contextValue): Promise => { + const node = Object.assign(treeNode(viewId), { contextValue }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + + await signInAgain(actionContext(), node); + + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(refreshAuthenticationNode).toHaveBeenCalledBefore(vi.mocked(vscode.window.showErrorMessage)); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection was removed. Choose another connection.', + { modal: true }, + ); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }, + ); + + it('propagates an unexpected stale refresh failure without a second refresh or modal', async (): Promise => { + const error = new Error('refresh failed'); + vi.mocked(refreshAuthenticationNode).mockImplementationOnce(() => { + throw error; + }); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + + await expect(signInAgain(actionContext(), treeNode())).rejects.toBe(error); + + expect(refreshAuthenticationNode).toHaveBeenCalledTimes(1); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); + + it.each(['connectionRemoved', 'credentialsChanged', 'identityChanged', 'userDisconnected'] as const)( + 'keeps stale worker recovery quiet for %s', + async (reason): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).resolves.toBeUndefined(); + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(getEntraSession).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }, + ); + + it('keeps an obsolete pending worker sign-in quiet without restarting', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(getEntraSession).mockImplementationOnce(async () => { + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('connectionRemoved'); + return { account: { id: pin.accountId, label: pin.accountLabel } } as vscode.AuthenticationSession; + }); + + await expect(signInAgainForWorker(actionContext(), clusterId, pin)).resolves.toBeUndefined(); + + expect(refreshAuthenticationNode).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(showClusterConnectFailure).not.toHaveBeenCalled(); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + }); }); diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index aa5c6b6d5..db777d794 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -19,6 +19,7 @@ import { addEstablishedConnectionContext, ClustersClient } from '../../documentd import { classifyConnectionFailure } from '../../documentdb/connectionFailures'; 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'; @@ -85,7 +86,47 @@ async function signInAgainInternal( } const epoch = ClustersClient.getEpoch(clusterId); const reason = ClustersClient.getLatchReason(clusterId); + let closedReported = false; + const reportClosed = (): void => { + if (expectedIdentity || closedReported) { + return; + } + closedReported = true; + if (node) { + if ( + node.cluster.viewId !== String(Views.ConnectionsView) && + node.cluster.viewId !== String(Views.DiscoveryView) && + !( + node.cluster.viewId === String(Views.AzureResourcesView) && + /\bruBranch\b|\bdocumentDbBranch\b/i.test(node.contextValue) + ) + ) { + return; + } + 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, + }); + } + }; if (reason && reason !== 'credentialsRejected') { + reportClosed(); return; } const storedIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); @@ -112,16 +153,9 @@ async function signInAgainInternal( const currentIdentity = ClustersClient.getLastVerifiedIdentity(clusterId); return currentIdentity?.kind === 'entra' && sameEntraIdentity(currentIdentity, expectedIdentity); }; - const reportClosed = (): void => { - if (!expectedIdentity) { - void vscode.window.showErrorMessage(vscode.l10n.t('The connection was closed while you were signing in.'), { - modal: true, - }); - } - }; - let starting = false; let establishedClient: ClustersClient | undefined; + let dismissal: unknown; try { const handler = new MicrosoftEntraIDAuthHandler(credentials, { interactive: false, @@ -133,8 +167,20 @@ async function signInAgainInternal( if (!isCurrent()) { throw new UserCancelledError('signInAgain'); } - const session = await getEntraSession(request); - if (!session || !isCurrent()) { + let session: vscode.AuthenticationSession | undefined; + try { + session = await getEntraSession(request); + } catch (error) { + if (isSignInDismissal(error)) { + dismissal = error; + } + throw error; + } + if (!session) { + dismissal = new UserCancelledError('signInAgain'); + throw dismissal; + } + if (!isCurrent()) { throw new UserCancelledError('signInAgain'); } if (session.account.id !== identity.accountId) { @@ -180,6 +226,12 @@ async function signInAgainInternal( } return auth.verifiedIdentity ? { identity: auth.verifiedIdentity, epoch: startupEpoch } : undefined; } catch (error) { + if (dismissal !== undefined && error === dismissal) { + throw new UserCancelledError('signInAgain'); + } + if (closedReported) { + throw error; + } if (!starting && !isCurrent()) { reportClosed(); return undefined; diff --git a/src/documentdb/ClustersExtension.ts b/src/documentdb/ClustersExtension.ts index a5b81c0ef..45a3dcd58 100644 --- a/src/documentdb/ClustersExtension.ts +++ b/src/documentdb/ClustersExtension.ts @@ -68,6 +68,7 @@ import { openIndexManagementView } from '../commands/openIndexManagementView/ope import { openInteractiveShell, openInteractiveShellWithInput, + openUnauthenticatedShell, } from '../commands/openInteractiveShell/openInteractiveShell'; import { pasteCollection } from '../commands/pasteCollection/pasteCollection'; import { pasteIndexes } from '../commands/pasteIndexes/pasteIndexes'; @@ -1020,6 +1021,10 @@ export class ClustersExtension implements vscode.Disposable { 'vscode-documentdb.command.internal.connectDisconnected', withTreeNodeCommandCorrelation(connectDisconnected), ); + registerCommandWithTreeNodeUnwrapping( + 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', + withTreeNodeCommandCorrelation(openUnauthenticatedShell), + ); registerCommandWithTreeNodeUnwrapping( 'vscode-documentdb.command.signInAgain', withTreeNodeCommandCorrelation(signInAgain), diff --git a/src/documentdb/ConnectionUnavailableError.ts b/src/documentdb/ConnectionUnavailableError.ts index dd8404caf..45c9fd6f3 100644 --- a/src/documentdb/ConnectionUnavailableError.ts +++ b/src/documentdb/ConnectionUnavailableError.ts @@ -16,6 +16,10 @@ export type ConnectionUnavailableReason = | 'connectionRemoved' | 'unreachable'; +export function isDiagnosticAuthenticationHold(reason: ConnectionUnavailableReason | undefined): boolean { + return reason === 'credentialsRejected' || reason === 'signInRequired' || reason === 'credentialsMissing'; +} + export class ConnectionUnavailableError extends Error { constructor( readonly reason: ConnectionUnavailableReason, diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts index 1c1ecab89..03bc04070 100644 --- a/src/documentdb/connectionTeardown.test.ts +++ b/src/documentdb/connectionTeardown.test.ts @@ -185,7 +185,7 @@ describe('connection teardown', () => { 'Disconnect?', expect.objectContaining({ modal: true }), 'Close all', - 'Keep open (disabled)', + 'Keep open', ); expect(draft.dispose).not.toHaveBeenCalled(); expect(draft.disable).not.toHaveBeenCalled(); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts index a0e280eef..b52147385 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -75,7 +75,7 @@ export async function confirmTeardown( setting !== 'keepOpenDisabled' && ids.some((id) => getConnectionSurfaces(id).length) ) { - const keepOpen = vscode.l10n.t('Keep open (disabled)'); + const keepOpen = vscode.l10n.t('Keep open'); const selected = await vscode.window.showWarningMessage( intent === 'connectionRemoved' ? vscode.l10n.t('Remove the connection?') : vscode.l10n.t('Disconnect?'), { modal: true, detail: vscode.l10n.t('What should happen to the open tabs for this connection?') }, diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index f4d8cffbe..cdfdfdf30 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -26,6 +26,7 @@ import * as managedIdentityProvider from '../auth/managedIdentityTokenProvider'; import { EntraDestinationRejectedError } from '../auth/oidcAllowedHosts'; import { WorkerTokenRelay } from '../auth/WorkerTokenRelay'; import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; import { ShellSessionManager } from '../shell/ShellSessionManager'; import { @@ -754,6 +755,171 @@ describe('WorkerSessionManager', () => { expect(metadata).toMatchObject({ host: 'cluster.mongocluster.cosmos.azure.us', additionalHostCount: 0 }); session.dispose(); }); + + describe('diagnostic Shell startup', (): void => { + const clusterId = 'diagnostic-cluster'; + const authenticationHolds = ['credentialsRejected', 'signInRequired', 'credentialsMissing'] as const; + const blockingReasons = [ + 'credentialsUpdating', + 'credentialsChanged', + 'identityChanged', + 'userDisconnected', + 'connectionRemoved', + 'unreachable', + ] as const; + let session: ShellSessionManager; + let isolationSpies: MockInstance[]; + const reread = vi.fn<() => Promise>(); + + beforeEach((): void => { + reread.mockReset().mockResolvedValue(originalUri); + session = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'testdb' }, + undefined, + {}, + { connectionString: originalUri, reread }, + ); + isolationSpies = [ + vi.spyOn(ClustersClient, 'getExpectedFingerprint'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'getClient'), + vi.spyOn(ClustersClient, 'deleteClient'), + vi.spyOn(WorkerTokenRelay.prototype, 'relay'), + vi.spyOn(entraSession, 'getEntraSession'), + vi.spyOn(managedIdentityProvider, 'getManagedIdentityAccessToken'), + vi.spyOn(ClustersClient, 'unlatch'), + ]; + }); + + afterEach((): void => { + try { + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.getConnectionStringWithPassword).not.toHaveBeenCalled(); + expect(CredentialCache.getConnectionUser).not.toHaveBeenCalled(); + for (const spy of isolationSpies) { + expect(spy).not.toHaveBeenCalled(); + } + } finally { + session.dispose(); + for (const spy of isolationSpies) { + spy.mockRestore(); + } + ClustersClient.unlatch(clusterId); + } + }); + + it.each(authenticationHolds)( + 'spawns the real worker under %s without authentication or clearing the hold', + async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + const initializing = session.initialize(); + await vi.waitFor(() => expect(Worker).toHaveBeenCalledOnce()); + const posted = replyInit(); + await expect(initializing).resolves.toMatchObject({ + authMechanism: 'NoAuth', + username: undefined, + }); + expect(posted).toEqual({ + type: 'init', + requestId: expect.any(String), + connectionString: originalUri, + databaseName: 'testdb', + authMechanism: 'NoAuth', + persistent: true, + clientOptions: { + serverSelectionTimeoutMS: undefined, + tlsAllowInvalidCertificates: undefined, + appName: undefined, + tls: undefined, + }, + oidcDestinationPolicy: undefined, + }); + workerMock()._emit('message', { type: 'tokenRequest', requestId: 'unexpected-token' }); + await Promise.resolve(); + expect(workerMock().postMessage).toHaveBeenCalledOnce(); + expect(session.pinnedEntraIdentity).toBeUndefined(); + expect(session.isInitialized).toBe(true); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }, + ); + + it.each(authenticationHolds)( + 'keeps ordinary NoAuth worker startup strict under %s', + async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + const manager = new WorkerSessionManager(callbacks); + try { + await expect(manager.ensureWorker(clusterId, initMessage())).rejects.toMatchObject({ reason }); + expect(prepareDriverConnectionString).not.toHaveBeenCalled(); + expect(Worker).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + } finally { + manager.dispose(); + } + }, + ); + + it.each(blockingReasons)('blocks %s before diagnostic startup', async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + await expect(session.initialize()).rejects.toMatchObject({ reason }); + expect(reread).not.toHaveBeenCalled(); + expect(prepareDriverConnectionString).not.toHaveBeenCalled(); + expect(Worker).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }); + + it.each(blockingReasons)( + 'blocks %s introduced during diagnostic worker preparation', + async (reason): Promise => { + ClustersClient.latch(clusterId, 'credentialsRejected'); + const pending = deferred(); + vi.mocked(prepareDriverConnectionString).mockReturnValueOnce(pending.promise); + const initializing = session.initialize(); + await vi.waitFor(() => expect(prepareDriverConnectionString).toHaveBeenCalledOnce()); + ClustersClient.latch(clusterId, reason); + pending.resolve({ connectionString: originalUri, options: {}, srvResolution: 'notSrv' }); + await expect(initializing).rejects.toBeInstanceOf(ConnectionUnavailableError); + await expect(initializing).rejects.toMatchObject({ reason }); + expect(Worker).not.toHaveBeenCalled(); + expect(session.isInitialized).toBe(false); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }, + ); + + it.each(['abort', 'epoch'] as const)( + 'preserves the %s guard during diagnostic worker preparation', + async (guard): Promise => { + ClustersClient.latch(clusterId, 'credentialsRejected'); + const pending = deferred(); + vi.mocked(prepareDriverConnectionString).mockReturnValueOnce(pending.promise); + const initializing = session.initialize(); + await vi.waitFor(() => expect(prepareDriverConnectionString).toHaveBeenCalledOnce()); + if (guard === 'abort') { + session.killWorker(); + expect(vi.mocked(prepareDriverConnectionString).mock.calls[0][0].abortSignal?.aborted).toBe( + true, + ); + } else { + ClustersClient.invalidate(clusterId); + } + pending.resolve({ connectionString: originalUri, options: {}, srvResolution: 'notSrv' }); + await expect(initializing).rejects.toBeInstanceOf(UserCancelledError); + expect(Worker).not.toHaveBeenCalled(); + expect(session.isInitialized).toBe(false); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + }, + ); + + it('preserves the original preparation failure through diagnostic startup', async (): Promise => { + ClustersClient.latch(clusterId, 'credentialsRejected'); + const failure = new Error('DNS preparation failed'); + vi.mocked(prepareDriverConnectionString).mockRejectedValueOnce(failure); + await expect(session.initialize()).rejects.toBe(failure); + expect(prepareDriverConnectionString).toHaveBeenCalledOnce(); + expect(Worker).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + }); + }); }); describe('worker token relay environment binding', () => { diff --git a/src/documentdb/playground/WorkerSessionManager.ts b/src/documentdb/playground/WorkerSessionManager.ts index eff101c29..e65c3180d 100644 --- a/src/documentdb/playground/WorkerSessionManager.ts +++ b/src/documentdb/playground/WorkerSessionManager.ts @@ -27,7 +27,7 @@ import { import { createOidcDestinationPolicy } from '../auth/oidcClientOptions'; import { createWorkerAuthError } from '../auth/WorkerTokenRelay'; import { ClustersClient } from '../ClustersClient'; -import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; +import { ConnectionUnavailableError, isDiagnosticAuthenticationHold } from '../ConnectionUnavailableError'; import { SettingsHintError } from '../shell/SettingsHintError'; import { prepareDriverConnectionString } from '../srv/prepareDriverConnectionString'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; @@ -192,6 +192,7 @@ export class WorkerSessionManager implements vscode.Disposable { initMsg: MainToWorkerMessage & { type: 'init' }, initTimeoutMs: number = 30000, telemetryContext: WorkerStartupTelemetryContext = {}, + allowDiagnosticAuthenticationHold: boolean = false, ): Promise { // If worker is alive but connected to a different cluster, shut it down if (this._worker && (this._workerClusterId !== clusterId || this._authFailure || this._shuttingDownWorker)) { @@ -200,7 +201,13 @@ export class WorkerSessionManager implements vscode.Disposable { // Callers must not overlap ensureWorker calls because SRV preparation runs before _worker is set. if (!this._worker || this._workerState === 'idle') { - await this.spawnWorker(clusterId, initMsg, initTimeoutMs, telemetryContext); + await this.spawnWorker( + clusterId, + initMsg, + initTimeoutMs, + telemetryContext, + allowDiagnosticAuthenticationHold, + ); } } @@ -269,6 +276,7 @@ export class WorkerSessionManager implements vscode.Disposable { initMsg: MainToWorkerMessage & { type: 'init' }, initTimeoutMs: number, telemetryContext: WorkerStartupTelemetryContext, + allowDiagnosticAuthenticationHold: boolean, ): Promise { let originalFailure: { error: unknown } | undefined; const controller = new AbortController(); @@ -310,6 +318,7 @@ export class WorkerSessionManager implements vscode.Disposable { startup, controller.signal, telemetryContext, + allowDiagnosticAuthenticationHold, ); } catch (error) { if (this._startupAbortController === controller) { @@ -345,12 +354,13 @@ export class WorkerSessionManager implements vscode.Disposable { startup: WorkerStartup, abortSignal: AbortSignal, telemetryContext: WorkerStartupTelemetryContext, + allowDiagnosticAuthenticationHold: boolean, ): Promise { this._workerState = 'spawning'; const epoch = ClustersClient.getEpoch(clusterId); const assertAvailable = (): void => { const reason = ClustersClient.getLatchReason(clusterId); - if (reason) { + if (reason && !(allowDiagnosticAuthenticationHold && isDiagnosticAuthenticationHold(reason))) { throw new ConnectionUnavailableError(reason); } if (epoch !== ClustersClient.getEpoch(clusterId) || abortSignal.aborted) { diff --git a/src/documentdb/shell/DocumentDBShellPty.test.ts b/src/documentdb/shell/DocumentDBShellPty.test.ts index 1e88343ac..a6d58338c 100644 --- a/src/documentdb/shell/DocumentDBShellPty.test.ts +++ b/src/documentdb/shell/DocumentDBShellPty.test.ts @@ -8,12 +8,21 @@ import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockIn import { type UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; +import { ErrorExplanationService } from '../../services/errorExplanationService'; import { accumulateTelemetry } from '../../utils/accumulatingTelemetry'; import { AuthMethodId } from '../auth/AuthMethod'; import { ClustersClient } from '../ClustersClient'; +import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; +import { SchemaStore } from '../SchemaStore'; import { DocumentDBShellPty, type DocumentDBShellPtyOptions } from './DocumentDBShellPty'; import { ShellCompletionProvider } from './ShellCompletionProvider'; +import { + ShellSessionManager, + type ShellConnectionInfo, + type ShellSessionCallbacks, + type UnauthenticatedShellEndpoint, +} from './ShellSessionManager'; import { ShellSpinner } from './ShellSpinner'; const mockSessionTelemetry: Record[] = []; @@ -107,7 +116,12 @@ const mockSetActiveDatabase = vi.fn(); const mockResetAfterSignIn = vi.fn(); vi.mock('./ShellSessionManager', () => ({ - ShellSessionManager: vi.fn().mockImplementation(function (_connectionInfo, callbacks) { + ShellSessionManager: vi.fn().mockImplementation(function ( + connectionInfo: ShellConnectionInfo, + callbacks: ShellSessionCallbacks, + _telemetry: unknown, + unauthenticated?: UnauthenticatedShellEndpoint, + ) { // Store callbacks so tests can trigger events (mockInitialize as Mock & { _callbacks?: unknown })._callbacks = callbacks; return { @@ -119,6 +133,14 @@ vi.mock('./ShellSessionManager', () => ({ resetAfterSignIn: mockResetAfterSignIn, pinnedEntraIdentity: workerSignIn.pin, isInitialized: true, + getBlockingLatchReason: (): ReturnType => { + const reason = ClustersClient.getLatchReason(connectionInfo.clusterId); + return unauthenticated && + reason && + ['credentialsRejected', 'signInRequired', 'credentialsMissing'].includes(reason) + ? undefined + : reason; + }, }; }), })); @@ -194,6 +216,150 @@ describe('DocumentDBShellPty', () => { vi.restoreAllMocks(); }); + describe('unauthenticated isolation', () => { + const unauthenticated: UnauthenticatedShellEndpoint = { + connectionString: 'mongodb://anonymous-host/', + reread: async (): Promise => 'mongodb://anonymous-host/', + }; + let noCache: MockInstance; + let noClient: MockInstance; + let noSchema: MockInstance; + let noExplanation: MockInstance; + let noPrewarm: MockInstance; + + beforeEach((): void => { + pty.close(); + noCache = vi.spyOn(CredentialCache, 'getCredentials'); + noClient = vi.spyOn(ClustersClient, 'getExistingClient'); + noSchema = vi.spyOn(SchemaStore, 'getInstance'); + noExplanation = vi.spyOn(ErrorExplanationService, 'explain'); + noPrewarm = vi.spyOn(ShellCompletionProvider.prototype, 'prewarmCollections'); + pty = new DocumentDBShellPty({ ...defaultOptions, unauthenticated }); + pty.onDidWrite((data): void => { + written += data; + }); + mockInitialize.mockResolvedValueOnce({ + host: 'anonymous-host', + additionalHostCount: 0, + authMechanism: 'NoAuth', + isEmulator: false, + }); + mockEvaluate.mockResolvedValue({ type: 'string', printable: '"x"', durationMs: 1 }); + }); + + afterEach((): void => { + pty.close(); + for (const spy of [noCache, noClient, noSchema, noExplanation, noPrewarm]) { + expect(spy).not.toHaveBeenCalled(); + } + }); + + async function openAnonymous(): Promise { + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 10)); + written = ''; + } + + it('passes the anonymous option to the session and metadata-free context to local completions', async (): Promise => { + const completions = vi.spyOn(ShellCompletionProvider.prototype, 'getCompletions'); + await openAnonymous(); + expect(vi.mocked(ShellSessionManager).mock.calls.at(-1)?.[3]).toBe(unauthenticated); + pty.handleInput('hel'); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(completions).toHaveBeenCalledWith('hel', 3, { + clusterId: 'test-cluster-id', + databaseName: 'testdb', + includeClusterMetadata: false, + }); + pty.handleInput('\t'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(mockEvaluate).toHaveBeenLastCalledWith('help', 80); + }); + + it('keeps local history suggestions without schema hints', async (): Promise => { + settingOverrides['documentDB.shell.display.colorSupport'] = true; + await openAnonymous(); + pty.handleInput("db['restaurants-something'].find()"); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + written = ''; + pty.handleInput('db['); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(written).toContain("\x1b[2m'restaurants-something'].find()"); + }); + + it('keeps closing-bracket ghosts even when shared schema is unavailable', async (): Promise => { + await openAnonymous(); + pty.handleInput('db.c.find({ _id: 1 '); + await new Promise((resolve) => setTimeout(resolve, 80)); + pty.handleInput('\x1b[C'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(mockEvaluate).toHaveBeenLastCalledWith('db.c.find({ _id: 1 })', 80); + }); + + it('uses the shared anonymous latch policy and reports rejection without authenticated fallback', async (): Promise => { + await openAnonymous(); + ClustersClient.latch('test-cluster-id', 'credentialsRejected'); + try { + mockEvaluate.mockRejectedValueOnce(new Error('Command requires authentication')); + pty.handleInput('db.stats()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(written).toContain('Command requires authentication'); + expect(written).not.toContain('saved credentials were rejected'); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(workerSignIn.recover).not.toHaveBeenCalled(); + } finally { + ClustersClient.unlatch('test-cluster-id'); + } + }); + + it('does not prewarm after use or feed anonymous query documents into shared schema', async (): Promise => { + await openAnonymous(); + mockEvaluate.mockResolvedValueOnce({ type: 'string', printable: '"switched to db next"', durationMs: 1 }); + pty.handleInput('use next'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + mockEvaluate.mockResolvedValueOnce({ + type: 'Document', + printable: '{"_id":1,"name":"value"}', + durationMs: 1, + source: { namespace: { db: 'next', collection: 'users' } }, + }); + pty.handleInput('db.users.find()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(mockSetActiveDatabase).toHaveBeenCalledWith('next'); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + }); + + it('omits only the shared-schema ghost hint for unknown fields', async (): Promise => { + await openAnonymous(); + pty.handleInput('db.users.find({ nam'); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(mockEvaluate).not.toHaveBeenCalled(); + expect(noSchema).not.toHaveBeenCalled(); + }); + + it('handles anonymous initialization failures without cache-backed explanations or redaction', async (): Promise => { + const notification = vi.spyOn(vscode.window, 'showErrorMessage'); + mockInitialize.mockReset().mockRejectedValueOnce(new Error('Server requires authentication')); + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(written).toContain('Server requires authentication'); + expect(ext.outputChannel.error).toHaveBeenCalled(); + expect(notification).not.toHaveBeenCalled(); + mockInitialize.mockResolvedValue({ + host: 'test-host.documents.azure.com:10255', + additionalHostCount: 0, + authMechanism: 'NativeAuth', + isEmulator: false, + }); + }); + }); + describe('open', () => { it.each([false, true])( 'offers one non-modal pinned recovery, respecting a superseding epoch (%s)', @@ -251,6 +417,522 @@ describe('DocumentDBShellPty', () => { }, ); + describe('stale sign-in notifications', () => { + let chooseAction: (choice: vscode.MessageItem | undefined) => void; + let warning: MockInstance; + let modal: MockInstance; + let getLatchReason: MockInstance; + let getEpoch: MockInstance; + let connectionStateCalls: MockInstance[]; + + beforeEach(async (): Promise => { + workerSignIn.pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'account', + accountLabel: 'Account', + tenantId: 'tenant', + }; + workerSignIn.canRecover.mockReturnValue(true); + getEpoch = vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(0); + getLatchReason = vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue(undefined); + pty = new DocumentDBShellPty(defaultOptions); + pty.onDidWrite((data): void => { + written += data; + }); + pty.open(undefined); + await new Promise((resolve) => setTimeout(resolve, 10)); + warning = vi.spyOn(vscode.window, 'showWarningMessage').mockImplementationOnce( + () => + new Promise((resolve) => { + chooseAction = resolve; + }), + ); + modal = vi.spyOn(vscode.window, 'showErrorMessage'); + mockEvaluate.mockRejectedValueOnce( + Object.assign(new Error('private session miss'), { name: 'EntraSignInRequiredError' }), + ); + pty.handleInput('db.stats()'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(warning).toHaveBeenCalledOnce()); + await new Promise((resolve) => setTimeout(resolve, 10)); + written = ''; + mockInitialize.mockClear(); + vi.mocked(ShellSessionManager).mockClear(); + connectionStateCalls = [ + vi.spyOn(CredentialCache, 'getCredentials'), + vi.spyOn(CredentialCache, 'setCredentials'), + vi.spyOn(CredentialCache, 'deleteCredentials'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'clearLastVerifiedIdentity'), + vi.spyOn(ClustersClient, 'getClient'), + vi.spyOn(ClustersClient, 'startAfterSignIn'), + vi.spyOn(ClustersClient, 'deleteClient'), + vi.spyOn(ClustersClient, 'latch'), + vi.spyOn(ClustersClient, 'unlatch'), + vi.spyOn(ClustersClient, 'invalidate'), + ]; + }); + + it.each([ + [ + 'before click', + 'connectionRemoved', + 'This connection was removed. Open a shell from another connection.', + ], + [ + 'before click', + 'credentialsChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + [ + 'before click', + 'identityChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + [ + 'during sign-in', + 'connectionRemoved', + 'This connection was removed. Open a shell from another connection.', + ], + [ + 'during sign-in', + 'credentialsChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + [ + 'during sign-in', + 'identityChanged', + 'This shell is bound to the previous connection. Open a new shell from the tree.', + ], + ] as const)( + 'explains %s %s on the existing terminal only', + async (stage, reason, message): Promise => { + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue(reason); + } else { + workerSignIn.recover.mockImplementationOnce(async (): Promise => { + getLatchReason.mockReturnValue(reason); + return undefined; + }); + } + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toBe(`\r\x1b[8C\x1b[J\r\n${message}\r\ntestdb> \r\x1b[8C\x1b[J`); + expect(warning).toHaveBeenCalledExactlyOnceWith( + 'Microsoft sign-in expired for this shell. Sign in again to continue.', + 'Sign in again', + ); + expect(modal).not.toHaveBeenCalled(); + expect(workerSignIn.recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(mockResetAfterSignIn).not.toHaveBeenCalled(); + expect(mockInitialize).not.toHaveBeenCalled(); + expect(ShellSessionManager).not.toHaveBeenCalled(); + expect(mockKillWorker).not.toHaveBeenCalled(); + expect(mockDispose).not.toHaveBeenCalled(); + expect(workerSignIn.canRecover).toHaveBeenCalledOnce(); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + }, + ); + + it.each([ + ['success', '', 0, 80, '\r\x1b[8C\x1b[J', '\r\x1b[8C\x1b[J', 'X'], + ['success', 'abcdef', 2, 80, '\r\x1b[8Cabcdef\x1b[J', '\r\x1b[8Cabcdef\x1b[J\r\x1b[10C', 'abXcdef'], + [ + 'before click', + 'abcdef', + 2, + 80, + '\r\x1b[8Cabcdef\x1b[J', + '\r\x1b[8Cabcdef\x1b[J\r\x1b[10C', + 'abXcdef', + ], + [ + 'during sign-in', + 'abcdef', + 2, + 80, + '\r\x1b[8Cabcdef\x1b[J', + '\r\x1b[8Cabcdef\x1b[J\r\x1b[10C', + 'abXcdef', + ], + [ + 'success', + 'db.collection.find()', + 15, + 20, + '\x1b[1A\r\x1b[8Cdb.collection.find()\x1b[J', + '\r\x1b[8Cdb.collection.find()\x1b[J\r\x1b[3C', + 'db.collection.fXind()', + ], + [ + 'before click', + 'db.collection.find()', + 2, + 20, + '\r\x1b[8Cdb.collection.find()\x1b[J', + '\r\x1b[8Cdb.collection.find()\x1b[J\r\x1b[1A\x1b[10C', + 'dbX.collection.find()', + ], + [ + 'during sign-in', + 'db.c.find(1)', + 0, + 20, + '\r\x1b[8Cdb.c.find(1)\x1b[J', + '\r\x1b[8Cdb.c.find(1)\x1b[J\r\x1b[8C', + 'Xdb.c.find(1)', + ], + ] as const)( + 'redraws %s feedback around "%s" at cursor %s, width %s without resetting or submitting it', + async (stage, input, cursor, columns, oldRender, newRender, nextCommand): Promise => { + const message = + stage === 'success' + ? 'Sign-in restored. Run your command again.' + : 'This connection was removed. Open a shell from another connection.'; + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue('connectionRemoved'); + } else { + workerSignIn.recover.mockImplementationOnce(async () => { + if (stage === 'during sign-in') { + getLatchReason.mockReturnValue('connectionRemoved'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + } + pty.setDimensions({ columns, rows: 24 }); + pty.handleInput(input); + pty.handleInput('\x1b[H'); + for (let i = 0; i < cursor; i++) { + pty.handleInput('\x1b[C'); + } + const resetLine = vi.spyOn(pty['_inputHandler'], 'resetLine'); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toBe(`${oldRender}\r\n${message}\r\ntestdb> ${newRender}`); + expect(resetLine).not.toHaveBeenCalled(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(mockResetAfterSignIn).toHaveBeenCalledTimes(stage === 'success' ? 1 : 0); + expect(mockInitialize).not.toHaveBeenCalled(); + expect(mockKillWorker).not.toHaveBeenCalled(); + expect(modal).not.toHaveBeenCalled(); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + + getLatchReason.mockReturnValue(undefined); + mockEvaluate.mockResolvedValueOnce({ type: 'string', printable: '"continued"', durationMs: 1 }); + pty.handleInput('X'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith(nextCommand, columns); + }, + ); + + it.each(['success', 'failure'] as const)( + 'preserves the continuation prompt and accumulated lines after delayed %s', + async (outcome): Promise => { + const message = + outcome === 'success' + ? 'Sign-in restored. Run your command again.' + : 'This shell is bound to the previous connection. Open a new shell from the tree.'; + workerSignIn.recover.mockImplementationOnce(async () => { + if (outcome === 'failure') { + getLatchReason.mockReturnValue('identityChanged'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + pty.handleInput('db.test.find({'); + pty.handleInput('\r'); + pty.handleInput('name: "partial"'); + pty.handleInput('\x1b[H'); + const resetLine = vi.spyOn(pty['_inputHandler'], 'resetLine'); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toBe( + `\r\x1b[4Cname: "partial"\x1b[J\r\n${message}\r\n┆ > \r\x1b[4Cname: "partial"\x1b[J\r\x1b[4C`, + ); + expect(resetLine).not.toHaveBeenCalled(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + + getLatchReason.mockReturnValue(undefined); + mockEvaluate.mockResolvedValueOnce({ type: null, printable: null, durationMs: 1 }); + pty.handleInput('// '); + pty.handleInput('\r'); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(written.endsWith('\r\n┆ > ')).toBe(true); + pty.handleInput('})'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith('db.test.find({\n// name: "partial"\n})', 80); + }, + ); + + it.each(['success', 'before click', 'during sign-in'] as const)( + 'defers %s feedback during evaluation until the next database prompt', + async (stage): Promise => { + let resolveEvaluation!: (result: unknown) => void; + mockEvaluate.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveEvaluation = resolve; + }), + ); + pty.handleInput('use 日本語'); + pty.handleInput('\r'); + written = ''; + const message = + stage === 'success' + ? 'Sign-in restored. Run your command again.' + : 'This connection was removed. Open a shell from another connection.'; + if (stage === 'before click') { + getEpoch.mockReturnValue(1); + getLatchReason.mockReturnValue('connectionRemoved'); + } else { + workerSignIn.recover.mockImplementationOnce(async () => { + if (stage === 'during sign-in') { + getLatchReason.mockReturnValue('connectionRemoved'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + } + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toBe(''); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + resolveEvaluation({ type: null, printable: '"switched to db 日本語"', durationMs: 1 }); + await vi.waitFor(() => expect(written).toContain('日本語> ')); + + expect(written).toBe(`switched to db 日本語\r\n${message}\r\n日本語> `); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + getLatchReason.mockReturnValue(undefined); + written = ''; + pty.handleInput('\r'); + expect(written).toBe('\r\n日本語> '); + written = ''; + pty.handleInput('x'); + expect(written).toBe('\r\x1b[8Cx\x1b[J'); + }, + ); + + it.each([ + ['success', 'closed'], + ['success', 'disconnected'], + ['failure', 'closed'], + ['failure', 'disconnected'], + ] as const)( + 'discards queued %s feedback when the terminal is %s', + async (outcome, terminalState): Promise => { + let resolveEvaluation!: (result: unknown) => void; + mockEvaluate.mockImplementationOnce( + () => + new Promise((resolve) => { + resolveEvaluation = resolve; + }), + ); + pty.handleInput('pending()'); + pty.handleInput('\r'); + written = ''; + workerSignIn.recover.mockImplementationOnce(async () => { + if (outcome === 'failure') { + getLatchReason.mockReturnValue('connectionRemoved'); + return undefined; + } + return { identity: workerSignIn.pin, epoch: 0 }; + }); + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await new Promise((resolve) => setTimeout(resolve, 20)); + expect(written).toBe(''); + if (terminalState === 'closed') { + pty.close(); + } else { + pty.disconnect(); + } + const boundaryOutput = terminalState === 'closed' ? '' : 'Disconnected\r\ntestdb> '; + expect(written).toBe(boundaryOutput); + resolveEvaluation({ type: 'string', printable: '"obsolete result"', durationMs: 1 }); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toBe(boundaryOutput); + expect(mockEvaluate).toHaveBeenCalledTimes(2); + if (terminalState === 'disconnected') { + getLatchReason.mockReturnValue(undefined); + pty.handleInput('\r'); + expect(written).toBe(`${boundaryOutput}\r\ntestdb> `); + } + }, + ); + + it('waits for a safe prompt when input is disabled without an evaluation', async (): Promise => { + workerSignIn.recover.mockResolvedValueOnce({ identity: workerSignIn.pin, epoch: 0 }); + pty['_inputHandler'].setEnabled(false); + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(mockResetAfterSignIn).toHaveBeenCalledOnce()); + + expect(written).toBe(''); + expect(mockEvaluate).toHaveBeenCalledOnce(); + pty['_inputHandler'].setEnabled(true); + pty.handleInput('\r'); + expect(written).toBe('\r\nSign-in restored. Run your command again.\r\ntestdb> '); + written = ''; + pty.handleInput('\r'); + expect(written).toBe('\r\ntestdb> '); + }); + + it('keeps the history selection and its saved draft after delayed success', async (): Promise => { + workerSignIn.recover.mockResolvedValueOnce({ identity: workerSignIn.pin, epoch: 0 }); + pty.handleInput('draft()'); + pty.handleInput('\x1b[A'); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain('Sign-in restored.')); + + expect(written).toBe( + '\r\x1b[8Cdb.stats()\x1b[J\r\nSign-in restored. Run your command again.\r\ntestdb> \r\x1b[8Cdb.stats()\x1b[J', + ); + expect(mockEvaluate).toHaveBeenCalledOnce(); + written = ''; + pty.handleInput('\x1b[B'); + expect(written).toBe('\r\x1b[8Cdraft()\x1b[J'); + mockEvaluate.mockResolvedValueOnce({ type: null, printable: null, durationMs: 1 }); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith('draft()', 80); + }); + + it.each(['pending ghost', 'visible ghost', 'completion list'] as const)( + 'clears %s without resurrecting or accepting a suggestion after delayed success', + async (suggestionState): Promise => { + workerSignIn.recover.mockResolvedValueOnce({ identity: workerSignIn.pin, epoch: 0 }); + const completions = vi.spyOn(ShellCompletionProvider.prototype, 'getCompletions').mockReturnValue({ + candidates: + suggestionState === 'completion list' + ? [ + { label: 'help', insertText: 'help', kind: 'method' }, + { label: 'hello', insertText: 'hello', kind: 'method' }, + ] + : [{ label: 'help', insertText: 'help', kind: 'method' }], + prefix: 'hel', + replacementStart: 0, + }); + pty.handleInput('hel'); + if (suggestionState === 'visible ghost') { + await vi.waitFor(() => expect(written).toContain('p\x1b[1D')); + } else if (suggestionState === 'completion list') { + pty.handleInput('\x09'); + expect(written).toContain('hello'); + } + completions.mockClear(); + written = ''; + + chooseAction('Sign in again' as unknown as vscode.MessageItem); + await vi.waitFor(() => expect(written).toContain('Sign-in restored.')); + + const feedbackOutput = written; + expect(written).toBe( + `${suggestionState === 'visible ghost' ? '\x1b[K' : ''}\r\x1b[8Chel\x1b[J\r\nSign-in restored. Run your command again.\r\ntestdb> \r\x1b[8Chel\x1b[J`, + ); + expect(pty['_completionListVisible']).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 80)); + expect(written).toBe(feedbackOutput); + expect(completions).not.toHaveBeenCalled(); + expect(mockEvaluate).toHaveBeenCalledOnce(); + mockEvaluate.mockResolvedValueOnce({ type: null, printable: null, durationMs: 1 }); + pty.handleInput('\x1b[C'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(mockEvaluate).toHaveBeenCalledTimes(2)); + expect(mockEvaluate).toHaveBeenLastCalledWith('hel', 80); + }, + ); + + it.each([ + ['before click', 'cancelled'], + ['before click', 'closed'], + ['before click', 'revision changed'], + ['before click', 'epoch only'], + ['before click', 'unproven no latch'], + ['before click', 'already completed'], + ['during sign-in', 'cancelled'], + ['during sign-in', 'closed'], + ['during sign-in', 'revision changed'], + ['during sign-in', 'epoch only'], + ['during sign-in', 'unproven no latch'], + ['during sign-in', 'already completed'], + ] as const)('keeps %s %s quiet without reviving the worker', async (stage, outcome): Promise => { + const supersede = (): void => { + if (outcome === 'closed') { + pty.close(); + } else if (outcome === 'revision changed') { + pty.disconnect(); + } + getEpoch.mockReturnValue(2); + getLatchReason.mockReturnValue( + outcome === 'closed' || outcome === 'revision changed' || outcome === 'cancelled' + ? 'connectionRemoved' + : undefined, + ); + written = ''; + mockDispose.mockClear(); + mockKillWorker.mockClear(); + }; + if (stage === 'before click') { + supersede(); + } else { + workerSignIn.recover.mockImplementationOnce(async () => { + supersede(); + if (outcome === 'cancelled') { + const { UserCancelledError } = await import('@microsoft/vscode-azext-utils'); + throw new UserCancelledError('shell.signInAgain'); + } + return outcome === 'unproven no latch' ? undefined : { identity: workerSignIn.pin, epoch: 1 }; + }); + } + + chooseAction( + stage === 'before click' && outcome === 'cancelled' + ? undefined + : ('Sign in again' as unknown as vscode.MessageItem), + ); + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(written).toBe(''); + expect(warning).toHaveBeenCalledOnce(); + expect(modal).not.toHaveBeenCalled(); + expect(workerSignIn.recover).toHaveBeenCalledTimes(stage === 'before click' ? 0 : 1); + expect(mockEvaluate).toHaveBeenCalledOnce(); + expect(mockResetAfterSignIn).not.toHaveBeenCalled(); + expect(mockInitialize).not.toHaveBeenCalled(); + expect(ShellSessionManager).not.toHaveBeenCalled(); + expect(mockKillWorker).not.toHaveBeenCalled(); + expect(mockDispose).not.toHaveBeenCalled(); + expect(workerSignIn.canRecover).toHaveBeenCalledOnce(); + for (const call of connectionStateCalls) { + expect(call).not.toHaveBeenCalled(); + } + }); + }); + it('carries URL attribution into actual shell startup', async (): Promise => { const deepLink = { deepLinkCorrelationId: 'link-attempt', deepLinkSource: 'docs' }; pty = new DocumentDBShellPty({ ...defaultOptions, deepLink }); @@ -432,10 +1114,12 @@ describe('DocumentDBShellPty', () => { }); it('should show error and stay open on connection failure', async () => { + const notification = vi.spyOn(vscode.window, 'showErrorMessage'); mockInitialize.mockRejectedValue(new Error('Connection refused')); pty.open(undefined); await new Promise((resolve) => setTimeout(resolve, 10)); expect(written).toContain('Failed to connect: Connection refused'); + expect(notification).toHaveBeenCalledOnce(); // Closing would dispose the terminal and take the message with it; the prompt lets the // user retry, since evaluate() re-initializes an uninitialized session. expect(closeCode).toBeUndefined(); @@ -471,6 +1155,116 @@ describe('DocumentDBShellPty', () => { written = ''; // Reset to capture only subsequent output }); + it('should put a disconnect while idle on its own line with one new prompt', () => { + pty.disconnect(); + + expect(written).toBe('\r\nDisconnected\r\ntestdb> '); + expect(written.match(/Disconnected/g)).toHaveLength(1); + expect(written.match(/testdb> /g)).toHaveLength(1); + }); + + it('should preserve and visibly redraw partially typed single-line input after disconnect', async () => { + mockEvaluate.mockResolvedValue({ + type: 'string', + printable: '"continued"', + durationMs: 1, + }); + pty.handleInput('db.stats'); + written = ''; + + pty.disconnect(); + + expect(written).toBe('\r\nDisconnected\r\ntestdb> \r\x1b[8Cdb.stats\x1b[J'); + expect(written.match(/Disconnected/g)).toHaveLength(1); + expect(written.match(/testdb> /g)).toHaveLength(1); + + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('db.stats', 80); + }); + + it('should preserve the logical cursor in partially typed single-line input after disconnect', async () => { + mockEvaluate.mockResolvedValue({ + type: 'string', + printable: '"continued"', + durationMs: 1, + }); + pty.handleInput('abcdef'); + pty.handleInput('\x1b[H'); + pty.handleInput('\x1b[C'); + pty.handleInput('\x1b[C'); + + pty.disconnect(); + + expect(mockEvaluate).not.toHaveBeenCalled(); + pty.handleInput('X'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('abXcdef', 80); + }); + + it('should move to the end of a wrapped partial line before disconnect output', () => { + const input = 'db.collection.find()'; + expect(input).toHaveLength(20); + pty.setDimensions({ columns: 20, rows: 24 }); + pty.handleInput(input); + pty.handleInput('\x1b[H'); + written = ''; + + pty.disconnect(); + + expect(written).toBe( + `\r\x1b[8C${input}\x1b[J\r\nDisconnected\r\ntestdb> \r\x1b[8C${input}\x1b[J\r\x1b[1A\x1b[8C`, + ); + expect(mockEvaluate).not.toHaveBeenCalled(); + }); + + it('should stop an evaluation without an extra newline or late output after disconnect', async () => { + let rejectEvaluation: (error: Error) => void = () => { + throw new Error('Expected evaluation to be pending'); + }; + mockEvaluate.mockImplementation( + () => + new Promise((_resolve, reject) => { + rejectEvaluation = reject; + }), + ); + + pty.handleInput('db.test.find()'); + pty.handleInput('\r'); + written = ''; + pty.disconnect(); + + expect(written).toBe('Disconnected\r\ntestdb> '); + rejectEvaluation(new Error('Worker terminated')); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(written).toBe('Disconnected\r\ntestdb> '); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('db.test.find()', 80); + }); + + it('should keep prior multi-line output but discard the pending line on disconnect', async () => { + pty.handleInput('db.test.find({'); + pty.handleInput('\r'); + pty.handleInput('name: "partial"'); + const priorOutput = written; + + pty.disconnect(); + + const disconnectOutput = written.slice(priorOutput.length); + expect(written.startsWith(priorOutput)).toBe(true); + expect(disconnectOutput).toBe('\r\nDisconnected\r\ntestdb> '); + + mockEvaluate.mockResolvedValue({ + type: null, + printable: '"fresh"', + durationMs: 1, + }); + pty.handleInput('fresh()'); + pty.handleInput('\r'); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('fresh()', 80); + }); + it('should show new prompt on empty Enter', async () => { pty.handleInput('\r'); await new Promise((resolve) => setTimeout(resolve, 10)); @@ -530,6 +1324,45 @@ describe('DocumentDBShellPty', () => { expect(getLatchReason).toHaveBeenCalled(); }); + it.each([ + ['userDisconnected', 'Disconnected. Reconnect from the tree, then run your command again.'], + ['unreachable', 'The connection is unavailable. Check the server or network, then run your command again.'], + [ + 'credentialsRejected', + 'The saved credentials were rejected. Update them from the tree, then run your command again.', + ], + [ + 'credentialsUpdating', + 'This connection is being updated. Run your command again when the update finishes.', + ], + ['connectionRemoved', 'This connection was removed. Open a shell from another connection.'], + ['credentialsChanged', 'This shell is bound to the previous connection. Open a new shell from the tree.'], + ['identityChanged', 'This shell is bound to the previous connection. Open a new shell from the tree.'], + [ + 'credentialsMissing', + 'This connection is unavailable. Reconnect from the tree, then run your command again.', + ], + ['signInRequired', 'This connection is unavailable. Reconnect from the tree, then run your command again.'], + ] as const)('uses %s guidance for latch and worker failures', async (reason, message) => { + vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValueOnce(reason).mockReturnValue(undefined); + + pty.handleInput('blocked'); + pty.handleInput('\r'); + expect(written).toContain(message); + expect(mockEvaluate).not.toHaveBeenCalled(); + + written = ''; + const failure = new ConnectionUnavailableError(reason); + mockEvaluate.mockRejectedValueOnce(failure); + + pty.handleInput('retry'); + pty.handleInput('\r'); + await vi.waitFor(() => expect(written).toContain(message)); + + expect(written).toContain(message); + expect(mockEvaluate).toHaveBeenCalledExactlyOnceWith('retry', 80); + }); + it('should display error message on evaluation failure', async () => { mockEvaluate.mockRejectedValue(new Error('Syntax error')); diff --git a/src/documentdb/shell/DocumentDBShellPty.ts b/src/documentdb/shell/DocumentDBShellPty.ts index 6c087dc2b..24689d7a4 100644 --- a/src/documentdb/shell/DocumentDBShellPty.ts +++ b/src/documentdb/shell/DocumentDBShellPty.ts @@ -18,7 +18,7 @@ import { COMPLETION_OFFERED_EVENT, type CompletionCategory } from '../../telemet import { accumulateTelemetry } from '../../utils/accumulatingTelemetry'; import { classifyCommand, extractRunCommandName } from '../../utils/classifyCommand'; import { ClustersClient } from '../ClustersClient'; -import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; +import { ConnectionUnavailableError, type ConnectionUnavailableReason } from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; import { deserializeResultForSchema, feedResultToSchemaStore } from '../feedResultToSchemaStore'; import { @@ -37,7 +37,12 @@ import { findCommonPrefix, renderCompletionList } from './ShellCompletionRendere import { ShellGhostText } from './ShellGhostText'; import { ShellInputHandler } from './ShellInputHandler'; import { extractErrorCode, ShellOutputFormatter } from './ShellOutputFormatter'; -import { type ShellConnectionInfo, type ShellSessionCallbacks, ShellSessionManager } from './ShellSessionManager'; +import { + type ShellConnectionInfo, + type ShellSessionCallbacks, + ShellSessionManager, + type UnauthenticatedShellEndpoint, +} from './ShellSessionManager'; import { ShellSpinner } from './ShellSpinner'; import { ACTION_LINE_PREFIX, @@ -55,6 +60,7 @@ const COMPACT_CONNECTION_SUMMARY_MIN_COLUMNS = 100; * Configuration for the interactive shell Pseudoterminal. */ export interface DocumentDBShellPtyOptions { + readonly unauthenticated?: UnauthenticatedShellEndpoint; readonly deepLink?: DeepLinkTelemetry; /** Connection parameters for the shell session. */ readonly connectionInfo: ShellConnectionInfo; @@ -86,6 +92,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { private readonly _inputHandler: ShellInputHandler; private readonly _outputFormatter: ShellOutputFormatter; private readonly _connectionInfo: ShellConnectionInfo; + private readonly _unauthenticated: UnauthenticatedShellEndpoint | undefined; /** Current database name — updated when `use ` changes it. */ private _currentDatabase: string; @@ -95,6 +102,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { private _evaluating = false; /** Whether the shell has been closed. */ private _closed = false; + private readonly _deferredFeedback: string[] = []; /** Whether the current evaluation was cancelled by Ctrl+C. */ private _interrupted = false; /** Spinner shown during long-running evaluations. */ @@ -144,6 +152,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { constructor(options: DocumentDBShellPtyOptions) { this._deepLink = options.deepLink; this._connectionInfo = options.connectionInfo; + this._unauthenticated = options.unauthenticated; this._currentDatabase = options.connectionInfo.databaseName; this._initialInput = options.initialInput; @@ -182,13 +191,18 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { }, }; - this._connectionCorrelationId = ClustersClient.getExistingClient( - options.connectionInfo.clusterId, - )?.connectionCorrelationId; - this._sessionManager = new ShellSessionManager(options.connectionInfo, sessionCallbacks, { - shellSessionId: this._shellSessionId, - connectionCorrelationId: this._connectionCorrelationId, - }); + this._connectionCorrelationId = options.unauthenticated + ? undefined + : ClustersClient.getExistingClient(options.connectionInfo.clusterId)?.connectionCorrelationId; + this._sessionManager = new ShellSessionManager( + options.connectionInfo, + sessionCallbacks, + { + shellSessionId: this._shellSessionId, + connectionCorrelationId: this._connectionCorrelationId, + }, + options.unauthenticated, + ); this._outputFormatter = new ShellOutputFormatter(); @@ -237,6 +251,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { close(): void { this._closed = true; + this._deferredFeedback.length = 0; this._spinner?.stop(); this._spinner = undefined; if (this._ghostTextTimer) { @@ -272,16 +287,30 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { /** Keep the terminal and its scrollback, but stop the database worker. */ public disconnect(): void { + const wasEvaluating = this._evaluating; + const retainPartialInput = !wasEvaluating && !this._inputHandler.isInMultiLineMode; + const partialInput = retainPartialInput ? this._inputHandler.getBuffer() : ''; + const partialCursor = retainPartialInput ? this._inputHandler.getCursor() : 0; + this._disconnectRevision += 1; + this._deferredFeedback.length = 0; + this.clearGhostState(); this._spinner?.stop(); this._spinner = undefined; this._evaluating = false; this._inputHandler.clearPendingInput(); + if (!wasEvaluating) { + this._inputHandler.handleInput('\x1b[F'); + this.writeLine(''); + } this.writeLine(this._outputFormatter.formatSystemMessage(l10n.t('Disconnected'))); this._sessionManager.killWorker(); this._inputHandler.setEnabled(true); if (!this._closed) { this.showPrompt(); + if (partialInput.length > 0) { + this._inputHandler.restoreLine(partialInput, partialCursor); + } } } @@ -532,10 +561,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { throw new UserCancelledError('shell.sessionStart'); } - void this._completionProvider.prewarmCollections({ - clusterId: this._connectionInfo.clusterId, - databaseName: this._currentDatabase, - }); + if (!this._unauthenticated) { + void this._completionProvider.prewarmCollections({ + clusterId: this._connectionInfo.clusterId, + databaseName: this._currentDatabase, + }); + } // Stop the connection spinner this._spinner?.stop(); @@ -652,10 +683,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // Written as a separate line rather than merged into the message above, so the raw text // stays intact for extractErrorCode and the SettingsHintError check below. - const explanation = await ErrorExplanationService.explain({ - clusterId: this._connectionInfo.clusterId, - error, - }); + const explanation = this._unauthenticated + ? undefined + : await ErrorExplanationService.explain({ + clusterId: this._connectionInfo.clusterId, + error, + }); if (explanation) { this.writeLine(this._outputFormatter.formatError(explanation.message)); } @@ -677,13 +710,15 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // A notification as well: the terminal may be in the background, or closed by the user // before they read it. - void vscode.window.showErrorMessage( - explanation?.message ?? - l10n.t('Failed to connect to "{cluster}": {error}', { - cluster: this._connectionInfo.clusterDisplayName, - error: errorMessage, - }), - ); + if (!this._unauthenticated) { + void vscode.window.showErrorMessage( + explanation?.message ?? + l10n.t('Failed to connect to "{cluster}": {error}', { + cluster: this._connectionInfo.clusterDisplayName, + error: errorMessage, + }), + ); + } // Deliberately no _closeEmitter.fire(): disposing the terminal would take the message // with it. The session is still uninitialized, so ShellSessionManager.evaluate() re-runs @@ -702,7 +737,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { private async handleLineInput(line: string): Promise { const disconnectRevision = this._disconnectRevision; - const latchReason = ClustersClient.getLatchReason(this._connectionInfo.clusterId); + const latchReason = this._sessionManager.getBlockingLatchReason(); if (latchReason) { this.handleWorkerFailure(new ConnectionUnavailableError(latchReason)); if (!this._closed) { @@ -863,10 +898,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // talks to gets stopped, a port-forward drops — and the next command is where they find // out. Written as a separate line so the raw text above stays intact for extractErrorCode // and the checks below. - const explanation = await ErrorExplanationService.explain({ - clusterId: this._connectionInfo.clusterId, - error, - }); + const explanation = this._unauthenticated + ? undefined + : await ErrorExplanationService.explain({ + clusterId: this._connectionInfo.clusterId, + error, + }); if (explanation) { this.writeLine(this._outputFormatter.formatError(explanation.message)); } @@ -893,18 +930,36 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { return true; } if (error instanceof ConnectionUnavailableError) { - const message = - error.reason === 'userDisconnected' - ? l10n.t('Disconnected. Reconnect from the tree, then open a new shell.') - : error.reason === 'credentialsChanged' || error.reason === 'identityChanged' - ? l10n.t('This shell is bound to the previous connection. Open a new shell from the tree.') - : l10n.t('This connection is unavailable. Reconnect from the tree, then open a new shell.'); - this.writeLine(this._outputFormatter.formatError(message)); + this.writeLine(this._outputFormatter.formatError(this.unavailableMessage(error.reason))); return true; } return false; } + private unavailableMessage(reason: ConnectionUnavailableReason): string { + switch (reason) { + case 'userDisconnected': + return l10n.t('Disconnected. Reconnect from the tree, then run your command again.'); + case 'unreachable': + return l10n.t( + 'The connection is unavailable. Check the server or network, then run your command again.', + ); + case 'credentialsRejected': + return l10n.t( + 'The saved credentials were rejected. Update them from the tree, then run your command again.', + ); + case 'credentialsUpdating': + return l10n.t('This connection is being updated. Run your command again when the update finishes.'); + case 'connectionRemoved': + return l10n.t('This connection was removed. Open a shell from another connection.'); + case 'credentialsChanged': + case 'identityChanged': + return l10n.t('This shell is bound to the previous connection. Open a new shell from the tree.'); + default: + return l10n.t('This connection is unavailable. Reconnect from the tree, then run your command again.'); + } + } + private writeBoundedWorkerFailure(reason: WorkerAuthReason): void { const pin = this._sessionManager.pinnedEntraIdentity; if (reason === 'signInRequired' && pin && canSignInAgainForWorker(this._connectionInfo.clusterId, pin)) { @@ -953,6 +1008,16 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { revision !== this._disconnectRevision || ClustersClient.getEpoch(clusterId) !== epoch ) { + if (choice === action && !this._closed && revision === this._disconnectRevision) { + const reason = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' + ) { + this.writeAsyncFeedback(this._outputFormatter.formatError(this.unavailableMessage(reason))); + } + } return; } try { @@ -967,10 +1032,22 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { revision !== this._disconnectRevision || ClustersClient.getEpoch(clusterId) !== result.epoch ) { + if (!this._closed && revision === this._disconnectRevision) { + const reason = ClustersClient.getLatchReason(clusterId); + if ( + reason === 'connectionRemoved' || + reason === 'credentialsChanged' || + reason === 'identityChanged' + ) { + this.writeAsyncFeedback( + this._outputFormatter.formatError(this.unavailableMessage(reason)), + ); + } + } return; } this._sessionManager.resetAfterSignIn(result.identity, result.epoch); - this.writeLine( + this.writeAsyncFeedback( this._outputFormatter.formatSystemMessage(l10n.t('Sign-in restored. Run your command again.')), ); }); @@ -1044,10 +1121,12 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { if (newDb) { this._currentDatabase = newDb; this._sessionManager.setActiveDatabase(newDb); - void this._completionProvider.prewarmCollections({ - clusterId: this._connectionInfo.clusterId, - databaseName: newDb, - }); + if (!this._unauthenticated) { + void this._completionProvider.prewarmCollections({ + clusterId: this._connectionInfo.clusterId, + databaseName: newDb, + }); + } this.updateTerminalTitle(); } } @@ -1092,7 +1171,41 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { this._ghostTextTimer = undefined; } + if (!this._closed) { + for (const line of this._deferredFeedback.splice(0)) { + this.writeLine(line); + } + } + this._writeEmitter.fire(prompt); + } + + private writeAsyncFeedback(line: string): void { + if (this._closed) { + return; + } + if (this._evaluating || !this._inputHandler.isEnabled) { + this._deferredFeedback.push(line); + return; + } + + const text = this._inputHandler.buffer; + const cursor = this._inputHandler.cursor; + this.clearGhostState(); + if (this._ghostTextTimer) { + clearTimeout(this._ghostTextTimer); + this._ghostTextTimer = undefined; + } + this._completionListVisible = false; + + // Use the old render origin to move past all wrapped input before writing feedback. + this._inputHandler.restoreLine(text, text.length); + this._writeEmitter.fire('\r\n'); + this.writeLine(line); + + const prompt = this._inputHandler.isInMultiLineMode ? '┆ > ' : `${this._currentDatabase}> `; + this._inputHandler.setPromptWidth(terminalDisplayWidth(prompt)); this._writeEmitter.fire(prompt); + this._inputHandler.restoreLine(text, cursor); } /** @@ -1210,6 +1323,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { * Failures are silently ignored — schema feeding is best-effort. */ private maybeFeedSchemaStore(result: SerializableExecutionResult): void { + if (this._unauthenticated) { + return; + } // Only Cursor and Document results with a namespace are worth parsing if (result.type !== 'Cursor' && result.type !== 'Document') { return; @@ -1337,6 +1453,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { return this._completionProvider.getCompletions(buffer, cursor, { clusterId: this._connectionInfo.clusterId, databaseName: this._currentDatabase, + ...(this._unauthenticated ? { includeClusterMetadata: false } : {}), }); } @@ -1497,7 +1614,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { // No completions inside a method argument — show schema hint only if // SchemaStore has no fields for this collection (not just a typo/no match) - if (result.candidates.length === 0) { + if (!this._unauthenticated && result.candidates.length === 0) { const ctx = this._completionProvider.detectContext(buffer, cursor); if (ctx.kind === 'method-argument') { const fields = SchemaStore.getInstance().getKnownFields( @@ -1696,6 +1813,9 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { /** Cached secrets for this cluster, so they can be redacted before anything is logged. */ private credentialSecrets(): string[] { + if (this._unauthenticated) { + return [this._unauthenticated.connectionString]; + } const credentials = CredentialCache.getCredentials(this._connectionInfo.clusterId); return [credentials?.nativeAuthConfig?.connectionPassword, credentials?.connectionString].filter( (secret): secret is string => !!secret, @@ -1708,11 +1828,13 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { */ private collectShellDomainTelemetry(properties: Record): void { try { - const credentials = CredentialCache.getCredentials(this._connectionInfo.clusterId); - if (!credentials?.connectionString) { + const connectionString = this._unauthenticated + ? this._unauthenticated.connectionString + : CredentialCache.getCredentials(this._connectionInfo.clusterId)?.connectionString; + if (!connectionString) { return; } - const hosts = getHostsFromConnectionString(credentials.connectionString); + const hosts = getHostsFromConnectionString(connectionString); addDomainInfoToProperties(hosts, properties); } catch { // Domain info is best-effort — don't fail telemetry if parsing fails diff --git a/src/documentdb/shell/ShellCompletionProvider.test.ts b/src/documentdb/shell/ShellCompletionProvider.test.ts index 81e496fbe..d4efe02a4 100644 --- a/src/documentdb/shell/ShellCompletionProvider.test.ts +++ b/src/documentdb/shell/ShellCompletionProvider.test.ts @@ -63,6 +63,34 @@ describe('ShellCompletionProvider', () => { mockSchemaStore(); }); + describe('metadata-free completions', () => { + const context = { ...TEST_CONTEXT, includeClusterMetadata: false }; + + it.each(['use ', 'db[', "db['", 'db.users.find({ na'])( + 'does not consult shared clients or schema for %s', + async (input): Promise => { + expect(provider.getCompletions(input, input.length, context).candidates).toEqual([]); + await provider.prewarmCollections(context); + expect(ClustersClient.getExistingClient).not.toHaveBeenCalled(); + expect(SchemaStore.getInstance).not.toHaveBeenCalled(); + }, + ); + + it.each([ + ['hel', 'command'], + ['db.', 'method'], + ['db.users.', 'method'], + ['db.users.find({ $', 'operator'], + ['db.users.find({ _id: ', 'bson'], + ] as const)('retains local %s completions (%s)', (input, kind): void => { + const result = provider.getCompletions(input, input.length, context); + expect(result.candidates.length).toBeGreaterThan(0); + expect(result.candidates.some((candidate) => candidate.kind === kind)).toBe(true); + expect(ClustersClient.getExistingClient).not.toHaveBeenCalled(); + expect(SchemaStore.getInstance).not.toHaveBeenCalled(); + }); + }); + describe('context detection', () => { it('should detect empty buffer as top-level', () => { const ctx = provider.detectContext('', 0); diff --git a/src/documentdb/shell/ShellCompletionProvider.ts b/src/documentdb/shell/ShellCompletionProvider.ts index ec0861d75..03794440e 100644 --- a/src/documentdb/shell/ShellCompletionProvider.ts +++ b/src/documentdb/shell/ShellCompletionProvider.ts @@ -56,6 +56,7 @@ export interface CompletionCandidate { * Context required by the completion provider to resolve dynamic completions. */ export interface ShellCompletionContext { + readonly includeClusterMetadata?: boolean; /** Stable cluster ID for cache lookups. */ readonly clusterId: string; /** Current active database name. */ @@ -164,6 +165,9 @@ export class ShellCompletionProvider { * Warm the collection cache for a database without blocking shell input. */ async prewarmCollections(context: ShellCompletionContext): Promise { + if (context.includeClusterMetadata === false) { + return; + } const fetchKey = `colls:${context.clusterId}:${context.databaseName}`; if (this._backgroundFetchTriggered.has(fetchKey)) { return; @@ -584,6 +588,9 @@ export class ShellCompletionProvider { * Get database name candidates from ClustersClient cache + SchemaStore. */ private getDatabaseCandidates(context: ShellCompletionContext): CompletionCandidate[] { + if (context.includeClusterMetadata === false) { + return []; + } const candidates: CompletionCandidate[] = []; const seen = new Set(); @@ -651,7 +658,8 @@ export class ShellCompletionProvider { const seen = new Set(); // Collection names from ClustersClient cache - const client = ClustersClient.getExistingClient(context.clusterId); + const client = + context.includeClusterMetadata === false ? undefined : ClustersClient.getExistingClient(context.clusterId); if (client) { const cached = client.getCachedCollections(context.databaseName); if (cached) { @@ -668,15 +676,17 @@ export class ShellCompletionProvider { } // Collection names from SchemaStore - const store = SchemaStore.getInstance(); - const stats = store.getStats(); - const keyPrefix = `${context.clusterId}::${context.databaseName}::`; - for (const coll of stats.collections) { - if (coll.key.startsWith(keyPrefix)) { - const collName = coll.key.substring(keyPrefix.length); - if (collName && !seen.has(collName)) { - seen.add(collName); - candidates.push(this.makeCollectionCandidate(collName)); + if (context.includeClusterMetadata !== false) { + const store = SchemaStore.getInstance(); + const stats = store.getStats(); + const keyPrefix = `${context.clusterId}::${context.databaseName}::`; + for (const coll of stats.collections) { + if (coll.key.startsWith(keyPrefix)) { + const collName = coll.key.substring(keyPrefix.length); + if (collName && !seen.has(collName)) { + seen.add(collName); + candidates.push(this.makeCollectionCandidate(collName)); + } } } } @@ -712,6 +722,9 @@ export class ShellCompletionProvider { * `db['` inserts `restaurants']`. */ private getDbBracketCandidates(context: ShellCompletionContext, quote: '"' | "'" | ''): CompletionCandidate[] { + if (context.includeClusterMetadata === false) { + return []; + } const candidates: CompletionCandidate[] = []; const seen = new Set(); @@ -811,12 +824,13 @@ export class ShellCompletionProvider { } // Build a field type lookup from SchemaStore (pre-compute Map for O(1) lookups) - const fields = SchemaStore.getInstance().getKnownFields( - shellCtx.clusterId, - shellCtx.databaseName, - ctx.collectionName, + const fieldTypeByPath = new Map( + shellCtx.includeClusterMetadata === false + ? [] + : SchemaStore.getInstance() + .getKnownFields(shellCtx.clusterId, shellCtx.databaseName, ctx.collectionName) + .map((f) => [f.path, f.type]), ); - const fieldTypeByPath = new Map(fields.map((f) => [f.path, f.type])); const fieldLookup: FieldTypeLookup = (fieldName: string): string | undefined => { return fieldTypeByPath.get(fieldName); }; @@ -876,6 +890,9 @@ export class ShellCompletionProvider { context: ShellCompletionContext, collectionName: string, ): void { + if (context.includeClusterMetadata === false) { + return; + } const fields = SchemaStore.getInstance().getKnownFields( context.clusterId, context.databaseName, diff --git a/src/documentdb/shell/ShellInputHandler.test.ts b/src/documentdb/shell/ShellInputHandler.test.ts index 4c85887c0..f376f1fc1 100644 --- a/src/documentdb/shell/ShellInputHandler.test.ts +++ b/src/documentdb/shell/ShellInputHandler.test.ts @@ -566,6 +566,51 @@ describe('ShellInputHandler', () => { }); }); + describe('restoreLine', () => { + it('should restore text and cursor without firing onBufferChange', () => { + let changeCount = 0; + const restoreHandler = new ShellInputHandler({ + write: () => {}, + onLine: () => {}, + onInterrupt: () => {}, + onContinuation: () => {}, + onBufferChange: () => { + changeCount++; + }, + }); + + restoreHandler.restoreLine('abcdef', 2); + restoreHandler.handleInput('X'); + + expect(restoreHandler.getBuffer()).toBe('abXcdef'); + expect(restoreHandler.getCursor()).toBe(3); + expect(changeCount).toBe(1); + }); + + it.each([ + [-1, 0], + [99, 6], + ])('should clamp cursor %s to %s', (cursor, expected) => { + handler.restoreLine('abcdef', cursor); + + expect(handler.getCursor()).toBe(expected); + }); + + it('should preserve multiline state and history', () => { + handler.handleInput('db.test.find({'); + handler.handleInput('\r'); + + handler.restoreLine('})', 2); + expect(handler.isInMultiLineMode).toBe(true); + handler.handleInput('\r'); + expect(lines).toEqual(['db.test.find({\n})']); + + handler.resetLine(); + handler.handleInput('\x1b[A'); + expect(handler.getBuffer()).toBe('db.test.find({ })'); + }); + }); + describe('replaceText', () => { it('should replace text before cursor with new text', () => { handler.handleInput('address.ci'); diff --git a/src/documentdb/shell/ShellInputHandler.ts b/src/documentdb/shell/ShellInputHandler.ts index 5e6cd8b31..fde86d182 100644 --- a/src/documentdb/shell/ShellInputHandler.ts +++ b/src/documentdb/shell/ShellInputHandler.ts @@ -284,6 +284,15 @@ export class ShellInputHandler { this.reRenderLine(); } + /** + * Restore the current line text and logical cursor position. + */ + restoreLine(text: string, cursor: number): void { + this._buffer = text; + this._cursor = Math.max(0, Math.min(cursor, text.length)); + this.reRenderLine(); + } + /** * Replace text before the cursor and insert new text. * Used by the PTY when a completion needs to replace the typed prefix diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index a9ce75850..d486e86b2 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import type * as azureAuth from '@microsoft/vscode-azext-azureauth'; -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi, type Mock, type MockInstance } from 'vitest'; import * as vscode from 'vscode'; import { type AuthenticationSession } from 'vscode'; @@ -25,10 +25,11 @@ import { import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; import { PlaygroundEvaluator } from '../playground/PlaygroundEvaluator'; -import { type WorkerSessionCallbacks } from '../playground/WorkerSessionManager'; +import { WorkerSessionManager, type WorkerSessionCallbacks } from '../playground/WorkerSessionManager'; import { getWorkerAuthReason, type MainToWorkerMessage, type WorkerToMainMessage } from '../playground/workerTypes'; import { ConnectionStartupTimings } from '../utils/ConnectionStartupTimings'; import { ShellSessionManager } from './ShellSessionManager'; +import { toUnauthenticatedConnectionString } from './unauthenticatedEndpoint'; const mockGetSessionFromVSCode = vi.fn(); const mockGetManagedIdentityAccessToken = vi.fn(); @@ -168,6 +169,263 @@ describe('ShellSessionManager', () => { resetEntraTokenFailuresForTests(); }); + describe('unauthenticated sessions', () => { + const endpoint = 'mongodb://localhost:27017/test?tls=true&tlsCAFile=trust.pem'; + let manager: ShellSessionManager; + const reread = vi.fn<() => Promise>(); + let cacheSpies: MockInstance[]; + + function ensureWorker(): Mock { + const worker = vi.mocked(WorkerSessionManager).mock.results.at(-1)?.value as { ensureWorker: Mock }; + return worker.ensureWorker; + } + + beforeEach((): void => { + reread.mockReset().mockResolvedValue(endpoint); + manager = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }, + undefined, + {}, + { + connectionString: endpoint, + emulatorConfiguration: { isEmulator: true, disableEmulatorSecurity: true }, + reread, + }, + ); + cacheSpies = [ + vi.spyOn(CredentialCache, 'getCredentials'), + vi.spyOn(CredentialCache, 'hasCredentials'), + vi.spyOn(CredentialCache, 'getConnectionUser'), + vi.spyOn(CredentialCache, 'getConnectionStringWithPassword'), + vi.spyOn(CredentialCache, 'getEmulatorConfiguration'), + vi.spyOn(CredentialCache, 'setAuthCredentials'), + vi.spyOn(CredentialCache, 'deleteCredentials'), + vi.spyOn(ClustersClient, 'getExpectedFingerprint'), + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity'), + ]; + }); + + afterEach((): void => { + for (const spy of cacheSpies) { + expect(spy).not.toHaveBeenCalled(); + } + manager.dispose(); + ClustersClient.unlatch(clusterId); + vi.restoreAllMocks(); + }); + + it('initializes NoAuth with server TLS intact and no identity relay or credential state', async (): Promise => { + const metadata = await manager.initialize(); + expect(metadata).toMatchObject({ authMechanism: 'NoAuth', username: undefined, isEmulator: true }); + expect(ensureWorker()).toHaveBeenCalledWith( + clusterId, + { + type: 'init', + requestId: '', + connectionString: endpoint, + databaseName: 'test', + authMechanism: 'NoAuth', + persistent: true, + clientOptions: { serverSelectionTimeoutMS: 4000, tlsAllowInvalidCertificates: true }, + }, + expect.anything(), + {}, + true, + ); + expect(manager.pinnedEntraIdentity).toBeUndefined(); + const post = vi.fn(); + await workerCallbacks.onTokenRequest?.({ type: 'tokenRequest', requestId: 'token' }, post, () => true); + expect(post).not.toHaveBeenCalled(); + expect(mockGetSessionFromVSCode).not.toHaveBeenCalled(); + }); + + it('starts and evaluates when cached credentials have already been evicted', async (): Promise => { + vi.mocked(CredentialCache.deleteCredentials).mockRestore(); + CredentialCache.deleteCredentials(clusterId); + const deletion = vi.spyOn(CredentialCache, 'deleteCredentials'); + cacheSpies[6] = deletion; + await manager.initialize(); + await manager.evaluate('db.stats()'); + expect(sendEval).toHaveBeenCalledOnce(); + }); + + it.each([ + ['mongodb://127.0.0.1/?tls=true', true, 4000], + ['mongodb://public.example.com/?tls=true&tlsCAFile=trust.pem', undefined, undefined], + ] as const)('preserves host-gated TLS rules for %s', async (connectionString, tls, timeout): Promise => { + manager.dispose(); + manager = new ShellSessionManager( + { clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }, + undefined, + {}, + { + connectionString, + emulatorConfiguration: { isEmulator: false, disableEmulatorSecurity: true }, + reread: async (): Promise => connectionString, + }, + ); + await expect(manager.initialize()).resolves.toMatchObject({ isEmulator: false }); + expect(ensureWorker().mock.calls[0][1]).toMatchObject({ + connectionString, + authMechanism: 'NoAuth', + clientOptions: { tlsAllowInvalidCertificates: tls, serverSelectionTimeoutMS: timeout }, + }); + }); + + it('surfaces anonymous startup rejection without authentication or a retry', async (): Promise => { + const rejection = Object.assign(new Error('Authentication required'), { code: 13 }); + ensureWorker().mockRejectedValueOnce(rejection); + await expect(manager.initialize()).rejects.toBe(rejection); + expect(ensureWorker()).toHaveBeenCalledOnce(); + expect(manager.isInitialized).toBe(false); + expect(mockGetSessionFromVSCode).not.toHaveBeenCalled(); + }); + + it.each(['credentialsRejected', 'signInRequired', 'credentialsMissing'] as const)( + 'allows %s at initialization and evaluation without clearing the hold', + async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + expect(manager.getBlockingLatchReason()).toBeUndefined(); + await manager.initialize(); + await manager.evaluate('db.stats()'); + expect(sendEval).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + }, + ); + + it.each([ + 'credentialsUpdating', + 'credentialsChanged', + 'identityChanged', + 'userDisconnected', + 'connectionRemoved', + 'unreachable', + ] as const)('blocks %s before endpoint reads, initialization and evaluation', async (reason): Promise => { + ClustersClient.latch(clusterId, reason); + expect(manager.getBlockingLatchReason()).toBe(reason); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason }); + expect(reread).not.toHaveBeenCalled(); + expect(ensureWorker()).not.toHaveBeenCalled(); + expect(sendEval).not.toHaveBeenCalled(); + }); + + it.each([ + [undefined, 'connectionRemoved'], + ['mongodb://other-host/test', 'credentialsChanged'], + ] as const)('blocks endpoint %s before worker initialization', async (current, reason): Promise => { + reread.mockResolvedValue(current); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + expect(ensureWorker()).not.toHaveBeenCalled(); + }); + + it.each([ + [undefined, 'connectionRemoved'], + ['mongodb://other-host/test', 'credentialsChanged'], + ] as const)( + 'blocks endpoint %s changed during worker initialization', + async (current, reason): Promise => { + reread.mockResolvedValueOnce(endpoint).mockResolvedValueOnce(current); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + expect(manager.isInitialized).toBe(false); + }, + ); + + it.each(['endpointRead', 'workerInitialization'] as const)( + 'honors a superseding epoch during %s', + async (phase): Promise => { + let epoch = 0; + vi.spyOn(ClustersClient, 'getEpoch').mockImplementation(() => epoch); + const changeEpoch = async (): Promise => { + epoch++; + return endpoint; + }; + if (phase === 'endpointRead') { + reread.mockImplementationOnce(changeEpoch); + } else { + ensureWorker().mockImplementationOnce(changeEpoch); + } + await expect(manager.initialize()).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(manager.isInitialized).toBe(false); + }, + ); + + it.each(['credentialsUpdating', 'userDisconnected', 'connectionRemoved'] as const)( + 'honors %s introduced while awaiting the endpoint', + async (reason): Promise => { + reread.mockImplementationOnce(async (): Promise => { + ClustersClient.latch(clusterId, reason); + return endpoint; + }); + await expect(manager.initialize()).rejects.toMatchObject({ reason }); + expect(ensureWorker()).not.toHaveBeenCalled(); + }, + ); + + it('does not finish or respawn a disposed session', async (): Promise => { + reread.mockImplementationOnce(async (): Promise => { + manager.dispose(); + return endpoint; + }); + await expect(manager.initialize()).rejects.toMatchObject({ reason: 'connectionRemoved' }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason: 'connectionRemoved' }); + expect(ensureWorker()).not.toHaveBeenCalled(); + }); + + it('permits password-only edits on respawn but never switches endpoints', async (): Promise => { + await manager.initialize(); + manager.killWorker(); + reread.mockResolvedValue( + toUnauthenticatedConnectionString( + 'mongodb://user:new-password@localhost:27017/test?tls=true&tlsCAFile=trust.pem&authSource=admin', + ), + ); + await manager.evaluate('password-edit'); + manager.killWorker(); + reread.mockResolvedValue('mongodb://other-host/'); + await expect(manager.evaluate('changed-host')).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(sendEval).toHaveBeenCalledOnce(); + }); + + it('surfaces anonymous database rejection without replay or authenticated fallback', async (): Promise => { + const rejection = Object.assign(new Error('Command requires authentication'), { code: 13 }); + await manager.initialize(); + sendEval.mockRejectedValueOnce(rejection); + await expect(manager.evaluate('db.stats()')).rejects.toBe(rejection); + expect(sendEval).toHaveBeenCalledOnce(); + expect(ensureWorker()).toHaveBeenCalledOnce(); + }); + + it('rejects a reply superseded by Disconnect', async (): Promise => { + await manager.initialize(); + sendEval.mockImplementationOnce(async (): Promise => { + ClustersClient.latch(clusterId, 'userDisconnected'); + return { result: { type: 'number', printable: '1', durationMs: 0 } }; + }); + await expect(manager.evaluate('db.stats()')).rejects.toMatchObject({ reason: 'userDisconnected' }); + }); + }); + + it('keeps ordinary Shell initialization authenticated with the saved native credentials', async (): Promise => { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.NativeAuth, + 'mongodb://native.example.com/?tls=true', + { connectionUser: 'saved-user', connectionPassword: 'saved-password' }, + ); + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + const worker = vi.mocked(WorkerSessionManager).mock.results.at(-1)?.value as { ensureWorker: Mock }; + await expect(manager.initialize()).resolves.toMatchObject({ + authMechanism: 'NativeAuth', + username: 'saved-user', + }); + expect(worker.ensureWorker.mock.calls[0][1]).toMatchObject({ + authMechanism: 'NativeAuth', + connectionString: 'mongodb://saved-user:saved-password@native.example.com/?tls=true', + }); + manager.dispose(); + }); + it('permits a password-only respawn but blocks a username change', async (): Promise => { const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); const setNative = (connectionUser: string, connectionPassword: string): void => diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index a618bf397..88cccc227 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -7,6 +7,7 @@ import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import type * as vscode from 'vscode'; import { ext } from '../../extensionVariables'; +import { type EmulatorConfiguration } from '../../utils/emulatorConfiguration'; import { getBatchSizeSetting, getConnectionTimeoutMs } from '../../utils/workspacUtils'; import { type VerifiedEntraIdentity } from '../auth/AuthHandler'; import { AuthMethodId } from '../auth/AuthMethodId'; @@ -14,7 +15,11 @@ import { EntraIdentityMismatchError } from '../auth/entraErrors/entraCallbackErr import { createWorkerAuthError, sameEntraIdentity, WorkerTokenRelay } from '../auth/WorkerTokenRelay'; import { ClustersClient } from '../ClustersClient'; import { computeConnectionFingerprint } from '../connectionFingerprint'; -import { ConnectionUnavailableError } from '../ConnectionUnavailableError'; +import { + ConnectionUnavailableError, + isDiagnosticAuthenticationHold, + type ConnectionUnavailableReason, +} from '../ConnectionUnavailableError'; import { CredentialCache } from '../CredentialCache'; import { WorkerSessionManager, @@ -43,6 +48,12 @@ export interface ShellConnectionInfo { readonly databaseName: string; } +export interface UnauthenticatedShellEndpoint { + readonly connectionString: string; + readonly emulatorConfiguration?: EmulatorConfiguration; + readonly reread: () => Promise; +} + /** * Connection metadata returned after successful initialization. * Used by the PTY to display connection summary in the terminal. @@ -110,6 +121,7 @@ export class ShellSessionManager implements vscode.Disposable { connectionInfo: ShellConnectionInfo, callbacks?: ShellSessionCallbacks, private readonly _telemetryContext: WorkerStartupTelemetryContext = {}, + private readonly _unauthenticated?: UnauthenticatedShellEndpoint, ) { this._connectionInfo = connectionInfo; this._activeDatabase = connectionInfo.databaseName; @@ -244,7 +256,29 @@ export class ShellSessionManager implements vscode.Disposable { this.assertAuthRecovery(); const { clusterId } = this._connectionInfo; const epoch = ClustersClient.getEpoch(clusterId); - const fingerprint = ClustersClient.getExpectedFingerprint(clusterId, this._pin); + const checkEndpoint = async (): Promise => { + if (!this._unauthenticated) { + return; + } + const current = await this._unauthenticated.reread(); + this.assertConnectionAvailable(); + if (epoch !== ClustersClient.getEpoch(clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + if (current === undefined) { + throw new ConnectionUnavailableError('connectionRemoved'); + } + if (current !== this._unauthenticated.connectionString) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + }; + if (this._unauthenticated) { + await checkEndpoint(); + this.assertConnectionAvailable(); + } + const fingerprint = this._unauthenticated + ? undefined + : ClustersClient.getExpectedFingerprint(clusterId, this._pin); if (this._fingerprint !== undefined && this._fingerprint !== fingerprint) { throw new ConnectionUnavailableError('credentialsChanged'); } @@ -254,28 +288,30 @@ export class ShellSessionManager implements vscode.Disposable { this._workerManager.killWorker(); } this._initialized = false; - this._fingerprint ??= fingerprint; - const verified = ClustersClient.getLastVerifiedIdentity(clusterId); - const pin = this._pin ?? (verified?.kind === 'entra' ? verified : undefined); - if (initMsg.authMechanism === 'MicrosoftEntraID') { - this._pin = pin; + if (!this._unauthenticated) { + this._fingerprint ??= fingerprint; + const verified = ClustersClient.getLastVerifiedIdentity(clusterId); + const pin = this._pin ?? (verified?.kind === 'entra' ? verified : undefined); + if (initMsg.authMechanism === 'MicrosoftEntraID') { + this._pin = pin; + } + this._relay = new WorkerTokenRelay( + clusterId, + initMsg, + epoch, + this._managedIdentityTokenCorrelationId, + initMsg.authMechanism === 'MicrosoftEntraID' ? pin : undefined, + (identity) => { + this._pin = identity; + // The keyed fingerprint stays on the host for reconnect comparisons, not in worker messages. + this._fingerprint ??= computeConnectionFingerprint({ + connectionString: initMsg.connectionString, + principal: identity, + }); + this._displayName = identity.accountLabel || undefined; + }, + ); } - this._relay = new WorkerTokenRelay( - clusterId, - initMsg, - epoch, - this._managedIdentityTokenCorrelationId, - initMsg.authMechanism === 'MicrosoftEntraID' ? pin : undefined, - (identity) => { - this._pin = identity; - // The keyed fingerprint stays on the host for reconnect comparisons, not in worker messages. - this._fingerprint ??= computeConnectionFingerprint({ - connectionString: initMsg.connectionString, - principal: identity, - }); - this._displayName = identity.accountLabel || undefined; - }, - ); } const relay = this._relay; @@ -285,6 +321,7 @@ export class ShellSessionManager implements vscode.Disposable { initMsg, getConnectionTimeoutMs(), this._telemetryContext, + this._unauthenticated !== undefined, ); } catch (error) { if ( @@ -297,6 +334,10 @@ export class ShellSessionManager implements vscode.Disposable { throw error; } this.assertConnectionAvailable(); + if (this._unauthenticated) { + await checkEndpoint(); + this.assertConnectionAvailable(); + } if (relay !== this._relay || epoch !== ClustersClient.getEpoch(clusterId)) { throw new ConnectionUnavailableError('credentialsChanged'); } @@ -320,8 +361,10 @@ export class ShellSessionManager implements vscode.Disposable { // (`disableEmulatorSecurity` without `isEmulator`, design §7), which must not be // mislabeled "(Emulator)" in the banner or inflate the emulator telemetry metric. isEmulator: - CredentialCache.getCredentials(this._connectionInfo.clusterId)?.emulatorConfiguration?.isEmulator ?? - false, + (this._unauthenticated + ? this._unauthenticated.emulatorConfiguration?.isEmulator + : CredentialCache.getCredentials(this._connectionInfo.clusterId)?.emulatorConfiguration + ?.isEmulator) ?? false, username, displayName: this._displayName, }; @@ -362,7 +405,14 @@ export class ShellSessionManager implements vscode.Disposable { const relay = this._relay; const epoch = ClustersClient.getEpoch(this._connectionInfo.clusterId); try { - return (await this._workerManager.sendEval(evalMsg)).result; + const response = await this._workerManager.sendEval(evalMsg); + if (this._unauthenticated) { + this.assertConnectionAvailable(); + if (epoch !== ClustersClient.getEpoch(this._connectionInfo.clusterId)) { + throw new ConnectionUnavailableError('credentialsChanged'); + } + } + return response.result; } catch (error) { if ( relay === this._relay && @@ -405,7 +455,7 @@ export class ShellSessionManager implements vscode.Disposable { } private assertConnectionAvailable(): void { - const reason = ClustersClient.getLatchReason(this._connectionInfo.clusterId); + const reason = this.getBlockingLatchReason(); if (reason) { throw new ConnectionUnavailableError(reason); } @@ -414,7 +464,15 @@ export class ShellSessionManager implements vscode.Disposable { } } + public getBlockingLatchReason(): ConnectionUnavailableReason | undefined { + const reason = ClustersClient.getLatchReason(this._connectionInfo.clusterId); + return this._unauthenticated && isDiagnosticAuthenticationHold(reason) ? undefined : reason; + } + private assertAuthRecovery(): void { + if (this._unauthenticated) { + return; + } const reason = this._authFailure ?? this._workerManager.authFailure; if (this._pin && (reason === 'signInRequired' || reason === 'identityMismatch')) { throw createWorkerAuthError(reason); @@ -424,6 +482,26 @@ export class ShellSessionManager implements vscode.Disposable { // ─── Private: Init message ─────────────────────────────────────────────── private buildInitMessage(): MainToWorkerMessage & { type: 'init' } { + if (this._unauthenticated) { + const { connectionString, emulatorConfiguration } = this._unauthenticated; + const allowInvalidCertificates = resolveAllowInvalidCertificates( + emulatorConfiguration?.disableEmulatorSecurity, + connectionString, + ); + return { + type: 'init', + requestId: '', + connectionString, + databaseName: this._activeDatabase, + authMechanism: 'NoAuth', + persistent: true, + clientOptions: { + serverSelectionTimeoutMS: + emulatorConfiguration?.isEmulator || allowInvalidCertificates ? 4000 : undefined, + tlsAllowInvalidCertificates: allowInvalidCertificates, + }, + }; + } const credentials = CredentialCache.getCredentials(this._connectionInfo.clusterId); if (!credentials) { throw new Error(l10n.t('No credentials found for cluster {0}', this._connectionInfo.clusterId)); diff --git a/src/documentdb/shell/unauthenticatedEndpoint.test.ts b/src/documentdb/shell/unauthenticatedEndpoint.test.ts new file mode 100644 index 000000000..fff620720 --- /dev/null +++ b/src/documentdb/shell/unauthenticatedEndpoint.test.ts @@ -0,0 +1,65 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { describe, expect, it } from 'vitest'; +import { DocumentDBConnectionString } from '../utils/DocumentDBConnectionString'; +import { toUnauthenticatedConnectionString } from './unauthenticatedEndpoint'; + +describe('unauthenticated shell endpoint', () => { + it('removes all spellings of database, proxy and client-certificate authentication', (): void => { + const keys = [ + 'authMechanism', + 'authSource', + 'authMechanismProperties', + 'proxyUsername', + 'proxyPassword', + 'tlsCertificateKeyFile', + 'tlsCertificateKeyFilePassword', + 'sslPEMKeyFile', + 'sslPEMKeyPassword', + 'sslCert', + 'sslCertificateKeyFile', + ]; + const options = keys.flatMap((key) => [`${key}=private`, `${key.toUpperCase()}=private`]).join('&'); + const result = toUnauthenticatedConnectionString(`mongodb://account:password@localhost:27017/db?${options}`); + expect(result).toBe('mongodb://localhost:27017/db'); + }); + + it.each(['mongodb://host-a:27017,host-b:27018/db', 'mongodb+srv://cluster.example.com/db'])( + 'preserves endpoints and server trust options for %s', + (endpoint): void => { + const result = new DocumentDBConnectionString( + toUnauthenticatedConnectionString( + `${endpoint}?tls=true&tlsCAFile=trust.pem&tlsAllowInvalidCertificates=false&tlsAllowInvalidHostnames=false&replicaSet=rs&directConnection=true`, + ), + ); + expect(result.hosts).toEqual(new DocumentDBConnectionString(endpoint).hosts); + expect(result.pathname).toBe('/db'); + expect([...result.searchParams.entries()]).toEqual([ + ['tls', 'true'], + ['tlsCAFile', 'trust.pem'], + ['tlsAllowInvalidCertificates', 'false'], + ['tlsAllowInvalidHostnames', 'false'], + ['replicaSet', 'rs'], + ['directConnection', 'true'], + ]); + }, + ); + + it.each(['mongodb://user:private@', 'mongodb://us[er:private@host/', 'not-a-uri-private'])( + 'discards unsafe constructor errors for %s', + (input): void => { + try { + toUnauthenticatedConnectionString(input); + expect.fail('Expected an invalid endpoint'); + } catch (error) { + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe('Invalid connection string.'); + expect((error as Error).cause).toBeUndefined(); + expect((error as Error).stack).not.toContain(input); + } + }, + ); +}); diff --git a/src/documentdb/shell/unauthenticatedEndpoint.ts b/src/documentdb/shell/unauthenticatedEndpoint.ts new file mode 100644 index 000000000..61636ff23 --- /dev/null +++ b/src/documentdb/shell/unauthenticatedEndpoint.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as l10n from '@vscode/l10n'; +import { DocumentDBConnectionString } from '../utils/DocumentDBConnectionString'; + +export function toUnauthenticatedConnectionString(connectionString: string): string { + let endpoint: DocumentDBConnectionString; + try { + endpoint = new DocumentDBConnectionString(connectionString); + } catch { + throw new Error(l10n.t('Invalid connection string.')); + } + endpoint.password = ''; + endpoint.username = ''; + const authenticationOptions = new Set([ + 'authmechanism', + 'authsource', + 'authmechanismproperties', + 'proxyusername', + 'proxypassword', + 'tlscertificatekeyfile', + 'tlscertificatekeyfilepassword', + 'sslpemkeyfile', + 'sslpemkeypassword', + 'sslcert', + 'sslcertificatekeyfile', + ]); + const keys = [...endpoint.searchParams.keys()].filter((key) => authenticationOptions.has(key.toLowerCase())); + for (const key of keys) { + endpoint.searchParams.delete(key); + } + return endpoint.toString(); +} diff --git a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.test.ts b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.test.ts new file mode 100644 index 000000000..ffc1e2da0 --- /dev/null +++ b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.test.ts @@ -0,0 +1,270 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { type AzureSubscription } from '@microsoft/vscode-azureresources-api'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../../../documentdb/ClustersClient'; +import { CredentialCache, type CachedClusterCredentials } from '../../../../documentdb/CredentialCache'; +import * as unauthenticatedEndpoint from '../../../../documentdb/shell/unauthenticatedEndpoint'; +import { showClusterConnectFailure } from '../../../../documentdb/showClusterConnectFailure'; +import { DocumentDBConnectionString } from '../../../../documentdb/utils/DocumentDBConnectionString'; +import { Views } from '../../../../documentdb/Views'; +import { type AuthenticateWizardContext } from '../../../../documentdb/wizards/authenticate/AuthenticateWizardContext'; +import { DocumentDBExperience } from '../../../../DocumentDBExperiences'; +import { type TreeCluster } from '../../../../tree/models/BaseClusterModel'; +import { AzureVMResourceItem, type VirtualMachineModel } from './AzureVMResourceItem'; + +const prompts = vi.hoisted(() => ({ + port: vi.fn(), + credentials: vi.fn<(context: AuthenticateWizardContext) => Promise>(), +})); + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => { + const actual = await importOriginal>(); + return { + ...actual, + AzureWizard: class { + public constructor(private readonly context: AuthenticateWizardContext) {} + + public async prompt(): Promise { + await prompts.credentials(this.context); + } + }, + callWithTelemetryAndErrorHandling: vi.fn( + async (_name: string, callback: (context: IActionContext) => Promise): Promise => { + const context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + valuesToMask: [], + ui: { showInputBox: prompts.port }, + } as unknown as IActionContext; + try { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow) { + throw error; + } + return undefined; + } + }, + ), + }; +}); + +vi.mock('../../../../documentdb/ClustersClient', () => ({ + addEstablishedConnectionContext: vi.fn(), + ClustersClient: { + connectInteractive: vi.fn(), + exists: vi.fn(() => false), + getExistingClient: vi.fn(), + getEpoch: vi.fn(() => 0), + getLatchReason: vi.fn(), + getLastVerifiedIdentity: vi.fn(), + deleteClient: vi.fn(), + }, +})); + +vi.mock('../../../../documentdb/showClusterConnectFailure', () => ({ + showClusterConnectFailure: vi.fn(), +})); + +vi.mock('../../../../extensionVariables', () => ({ + ext: { + outputChannel: { append: vi.fn(), appendLine: vi.fn(), debug: vi.fn() }, + }, +})); + +class TestAzureVMResourceItem extends AzureVMResourceItem { + public override authenticateAndConnect(): Promise { + return super.authenticateAndConnect(); + } +} + +const subscription = { subscriptionId: 'sub', tenantId: 'tenant' } as unknown as AzureSubscription; +const clusterId = 'azure-vm_vm'; + +function item(connectionString: string = 'mongodb://vm.example:27017/'): TestAzureVMResourceItem { + return new TestAzureVMResourceItem('journey', subscription, { + name: 'vm', + treeId: 'discovery/vm', + clusterId, + dbExperience: DocumentDBExperience, + viewId: Views.DiscoveryView, + azureResourceId: '/subscriptions/sub/vm', + connectionString, + fqdn: 'vm.example', + } as TreeCluster); +} + +describe('Azure VM attempted unauthenticated endpoint', (): void => { + beforeEach((): void => { + vi.clearAllMocks(); + CredentialCache.deleteCredentials(clusterId); + vi.spyOn(console, 'warn').mockImplementation((): void => {}); + prompts.port.mockReset().mockResolvedValue('27017'); + prompts.credentials.mockReset().mockImplementation(async (context): Promise => { + context.selectedUserName = 'entered-user'; + context.password = 'entered-password'; + }); + vi.mocked(ClustersClient.connectInteractive).mockReset().mockRejectedValue(new Error('Connection refused')); + vi.mocked(vscode.window.showInputBox).mockReset(); + }); + + afterEach((): void => { + CredentialCache.deleteCredentials(clusterId); + vi.restoreAllMocks(); + }); + + it.each(['27017', '10260'])( + 'retains the actually attempted port %s after failure evicts credentials', + async (port): Promise => { + const vm = item(); + prompts.port.mockResolvedValue(port); + let endpointAtConnect: string | undefined; + let credentialsAtConnect: CachedClusterCredentials | undefined; + vi.mocked(ClustersClient.connectInteractive).mockImplementationOnce(async (): Promise => { + endpointAtConnect = await vm.getUnauthenticatedEndpoint(); + credentialsAtConnect = CredentialCache.getCredentials(clusterId); + throw new Error('Connection refused'); + }); + + await expect(vm.authenticateAndConnect()).resolves.toBeNull(); + expect(endpointAtConnect).toBe(`mongodb://vm.example:${port}/`); + expect(credentialsAtConnect).toMatchObject({ + connectionString: `mongodb://entered-user@vm.example:${port}/`, + nativeAuthConfig: { connectionUser: 'entered-user', connectionPassword: 'entered-password' }, + }); + expect(ClustersClient.connectInteractive).toHaveBeenCalledOnce(); + expect(showClusterConnectFailure).toHaveBeenCalledOnce(); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + + const cacheRead = vi.spyOn(CredentialCache, 'getCredentials'); + const cachePasswordRead = vi.spyOn(CredentialCache, 'getConnectionStringWithPassword'); + const credentialsRead = vi.spyOn(vm, 'getCredentials'); + const diagnosticsRead = vi.spyOn(vm, 'getCredentialsForDiagnostics'); + prompts.port.mockClear(); + prompts.credentials.mockClear(); + vi.mocked(ClustersClient.connectInteractive).mockClear(); + + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBe(`mongodb://vm.example:${port}/`); + + expect(cacheRead).not.toHaveBeenCalled(); + expect(cachePasswordRead).not.toHaveBeenCalled(); + expect(credentialsRead).not.toHaveBeenCalled(); + expect(diagnosticsRead).not.toHaveBeenCalled(); + expect(prompts.port).not.toHaveBeenCalled(); + expect(prompts.credentials).not.toHaveBeenCalled(); + expect(vscode.window.showInputBox).not.toHaveBeenCalled(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + }, + ); + + it('re-reads a later connection attempt rather than freezing the first port', async (): Promise => { + const vm = item(); + const reread = (): Promise => vm.getUnauthenticatedEndpoint(); + prompts.port.mockResolvedValueOnce('10260').mockResolvedValueOnce('27500'); + + await vm.authenticateAndConnect(); + await expect(reread()).resolves.toBe('mongodb://vm.example:10260/'); + await vm.authenticateAndConnect(); + await expect(reread()).resolves.toBe('mongodb://vm.example:27500/'); + expect(vm.cluster.connectionString).toBe('mongodb://vm.example:27017/'); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + }); + + it('fails closed for a new or recreated node even when the model and cache have endpoints', async (): Promise => { + const attempted = item(); + prompts.port.mockResolvedValue('10260'); + await attempted.authenticateAndConnect(); + await expect(attempted.getUnauthenticatedEndpoint()).resolves.toBe('mongodb://vm.example:10260/'); + CredentialCache.setCredentials(clusterId, 'mongodb://cached.example:27500/', 'cached-user', 'cached-password'); + const recreated = item(); + const cacheRead = vi.spyOn(CredentialCache, 'getCredentials'); + const credentialsRead = vi.spyOn(recreated, 'getCredentials'); + prompts.port.mockClear(); + prompts.credentials.mockClear(); + vi.mocked(ClustersClient.connectInteractive).mockClear(); + + await expect(recreated.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + + expect(cacheRead).not.toHaveBeenCalled(); + expect(credentialsRead).not.toHaveBeenCalled(); + expect(prompts.port).not.toHaveBeenCalled(); + expect(prompts.credentials).not.toHaveBeenCalled(); + expect(vscode.window.showInputBox).not.toHaveBeenCalled(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + }); + + it('strips original and prompted credentials and authentication options but preserves transport settings', async (): Promise => { + const vm = item( + 'mongodb://original-user:original-password@vm.example:27017/db?' + + 'authMechanism=SCRAM-SHA-256&authSource=admin&authMechanismProperties=private&' + + 'proxyUsername=proxy-user&proxyPassword=proxy-password&tlsCertificateKeyFile=private.pem&' + + 'tlsCertificateKeyFilePassword=private&tls=true&tlsCAFile=trust.pem&directConnection=true', + ); + prompts.port.mockResolvedValue('10260'); + + await vm.authenticateAndConnect(); + + const endpoint = await vm.getUnauthenticatedEndpoint(); + expect(endpoint).toBe('mongodb://vm.example:10260/db?tls=true&tlsCAFile=trust.pem&directConnection=true'); + const parsed = new DocumentDBConnectionString(endpoint ?? ''); + expect(parsed.username).toBe(''); + expect(parsed.password).toBe(''); + }); + + it('does not record a port when the credential wizard stops before connecting', async (): Promise => { + const vm = item(); + prompts.port.mockResolvedValue('10260'); + prompts.credentials.mockImplementationOnce(async (context): Promise => { + context.aborted = true; + }); + + await expect(vm.authenticateAndConnect()).resolves.toBeNull(); + + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + }); + + it('does not record or replace an endpoint from a diagnostics-only port prompt', async (): Promise => { + const vm = item(); + vi.mocked(vscode.window.showInputBox).mockResolvedValue('27500'); + const read = { signal: new AbortController().signal }; + + await expect(vm.getCredentialsForDiagnostics(read)).resolves.toMatchObject({ + connectionString: 'mongodb://vm.example:27500/', + }); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + + prompts.port.mockResolvedValue('10260'); + await vm.authenticateAndConnect(); + await expect(vm.getCredentialsForDiagnostics(read)).resolves.toMatchObject({ + connectionString: 'mongodb://vm.example:27500/', + }); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBe('mongodb://vm.example:10260/'); + }); + + it('clears the old endpoint and reports a bounded sanitizer failure before starting a client', async (): Promise => { + const vm = item(); + prompts.port.mockResolvedValueOnce('10260').mockResolvedValueOnce('27500'); + await vm.authenticateAndConnect(); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBe('mongodb://vm.example:10260/'); + const error = new Error('Invalid connection string.'); + vi.spyOn(unauthenticatedEndpoint, 'toUnauthenticatedConnectionString').mockImplementationOnce((): never => { + throw error; + }); + + await expect(vm.authenticateAndConnect()).resolves.toBeNull(); + + expect(ClustersClient.connectInteractive).toHaveBeenCalledOnce(); + await expect(vm.getUnauthenticatedEndpoint()).resolves.toBeUndefined(); + expect(showClusterConnectFailure).toHaveBeenLastCalledWith(expect.objectContaining({ error })); + expect(CredentialCache.getCredentials(clusterId)).toBeUndefined(); + expect(ClustersClient.deleteClient).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts index 9b266cb45..e55481234 100644 --- a/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts +++ b/src/plugins/service-azure-vm/discovery-tree/vm/AzureVMResourceItem.ts @@ -15,6 +15,7 @@ import * as vscode from 'vscode'; import { AuthMethodId } from '../../../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../../../documentdb/ClustersClient'; import { CredentialCache } from '../../../../documentdb/CredentialCache'; +import { toUnauthenticatedConnectionString } from '../../../../documentdb/shell/unauthenticatedEndpoint'; import { showClusterConnectFailure } from '../../../../documentdb/showClusterConnectFailure'; import { maskSensitiveValuesInTelemetry } from '../../../../documentdb/utils/connectionStringHelpers'; import { DocumentDBConnectionString } from '../../../../documentdb/utils/DocumentDBConnectionString'; @@ -90,6 +91,8 @@ function sessionPort(connectionString: string | undefined): number | undefined { } export class AzureVMResourceItem extends ClusterItemBase { + private _attemptedEndpoint?: string; + iconPath = new vscode.ThemeIcon('server-environment'); constructor( @@ -140,6 +143,10 @@ export class AzureVMResourceItem extends ClusterItemBase { }); } + public override async getUnauthenticatedEndpoint(): Promise { + return this._attemptedEndpoint; + } + /** * The diagnostics read (decision 0035, refined in WI-16): the VM's discovery data has no port, so * a port the user already entered in this session is reused silently. Otherwise the existing port @@ -314,6 +321,10 @@ export class AzureVMResourceItem extends ClusterItemBase { let clustersClient: ClustersClient; try { + this._attemptedEndpoint = undefined; + this._attemptedEndpoint = toUnauthenticatedConnectionString( + nonNullValue(connectionString, 'connectionString', 'AzureVMResourceItem.ts'), + ); clustersClient = await this.getClientWithProgress(this.cluster.clusterId); } catch (error) { if (error instanceof UserCancelledError) { diff --git a/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts b/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts index 51072e26f..4432b34a4 100644 --- a/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts +++ b/src/tree/connections-view/ConnectionsBranchDataProvider.test.ts @@ -76,14 +76,14 @@ describe('Connections recovery actions', () => { ...(reason ? ['vscode-documentdb.command.connectionsView.updateConnectionString'] : []), 'vscode-documentdb.command.connectionsView.updateCredentials', 'vscode-documentdb.command.diagnoseConnection', - 'vscode-documentdb.command.shell.open', + 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', 'vscode-documentdb.command.internal.retry', ]); expect(treeItems.map((child) => child.label)).toEqual([ ...(reason ? ['Update connection string…'] : []), 'Update credentials…', 'Diagnose connection…', - 'Open shell', + 'Open shell without authentication', 'Retry', ]); expect(treeItems.every((child) => !!child.command)).toBe(true); diff --git a/src/tree/connections-view/DocumentDBClusterItem.test.ts b/src/tree/connections-view/DocumentDBClusterItem.test.ts index 74027545f..7be74551e 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.test.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.test.ts @@ -150,6 +150,28 @@ describe('saved connection destination authentication', () => { ); }); + it.each([StorageZone.Clusters, StorageZone.Emulators])( + 'reads the current %s stored endpoint without preparing or authenticating it', + async (storageZone): Promise => { + const item = makeItem(); + item.cluster.storageZone = storageZone; + item.cluster.connectionString = 'mongodb://stale-model/'; + const getCredentials = vi.spyOn(item, 'getCredentials'); + vi.mocked(ConnectionStorageService.get) + .mockResolvedValueOnce(makeConnection('mongodb://user:password@current-host/')) + .mockResolvedValueOnce(undefined); + expect(await item.getUnauthenticatedEndpoint()).toBe('mongodb://user:password@current-host/'); + expect(await item.getUnauthenticatedEndpoint()).toBeUndefined(); + expect(ConnectionStorageService.get).toHaveBeenCalledWith('stable-id', storageZone); + expect(getCredentials).not.toHaveBeenCalled(); + expect(ConnectionReachabilityService.ensureReachable).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(CredentialCache.setAuthCredentials).not.toHaveBeenCalled(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(ClustersClient.connectInteractive).not.toHaveBeenCalled(); + }, + ); + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( 'reports a forced saved %s rejection without opening a picker or falling back', async (method): Promise => { @@ -318,6 +340,26 @@ describe('connect request telemetry', () => { }); }); + it('does not save the decoded password when the saved-credentials offer is dismissed', async (): Promise => { + const connection = makeConnection('mongodb://localhost:27017/', AuthMethodId.NativeAuth); + connection.secrets.nativeAuthConfig = { connectionUser: 'test-user', connectionPassword: 'test%40password' }; + vi.mocked(ConnectionStorageService.get).mockResolvedValue(connection); + vi.mocked(ClustersClient.connectInteractive) + .mockRejectedValueOnce(new Error('Authentication failed.')) + .mockResolvedValueOnce({ connectionCorrelationId: 'retry' } as ClustersClient); + showErrorMessage.mockResolvedValueOnce('Try with decoded password'); + vi.mocked(vscode.window.showInformationMessage).mockResolvedValueOnce(undefined); + + await expect(makeItem().connect()).resolves.toMatchObject({ connectionCorrelationId: 'retry' }); + + expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( + 'Connected to "Saved connection" using the decoded password. Would you like to update your saved credentials with the correctly formatted password?', + { modal: false }, + 'Update saved password', + ); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + }); + it('reports a successful connection with its connection ID', async (): Promise => { vi.mocked(ClustersClient.connectInteractive).mockResolvedValue({ connectionCorrelationId: 'attempt', diff --git a/src/tree/connections-view/DocumentDBClusterItem.ts b/src/tree/connections-view/DocumentDBClusterItem.ts index df2f60ac1..c3ad4dca3 100644 --- a/src/tree/connections-view/DocumentDBClusterItem.ts +++ b/src/tree/connections-view/DocumentDBClusterItem.ts @@ -54,6 +54,11 @@ export class DocumentDBClusterItem extends ClusterItemBase { + const connection = await ConnectionStorageService.get(this.storageId, resolveStorageZone(this.cluster)); + return connection && isConnection(connection) ? connection.secrets.connectionString : undefined; + } + public async getCredentials(options?: GetCredentialsOptions): Promise { const connectionType = resolveStorageZone(this.cluster); const connectionCredentials = await ConnectionStorageService.get(this.storageId, connectionType); @@ -352,7 +357,7 @@ export class DocumentDBClusterItem extends ClusterItemBase ClustersClientMock.exists.mockReturnValue(false); }); + it('reads only the available model endpoint without authentication or client acquisition', async (): Promise => { + const cluster: TreeCluster = { + ...makeCluster(), + connectionString: 'mongodb://user:password@host/', + }; + const item = new TestClusterItem(cluster, null); + const credentials = vi.spyOn(item, 'getCredentials'); + expect(await item.getUnauthenticatedEndpoint()).toBe(cluster.connectionString); + cluster.connectionString = undefined; + expect(await item.getUnauthenticatedEndpoint()).toBeUndefined(); + expect(credentials).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials).not.toHaveBeenCalled(); + expect(ClustersClientMock.connectInteractive).not.toHaveBeenCalled(); + }); + it('returns a retry node (and records telemetry) when listDatabases is rejected', async () => { const listDatabases = vi .fn() @@ -225,8 +239,8 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => expect(children[1].id).toBe('cluster-1/open-shell'); expect(children[1].contextValue).toBe('error'); - expect(children[1].label).toBe('Open shell'); - expect(children[1].commandId).toBe(ShellCommandIds.open); + expect(children[1].label).toBe('Open shell without authentication'); + expect(children[1].commandId).toBe('vscode-documentdb.command.internal.shell.openWithoutAuthentication'); expect(children[1].commandArgs).toEqual([item]); // The branch data provider detects (and caches) the error state via hasRetryNode(). @@ -243,7 +257,10 @@ describe('ClusterItemBase.getChildren — listDatabases failure handling', () => 'cluster-1/open-shell', 'cluster-1/retry', ]); - expect(children[1]).toMatchObject({ commandId: ShellCommandIds.open, commandArgs: [item] }); + expect(children[1]).toMatchObject({ + commandId: 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', + commandArgs: [item], + }); }); it.each(['authentication', 'listDatabases'] as const)( @@ -727,7 +744,7 @@ describe('ClusterItemBase.getChildren — cached client connection failure handl ]); expect(children.map((child) => (child as TreeElement & { commandId: string }).commandId)).toEqual([ 'vscode-documentdb.command.diagnoseConnection', - 'vscode-documentdb.command.shell.open', + 'vscode-documentdb.command.internal.shell.openWithoutAuthentication', 'vscode-documentdb.command.internal.retry', ]); }); diff --git a/src/tree/documentdb/ClusterItemBase.ts b/src/tree/documentdb/ClusterItemBase.ts index 1d4ccaeeb..8a458e698 100644 --- a/src/tree/documentdb/ClusterItemBase.ts +++ b/src/tree/documentdb/ClusterItemBase.ts @@ -29,7 +29,6 @@ import { import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { isEntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; import { classifyConnectionFailure, type ConnectionFailure } from '../../documentdb/connectionFailures'; -import { ShellCommandIds } from '../../documentdb/shell/constants'; import { showClusterConnectFailure } from '../../documentdb/showClusterConnectFailure'; import { ext } from '../../extensionVariables'; import { SettingsService } from '../../services/SettingsService'; @@ -223,6 +222,10 @@ export abstract class ClusterItemBase; + public async getUnauthenticatedEndpoint(): Promise { + return this.cluster.connectionString; + } + /** * Reads the connection details for connection diagnostics: no UI, no tunnels, typed * failures (see `diagnosticCredentialRead.ts`). `undefined` means the connection no longer exists. @@ -431,9 +434,9 @@ export abstract class ClusterItemBase { + const actual = await importOriginal>(); + return { ...actual, registerCommand: vi.fn() }; +}); + +vi.mock('vscode', async (importOriginal) => { + const actual = await importOriginal & { default: Record }>(); + // The shared VS Code mock omits this constructor, which the real parseError uses. + class CancellationError extends Error {} + actual.default.CancellationError = CancellationError; + return { ...actual, CancellationError }; +}); + +vi.mock('../services/errorExplanationService', () => ({ + ErrorExplanationService: { explain: vi.fn() }, +})); + +interface TestNode { + readonly id: string; + readonly cluster?: { readonly clusterId: string }; +} + +const node: TestNode = { id: 'folder/tree-node', cluster: { clusterId: 'stable-cluster' } }; +const explanation = { providerId: 'test-provider', message: 'Check the connection infrastructure.' }; + +function registerHandler( + handler: TreeNodeCommandCallback, +): (context: IActionContext, ...args: unknown[]) => unknown { + registerCommandWithTreeNodeUnwrappingAndDiagnostics('test.databaseAction', handler); + const callback = vi.mocked(registerCommand).mock.calls.at(-1)?.[1]; + if (!callback) { + throw new Error('Command was not registered.'); + } + return callback; +} + +describe('tree command failure feedback', () => { + let context: IActionContext; + + beforeEach(async () => { + vi.clearAllMocks(); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(undefined); + vi.mocked(vscode.window.showErrorMessage).mockResolvedValue(undefined); + context = await createTestActionContext(); + context.errorHandling.suppressDisplay = false; + context.errorHandling.rethrow = true; + }); + + it('passes unwrapped tree selections to the handler and preserves successful results', async () => { + const result = { completed: true }; + const handler = vi.fn(() => result); + const command = registerHandler(handler); + + await expect(command(context, { unwrap: () => node }, [{ unwrap: () => node }])).resolves.toBe(result); + + expect(handler).toHaveBeenCalledExactlyOnceWith(context, node, [node]); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + }); + + it('shows one translated tree modal with separate detail and rethrows the original error', async () => { + const cause = Object.freeze(new Error('Original cause')); + const error: Error = Object.freeze(new Error('Driver failure', { cause })); + const handler = vi.fn(() => { + throw error; + }); + const command = registerHandler(handler); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, { unwrap: () => node }, [{ unwrap: () => node }])).rejects.toBe(error); + + expect(handler).toHaveBeenCalledExactlyOnceWith(context, node, [node]); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error, + }); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(explanation.message, { + modal: true, + detail: 'Driver failure', + }); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.errorHandling.rethrow).toBe(true); + expect(error.cause).toBe(cause); + }); + + it.each([new Error('Presented failure'), 'Presented primitive failure'])( + 'does not duplicate feedback marked for the same error: %#', + async (error) => { + const rejectFailure = vi.fn<() => Promise>().mockRejectedValue(error); + const command = registerHandler(async (actionContext) => { + actionContext.errorHandling.suppressDisplay = true; + await vscode.window.showErrorMessage('Callback feedback.', { modal: true }); + markCommandErrorPresented(actionContext, error); + return rejectFailure(); + }); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error, + }); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Callback feedback.', { + modal: true, + }); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.errorHandling.rethrow).toBe(true); + }, + ); + + it('does not treat suppressDisplay without a presentation marker as feedback ownership', async () => { + const error = new ConnectionUnavailableError('identityChanged'); + const command = registerHandler((actionContext) => { + rethrowBoundCommandUnavailable(actionContext, error); + }); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail: error.message, + }); + expect(context.errorHandling.suppressDisplay).toBe(true); + }); + + it('shows a different error thrown during cleanup after the original error was presented', async () => { + const original = new Error('Original failure'); + const cleanup = new Error('Cleanup failure'); + const failCleanup = (): never => { + throw cleanup; + }; + const command = registerHandler(async (actionContext) => { + try { + throw original; + } catch (error) { + await vscode.window.showErrorMessage('Original callback feedback.', { modal: true }); + markCommandErrorPresented(actionContext, error); + throw error; + } finally { + failCleanup(); + } + }); + + await expect(command(context, node, [node])).rejects.toBe(cleanup); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledTimes(2); + expect(vscode.window.showErrorMessage).toHaveBeenNthCalledWith(2, 'Unable to complete this tree action.', { + modal: true, + detail: cleanup.message, + }); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error: cleanup, + }); + }); + + it.each([ + { error: new Error('Driver failure'), detail: 'Driver failure' }, + { error: { error: { message: 'Structured driver failure' } }, detail: 'Structured driver failure' }, + ])('shows one fallback tree modal with parsed detail: $detail', async ({ error, detail }) => { + const command = registerHandler(vi.fn().mockRejectedValue(error)); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith('Unable to complete this tree action.', { + modal: true, + detail, + }); + expect(vscode.l10n.t).toHaveBeenCalledWith('Unable to complete this tree action.'); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.telemetry.properties.explanationProviderId).toBeUndefined(); + }); + + it('preserves UserFacingError content and details in the tree modal without translating it', async () => { + const cause = new Error('Underlying cause'); + const error = new UserFacingError('Repair the connection.', { cause, details: 'Existing detail.' }); + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith(error.message, { + modal: true, + detail: error.options.details, + }); + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(error.options.cause).toBe(cause); + }); + + it.each(['collectionView', 'clusterDashboard'])( + 'keeps explained %s failures non-modal and passes origin metadata through real unwrapping', + async (view) => { + const error = new Error('Driver failure'); + const metadata = { source: `webview;${view}`, binding: { clusterId: 'stable-cluster' } }; + const handler = vi.fn(() => { + throw error; + }); + const command = registerHandler(handler); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, { unwrap: () => node }, null, metadata)).rejects.toBe(error); + + expect(handler).toHaveBeenCalledExactlyOnceWith(context, node, undefined, metadata); + expect(ErrorExplanationService.explain).toHaveBeenCalledExactlyOnceWith({ + clusterId: node.cluster?.clusterId, + error, + }); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + `${explanation.message} (${error.message})`, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + }, + ); + + it('keeps webview notification behavior for an error marked by its callback', async () => { + const error = new Error('Driver failure'); + const command = registerHandler((actionContext) => { + markCommandErrorPresented(actionContext, error); + throw error; + }); + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + + await expect(command(context, node, null, { source: 'webview;collectionView' })).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + `${explanation.message} (${error.message})`, + ); + expect(context.errorHandling.suppressDisplay).toBe(true); + expect(context.telemetry.properties.explanationProviderId).toBe(explanation.providerId); + }); + + it('keeps unexplained webview failures on the default notification path', async () => { + const error = new Error('Driver failure'); + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, node, null, { source: 'webview;collectionView' })).rejects.toBe(error); + + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + expect(context.errorHandling.rethrow).toBe(true); + }); + + it('keeps webview UserFacingError content and actions on the default notification path', async () => { + const error = new UserFacingError('Existing message.', { details: 'Existing detail.' }); + const buttons = [{ title: 'Existing action', callback: vi.fn(async (): Promise => {}) }]; + context.errorHandling.buttons = buttons; + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, node, null, { source: 'webview;clusterDashboard' })).rejects.toBe(error); + + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + expect(context.errorHandling.buttons).toBe(buttons); + expect(error.message).toBe('Existing message.'); + expect(error.options.details).toBe('Existing detail.'); + }); + + it.each([new Error('Unassociated failure'), new UserFacingError('Unassociated user-facing failure')])( + 'keeps failures with no associated cluster on the default path: $message', + async (error) => { + const command = registerHandler(() => { + throw error; + }); + + await expect(command(context, { id: 'no-cluster' }, [])).rejects.toBe(error); + + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(false); + }, + ); + + it.each([ + { error: new UserCancelledError(), suppressDisplay: false }, + { error: new UserCancelledError(), suppressDisplay: true }, + { + error: { _isUserCancelledError: true, message: 'Cancelled by another package copy.' }, + suppressDisplay: false, + }, + ])('rethrows cancellation silently without changing suppression: %#', async ({ error, suppressDisplay }) => { + context.errorHandling.suppressDisplay = suppressDisplay; + vi.mocked(ErrorExplanationService.explain).mockResolvedValue(explanation); + const command = registerHandler(vi.fn().mockRejectedValue(error)); + + await expect(command(context, node, [node])).rejects.toBe(error); + + expect(ErrorExplanationService.explain).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(context.errorHandling.suppressDisplay).toBe(suppressDisplay); + expect(context.errorHandling.rethrow).toBe(true); + }); +}); diff --git a/src/utils/commandErrorHandling.ts b/src/utils/commandErrorHandling.ts index 5e201349e..91fe0e919 100644 --- a/src/utils/commandErrorHandling.ts +++ b/src/utils/commandErrorHandling.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { + parseError, registerCommand, type CommandCallback, type IActionContext, @@ -13,6 +14,12 @@ import { unwrapArgs } from '@microsoft/vscode-azureresources-api'; import * as vscode from 'vscode'; import { ErrorExplanationService } from '../services/errorExplanationService'; +const presentedCommandErrors = new WeakMap(); + +export function markCommandErrorPresented(context: IActionContext, error: unknown): void { + presentedCommandErrors.set(context, error); +} + /** * UserFacingError represents an error that should be prominently displayed to the user * in a modal dialog rather than a notification. Use this for critical errors that @@ -101,14 +108,20 @@ export function registerCommandWithModalErrors( ); } +function isWebviewInvocation(args: unknown[]): boolean { + const metadata = args[2]; + return ( + typeof metadata === 'object' && + metadata !== null && + 'source' in metadata && + typeof metadata.source === 'string' && + metadata.source.startsWith('webview;') + ); +} + /** - * Registers a tree-node command that explains infrastructure-caused failures, without changing how - * anything else is reported. - * - * Separate from {@link registerCommandWithTreeNodeUnwrappingAndModalErrors}: the database commands - * (create, drop, import, export, index) report their failures as notifications today, and a - * explanation is not a reason to start blocking the user with a modal. Only the wording changes, and - * only when a provider recognises the cluster. + * Registers a tree-node command that explains infrastructure-caused failures. Tree-origin failures + * associated with a cluster use a modal; shared webview calls retain their notification behavior. * * @param commandId The command ID to register * @param callback The command handler function that expects unwrapped tree node arguments @@ -124,22 +137,48 @@ export function registerCommandWithTreeNodeUnwrappingAndDiagnostics( registerCommand( commandId, async (context: IActionContext, ...args: unknown[]) => { + const webviewInvocation = isWebviewInvocation(args); let unwrappedArgs: ReturnType> = []; try { unwrappedArgs = unwrapArgs(args); return await callback(context, ...unwrappedArgs); } catch (error) { - // A UserFacingError already says what it needs to; leave it to default handling. + const presented = presentedCommandErrors.has(context) && presentedCommandErrors.get(context) === error; + const clusterId = (unwrappedArgs[0] as unknown as { cluster?: { clusterId?: string } } | undefined) + ?.cluster?.clusterId; + const treeError = !webviewInvocation && clusterId ? parseError(error) : undefined; + if (treeError?.isUserCancelledError) { + throw error; + } + if (error instanceof UserFacingError) { + if (treeError) { + context.errorHandling.suppressDisplay = true; + if (!presented) { + await vscode.window.showErrorMessage(error.message, { + modal: true, + detail: error.options.details, + }); + } + } throw error; } - const clusterId = (unwrappedArgs[0] as unknown as { cluster?: { clusterId?: string } } | undefined) - ?.cluster?.clusterId; const explanation = clusterId ? await ErrorExplanationService.explain({ clusterId, error }) : undefined; if (explanation) { context.telemetry.properties.explanationProviderId = explanation.providerId; + } + + if (treeError) { + context.errorHandling.suppressDisplay = true; + if (!presented) { + await vscode.window.showErrorMessage( + explanation?.message ?? vscode.l10n.t('Unable to complete this tree action.'), + { modal: true, detail: treeError.message }, + ); + } + } else if (explanation) { context.errorHandling.suppressDisplay = true; // `detail` is only rendered for modal messages, so the raw text is appended. const cause = error instanceof Error ? error.message : String(error); diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx index 6957636bd..099ad97c1 100644 --- a/src/webviews/components/DisconnectedOverlay.test.tsx +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -7,7 +7,7 @@ import { act } from 'react'; import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules -import { expect, it, vi } from 'vitest'; +import { beforeEach, expect, it, vi } from 'vitest'; import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; import { DisconnectedOverlay } from './DisconnectedOverlay'; @@ -18,6 +18,10 @@ vi.mock('../_integration/useTrpcClient', () => ({ useTrpcClient: () => ({ common: { confirm: { mutate: confirm } } }), })); +beforeEach((): void => { + confirm.mockReset(); +}); + it('dismisses without closing, and only closes a dirty view after confirmation', async (): Promise => { const unavailable: ConnectionUnavailableDetails = { reason: 'signInRequired', @@ -69,7 +73,9 @@ it('dismisses without closing, and only closes a dirty view after confirmation', expect(onAction).not.toHaveBeenCalled(); expect(dialog()).not.toBeNull(); await act(async () => - dialog()?.querySelector('button[aria-label^="Dismiss dialog"]')?.click(), + dialog() + ?.querySelector('button[aria-label="Dismiss dialog to access view contents"]') + ?.click(), ); expect(onDismiss).toHaveBeenCalledOnce(); expect(confirm).not.toHaveBeenCalled(); @@ -116,3 +122,102 @@ it('dismisses without closing, and only closes a dirty view after confirmation', host.remove(); } }); + +it('announces retry failure and restores dialog controls', async (): Promise => { + const unavailable: ConnectionUnavailableDetails = { + reason: 'userDisconnected', + title: 'Disconnected', + detail: 'Connect from the connection tree, then click Retry.', + action: 'retry', + }; + const retryFailure = 'Unable to recover the connection. Try Retry again, or close this view.'; + const onAction = vi.fn(); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + const render = async (recovering: boolean, failure?: string): Promise => { + await act(async () => + root.render( + undefined} + recovering={recovering} + retryFailure={failure} + > +