diff --git a/.github/skills/tree-cluster-architecture/SKILL.md b/.github/skills/tree-cluster-architecture/SKILL.md index 02725fa12..739d5def2 100644 --- a/.github/skills/tree-cluster-architecture/SKILL.md +++ b/.github/skills/tree-cluster-architecture/SKILL.md @@ -66,17 +66,28 @@ Rules: ## Connection Binding Contract A long-lived surface binds to `{ clusterId, fingerprint, generation }`, not to a `ClustersClient` -instance. Resolve the client for every operation through the binding with +instance. Resolve the client for every operation through that shared binding with `ClustersClient.resolveBoundClient()` or `runWithClient()`. Never retain a `ClustersClient` in view, router, shell, playground, task, or clipboard state. -- A new generation with the same fingerprint is a transparent same-connection replacement. +- A normal replacement advances the physical client generation while keeping the fingerprint. + An operation bound to the old generation must not attribute its late failure to the replacement, + but a later explicit operation may use the replacement for the same identity. +- Explicit Disconnect, Remove or Disconnect-before-update retires the logical host lifetime once. + That cutoff is one-way: same-account `Reconnect` creates a new live session but does not revive + retained views or canceled handoffs from the retired lifetime. - A different fingerprint is an identity or settings change. Never rebind an existing surface. -- Check latches and the binding again at operation and async-reply boundaries. +- Use one shared per-operation resolution path. Assert binding/latch state after client resolution, + and capture the originating lifetime or cancellation signal across async handoffs. Check it + again immediately before external side effects, replies and Playground/model sends. - An operation may hold the resolved client only for the duration of that operation. A stale reply must not mutate the new connection or replay a failed write. -- 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. +- Shell and Playground workers may keep their own connection, but pin the originating identity and + use equivalent renewal, cancellation and lifetime checks when they respawn. +- Ordinary token, sign-in or network repair is not retirement. Keep the same tab usable and show + an actionable error for a failed operation; require no Retry-to-unlock step and no automatic + replay. A retained tab after explicit teardown is permanently read-only: dismissing its notice + exposes only copyable contents, and closing it requires the normal dirty confirmation. 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 @@ -241,7 +252,9 @@ Before approving a cluster tree change, answer yes to all: - [ ] `clusterId`, `treeId`, and `viewId` have documented owners. - [ ] Credentials and clients use `clusterId` only. - [ ] Long-lived surfaces retain bindings, not `ClustersClient` instances. -- [ ] Per-operation resolution checks the fingerprint and generation. +- [ ] Normal same-fingerprint generation replacement remains separate from one-way lifetime retirement. +- [ ] Per-operation resolution uses the shared path and checks the binding after resolution. +- [ ] Async handoffs fence external side effects with the captured lifetime or cancellation. - [ ] Every rendered layout has a reverse lookup strategy. - [ ] Cluster and collection lookup share one resolver. - [ ] Synthetic ownership is exact and isolated from stored lookup. diff --git a/build/verification/browser/scenarios.test.ts b/build/verification/browser/scenarios.test.ts index 0817b91d3..714139ecb 100644 --- a/build/verification/browser/scenarios.test.ts +++ b/build/verification/browser/scenarios.test.ts @@ -32,8 +32,8 @@ describe('L2-dev manifest and routes', (): void => { it('round-trips every scenario and theme, without duplicate routes', (): void => { const routes = scenarioRoutes(); - expect(routes).toHaveLength(186); - expect(new Set(routes.map((route): string => route.path)).size).toBe(186); + expect(routes).toHaveLength(189); + expect(new Set(routes.map((route): string => route.path)).size).toBe(189); for (const route of routes) expect(parseScenarioRoute(route.path)).toEqual(route); }); @@ -71,7 +71,7 @@ describe('L2-dev manifest and routes', (): void => { }); it('provides path-only all/view/theme helpers and rejects unknown subsets', (): void => { - expect(runnerRoutes('/scenarios/run-all.js')).toHaveLength(186); + expect(runnerRoutes('/scenarios/run-all.js')).toHaveLength(189); expect(runnerRoutes('/scenarios/run-all/connectionDiagnostics.js')).toHaveLength(84); expect(runnerRoutes('/scenarios/run-all/localQuickStart.js')).toHaveLength(75); expect(runnerRoutes('/scenarios/run-all/localQuickStart/dark.js')).toHaveLength(25); diff --git a/build/verification/browser/scenarios.ts b/build/verification/browser/scenarios.ts index 6efcce13d..dc4ab2b9b 100644 --- a/build/verification/browser/scenarios.ts +++ b/build/verification/browser/scenarios.ts @@ -2435,8 +2435,7 @@ const saveDocumentPath = 'mongoClusters.documentView.saveDocument'; const disconnectedDocument = { reason: 'userDisconnected', title: 'Disconnected', - detail: 'Reconnect from the connection tree, then click Retry.', - action: 'retry', + detail: 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', } as const; const documentEditorName = 'Document Editor: Edit the document in JSON format'; const firstDocumentEdit = { @@ -2489,37 +2488,33 @@ const documentViewScenarios = { holdReply: true, results: [{ documentId: '"stage0-1"', documentStringified: '{"name":"Old save reply"}' }], }, - 'mongoClusters.documentView.recoverUnavailable': { + 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, + 'mongoClusters.documentView.closeView': { type: 'mutation', - results: [{ recovered: { text: 'Reconnected' } }], + results: [], + undefinedResult: true, }, - 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, }, assertions: [ { kind: 'attribute', - name: 'recovery does not discard the editor', + name: 'a terminal notice preserves the editor and its draft', selector: '.disconnectedOverlayBackground', attribute: 'inert', expected: null, steps: [ firstDocumentEdit, saveDocumentStep, + { + ...firstDocumentEdit, + value: '{"_id":"stage0-1","name":"Newer unsaved edit"}', + }, { action: 'post', name: 'disable Document View', message: { type: 'documentView.connectionUnavailable', unavailable: disconnectedDocument }, }, - { action: 'click', role: 'button', name: 'Retry' }, - { - action: 'waitFor', - name: 'the editor to be enabled after reconnect', - selector: '.disconnectedOverlayBackground:not([inert])', - }, - { - ...firstDocumentEdit, - value: '{"_id":"stage0-1","name":"Newer unsaved edit"}', - }, + { action: 'click', role: 'button', name: 'Dismiss notice' }, ], }, { @@ -2530,10 +2525,26 @@ const documentViewScenarios = { }, { kind: 'attribute', - name: 'the newer edit stays dirty and can be saved', + name: 'the newer edit stays dirty and terminal Save stays disabled', selector: 'button[aria-label="Save to the database"]', attribute: 'disabled', - expected: null, + expected: '', + }, + { + kind: 'calls', + name: 'the terminal tab never calls recovery or submits the newer draft', + path: saveDocumentPath, + count: 1, + checkInput: false, + steps: [], + }, + { + kind: 'calls', + name: 'the terminal tab never calls the close RPC without confirmation', + path: 'mongoClusters.documentView.closeView', + count: 0, + checkInput: false, + steps: [], }, ], }, @@ -2541,7 +2552,66 @@ const documentViewScenarios = { const clusterDashboardBase = defaultScenario('clusterDashboard'); const clusterDashboardScenarios = { - default: clusterDashboardBase, + default: { + ...clusterDashboardBase, + assertions: [ + ...(clusterDashboardBase.assertions ?? []), + { + kind: 'text', + name: 'a healthy poll keeps the Dashboard connected', + selector: '.dashboardConnectionStatus', + includes: ['Connected'], + excludes: ['Disconnected'], + }, + ], + }, + 'recoverable-health-polls': { + ...clusterDashboardBase, + config: { ...fixtures.clusterDashboard.config, refreshIntervalMs: 25 }, + readiness: { ...clusterDashboardBase.readiness, content: ['Disconnected'] }, + rpc: { + ...clusterDashboardBase.rpc, + 'clusterDashboard.measureRtt': { + ...fixtures.clusterDashboard.rpc['clusterDashboard.measureRtt'], + afterFirst: { + results: [ + { + unavailable: { + reason: 'unreachable', + title: 'Connection lost', + detail: 'Check the network or server.', + }, + }, + ], + }, + }, + 'common.displayErrorMessage': { type: 'mutation', results: [], undefinedResult: true }, + }, + assertions: [ + { + kind: 'text', + name: 'repeated failures are recorded in the connection status', + selector: '.dashboardConnectionStatus', + includes: ['Disconnected'], + excludes: [], + }, + { + kind: 'attribute', + name: 'recoverable poll failures do not show the terminal notice', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + }, + { + kind: 'calls', + name: 'background recoverable poll failures do not toast', + path: 'common.displayErrorMessage', + count: 0, + checkInput: false, + steps: [], + }, + ], + }, disconnected: { ...clusterDashboardBase, config: { ...fixtures.clusterDashboard.config, refreshIntervalMs: 2000 }, @@ -2552,10 +2622,7 @@ const clusterDashboardScenarios = { ...fixtures.clusterDashboard.rpc['clusterDashboard.measureRtt'], holdReply: true, }, - 'clusterDashboard.recoverUnavailable': { - type: 'mutation', - results: [{ recovered: { text: 'Reconnected' } }], - }, + 'clusterDashboard.closeView': { type: 'mutation', results: [], undefinedResult: true }, }, assertions: [ { @@ -2601,25 +2668,21 @@ const clusterDashboardScenarios = { attribute: 'value', expected: 'stage0', }, + { + kind: 'attribute', + name: 'dismissing the notice exposes the retained inventory for copying only', + selector: '.disconnectedOverlayBackground', + attribute: 'inert', + expected: null, + steps: [{ action: 'click', role: 'button', name: 'Dismiss notice' }], + }, { kind: 'calls', - name: 'tree reconnect resumes the retained Dashboard through Retry', - path: 'clusterDashboard.recoverUnavailable', - count: 1, - checkInput: true, - input: { action: 'retry' }, - steps: [ - { - action: 'post', - name: 'reveal the Dashboard after reconnecting in the tree', - message: { type: 'clusterDashboard.retryAfterReconnect' }, - }, - { - action: 'waitFor', - name: 'Dashboard is enabled again', - selector: '.disconnectedOverlayBackground:not([inert])', - }, - ], + name: 'the retained Dashboard never calls close after reconnect', + path: 'clusterDashboard.closeView', + count: 0, + checkInput: false, + steps: [], }, ], }, @@ -2644,8 +2707,7 @@ const runCollectionQuery = { const collectionSignInRequired = { reason: 'signInRequired', title: 'Sign-in required', - detail: 'Sign in from the connection tree, then click Retry.', - action: 'retry', + detail: 'Sign in from the connection tree.', } as const; const collectionViewScenarios = { default: collectionViewBase, @@ -2657,28 +2719,34 @@ const collectionViewScenarios = { ...fixtures.collectionView.rpc[collectionQueryPath], afterFirst: { results: [{ unavailable: collectionSignInRequired }] }, }, - 'mongoClusters.collectionView.recoverUnavailable': { + 'mongoClusters.collectionView.closeView': { type: 'mutation', - results: [{ recovered: { text: 'Reconnected' } }], + results: [], + undefinedResult: true, }, 'mongoClusters.collectionView.copyQueryToClipboard': { type: 'mutation', results: [null], }, 'common.confirm': { type: 'mutation', results: [{ confirmed: false }] }, + 'common.displayErrorMessage': { type: 'mutation', results: [], undefinedResult: true }, 'common.reportEvent': { type: 'mutation', results: [], undefinedResult: true }, }, assertions: [ { kind: 'attribute', - name: 'keeps the query and results mounted but disables their controls', + name: 'a recoverable failure keeps the same query and controls live', selector: '.disconnectedOverlayBackground', attribute: 'inert', - expected: '', + expected: null, steps: [ collectionFilter, runCollectionQuery, - { action: 'waitFor', name: 'sign-in overlay', selector: '.disconnectedOverlay' }, + { + action: 'waitFor', + name: 'actionable sign-in error reaches the host', + selector: '.collectionView', + }, ], }, { @@ -2688,28 +2756,18 @@ const collectionViewScenarios = { includes: ['"name":"Alpha"'], excludes: [], }, - { - kind: 'text', - name: 'offers Retry and Close view while sign-in stays in the tree', - selector: '.disconnectedOverlay', - includes: ['Sign-in required', 'Sign in from the connection tree, then click Retry.', 'Close view'], - excludes: ['Reconnect', 'Retry sign-in'], - }, { kind: 'calls', - name: 'the query shortcut while disconnected does not run another query', - path: collectionQueryPath, - count: 2, - checkInput: false, - steps: [{ action: 'press', role: 'button', name: 'Retry', key: 'Control+Enter' }], - }, - { - kind: 'attribute', - name: 'dismissing the dialog makes the existing view accessible', - selector: '.disconnectedOverlayBackground', - attribute: 'inert', - expected: null, - steps: [{ action: 'click', role: 'button', name: 'Dismiss dialog to access view contents' }], + name: 'the failed query surfaces one actionable repair error', + path: 'common.displayErrorMessage', + count: 1, + checkInput: true, + input: { + message: 'Sign-in required', + modal: false, + cause: 'Sign in from the connection tree.', + }, + steps: [], }, { kind: 'text', @@ -2728,22 +2786,19 @@ const collectionViewScenarios = { }, { kind: 'calls', - name: 'Find Query after dismissal shows the dialog without submitting another query', + name: 'the next explicit query runs once in the same tab after repair', path: collectionQueryPath, - count: 2, + count: 3, checkInput: false, - steps: [ - runCollectionQuery, - { action: 'waitFor', name: 'sign-in overlay returns', selector: '.disconnectedOverlay' }, - ], + steps: [runCollectionQuery], }, { kind: 'calls', - name: 'Close view requests confirmation through the host', - path: 'common.confirm', - count: 1, + name: 'recoverable failures never call the close RPC', + path: 'mongoClusters.collectionView.closeView', + count: 0, checkInput: false, - steps: [{ action: 'click', role: 'button', name: 'Close view' }], + steps: [], }, ], }, @@ -2791,7 +2846,10 @@ const collectionViewScenarios = { kind: 'text', name: 'the late reply does not change the displayed disconnect reason', selector: '.disconnectedOverlay', - includes: ['Disconnected', 'Retry'], + includes: [ + 'Disconnected', + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + ], excludes: ['Retry sign-in'], }, ], diff --git a/docs/ai-and-plans/README.md b/docs/ai-and-plans/README.md index fe89befb9..6c2120633 100644 --- a/docs/ai-and-plans/README.md +++ b/docs/ai-and-plans/README.md @@ -22,37 +22,37 @@ treat `status: historical` or `status: superseded` as current. ## Features -| Feature | What it covers | Status | -| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ----------------------------------------- | -| [local-quickstart](./features/local-quickstart/README.md) | Run DocumentDB locally in one click: Docker provisioning, readiness, lifecycle | shipped 0.10.0 | -| [query-insights](./features/query-insights/README.md) | Query performance rating, static analysis, and streaming AI recommendations | shipped | -| [interactive-shell](./features/interactive-shell/README.md) | The in-terminal REPL, its runtime, completions, and highlighting | shipped | -| [query-playground](./features/query-playground/README.md) | `.documentdb` files, persistent worker evaluation, per-document connections | shipped | -| [completions-and-schema](./features/completions-and-schema/README.md) | Operator registry, schema analyzer, and the shared completion layer | shipped | -| [index-management](./features/index-management/README.md) | The Indexes tab, the create drawer, and the Collection View chrome redesign | shipped | -| [atlas-discovery](./features/atlas-discovery/README.md) | MongoDB Atlas discovery: Admin API auth, discovery tree, credentials | shipped | -| [kubernetes-discovery](./features/kubernetes-discovery/README.md) | Kubernetes service discovery and connect-time reachability providers | shipped | -| [webview-ext-package](./features/webview-ext-package/README.md) | `@microsoft/vscode-ext-webview`: the extracted webview transport package | published preview | -| [webview-fluentui-package](./features/webview-fluentui-package/README.md) | `@microsoft/vscode-ext-webview-fluentui`: Fluent theming and reusable components for webviews | 1.3.0 prepared | -| [connections-tree](./features/connections-tree/README.md) | The Connections view: node item counts, connection load performance | shipped | -| [no-auth](./features/no-auth/README.md) | Credential-free connections and connection-string TLS handling | shipped | -| [managed-identities](./features/managed-identities/README.md) | Explicit managed identity authentication from Azure VMs | PR #886 | -| [copy-paste-collections](./features/copy-paste-collections/README.md) | Collection copy/paste tasks, document streaming, conflict handling, and optional index copying | active | -| [cluster-dashboard](./features/cluster-dashboard/README.md) | Cluster-wide inventory and resilience facts | POC, unmerged | -| [settings](./features/settings/README.md) | Settings editor grouping, setting ID naming, and how a setting is renamed safely | active | -| [welcome](./features/welcome/README.md) | Welcome walkthrough onboarding and quiet next-session deferral for upgraded installations | active | -| [escaping](./features/escaping/README.md) | Safe rendering of user/database content and least-privilege Markdown tooltips | active | -| [srv-dns-fallback](./features/srv-dns-fallback/README.md) | In-memory SRV fallback for `mongodb+srv://` when c-ares rejects compressed SRV replies (#993) | implemented (manual checks pending) | -| [build-and-test-stack](./features/build-and-test-stack/README.md) | Vite host and webview builds, Vitest, packaged checks, CI tiers, and modernization history | active | -| [e2e-testing](./features/e2e-testing/README.md) | The planned installed-workbench and webview end-to-end test iteration | planned | -| [data-grid](./features/data-grid/README.md) | The Collection View table and tree, including the planned SlickGrid replacement | planned | -| [survey](./features/survey/README.md) | Survey refresh: simpler eligibility, broader activity coverage, cohort telemetry, and invitation surface | draft #992; enabled | -| [docs-site](./features/docs-site/README.md) | The GitHub Pages documentation site: Just the Docs theme, OS dark mode, local preview | draft #420 | -| [pre-release-polish](./features/pre-release-polish/README.md) | Cross-feature visual and documentation refinements prepared for the 1.0 release | active | -| [sovereign-clouds](./features/sovereign-clouds/README.md) | Entra sign-in in Azure Government and China: per-cloud token audience, Entra error classifier | implemented; sovereign checks pending | -| [Diagnose connection](./features/connectivity-troubleshooter/README.md) | Read-only connection diagnosis, a server summary and readable Markdown diagnostics (#100) | implemented; handover blocked on operator | -| [deep-links](./features/deep-links/README.md) | `vscode://` links: action routing, `/connect`, `/local`, `/connect/azure` for Azure portal links | active; iteration 3 implemented | -| [connection-lifecycle](./features/connection-lifecycle/README.md) | Connections that survive token expiry and idle drops; reconnect, disconnect and identity-bound tabs | planned (#1102) | +| Feature | What it covers | Status | +| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | ---------------------------------------------- | +| [local-quickstart](./features/local-quickstart/README.md) | Run DocumentDB locally in one click: Docker provisioning, readiness, lifecycle | shipped 0.10.0 | +| [query-insights](./features/query-insights/README.md) | Query performance rating, static analysis, and streaming AI recommendations | shipped | +| [interactive-shell](./features/interactive-shell/README.md) | The in-terminal REPL, its runtime, completions, and highlighting | shipped | +| [query-playground](./features/query-playground/README.md) | `.documentdb` files, persistent worker evaluation, per-document connections | shipped | +| [completions-and-schema](./features/completions-and-schema/README.md) | Operator registry, schema analyzer, and the shared completion layer | shipped | +| [index-management](./features/index-management/README.md) | The Indexes tab, the create drawer, and the Collection View chrome redesign | shipped | +| [atlas-discovery](./features/atlas-discovery/README.md) | MongoDB Atlas discovery: Admin API auth, discovery tree, credentials | shipped | +| [kubernetes-discovery](./features/kubernetes-discovery/README.md) | Kubernetes service discovery and connect-time reachability providers | shipped | +| [webview-ext-package](./features/webview-ext-package/README.md) | `@microsoft/vscode-ext-webview`: the extracted webview transport package | published preview | +| [webview-fluentui-package](./features/webview-fluentui-package/README.md) | `@microsoft/vscode-ext-webview-fluentui`: Fluent theming and reusable components for webviews | 1.3.0 prepared | +| [connections-tree](./features/connections-tree/README.md) | The Connections view: node item counts, connection load performance | shipped | +| [no-auth](./features/no-auth/README.md) | Credential-free connections and connection-string TLS handling | shipped | +| [managed-identities](./features/managed-identities/README.md) | Explicit managed identity authentication from Azure VMs | PR #886 | +| [copy-paste-collections](./features/copy-paste-collections/README.md) | Collection copy/paste tasks, document streaming, conflict handling, and optional index copying | active | +| [cluster-dashboard](./features/cluster-dashboard/README.md) | Cluster-wide inventory and resilience facts | POC, unmerged | +| [settings](./features/settings/README.md) | Settings editor grouping, setting ID naming, and how a setting is renamed safely | active | +| [welcome](./features/welcome/README.md) | Welcome walkthrough onboarding and quiet next-session deferral for upgraded installations | active | +| [escaping](./features/escaping/README.md) | Safe rendering of user/database content and least-privilege Markdown tooltips | active | +| [srv-dns-fallback](./features/srv-dns-fallback/README.md) | In-memory SRV fallback for `mongodb+srv://` when c-ares rejects compressed SRV replies (#993) | implemented (manual checks pending) | +| [build-and-test-stack](./features/build-and-test-stack/README.md) | Vite host and webview builds, Vitest, packaged checks, CI tiers, and modernization history | active | +| [e2e-testing](./features/e2e-testing/README.md) | The planned installed-workbench and webview end-to-end test iteration | planned | +| [data-grid](./features/data-grid/README.md) | The Collection View table and tree, including the planned SlickGrid replacement | planned | +| [survey](./features/survey/README.md) | Survey refresh: simpler eligibility, broader activity coverage, cohort telemetry, and invitation surface | draft #992; enabled | +| [docs-site](./features/docs-site/README.md) | The GitHub Pages documentation site: Just the Docs theme, OS dark mode, local preview | draft #420 | +| [pre-release-polish](./features/pre-release-polish/README.md) | Cross-feature visual and documentation refinements prepared for the 1.0 release | active | +| [sovereign-clouds](./features/sovereign-clouds/README.md) | Entra sign-in in Azure Government and China: per-cloud token audience, Entra error classifier | implemented; sovereign checks pending | +| [Diagnose connection](./features/connectivity-troubleshooter/README.md) | Read-only connection diagnosis, a server summary and readable Markdown diagnostics (#100) | implemented; handover blocked on operator | +| [deep-links](./features/deep-links/README.md) | `vscode://` links: action routing, `/connect`, `/local`, `/connect/azure` for Azure portal links | active; iteration 3 implemented | +| [connection-lifecycle](./features/connection-lifecycle/README.md) | Renewal, disconnect and identity-bound tabs, including permanently read-only retained views | feature branch; integration/live gates pending | Everything else is a single file at this root, such as: diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 4b3d32647..cfb2e2ea8 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -18,10 +18,11 @@ code: # Connection lifecycle -**Status:** implemented in the feature branch; documentation draft ready; release and final -integration pending. Package P (A2, B2, C-balanced and D2; decisions 0026, 0027, 0029–0031) is -approved but not implemented. Code still has the older edit-while-connected and recoverable-view -Retry behavior · **Issues:** +**Status:** package P (A2, B2, C-balanced and D2; decisions 0026, 0027, 0029–0032) is implemented +in [draft #1149](https://github.com/microsoft/vscode-documentdb/pull/1149), stacked on the feature +branch. Integrated host checks pass; rendered/workbench and live verification remain incomplete. The +[iteration 3 section 6 evidence ledger](./iterations/03-complexity-reduction-analysis.md#6-packages-regenerated-2026-11-30) +records committed slices and remaining verification. **Issues:** - [#1102](https://github.com/microsoft/vscode-documentdb/issues/1102) - [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059) @@ -35,18 +36,25 @@ Retry behavior · **Issues:** **Branch:** `feature/connection-lifecycle`, with stacked sub-PRs from `dev/tnaum/*`. Implementation does not wait for intermediate merges; the operator handles approvals and merges (decision 0006). +**Review follow-up:** [decision 0033](./decisions.md#0033-approve-the-pr1149-review-dispositions-with-explicit-complexity-tradeoffs) +approves nine fixes and three no-code dispositions from the +[PR #1149 review](./iterations/03-pr1149-copilot-review.md). The follow-up fixes are implemented in +[draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154); workbench and live +verification remain incomplete. The accepted C01/C08 exceptions and selected C06/C10 behavior +are reflected in the intent below. + > How database connections stay usable across Entra token expiry, idle drops and credential -> changes, and what open surfaces do when the user must act or the identity changes. +> changes, and what open surfaces do when the user must act or explicitly ends the session. ## Problem -After an hour or more, connections stop working, and only restarting VS Code helps. There are three -defects: +Before this work, connections could stop working after an hour or more and require restarting VS +Code. The original defects were: 1. Interactive Entra ID returns a captured token from the OIDC callback forever. 2. Azure Discovery holds subscriptions whose ARM token is frozen, and the ARM 401 challenge crashes. -3. Nothing evicts or recreates a failed client, Retry reuses it, and Collection View tabs hold the - old instance. +3. Nothing evicted or recreated a failed client, Retry reused it, and Collection View tabs held + the old instance. Evidence, telemetry and source pointers: [research-findings.md](./research-findings.md). @@ -81,23 +89,32 @@ entries are unpublished drafts and do not represent a shipped release. A partial listing shows one warning with a **Show Output** action, and telemetry counts skipped accounts and tenants without identifying them. - **Keep one client per cluster.** Preserve same-identity physical-client replacement and its - internal generation check for late failures. A one-way host lifetime ends on Disconnect; - pending work from the old lifetime must not adopt a later connection. The implementation - currently carries more fingerprint/binding plumbing than the chosen C-balanced design needs. -- **Change identity only while disconnected** (0003, 0026, 0027, 0030). **Update Credentials** and + internal generation check for late failures. Keep the fingerprint and identity checks where + async callers are not yet covered by an equivalent host lifetime. A one-way host lifetime ends + on explicit Disconnect; pending work from that lifetime must not adopt a later connection. +- **Change identity only while disconnected** (0003, 0026, 0027, 0030, 0033). **Update Credentials** and **Update Connection String** offer **Disconnect and update**, perform the ordinary Disconnect - flow, and proceed only after successful teardown. Cancel, a task conflict or teardown failure - must not fall through to editing. Disconnect and Remove Connection still offer Close or Keep - open. A kept view stays open and copyable under a shaded, disabled dialog, but it is permanently - disabled. **X** dismisses the notice so the user can select and copy existing text; **Close - view** closes the tab. Neither restores database access. Open fresh views from the tree. + flow, and explain that edits require a disconnected connection. The command initiating Disconnect + waits for its own teardown; cancellation, a task conflict or failure in that flow does not fall + through to editing. C01's concurrent-edit edge remains accepted: another edit can observe the + disconnected latch before the driver close settles; no additional completion tracking is required + (0033). Disconnect and Remove Connection still offer Close, Keep open + and Cancel. A kept view stays open and copyable under a shaded, disabled dialog, but it is + permanently disabled for database access. **X** dismisses the notice so the user can select and copy existing text; + **Close view** closes the tab. Neither restores database access. Open fresh views from the tree. + Local Collection View query editing after dismissal is accepted at the user's discretion; + C08 does not require additional read-only gates. Document View's existing read-only and dirty + protections remain unchanged (0033). **Sign in again** accepts only the pinned account and tenant. Credential repair stays in the tree. - **Close view** asks for confirmation. On an ordinary recoverable operation failure, show a - translated actionable error; after repairing the cause, the user reruns the operation. Do not - require a separate view-level Retry to unlock it, and never replay a write automatically. - A network drop or same-account tree sign-in does not end the session or freeze its tabs (0032). + **Close view** closes directly unless a dirty Document View needs an unsaved-changes warning. + On an ordinary recoverable operation failure, keep the + tab usable, retain its query, results or draft, and show a translated actionable error. After + repairing the cause, the user explicitly runs the operation again. There is no separate + Retry-to-unlock step and failed writes are never replayed automatically. A network drop or + same-account tree sign-in does not end the session or freeze its tabs (0032). - After an explicit Disconnect, the tree offers **Reconnect**. Views kept open across the - Disconnect do not resume; Reconnect opens nothing in them (0027). + Disconnect do not resume; **Reconnect** creates a new session and does not revive old tabs + (0027, 0032). New live views are opened from the tree. - A pending Dashboard delete confirmation does not survive Disconnect, even when the user reconnects as the same identity. Dashboard **Copy Collection** keeps a tree reference; **Paste Collection** stays in the tree and uses the current connection. @@ -109,27 +126,39 @@ entries are unpublished drafts and do not represent a shipped release. 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 is possible only while the connection is closed (0026, 0030). Enforce this - across asynchronous saves/reconnects; host work already in flight still needs cancellation at - side-effect boundaries. Silent token renewal and a network reconnect for the unchanged identity - remain supported. Worker pinning is not removed by the retained-webview decision. + connection details uses the disconnected edit flow (0026, 0030), subject to C01's accepted + concurrency limitation (0033). A connected edit starts with **Disconnect and update**; preserve + that flow's cancellation, task-conflict and failure handling. Retire the prior logical lifetime + at the edit boundary even when resource registries are empty (C02). Enforce the boundary across asynchronous + saves/reconnects; pending host work still needs cancellation at side-effect boundaries. Silent + token renewal and a network reconnect for the unchanged identity remain supported. Workers stay + pinned to their originating identity and do not replay interrupted work. +- A selected Playground displays **Disconnected** immediately after explicit Disconnect, without + requiring a failed Run first. Keep its file text and selected connection for Disconnect. + After Remove, clear the removed connection's Playground selection and reuse the existing + **Connect** affordance while preserving the file text (C06, 0033). Refreshing the indicator must + not start a worker or run a script. +- After a recoverable index-build poll failure, stop polling the table. Network or sign-in repair + does not resume it automatically; explicit manual **Refresh** is required. A successful manual + refresh may resume normal build polling, while a failed one leaves it paused (C10, 0033). - Disconnect uses the existing task-conflict guard: if a copy or export is using the cluster, leave the task and connection running. The user can retry after the task finishes or is stopped. ## 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/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/02-pr1136-copilot-review.md](./iterations/02-pr1136-copilot-review.md) | 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/02-pr1136-copilot-review.md](./iterations/02-pr1136-copilot-review.md) | review | | [iterations/03-complexity-reduction-analysis.md](./iterations/03-complexity-reduction-analysis.md) | analysis | -| [iterations/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 | +| [iterations/03-pr1149-copilot-review.md](./iterations/03-pr1149-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 @@ -167,19 +196,24 @@ See [decisions.md](./decisions.md): - 0029 land the simplification inside #1136 before 1.2.0. - 0030 offer Disconnect and update and perform the ordinary teardown before editing (A2). - 0031 choose package P: A2, B2, C-balanced, D2 and guarded handoffs. -- 0032 same-account recovery keeps the tab live; only explicit session end freezes it, and X dismisses only the notice. +- 0032 same-account recovery keeps the tab live; only an explicit session end freezes it, and X + dismisses only the terminal notice. +- 0033 approve the PR #1149 review dispositions: accept C01's concurrency edge, clear removed + Playground selections for C06, leave C08's local editing unchanged, and require manual refresh + after a stopped index-build poll for C10; C12 remains a no-code disposition. ## Timeline -| Date | Event | -| ---------- | --------------------------------------------------------------------------- | -| 2026-11-18 | Investigation: code read, telemetry attribution, vscode-cosmosdb comparison | -| 2026-11-19 | Operator decisions 0001–0005; implementation plan (iteration 1) | -| 2026-11-19 | Decision 0006: delivery model (feature branch, sub-PRs, one release) | -| 2026-11-23 | WI-1 through WI-5 implement renewal, Azure auth, bindings and recovery | -| 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 | -| 2026-11-29 | Complexity analysis (iteration 3); decisions 0026, 0027 and 0029; 0028 proposed | -| 2026-11-30 | A2 approved (0030); package P chosen (0031); implementation pending | +| Date | Event | +| ---------- | ------------------------------------------------------------------------------------ | +| 2026-11-18 | Investigation: code read, telemetry attribution, vscode-cosmosdb comparison | +| 2026-11-19 | Operator decisions 0001–0005; implementation plan (iteration 1) | +| 2026-11-19 | Decision 0006: delivery model (feature branch, sub-PRs, one release) | +| 2026-11-23 | WI-1 through WI-5 implement renewal, Azure auth, bindings and recovery | +| 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 | +| 2026-11-29 | Complexity analysis (iteration 3); decisions 0026, 0027 and 0029; 0028 proposed | +| 2026-11-30 | A2 approved (0030); package P chosen (0031–0032); implementation partially committed | +| 2026-12-01 | PR #1149 review dispositions approved (0033); follow-up implementation pending | diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index c7316448a..d0409c7c1 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -10,40 +10,42 @@ created: 2026-11-19 > Why connections stay usable across token expiry and idle drops, and how open surfaces behave > when credentials or the identity change. Evidence: [research-findings.md](./research-findings.md). -| # | Decision | Status | Changed from the proposal? | Date | PR | -| ---- | ---------------------------------------------------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------ | ---------- | ---------------------------------------------------------------- | -| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | -| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | -| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted (modified by 0026) | Operator requirement | 2026-11-19 | — | -| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | -| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | -| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | -| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted (modified by 0018) | Operator: modal cannot pre-select; saved edits are close-only | 2026-11-19 | — | -| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | -| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | -| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | -| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 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 (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 0031–0032) | Dismissible notice for ended sessions, not for unlocking a recoverable view | 2026-11-24 | Yes; retains copy access | -| 0017 | Limit unavailable webview recovery to Retry and Close view | Superseded by 0031 | No view-level Retry; same-account repair stays in the tree | 2026-11-24 | See 0032 for notice dismissal versus closing a tab | -| 0018 | Saved connection edits permanently lock existing views | Superseded by 0026, 0027 | 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 | Superseded by 0031 | D2 removes the retained-view Retry episode | 2026-11-27 | No automatic operation replay | -| 0024 | Classify explicit stale recovery clicks and explain only failed actions | Accepted | Operator selected F5 option C | 2026-11-27 | Cancellation, disposed work and obsolete replies remain quiet | -| 0025 | Tree-origin failures use modals; webview-origin command feedback stays unchanged | Accepted | Operator confirmed F3 scope | 2026-11-27 | Shared command registrations must preserve origin | -| 0026 | Update Credentials and Update Connection String require a closed connection; Sign in again keeps the pin | Accepted (modified by 0030) | Operator initially chose A1; 0030 replaces it with A2 | 2026-11-29 | Yes; removes the edit-while-connected path | -| 0027 | Views kept open after Disconnect are permanently disabled; Disconnect still asks Close or Keep open | Accepted | Operator chose B2 over B1 (always close): "still ask the user" | 2026-11-29 | Yes; no rebinding or revival of retained views | -| 0028 | Surfaces hold only the cluster ID; remove the fingerprint, generation and binding carry-through | Rejected by 0031 | Operator chose C-balanced; preserve internal client generation and lifetime guards | 2026-11-29 | Broad removal weakens same-client failure and async lifetime checks | -| 0029 | Land the simplification inside #1136 before 1.2.0 | Accepted | Operator: before 1.2.0, as part of the feature PR | 2026-11-29 | — | -| 0030 | Offer Disconnect and update, performing the ordinary Disconnect flow before editing | Accepted | Operator reconsidered A1 and explicitly approved A2 | 2026-11-30 | Modifies 0026; pinned-account rule and pre-release timing remain | -| 0031 | Choose package P: A2, B2, C-balanced, D2 and guarded handoffs | Accepted | Operator chose the revised proposals in iteration 3 | 2026-11-30 | Simplifies recovery without dropping lifetime or worker guards | -| 0032 | Keep tabs live through same-account recovery; X on a frozen tab dismisses only its notice | Accepted | Clarifies B2 and D2; only explicit session end freezes kept tabs | 2026-11-30 | No tab revival or extra recovery workflow | +| # | Decision | Status | Changed from the proposal? | Date | PR | +| ---- | ---------------------------------------------------------------------------------------------------------- | -------------------------------- | ---------------------------------------------------------------------------------- | ---------- | ------------------------------------------------------------------- | +| 0001 | Entra tokens are renewed silently in every OIDC callback; the callback never prompts | Accepted | Operator accepted the explanation (2026-11-19) | 2026-11-19 | — | +| 0002 | Keep one cached client per cluster; surfaces resolve it per operation with identity + generation | Accepted (modified by 0010) | Operator position: per-operation clients cost too much | 2026-11-19 | — | +| 0003 | An open surface never moves to a different identity; it becomes disconnected, keeps its state and says why | Accepted (modified by 0026) | Operator requirement | 2026-11-19 | — | +| 0004 | Disconnect lets the user choose: close all affected tabs, or keep them open and disabled | Accepted | Operator position; the default is still open (Q2) | 2026-11-19 | — | +| 0005 | Fix stale ARM credentials by upgrading azureauth to v6 (#990), not with a local shim | Accepted | Operator: open to updating dependencies | 2026-11-19 | — | +| 0006 | Deliver through `feature/connection-lifecycle` with stacked sub-PRs, ship once | Accepted (amended) | Operator removed the intermediate merge wait | 2026-11-19 | — | +| 0007 | The Disconnect choice is a VS Code modal with nothing remembered; a setting can set the default | Accepted (modified by 0018) | Operator: modal cannot pre-select; saved edits are close-only | 2026-11-19 | — | +| 0008 | Upgrade the azext stack as high as viable without breaking workflows, using Azure Resources as reference | Accepted | Operator: replaces the "minimal versions" proposal | 2026-11-19 | — | +| 0009 | Kubernetes tunnel recovery, cluster ID case handling and wider network-resilience testing move to #1105 | Accepted | Operator: keep 1.2.0 focused; schedule after release | 2026-11-19 | — | +| 0010 | Rely on the server to reject expired tokens; replacing a client for the same identity is transparent | Accepted | Operator: no rotation, no out-of-date notices | 2026-11-19 | — | +| 0011 | Disconnect keeps the cached credentials and the verified identity; only Remove drops them | Accepted | Operator: reverses the #1059 proposal (plan Q3) | 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 (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 0031–0032) | Dismissible notice for ended sessions, not for unlocking a recoverable view | 2026-11-24 | Yes; retains copy access | +| 0017 | Limit unavailable webview recovery to Retry and Close view | Superseded by 0031 | No view-level Retry; same-account repair stays in the tree | 2026-11-24 | See 0032 for notice dismissal versus closing a tab | +| 0018 | Saved connection edits permanently lock existing views | Superseded by 0026, 0027 | 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 | Superseded by 0031 | D2 removes the retained-view Retry episode | 2026-11-27 | No automatic operation replay | +| 0024 | Classify explicit stale recovery clicks and explain only failed actions | Accepted | Operator selected F5 option C | 2026-11-27 | Cancellation, disposed work and obsolete replies remain quiet | +| 0025 | Tree-origin failures use modals; webview-origin command feedback stays unchanged | Accepted | Operator confirmed F3 scope | 2026-11-27 | Shared command registrations must preserve origin | +| 0026 | Update Credentials and Update Connection String require a closed connection; Sign in again keeps the pin | Accepted (modified by 0030) | Operator initially chose A1; 0030 replaces it with A2 | 2026-11-29 | Yes; removes the edit-while-connected path | +| 0027 | Views kept open after Disconnect are permanently disabled; Disconnect still asks Close or Keep open | Accepted | Operator chose B2 over B1 (always close): "still ask the user" | 2026-11-29 | Yes; no rebinding or revival of retained views | +| 0028 | Surfaces hold only the cluster ID; remove the fingerprint, generation and binding carry-through | Rejected by 0031 | Operator chose C-balanced; preserve internal client generation and lifetime guards | 2026-11-29 | Broad removal weakens same-client failure and async lifetime checks | +| 0029 | Land the simplification inside #1136 before 1.2.0 | Accepted | Operator: before 1.2.0, as part of the feature PR | 2026-11-29 | — | +| 0030 | Offer Disconnect and update, performing the ordinary Disconnect flow before editing | Accepted (modified by 0033) | A2 remains; 0033 accepts C01's concurrent teardown/edit edge case | 2026-11-30 | Modifies 0026; pinned-account rule and pre-release timing remain | +| 0031 | Choose package P: A2, B2, C-balanced, D2 and guarded handoffs | Accepted (modified by 0033) | 0033 records the review dispositions and bounded complexity tradeoffs | 2026-11-30 | Lifecycle and worker guards remain; see C01/C08 exceptions | +| 0032 | Keep tabs live through same-account recovery; X on a frozen tab dismisses only its notice | Accepted (modified by 0033) | 0033 permits local Collection View query editing after notice dismissal | 2026-11-30 | Database access stays permanently disabled on retained views | +| 0033 | Approve the PR1149 review dispositions with explicit complexity tradeoffs | Accepted | C01 option 3; C06 option 2 direction; C08 won't fix; C10 option 2 | 2026-12-01 | Nine code fixes; C01/C08/C12 are no-code dispositions | +| 0034 | Keep manual Refresh as the only way to resume paused index polling after Create | Accepted | Document the workaround; no code change | 2026-12-01 | Clarifies 0033 for pre-review finding N01 | > 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 @@ -829,3 +831,76 @@ is finished. **X dismisses the notice**, exposing already-loaded contents for co view closes the tab**. Neither action reconnects it. A new connection opens fresh live views, even for the same account. Freezing on every drop, or on same-account tree sign-in, was not chosen: it would force users to reopen their work in precisely the recovery scenario they want to preserve. + +**Operator clarification after manual testing (2026-11-30):** **Close view** in the disconnected +notice closes Dashboard, Collection View and a clean Document View directly, without another modal. +Only a dirty Document View retains the unsaved-changes warning. This replaces the earlier blanket +close-confirmation implementation; it does not change X dismissal, permanent read-only state or +Disconnect's own Close/Keep/Cancel and dirty-document checks. + +## 0033. Approve the PR1149 review dispositions with explicit complexity tradeoffs + +**Accepted** by the operator on 2026-12-01: + +> record the recommended solutions as approved, except: + +The source is the [PR #1149 Copilot evaluation](./iterations/03-pr1149-copilot-review.md). +The operator approved its recommended options except for C01, C06, C08 and C10. This records +the choices and their stated reasoning; it does not claim that the fixes have been implemented. + +| Item | Approved choice | +| ---- | --------------------------------------------------------------------------------------------- | +| C01 | Option 3: retain the existing latch/idle eligibility check; accept the edge case | +| C02 | Option 1: retire the prior lifetime at the common edit boundary, including idle edits | +| C03 | Option 1: reject closed Shell origins, including callbacks captured before closure | +| C04 | Option 1: carry the Dashboard binding/lifetime through session creation and panel publication | +| C05 | Option 1: defer the full binding guard until after bound-client resolution | +| C06 | Option 2 direction: clear the removed connection's Playground selection and reuse Connect | +| C07 | Option 1: make a rejected Entra account recoverable through explicit same-account sign-in | +| C08 | Won't fix: retain the overlay and database guards without adding local query read-only gates | +| C09 | Option 1: settle an invalidated current collections read as interrupted | +| C10 | Option 2: stop failed index-build polling; require explicit manual Refresh to resume | +| C11 | Option 1: use the localized title and detail in the existing notification contract | +| C12 | Option 1: no standalone retained-state refactor | + +### Accepted exceptions and rejected alternatives + +- **C01:** the operator chose option 3 because "this is an edge case, and option 1 adds a lot of + complexity." Do not introduce the proposed teardown-completion record. A concurrent edit can + still observe the disconnected latch before another teardown's driver close settles, including + the reviewed close-failure case. This is an accepted limitation, not a fixed race. The command + initiating Disconnect still awaits its own teardown and retains its existing cancellation, + task-conflict and error handling. This qualifies 0030's absolute teardown-success wording; it + does not remove C02's separately approved lifetime retirement. +- **C06:** the operator preferred the simpler option 2 direction because the existing **Connect** + affordance already provides recovery. Clear the selected binding for a removed connection and + preserve the Playground file text. Do not add option 1's shared reason-aware presentation layer. + Ordinary Disconnect still retains its selection; removal uses the existing unbound Connect path. +- **C08:** the operator considers the existing overlay sufficient to show that the connection is + disabled, and local editing after dismissal is the user's responsibility. Do not add the + proposed query-editor read-only controls or treat the previous copy-only local-editing + requirement as a blocker. This narrowly qualifies 0031/0032: retained views still cannot regain + database access, while local Collection View query editing is accepted. Document View's + existing read-only/dirty protection and all host lifetime/identity guards remain unchanged. +- **C10:** the operator chose stopping the poll, not option 1's new foreground/background callback + policy. Once stopped after a recoverable failure, the table must not resume polling merely + because connectivity or sign-in has recovered. The user must explicitly refresh the table. + A successful manual refresh may resume normal build polling; a failed one leaves it paused. +- **C12:** the recommended no-standalone-refactor disposition is approved. The optional state + redesign is not another required fix in this round. + +The other seven recommended options are accepted as evaluated in the linked review; no additional +operator rationale is inferred. There are nine code-fix items and three no-code dispositions. +The [approved execution handoff](./iterations/03-pr1149-copilot-review.md#approved-execution-handoff) +records the separate branch/PR, model routing, advisor authority, per-fix commit/push/thread-reply +requirements and final verification iteration. + +## 0034. Keep manual Refresh as the only way to resume paused index polling after Create + +**Accepted** by the operator on 2026-12-01: keep Decision 0033's manual-Refresh-only rule and +document the workaround for [pre-review finding N01](./iterations/03-pr1149-copilot-review.md#n01-creating-an-index-while-polling-is-paused). +If polling was paused before a successful Create, its row can still say **Creating**. Select +**Refresh** to get the current status and resume polling if a build is still active. + +The operator did not select either resuming polling on successful Create or adding a +localized pause indicator. No runtime change or exception to Decision 0033 was approved. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1136-copilot-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1136-copilot-review.md index 3a3c9630b..b2adc1f93 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1136-copilot-review.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/02-pr1136-copilot-review.md @@ -28,13 +28,13 @@ Severity is assessed independently of Copilot: **High** is a plausible cross-ide **Medium** is a concrete write or wrong-target risk with a constrained trigger; **Low** affects recovery guidance or telemetry. No actual disclosure or database write was observed. -| Item | Finding | Verdict | Severity | Proposed direction | -| ---- | ------- | ------- | -------- | ------------------ | -| [C01](#c01-create-commands-can-start-after-a-credential-update-latch) | Create after credential-update latch | Confirmed | Medium | Fence the bound command immediately before its operation | -| [C02](#c02-query-generation-can-sample-and-send-the-replacement-identitys-schema) | Replacement schema sent to Copilot | Confirmed | High | Bind and cancel the host generation path | -| [C03](#c03-playground-handoffs-can-adopt-a-replacement-identity) | Playground adopts a replacement identity | Confirmed | Medium | Carry and validate the originating binding and pin | -| [C04](#c04-provider-changes-are-explained-as-expired-sign-in) | Provider change reported as expiry | Confirmed | Low | Use reason-aware, truthful recovery guidance | -| [C05](#c05-stage-3-unavailability-is-recorded-as-cancellation) | Stage 3 unavailability recorded as cancellation | Confirmed | Low | Set the bounded outcome before the terminal yield | +| Item | Finding | Verdict | Severity | Proposed direction | +| --------------------------------------------------------------------------------- | ----------------------------------------------- | --------- | -------- | -------------------------------------------------------- | +| [C01](#c01-create-commands-can-start-after-a-credential-update-latch) | Create after credential-update latch | Confirmed | Medium | Fence the bound command immediately before its operation | +| [C02](#c02-query-generation-can-sample-and-send-the-replacement-identitys-schema) | Replacement schema sent to Copilot | Confirmed | High | Bind and cancel the host generation path | +| [C03](#c03-playground-handoffs-can-adopt-a-replacement-identity) | Playground adopts a replacement identity | Confirmed | Medium | Carry and validate the originating binding and pin | +| [C04](#c04-provider-changes-are-explained-as-expired-sign-in) | Provider change reported as expiry | Confirmed | Low | Use reason-aware, truthful recovery guidance | +| [C05](#c05-stage-3-unavailability-is-recorded-as-cancellation) | Stage 3 unavailability recorded as cancellation | Confirmed | Low | Set the bounded outcome before the terminal yield | The active [feature intent](../README.md#intent) says open surfaces must not move to a different identity and saved edits lock old views. C02 and C03 expose gaps between that intent and the code. @@ -261,7 +261,7 @@ unavailable event and immediately closed the iterator. It observed `outcome=canc `aborted=true` and no `unavailableReason`. This is a telemetry error, not evidence of a failed recovery dialog. -**Related edge found during verification:** the generator also sets `success` only *after* +**Related edge found during verification:** the generator also sets `success` only _after_ yielding `complete`. Immediate iterator closure after that event likewise recorded cancellation in the probe. This is the same terminal-yield ordering problem, not another Copilot thread. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md index c5e4df0cf..2d3c87051 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-complexity-reduction-analysis.md @@ -31,14 +31,14 @@ common path first. [Decisions 0031–0032](../decisions.md) define the following [section 6](#6-packages-regenerated-2026-11-30) compares packages. **Implementers:** read this table, then use the [implementation handoff](#implementation-handoff). -| What the user does or sees | What must happen | -| --- | --- | -| Work continues across Entra token expiry or the machine wakes after sleep | Renew silently or recover the connection for the same account. Keep the tab, query and draft. If an operation failed, report it; don't silently replay it. | -| Silent renewal needs help | Offer **Sign in again** in the tree for the pinned account. Once repaired, the user can run the next operation **in the same tab**. No separate Retry to unlock it. | -| Explicit **Disconnect** or **Remove** | Honor Close/Keep/Cancel and protect unsaved edits. A **kept** tab is permanently read-only, even after reconnecting to the same account. New work belongs in a fresh tab. | -| Look at a kept tab | Show a notice such as **“This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.”** **X** dismisses the notice for copying; **Close view** closes the tab. Neither enables database access. | -| Change credentials or the connection string | Offer **Disconnect and update**. Edit only once the old session has ended. This is a new session, not same-account repair. | -| Use Shell or Playground | Renew and recover for the pinned account without a background prompt. Keep scrollback or file text on Disconnect, stop the worker, and never replay a command or silently bind old work to another identity. | +| What the user does or sees | What must happen | +| ------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Work continues across Entra token expiry or the machine wakes after sleep | Renew silently or recover the connection for the same account. Keep the tab, query and draft. If an operation failed, report it; don't silently replay it. | +| Silent renewal needs help | Offer **Sign in again** in the tree for the pinned account. Once repaired, the user can run the next operation **in the same tab**. No separate Retry to unlock it. | +| Explicit **Disconnect** or **Remove** | Honor Close/Keep/Cancel and protect unsaved edits. A **kept** tab is permanently read-only, even after reconnecting to the same account. New work belongs in a fresh tab. | +| Look at a kept tab | Show a notice such as **“This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.”** **X** dismisses the notice for copying; **Close view** closes the tab. Neither enables database access. | +| Change credentials or the connection string | Offer **Disconnect and update**. Edit only once the old session has ended. This is a new session, not same-account repair. | +| Use Shell or Playground | Renew and recover for the pinned account without a background prompt. Keep scrollback or file text on Disconnect, stop the worker, and never replay a command or silently bind old work to another identity. | **Scope cutoff.** The things missing from that user-facing list are safeguards, not new flows: keep unsaved text, block teardown during an active transfer, and prevent old work from acting on @@ -80,7 +80,7 @@ where it is not enforced. | 2026-11-19 | 0013 | Latch before save, epoch on replies, bindings through handoffs, `runWithClient` | | 2026-11-23 | 0014/0015 | Keep settings after rejection; reuse the latch to block startup | | 2026-11-24 | 0016/0017 | Full-view overlay; Retry and Close view only | -| 2026-11-24 | 0018 | Saved edits lock views permanently (a simplification that still needs a retirement map) | +| 2026-11-24 | 0018 | Saved edits lock views permanently (a simplification that still needs a retirement map) | | 2026-11-24 | 0019 | Dashboard delete confirmation does not survive Disconnect | | 2026-11-26 | 0021 | HMAC-keyed fingerprint, plus a CodeQL exception | | 2026-11-27 | 0022–0025 | Anonymous Shell entry, in-dialog retry feedback, stale-click classification, tree modals | @@ -101,13 +101,13 @@ policies and representations while keeping a small shared cancellation contract. Merge base `60e17e46` with `origin/main`, head `1e362403`. -| Measure | Value | -| ------------------------------------------- | ---------------------------------------------------------------------------------------------- | -| Files changed | 281 | -| Production code (src + packages) | +10,008 / −2,807 | -| Tests | +13,417 / −427 | -| Docs | +8,517 | -| `ClustersClient.ts` | 1,477 → 2,096 lines | +| Measure | Value | +| -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | +| Files changed | 281 | +| Production code (src + packages) | +10,008 / −2,807 | +| Tests | +13,417 / −427 | +| Docs | +8,517 | +| `ClustersClient.ts` | 1,477 → 2,096 lines | | Added production lines that use the binding vocabulary (`binding`, `fingerprint`, `epoch`, `latch`, `assertCurrent`, `unavailable`, `retire`, the nine reason names) | **1,428 of 9,587 (15%)**; 645 of 3,325 (19%) in `src/webviews` | The keyword share measures the spread of the vocabulary, **not a lower bound on deletable code**. @@ -115,15 +115,15 @@ Neighbouring lines also participate, but many matching guards remain useful afte Concept spread in production code (grep hits / files): -| Concept | Hits / files | -| -------------------------------------------------- | ------------ | -| epoch, `assertCurrent`, `beginOperation` | 344 / 51 | -| `ConnectionUnavailableError` | 118 / 33 | -| `entraIdentity`, `lastVerifiedIdentity` | 112 / 24 | -| `ConnectionBinding`, `getBinding`, `resolveBoundClient` | 80 / 24 | -| latch (`latch`, `getLatchReason`, `unlatch`) | 77 / 21 | -| `fingerprint` | 64 / 10 | -| `describeUnavailable`, `ConnectionUnavailableReason` | 58 / 18 | +| Concept | Hits / files | +| ------------------------------------------------------- | ------------ | +| epoch, `assertCurrent`, `beginOperation` | 344 / 51 | +| `ConnectionUnavailableError` | 118 / 33 | +| `entraIdentity`, `lastVerifiedIdentity` | 112 / 24 | +| `ConnectionBinding`, `getBinding`, `resolveBoundClient` | 80 / 24 | +| latch (`latch`, `getLatchReason`, `unlatch`) | 77 / 21 | +| `fingerprint` | 64 / 10 | +| `describeUnavailable`, `ConnectionUnavailableReason` | 58 / 18 | Latches are set only by the rejection paths (`credentialsRejected`), teardown (`userDisconnected`, `connectionRemoved`, and `credentialsChanged` as a teardown reason) and the edit path @@ -136,24 +136,24 @@ can evict or hold a client. Reducing UI reasons does not justify deleting authen "Wanted" means it belongs to the original ask (renewal, reconnect) or is a safety need. -| # | Scenario | Wanted? | Cost today | Proposal | -| --- | ---------------------------------------------------------- | --------- | -------------------------------------------------------------------------- | ---------------------------------------------- | -| S1 | Token expires, silent renewal | Original | Core callback; small | **Keep** | -| S2 | Sleep or network drop, reconnect | Original | Closed-client replacement; moderate | **Keep** | -| S3 | Silent renewal impossible, sign-in needed | Original | Tree action plus overlay, Retry, binding re-check | **Keep tree sign-in; D2 removes the recovery dialog** | -| S4 | Server rejects credentials | Safety | Latch prevents retry storms and lockout | **Keep** (one latch reason) | -| S5 | Disconnect | Added | Close/Keep modal, setting, retained disabled views, Reconnect, Retry | **Keep the choice; B2 retained views never revive** | -| S6 | Remove connection or folder | Added | Batch latching, epoch and latch recovery, retained views | **Limit: same teardown as Disconnect** | -| S7 | Update credentials or connection string while connected | Added | `saveConnectionEdit`, retirement map, pin diffing, shell modal | **Limit: disconnect first** | -| S8 | Update credentials while not connected | Main | Was a few lines on `main` | **Keep editing; serialize save against reconnect** | -| S9 | Sign in again as a different account | Added | Account-label heuristic, `identityChanged` for open views | **Limit: pinned account only** | -| S10 | Retained disabled view: Keep open, Retry, Reconnect resumes | Added | Binding, generation, overlay, hook, revision guards in three views | **Keep copyable contents; drop revival** | -| S11 | Handoffs from a bound view (create, delete, import, export, indexes, playground, Copilot) | Added | `runBoundNamespaceCommand`, `boundViewOperations`, binding carry-through | **Simpler host lifetime/cancellation; not unguarded clusterId** | -| S12 | Dashboard delete confirmation across Disconnect (0019) | Added | Epoch snapshot per pending delete | **Keep cancellation; share the lifetime guard** | -| S13 | Shell and Playground after a lifecycle change | Partly | Per-worker pins, anonymous Shell entry (0022) | **Keep pins; worker simplification needs an explicit rebind policy** | -| S14 | Worker token renewal (`WorkerTokenRelay`) | Original | 307 lines | **Keep** | -| S15 | Running transfer blocks teardown | Safety | Task guard | **Keep** | -| S16 | Another window edits the same connection | None | No cross-window watcher; equality guards can reject observed changes | **Do not confuse no watcher with no protection** | +| # | Scenario | Wanted? | Cost today | Proposal | +| --- | ----------------------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------- | +| S1 | Token expires, silent renewal | Original | Core callback; small | **Keep** | +| S2 | Sleep or network drop, reconnect | Original | Closed-client replacement; moderate | **Keep** | +| S3 | Silent renewal impossible, sign-in needed | Original | Tree action plus overlay, Retry, binding re-check | **Keep tree sign-in; D2 removes the recovery dialog** | +| S4 | Server rejects credentials | Safety | Latch prevents retry storms and lockout | **Keep** (one latch reason) | +| S5 | Disconnect | Added | Close/Keep modal, setting, retained disabled views, Reconnect, Retry | **Keep the choice; B2 retained views never revive** | +| S6 | Remove connection or folder | Added | Batch latching, epoch and latch recovery, retained views | **Limit: same teardown as Disconnect** | +| S7 | Update credentials or connection string while connected | Added | `saveConnectionEdit`, retirement map, pin diffing, shell modal | **Limit: disconnect first** | +| S8 | Update credentials while not connected | Main | Was a few lines on `main` | **Keep editing; serialize save against reconnect** | +| S9 | Sign in again as a different account | Added | Account-label heuristic, `identityChanged` for open views | **Limit: pinned account only** | +| S10 | Retained disabled view: Keep open, Retry, Reconnect resumes | Added | Binding, generation, overlay, hook, revision guards in three views | **Keep copyable contents; drop revival** | +| S11 | Handoffs from a bound view (create, delete, import, export, indexes, playground, Copilot) | Added | `runBoundNamespaceCommand`, `boundViewOperations`, binding carry-through | **Simpler host lifetime/cancellation; not unguarded clusterId** | +| S12 | Dashboard delete confirmation across Disconnect (0019) | Added | Epoch snapshot per pending delete | **Keep cancellation; share the lifetime guard** | +| S13 | Shell and Playground after a lifecycle change | Partly | Per-worker pins, anonymous Shell entry (0022) | **Keep pins; worker simplification needs an explicit rebind policy** | +| S14 | Worker token renewal (`WorkerTokenRelay`) | Original | 307 lines | **Keep** | +| S15 | Running transfer blocks teardown | Safety | Task guard | **Keep** | +| S16 | Another window edits the same connection | None | No cross-window watcher; equality guards can reject observed changes | **Do not confuse no watcher with no protection** | ### S1. Token expires (same before and after) @@ -349,18 +349,18 @@ accepted; the operator has not approved dropping these guards. Line counts rechecked at `1e362403` on 2026-11-30 (including comments and blank lines): -| Component | Lines | Revised disposition | -| --- | ---: | --- | -| `connectionSurfaces` | 39 | Keep registration; B2 needs host lifetime invalidation as well as notification | -| `connectionTeardown` | 337 | Keep Close/Keep, dirty checks, task guard and removal cleanup; shrink edit-specific policy | -| `saveConnectionEdit` | 152 | Replace live-edit reconciliation with disconnected editing; save exclusion and failure reporting remain | -| `useBoundViewRecovery` | 192 | D2 replaces its recovery workflow; retain simpler frozen-state and stale-reply checks | -| `DisconnectedOverlay` + stylesheet | 145 + 3 | B2 keeps or simplifies the copy/Close presentation; not wholly removable | -| `describeUnavailableConnection` + `connectionUnavailable` | 83 + 83 | Narrow/rework under D2; actionable error translation and frozen notification remain | -| `boundViewOperations` | 127 | Recovery part shrinks; side-effect and late-reply guards survive in a smaller form | -| `runBoundNamespaceCommand` | 49 | May consolidate, but do not remove cancellation before create/delete | -| Fingerprint + retirement modules | 39 + 17 | Retirement can be replaced by permanent surface lifetime; fingerprint removal needs C's coverage gate | -| `useBoundViewRecovery.test.tsx` | 436 | Some episode/Retry tests disappear; frozen state, cancellation and dirty-close contracts still need tests | +| Component | Lines | Revised disposition | +| --------------------------------------------------------- | ------: | --------------------------------------------------------------------------------------------------------- | +| `connectionSurfaces` | 39 | Keep registration; B2 needs host lifetime invalidation as well as notification | +| `connectionTeardown` | 337 | Keep Close/Keep, dirty checks, task guard and removal cleanup; shrink edit-specific policy | +| `saveConnectionEdit` | 152 | Replace live-edit reconciliation with disconnected editing; save exclusion and failure reporting remain | +| `useBoundViewRecovery` | 192 | D2 replaces its recovery workflow; retain simpler frozen-state and stale-reply checks | +| `DisconnectedOverlay` + stylesheet | 145 + 3 | B2 keeps or simplifies the copy/Close presentation; not wholly removable | +| `describeUnavailableConnection` + `connectionUnavailable` | 83 + 83 | Narrow/rework under D2; actionable error translation and frozen notification remain | +| `boundViewOperations` | 127 | Recovery part shrinks; side-effect and late-reply guards survive in a smaller form | +| `runBoundNamespaceCommand` | 49 | May consolidate, but do not remove cancellation before create/delete | +| Fingerprint + retirement modules | 39 + 17 | Retirement can be replaced by permanent surface lifetime; fingerprint removal needs C's coverage gate | +| `useBoundViewRecovery.test.tsx` | 436 | Some episode/Retry tests disappear; frozen state, cancellation and dirty-close contracts still need tests | The four recovery/presentation TypeScript files total **503 lines**; including the stylesheet, **506**. They are a concrete simplification target, not 506 deletable lines. The old "about 1,095 @@ -395,7 +395,7 @@ credentials unchanged; cancel after Disconnect does not silently reconnect. reconnect until the storage writes finish. Prefer the existing latch/epoch; do not queue reconnects, resume stale wizards, or try to roll back Disconnect. - [saveConnectionEdit](../../../../../src/commands/saveConnectionEdit.ts) handles non-atomic - secrets/metadata writes. Ending the old lifetime removes the need to reconcile *live views* on + secrets/metadata writes. Ending the old lifetime removes the need to reconcile _live views_ on partial failure, not the obligation to report an incomplete save and clear stale cached auth. **Trade-off:** A1 is marginally smaller, but A2 removes a navigation dead end without adding @@ -407,11 +407,11 @@ remains: Sign in again is for the pinned account; switching accounts uses this e **Chosen: B2 (decision 0031, reaffirming 0027).** Preserve the user's Close/Keep choice, but make Keep mean **keep the contents read-only, not keep a connection that can be resumed**. -| Choice | User experience | Maintenance cost | -| --- | --- | --- | -| B1: close | Copy first; all result tabs disappear at Disconnect | Smallest UI, but still needs cancellation of host work | -| B2: keep a frozen view | Copy loaded results, queries or unsaved text; reconnect opens new live views | One-way host lifetime + presentation; no recovery negotiation | -| Current recoverable retention | Reconnect/sign in, then Retry may revive the tab | Identity comparison, retirement exceptions, recovery RPC and UI episodes | +| Choice | User experience | Maintenance cost | +| ----------------------------- | ---------------------------------------------------------------------------- | ------------------------------------------------------------------------ | +| B1: close | Copy first; all result tabs disappear at Disconnect | Smallest UI, but still needs cancellation of host work | +| B2: keep a frozen view | Copy loaded results, queries or unsaved text; reconnect opens new live views | One-way host lifetime + presentation; no recovery negotiation | +| Current recoverable retention | Reconnect/sign in, then Retry may revive the tab | Identity comparison, retirement exceptions, recovery RPC and UI episodes | The useful boundary is **one-way versus reversible**, not open versus closed. B2 has only `active -> frozen -> closed`; no `frozen -> active` transition. An ordinary temporary network @@ -482,11 +482,11 @@ Its name is not important. **When it changes and who must retain it are importan There are three different questions in the current code: -| Question | Current mechanism | Necessary after A2/B2? | -| --- | --- | --- | -| Did this error come from the client still in the cache? | Physical client `generation` in `reportFailure` | Yes; generation or object identity is sufficient | -| Did Disconnect/recovery supersede an unfinished startup or operation? | `_epochs`, latches and cancellation | Yes; a generation assigned only after successful startup cannot cover this | -| May an old surface use a different physical client? | Fingerprint equality plus retirement-generation cutoff | Simpler with immutable live settings and one-way frozen surfaces; still needs host lifetime enforcement | +| Question | Current mechanism | Necessary after A2/B2? | +| --------------------------------------------------------------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- | +| Did this error come from the client still in the cache? | Physical client `generation` in `reportFailure` | Yes; generation or object identity is sufficient | +| Did Disconnect/recovery supersede an unfinished startup or operation? | `_epochs`, latches and cancellation | Yes; a generation assigned only after successful startup cannot cover this | +| May an old surface use a different physical client? | Fingerprint equality plus retirement-generation cutoff | Simpler with immutable live settings and one-way frozen surfaces; still needs host lifetime enforcement | #### Same identity, failed client: this is existing recovery, not future speculation @@ -614,11 +614,11 @@ does not mean replacing every current error with a new notification system. #### Choices -| Choice | Behavior | Pros | Cons | -| --- | --- | --- | --- | -| D1: keep recoverable overlay | Failure blocks the tab; tree repair, then Retry to unlock | Most explicit global connection status; closest to current UX | Keeps recovery RPC, episode rules and duplicate host/UI recovery state | -| **D2: frozen notice + ordinary recoverable errors** | Only explicit Disconnect/Remove freezes; otherwise report failure and let the next explicit operation use the repaired client | Removes a recovery step and most episode machinery; preserves B2 | A user can repeat an operation while still offline and receive another error | -| D3: permanently freeze on every connection failure | Error means reopen a fresh view | One-way state everywhere | Punishes transient failures and same-account sign-in; undermines the original goal | +| Choice | Behavior | Pros | Cons | +| --------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------- | +| D1: keep recoverable overlay | Failure blocks the tab; tree repair, then Retry to unlock | Most explicit global connection status; closest to current UX | Keeps recovery RPC, episode rules and duplicate host/UI recovery state | +| **D2: frozen notice + ordinary recoverable errors** | Only explicit Disconnect/Remove freezes; otherwise report failure and let the next explicit operation use the repaired client | Removes a recovery step and most episode machinery; preserves B2 | A user can repeat an operation while still offline and receive another error | +| D3: permanently freeze on every connection failure | Error means reopen a fresh view | One-way state everywhere | Punishes transient failures and same-account sign-in; undermines the original goal | **Chosen: D2 (decision 0031).** Concrete flows: @@ -692,11 +692,11 @@ handoffs. All packages retain F: renewal, pinned sign-in, same-account client replacement, startup single-flight, rejection holds, worker token relay and the transfer guard. -| Package | Contents | What becomes simpler | What remains / trade-off | -| --- | --- | --- | --- | -| **P: practical simplification (chosen)** | A2 + B2 + C-balanced + D2 + guarded handoffs | No live credential migration, no revival of retained tabs, no separate recoverable-view Retry workflow; consolidate host guards | Keep copyable snapshots, internal client generation, startup epochs, cancellation and worker pins | -| U: preserve recovery UI | A2 + B2 + C-balanced + D1 | Removes live edits and post-Disconnect revival only | Lower UX change, but retains most recovery hook/mapper/episode machinery; smaller architectural saving | -| X: close-only | A2 + B1 + C-balanced + D2 | P plus no frozen-tab UI or old/new Dashboard snapshot coexistence | Smallest surface policy, but loses the user benefit explicitly valued here; host guards are still needed | +| Package | Contents | What becomes simpler | What remains / trade-off | +| ---------------------------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | +| **P: practical simplification (chosen)** | A2 + B2 + C-balanced + D2 + guarded handoffs | No live credential migration, no revival of retained tabs, no separate recoverable-view Retry workflow; consolidate host guards | Keep copyable snapshots, internal client generation, startup epochs, cancellation and worker pins | +| U: preserve recovery UI | A2 + B2 + C-balanced + D1 | Removes live edits and post-Disconnect revival only | Lower UX change, but retains most recovery hook/mapper/episode machinery; smaller architectural saving | +| X: close-only | A2 + B1 + C-balanced + D2 | P plus no frozen-tab UI or old/new Dashboard snapshot coexistence | Smallest surface policy, but loses the user benefit explicitly valued here; host guards are still needed | **Why P:** it limits the hard-to-maintain promise (resume a retained view), rather than the useful one (read/copy its contents). It also removes a redundant recovery step: repairing the connection @@ -726,7 +726,7 @@ mechanisms and boundaries, not that hypothetical diff. #### Implementation handoff **Deliverable:** implement P on the feature line for #1136. The table at the top and decisions -0030–0032 are the target; old tests which revive a *deliberately disconnected* view describe the +0030–0032 are the target; old tests which revive a _deliberately disconnected_ view describe the previous target. Preserve their protections for dirty text and late replies, not the revival. Do not add a recovery framework, redesign unrelated worker features, or pursue a line-count target. @@ -749,15 +749,526 @@ E, U or H; their test cases can be prepared in parallel. Integrate and rerun aff combined revision before P. Plan the live gate early; unavailable live infrastructure does not block independent deterministic work. -| ID / status | Deliverable | How the agent demonstrates it | -| --- | --- | --- | -| **R — not run** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. | -| **W — not run** | Shell and Playground renew independently; explicit teardown stops the old worker, not the user's text. | Exercise both manager/evaluator suites, PTY and `executePlaygroundCode.test.ts`. Hold a token reply or evaluation across Disconnect, release it after reconnect: no delivery to the replacement worker, automatic command replay or silent rebinding; scrollback/file contents survive. Positive control: a valid pinned worker receives its reply and executes once. | -| **F — not run** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. | -| **E — not run** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. | -| **U — not run** | X dismisses the frozen notice; Close closes the tab. Ordinary recoverable errors do not freeze it. | Update the existing rendered scenarios below. Keep a draft, dismiss with X, select/copy the original text, attempt Save, release a stale response: draft unchanged, no new save RPC. Close/cancel the dirty-close confirmation separately. Pair with a failed live query → same-account repair → user runs again in the **same tab**, with no unlock RPC and no automatic replay. On uncertain write outcome retain text and never claim nothing was written. | -| **H — not run** | Shared host checks stop delayed side effects without making ordinary reads carry identity policy. | Exercise [review cases C01–C03](./02-pr1136-copilot-review.md): pause create after client resolution; pause query generation before sampling and again at model selection; pause Playground document opening, including a retained Shell link. End the old lifetime, install the replacement, release the pause. Assert zero stale writes, replacement-schema samples, model sends after invalidation, or replacement bindings, as applicable. Run the same paths without invalidation to rule out a blanket disable. Use fake DB/model boundaries, not real data or model calls. | -| **P — not run** | Combined candidate and release evidence. | Rerun affected checks after integration. Walk a normal read and a delayed write/send in the diff: the read uses a shared path, the delayed side effect checks its captured origin. Record obsolete recovery handlers/tests removed and guards intentionally retained. Update user-facing docs/localization and affected telemetry contracts for the behavior actually shipped. Run the repository handoff gates and the live checks below on the identified candidate. | +**Run started (2026-11-30, 12:16 UTC):** baseline +`3d66aa9374fefadcde8c236e0384cc8d18310372`; implementation branch +`dev/tnaum/connection-lifecycle-simplification`, targeting `feature/connection-lifecycle`. +The operator requested a stacked draft PR, then Case 2 after the implementation push, fixes for +any failures, and readiness only after the required gates pass. The existing untracked relay +and telemetry directories are outside this work. + +**Baseline evidence (2026-11-30):** at the starting revision, `npm run build` passed +(exit 0, 51.09 s). The exact first-run Vitest command above passed all 271 tests in four +files (5.44 s wall time). Evidence: command-runner agent +`6fe1d510-b864-4fc4-81f1-2667393cb664`, completed baseline report. This establishes the +pre-change host baseline, not R/W completion, rendered behavior, packaged activation or live +expiry/sleep-wake. Planning advisor: `claude-opus-5.5`; command runner: `mai-code-2-flash`. +At docs-only revision `17225d6f938c80b52e9dc2e543539f0b78cb07b6`, the expanded baseline +command passed 413 tests in 13 files (16.52 s), including sign-in, worker/PTY execution, +teardown and all three controller/router suites. No failures or `TDD:` failures occurred. +Exact command/evidence: agent `666c92f9-15bf-4764-a3c9-fa13a6cebfeb`, baseline-extension +report; the original build and four initial suites were not rerun for docs-only changes. + +```sh +npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts src/documentdb/connectionTeardown.test.ts src/documentdb/connectionSurfaces.test.ts src/commands/disconnect/disconnect.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts +``` + +| ID / status | Deliverable | How the agent demonstrates it | +| -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **R — host pass; integrated/live pending** | Token expiry/drop is not Disconnect. Same-account tree repair keeps the same tab usable. | In the client/auth and `signInAgain.test.ts` suites, drive silent success, no session and a rejected callback. Replace the client, then release an old client's failure: no extra replacement or eviction. Assert no background interactive request; wrong account cannot repair; next explicit operation on the repaired connection runs once. Commit/revision/command evidence is recorded under R below. | +| **W — host pass; integrated/live pending** | Shell and Playground renew independently; explicit teardown stops the old worker, not the user's text. | Exercise both manager/evaluator suites, PTY and `executePlaygroundCode.test.ts`. Hold a token reply or evaluation across Disconnect, release it after reconnect: no delivery to the replacement worker, automatic command replay or silent rebinding; scrollback/file contents survive. Positive control: a valid pinned worker receives its reply and executes once. Commit/revision/command evidence is recorded under W below. | +| **F — host pass; integrated pending** | End the old host lifetime once; freezing is permanent. Cover Collection, Document and Dashboard. | In `connectionTeardown.test.ts`, controller and router suites, keep an old dirty view, reconnect, open a fresh view, then disconnect again. Old snapshot retains its draft and is not included in the second Close all. Invoke an old RPC and an old Dashboard native menu action directly, not just disabled buttons: **zero** database calls on the new client. A fresh panel's action must work. Advance polling while frozen: zero new polls; background work cannot redial or prompt. Commit/revision/command evidence is recorded under F1/F2 below. | +| **E — host pass; integrated pending** | A2 uses ordinary Disconnect; edits cannot cross a reconnect or expose mixed credentials. | Cover **both** `updateCredentials.test.ts` and `updateConnectionString.test.ts`. Successful teardown precedes wizard/save; already safely disconnected skips redundant teardown. Cancel, active transfer, dirty-close refusal or teardown failure: zero saves, active transfer unaffected. Cancel after Disconnect stays disconnected. Include evicted-client/pending-startup cases. Pause between storage writes, attempt reconnect, then fail metadata: no client sees mixed settings, no success report; partial failure is visible. A wizard superseded before save does not write. Commit/revision/command evidence is recorded under E below. | +| **U — host/unit pass; rendered pending** | X dismisses the frozen notice; Close closes the tab. Ordinary recoverable errors do not freeze it. | Update the existing rendered scenarios below. Keep a draft, dismiss with X, select/copy the original text, attempt Save, release a stale response: draft unchanged, no new save RPC. Close/cancel the dirty-close confirmation separately. Pair with a failed live query → same-account repair → user runs again in the **same tab**, with no unlock RPC and no automatic replay. On uncertain write outcome retain text and never claim nothing was written. Commit/revision/command evidence is recorded under U1/U2 below. | +| **H — host pass; integrated pending** | Shared host checks stop delayed side effects without making ordinary reads carry identity policy. | Exercise [review cases C01–C03](./02-pr1136-copilot-review.md): pause create after client resolution; pause query generation before sampling and again at model selection; pause Playground document opening, including a retained Shell link. End the old lifetime, install the replacement, release the pause. Assert zero stale writes, replacement-schema samples, model sends after invalidation, or replacement bindings, as applicable. Run the same paths without invalidation to rule out a blanket disable. Use fake DB/model boundaries, not real data or model calls. Commit/revision/command evidence is recorded under H1/H2/H3 below. | +| **P — draft published; final receipts in #1149; live blocked** | Combined candidate and release evidence. | Rerun affected checks after integration. Walk a normal read and a delayed write/send in the diff: the read uses a shared path, the delayed side effect checks its captured origin. Record obsolete recovery handlers/tests removed and guards intentionally retained. Update user-facing docs/localization and affected telemetry contracts for the behavior actually shipped. Run the repository handoff gates and the live checks below on the identified candidate. The draft's validation section records the final pushed-head results; manual/live readiness gates remain outstanding. | + +**Implementation mapping (2026-11-30, advised by `claude-opus-5.5`):** the seven +accepted checkpoints remain the plan; the lettered slices below do not expand its scope. +Advisor verdict: follow the mapping, **82/100 confidence**. The remaining technical risks +require direct effects checks for synchronous cutoff retirement, retained-registry exclusion +and originating Dashboard menu routing; they are not substitutes for passing tests. +Coordination decision (leader, 99% confidence): run disjoint files in parallel, but serialize +shared controllers/routers and teardown edits so every work-item commit has clear ownership. + +- **R / `mai-code-2`, implementation committed; integrated checks pending:** agent + `48d5a5d1-32c4-4352-a808-ae0dd072317f`. Enforce the existing pinned-account tree sign-in contract and add + recovery/late-failure controls in the sign-in, client and auth tests. It is independent of W + and F, but must not edit F's client implementation. The advisor recommended this model for + the small source change and focused tests. + **Done (2026-11-30), commit `b58b74501`:** tree recovery now rejects every different account + ID, retaining the pinned-account success path and existing messages. Seven regressions + cover account rejection, silent callbacks, same-account replacement and late-failure + attribution. Decision: implement the operator's pinned-account contract without new wording; + advised (`claude-opus-5.5`), review approved at 88% confidence. The changed acceptance test + preserves exact pinned-session/startup assertions and adds zero-startup/unchanged-pin/hold + assertions for rejection; no `TDD:` contract was weakened. + **Interim host pass:** the three R suites passed within the R/W command below at + `af8ace13b` plus the working changes; the combined command failed in W, not R. + Build and affected suites are being rerun on the stabilized R/F1 candidate before + claiming the integrated gate. + **Stabilized host pass:** at `8c4854f0d` plus F1 working changes, `npm run build` + passed (exit 0, 43 s), and the combined R/F1 command recorded below passed all + 302 tests in 11 files (5 s). Evidence: runner + `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2`, corrected F1 rerun. R's same-account + repair and late-failure tests are green; this still does not pass the live gates. +- **W / `mai-code-2`, host pass; integrated rerun pending:** agent + `6b87164b-c07d-4fb5-a918-488b29840278`. Characterize held worker-token replies and evaluations across + Disconnect/reconnect, including a valid-worker positive control and retained text. Own the + manager/evaluator, PTY and execution tests; preserve `TDD:` contracts. Existing production + guards should suffice; a discovered production lifecycle defect returns to the advisor. + **Host fail (2026-11-30), revision `af8ace13b` plus R/W/F1 working changes:** + `npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/ClustersClient.test.ts src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts src/documentdb/shell/ShellSessionManager.test.ts src/documentdb/playground/PlaygroundEvaluator.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts` + passed 601 tests in seven files but failed the new held-evaluation test in + `PlaygroundEvaluator.test.ts` after 15 s, with one unhandled rejection: expected + `Worker terminated`, received `The connection is unavailable.` The credential-cleanup + assertion also failed. Evidence: runner `05e84afa-064f-49cb-95bb-5e07f6ac1441` + (22.22 s). Technical diagnosis is assigned to the advisor; no production behavior or + existing contract has been changed to make this failure disappear. + **Done (2026-11-30), commit `4c5ff5fa2`:** added held-token and in-flight evaluation + regressions. The first attempt latched before the evaluation reached the worker; advised + (`claude-opus-5.5`), about 90% confidence, the correction waits for the actual `old` + `sendEval` effect before teardown. Exact no-replay sequence, replacement reply count and + silent pinned-account assertions are unchanged. No production behavior or existing + `TDD:` contract changed. + **Host pass:** at `d6be5ea89` plus W/F1 working changes, + `npx vitest run src/documentdb/shell/ShellSessionManager.test.ts src/documentdb/playground/PlaygroundEvaluator.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts` + passed all 391 tests in five files (14.58 s), no failures/unhandled errors/TDD failures. + Evidence: runner `05e84afa-064f-49cb-95bb-5e07f6ac1441`, corrected-test rerun. + The root build also passed on the stabilized R/W/F1 working candidate (43 s); + no test type errors remained. Integrated candidate rerun is still required. +- **F1 / `gpt-6.1-sol`, committed and host-verified:** agent + `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Reuse the existing binding-retirement cutoff as the one-way host + lifetime end, with its reason and synchronous cancellation. Explicit teardown ends that + lifetime before awaiting; same-account replacement does not. Detach retained surfaces from + the active registry and cover absent/held clients and pending startup. + **Review/checks fail (2026-11-30):** advised (`claude-opus-5.5`), changes requested at + 85% confidence. Failed storage removal must not leave kept tabs/old RPCs claiming the + connection was removed; the detached-surface failure path needs truthful disconnected + feedback without reviving the lifetime. This is an introduced regression, not an accepted + cosmetic exception. + At `af8ace13b` plus working R/F1 changes, `npm run build` failed after 55 s with TS2352 + in `src/commands/disconnect/disconnect.test.ts:190`: the new shell fixture lacks its + required terminal and complete info. The F1 command above, preceded by the three R suites, + passed 292/293 tests in 10/11 files (5 s), failing + `keeps teardown scoped to the current registered surfaces for one cluster` because a new + `it()` was nested inside it. Evidence: runner `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2` + and advisor `873c8316-29fd-47c1-aa2d-ff9dce2f1254`. Neither failure is a `TDD:` + behavior-contract failure; fix the fixture/registration, not the assertions. + **Correction authorized by the advisor:** only the matching newest failed-removal + retirement range can be corrected to `userDisconnected`, under the existing epoch/latch + guard. Captured detached surfaces receive the truthful notice; their signals stay aborted + and earlier/later lifetimes are untouched. Fix the shell fixture with complete proper types + and move the surface test to top level. Worker rework is running; review and checks must rerun. + **Rerun pass, review still pending:** at `8c4854f0d` plus F1 working changes, + `npm run build` passed (43 s), and the exact command below passed 302/302 tests + in 11/11 files (5 s). Evidence: runner `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2`. + Advisor review then found a repeated-failed-Remove regression: a no-op retirement + correction must not prevent the epoch/latch-guarded restoration of `userDisconnected`. + Decision: advisor, 88% confidence, restore that latch unconditionally inside the existing + guard and add two regressions; keep the exact-range correction and all supersession guards. + This corrective slice must be checked and reviewed before F1 is committed. + **Technical gate, no edits made:** the worker found that the new `laterGeneration` + superseded-delete fixture keeps the epoch unchanged, so the unconditional restoration + would change its latch/redisable expectations. The advisor must distinguish incidental + fixture expectations from a real newer-lifetime protection before approving a correction. + Preserve the epoch-superseded case and retirement-range immutability; do not weaken the + newer-lifetime contract to make the tests green. + **Gate resolved, advised (`claude-opus-5.5`), 85% confidence:** use the narrower helper + eligibility contract instead of the unconditional caller proposal. A matching latest + generation returns true even when its reason is already truthful; rewrite only + `connectionRemoved`, never existing `userDisconnected`/`credentialsChanged`. Missing or + later generations return false. The caller's existing epoch/latch/eligibility guards and + both superseded-test branches stay unchanged. Add repeated-failure and already-ended + reason cases; the operator's newer-lifetime contract is preserved without a new framework. + **Done (2026-11-30), commit `b7fd8bff5`:** explicit teardown now synchronously retires the + old host lifetime and detaches retained Collection/Document surfaces before async cleanup; + same-account client replacement stays live. Direct stale RPC/background-effect tests have + fresh-client positive controls. Failed storage removal restores truthful feedback without + reviving the lifetime or touching earlier/later ranges; repeated failures remain retryable. + Decisions: reuse the existing cutoff/cancellation boundary, advised (`claude-opus-5.5`); + final exact revision approved at 90% confidence. Correct the introduced failed-removal + feedback and idempotency defects within that boundary, advised at 85-88% confidence. + No user wording, persisted schema or `TDD:` contract changed. + **Final affected host pass:** at `dce388d99` plus final F1 changes, + `npx vitest run src/documentdb/connectionBindingRetirement.test.ts src/documentdb/connectionTeardown.test.ts` + passed 40/40 tests in two files (4 s, exit 0). Evidence: runner + `cb8fea69-b6fd-4ce2-95b1-b2d18f2a7bb2`; final advisor + `873c8316-29fd-47c1-aa2d-ff9dce2f1254`. The preceding root build and 302-test + R/F1 run passed before the final small helper/test delta. Rerun the integrated candidate + after F2/E/U/H; Dashboard native-menu coverage is still F2, not passed by F1. + + ```sh + npx vitest run src/commands/signInAgain/signInAgain.test.ts src/documentdb/ClustersClient.test.ts src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts src/documentdb/connectionTeardown.test.ts src/documentdb/connectionSurfaces.test.ts src/documentdb/connectionBindingRetirement.test.ts src/commands/disconnect/disconnect.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts + ``` + +- **F2 / `gpt-6.1-sol`, running after F1:** agent + `3c5e8387-8a8d-45bf-bd21-39c89459d597`. Route native Dashboard actions to the originating panel + session, never a replacement panel; remove frozen panels from the live-panel lookup. + F1/F2 are genuinely complex host lifecycle and cross-module work. + **F2 pre-edit gate resolved:** the existing ordinary-unreachable/Retry-lock test predates + D2. Advisor `4b1a9f9a-4c67-40c4-8e3f-2a8fcdeb5cbe`, 85% confidence, confirmed that + it must now preserve same-account/no-replay coverage while allowing the next explicit + native action without Retry. Keep explicit-end copy-only/frozen protections. NamespaceTable + already has `configuration.dashboardSessionId`; no extra parent prop wiring is needed. + The worker is implementing those scoped changes and its direct H1 mock dependencies. + **F2 implementation returned; first host check failed:** at `95cd11d0a` plus F2/E + working changes, + `npx vitest run src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts` + passed 48/49 tests in one of two files (2.57 s runtime). The new + `blocks frozen poll timers before acquisition, database calls or prompts and lets a fresh poll run once` + failed before its behavior assertions because the VS Code mock lacked `authentication`. + Source inspection confirmed neither suite nor test has a `TDD:` prefix; fix only the + fixture, retaining the effect assertions. Evidence: runner + `786c177f-56f7-4d20-9574-ac466cb4ac5a`. F2 advisor review and the fixture correction + are active; no F2 pass is claimed. + **Done (2026-11-30), commit `7417e01ea`:** native actions resolve the originating + Dashboard session only; retained snapshots leave the live-panel index without deleting a + newer panel. Ordinary failures do not lock the next explicit action. Decisions: advised + (`claude-opus-5.5`), source approved at 88% confidence; poll evidence reviewed at 87%. + Eight focused regressions were added; five scheduled frozen polls are explicitly awaited + and resolved, with zero acquisition/DB effects and a fresh-poll positive control. + The missing authentication fixture and two terminal `retry` expectations were corrected + without relaxing zero-delete, reason, ordering or polling assertions. + **F2 host pass:** at `b322b7463` plus F2/E/U1/H2 working changes, the same two-suite + command above passed all 49 tests in two files (2.70 s). Evidence: runner + `786c177f-56f7-4d20-9574-ac466cb4ac5a`. Final wave build also passed + (43.19 s); integrated rerun remains required. +- **E / `gpt-6.1-sol`, running after F1 in parallel with F2:** agent + `dfd29c24-8a4e-4f14-990e-6ad883077a38`. Ordinary Disconnect completes before either edit + wizard. Preserve the epoch/latch across disconnected editing and both storage writes; + cancellation or supersession writes nothing and partial failures remain visible. + The settled internal interface is + `ensureDisconnectedForEdit(clusterId: string, refreshTree: () => void): Promise`. + Capture its returned epoch after ordinary teardown, before wizard/storage reads; pass the + epoch guard to the existing save path. Reuse `Disconnect?` and the approved + `Disconnect and update` button, remove the obsolete post-save Shell notice, and retain + the existing partial-save warning. No new persisted schema or general source parameter. + Coordination decision: E's owned teardown/save/update files do not overlap F2's Dashboard + files, so F1 approval is the actual prerequisite; F2 is not an edit dependency. + **Partial implementation returned, not verified:** the worker added 35 cases and the + ordinary-disconnect edit flow, then stopped on an idle-startup race: a new client can start + during an unlatched idle wizard without changing its epoch. No completion is claimed. + **Gate resolved:** advisor `06b2055c-d1d9-416f-a12c-7a2af7657e55`, 85% confidence, + chose a behavior-preserving atomic pre-save predicate, not a new wizard hold or changed + cancellation/presentation. Export `canSaveEdit(clusterId, epoch)` using matching epoch + and either `userDisconnected` or the existing idle predicate; use it after prompts and + in `canStart`. Registered disconnected shells must remain allowed under `userDisconnected`. + The existing synchronous task guard/latch then excludes startup during both storage writes. + Add concurrent-work/no-write cases and positive controls; the worker is finishing this correction. + **E first host check failed:** at `b322b7463` plus E/F2/U1 working changes, + `npx vitest run src/commands/updateCredentials src/commands/updateConnectionString src/commands/saveConnectionEdit.test.ts src/documentdb/connectionTeardown.test.ts` + passed 143 tests and failed two failed-startup/disappearance positive controls (3.22 s). + Their real startup error path hit a missing `vscode.CancellationError` in the fixture + parser; the worker repaired only the parser fixture, keeping the original failure and + zero/positive-save assertions. Evidence: runner `3b7b403c-c6b3-46fc-b2cf-23a2860b3158`. + **E review:** advisor approved the atomic edit flow at 87% confidence, then confirmed + that the existing Yes/Reconnect choice became a no-op after restoring `userDisconnected`. + Correct it at 90% confidence: only a successful error-node Yes choice clears that hold + before resetting errors and refreshing; No, failure and another hold never clear it. + This honors the existing choice without reviving old views. Four regressions were added. + **Done (2026-11-30), commit `1d971f4c1`:** ordinary Disconnect now precedes either edit; + atomic save eligibility prevents newly started work from crossing an idle wizard, and the + existing storage latch prevents mixed settings. Existing partial-save feedback is retained. + Successful explicit Yes/Reconnect starts a fresh session; kept dirty tabs stay retired. + Decisions: advised (`claude-opus-5.5`), core review 87%, final Reconnect correction + approved at 92%. No temporary wizard hold, schema change or cancellation-policy change. + New effect cases cover both actual command paths, failed startup, active/pending work, + storage exclusion and the four Reconnect outcomes. + **E host pass:** at `b322b7463` plus final E/F2/U1/H2 working changes, the exact E + command above passed 149 tests in eight files (3.28 s), no failures. Evidence: runner + `3b7b403c-c6b3-46fc-b2cf-23a2860b3158`. Final root build passed + (43.19 s), including the typed fixture repairs. Integrated candidate rerun remains. +- **H1 / `mai-code-2`, after F1:** fence the shared client-operation callback and add C01 + effect-level regressions. **H2/H3 / `gpt-6.1-sol`, after F2:** propagate the captured host + lifetime/cancellation through schema/model and Playground handoffs; serialize H2/H3 because + they share the Collection router. The Sol slices involve multiple async side-effect boundaries. + **H1 preparation returned:** agent `12d342e8-2c9c-42f2-b4d8-619c13473792` added nine + create-command race/control cases in the new namespace-helper test file. No production + code or existing tests changed and no tests were run. The shared source guard remains + gated on F1 approval; preparation alone is not H host evidence. + **H1 source implementation running after F1 approval:** the same `mai-code-2` worker + now owns the shared last-synchronous operation check and the prepared namespace-helper + tests. E/F2 use disjoint files. Review and focused runtime evidence remain pending. + **H1 implementation returned:** the shared operation fence and nine effect cases are + written. Direct-dependent Class mock fixtures need the new method; the H1 worker owns + the five disjoint fixtures, and F2 owns its two Dashboard fixtures. No existing test + assertions or behavior are being changed merely to accommodate a mock method. Advisor + `789b6f3c-8f68-4bed-ba93-3fd0c2ec9d78` is reviewing the source boundary. + **H1 Done (2026-11-30), commit `95cd11d0a`:** the shared binding check now runs after + client resolution at the last synchronous point before the operation callback. Nine + regressions cover stale creates, temporary holds, permanent retirement, same-account + replacement and stale delete confirmation. Decisions: advised (`claude-opus-5.5`), + source review approved at about 90% confidence; retain the existing failure-attribution path. + Existing fixtures gained the required mock method without changing assertions. + **H1 host pass:** at `a0cb19066` plus H1/F2/E working changes, the command below passed + 151 tests in seven files (4.55 s), no failures. Evidence: runner + `14f3d87b-cf9c-40f6-96f0-3650c02abfd8`, advisor + `789b6f3c-8f68-4bed-ba93-3fd0c2ec9d78`. H2/H3 and integrated rerun remain pending. + + ```sh + npx vitest run src/commands/runBoundNamespaceCommand.test.ts src/commands/dashboardBoundCommands.test.ts src/commands/importDocuments/importDocuments.test.ts src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/documentView/documentsViewController.test.ts src/webviews/documentdb/documentView/documentsViewRouter.test.ts src/documentdb/ClustersClient.test.ts + ``` + +- **H2 / `gpt-6.1-sol`, implementation running:** agent + `b07a97fc-1db9-4155-9be9-3983e34df17c`; planned by advisor + `77bcdc61-58c3-480b-8775-0fee9bcbe27b` at 88% confidence. The sole producer is + Collection View, so `QueryGenerationContext` replaces `clusterId` with required + `binding: ConnectionBinding` and `signal: AbortSignal`. Capture the origin before + availability, but create the operation-epoch guard afterwards so same-account replacement + stays usable. Guard every sample; cancellation reaches the existing post-model-selection + send fence. Catch typed unavailable inside the telemetry callback rather than letting it + be swallowed, and pass client cancellation from QueryEditor. + **Done (2026-11-30), commit `54e890813`:** captured-origin sampling and combined + cancellation now fence schema/model side effects; typed unavailability and original + cancellation cross the telemetry wrapper correctly. Decisions: advised + (`claude-opus-5.5`), initial review 85%, final model-boundary correction approved at 90%. + Preserve DB epoch guards, but use the lifetime/request signal around the model call so + same-account repair does not discard a valid result. Twenty-four new effect cases include + same-account replacement, stale sampling, post-selection zero sends and ignored-abort replies. + The new cancellation assertion was corrected to `stepName`, not the generic translated message. + **H2 host pass:** at `b322b7463` plus working changes, `npm run build` passed + (43.19 s) and the three-suite H2 command passed 31 tests (4.07 s) before the final two + model cases. At `52a70c00b` plus final H2 changes, + `npx vitest run src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts` + passed all 14 generator cases (4.15 s). Evidence: runner + `9a70e0df-465b-417f-9b58-3a680ee602b0`; integrated rerun still required. +- **H3 / `gpt-6.1-sol`, exact contract settled; queued after H2:** advisor follow-up, + 85% confidence, reuses `DocumentDBShellPty._disconnectRevision`, not the host epoch. + Same-account recovery does not change that counter; explicit teardown does. A retained + Shell's links capture origin at click and remain unbound after any Disconnect. + Required `PlaygroundHandoffOrigin` has four cases: binding plus optional original pin/signal; + shell fingerprint/pin with an `isCurrent()` counter check; saved tree origin with epoch; + or none for anonymous/uninitialized/disconnected Shells. The saved case has no fingerprint + because no identity was captured. Validate after document display, remove any restored + connection on rejection, and preserve the supplied original pin using the existing service API. + No new lifetime framework or `PlaygroundService` change is authorized. + **H3 implementation running:** the same Sol worker starts only after the H2 commit, + with exclusive ownership of the shared Collection router. Docs-only P work is independent. + **H3 source review approved, 87% confidence; checks failed:** thirty effect cases were + added across six tests. At `1a1c6ceff` plus H3 working changes, `npm run build` failed + (47.31 s) with twelve TS2352 diagnostics from incomplete Uri/TextDocument fixtures in + four new/extended test files. The nine-suite H3 command below passed 395 tests and failed + eleven (16.43 s): the new Playground/index table cases accumulated earlier spy calls. + Exact-once and anonymous-no-warning assertions must stay; fix fixture types and clear each + owned mock's history between cases. No product logic change is indicated by these failures. + Evidence: runner `25c30672-1fd3-44ee-b249-979bd51c8647`, advisor + `77bcdc61-58c3-480b-8775-0fee9bcbe27b`. Source approval is not a host pass. + **Done (2026-11-30), commit `c640d447d`:** all four handoffs capture their originating + lifetime/pin before document-opening awaits. Rejected handoffs clear any restored binding + but retain text. Anonymous/missing/ended Shell origins stay unbound; same-account Shell + recovery uses the existing PTY disconnect counter rather than the host recovery epoch. + Decision: advised (`claude-opus-5.5`), exact source approved at 87% confidence; retain + existing explicit re-pick and the service API, without a new framework or worker pin removal. + Thirty regressions were added. Proper existing Uri/document builders and per-case mock + cleanup fixed the fixture failures without changing production logic or effect assertions. + **H3 host pass:** at `1a1c6ceff` plus final H3 changes, `npm run build` passed + (exit 0; precise wall duration not reported by runner), and the nine-suite command below + passed all 406 tests in nine files (15.29 s). Evidence: runner + `25c30672-1fd3-44ee-b249-979bd51c8647`. Integrated candidate rerun remains required. + + ```sh + npx vitest run src/commands/playground/newPlayground.test.ts src/documentdb/playground/PlaygroundService.test.ts src/documentdb/playground/PlaygroundEvaluator.test.ts src/documentdb/shell/ShellTerminalLinkProvider.test.ts src/documentdb/shell/ShellSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/openInteractiveShell/openInteractiveShell.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/collectionView/indexesTab/indexViewRouter.test.ts + ``` + +- **U1 / `mai-code-2`, running after F1 in parallel with F2:** agent + `559eab2f-1c5b-4190-9c53-0e959a8c756e`. Terminal notice only, X/copy without writes, ordinary + recoverable errors without freezing, and rendered-scenario updates. Exclude F2's Dashboard + row/session wiring from parallel ownership. **U2 / `mai-code-2`, after H2/H3:** remove + obsolete host Retry/unlock procedures and protocol; shared routers/controllers require serialization. + Coordination decision: F2's existing session configuration makes its files disjoint from U1. + Keep the approved notice and existing translated repair instruction, removing only the obsolete + Retry clause rather than introducing new recovery prose; uncertain-write cautions remain. + Rendered runs stay last, on the integrated candidate, not during parallel source edits. + **Close-path gate resolved:** advisor `439e40a0-1e6c-4d2a-9322-3c127897f0e9`, + 85% confidence, approved temporary close-only use of the existing recovery RPC for U1. + The hook accepts only `{ action: 'close' }`; keep dirty confirmation, cancellation, + double-click guard and translated close failures. U1 must remove all Retry/unlock calls from the UI. + U2 must replace this with a dedicated `closeView` procedure and remove the old protocol, + including its action field, after H2/H3. This is an intermediate compatibility slice, + not final protocol-removal evidence. + **U1 review/checks:** the one-way notice, close confirmation and stale-text protections + are present, but the advisor found repeating Dashboard recoverable-poll toasts and a + stale-close busy flag. Fix only failed-sample accounting for nonterminal polls and clear + the busy flag when still mounted; preserve the latest notice. A poll scenario and the + close-race assertion were added. + At `b322b7463` plus working changes, the wave `npm run build` failed (43.16 s) on + 13 E test-fixture overload/unused-import diagnostics and one U1 deferred-resolver type. + U1 unit command passed 20/25 tests (11.01 s); five Document View normal-save/dirty/ID/error + cases failed and require root-cause diagnosis, not assertion changes. The browser manifest + command passed 47 tests (1.96 s), which is not rendered proof. Evidence: runner + `35fcbb46-f009-4eeb-90ee-cae3703b37de`. Owners are fixing the typed fixtures and the + advisor is investigating valid Save completion suppression. + **Done (2026-11-30), commit `674ab9c41`:** terminal tabs keep a copy-only notice; + ordinary recoverable failures no longer lock the tab, and the UI has no Retry/unlock. + X only hides the notice. Close retains confirmation, dirty warning, cancellation and + error feedback through the temporary close-only RPC, pending U2 removal. + Decisions: advised (`claude-opus-5.5`), final source review 85%. Corrected the introduced + unstable callback dependency that falsely marked normal rerenders disposed (90% + diagnosis); existing Save/dirty/ID/error assertions are unchanged and all pass. + Repeating recoverable polls count failed samples without toasts; Close always clears its + busy flag while mounted. The new poll scenario waits for handled failed-sample readiness + rather than racing an exact repeating call count. + **U1 unit/fixture pass:** at `b322b7463` plus the corrected working changes, the four + UI suites passed 25/25 tests (10.62 s), including the five previously failing Save cases. + At `52a70c00b` plus U1 changes, the browser-manifest command passed 47/47 tests + (2.36 s), with 189 routes including the new three-theme poll scenario; only incidental + total counts changed. Evidence: runner `35fcbb46-f009-4eeb-90ee-cae3703b37de`. + Root build passed in the same wave before the final small hook/scenario correction. + **Rendered U, final U2 protocol and integrated checks remain pending.** + **U2 implementation running:** `mai-code-2` agent + `efa3a45f-b1e8-4d2a-882d-36cdc2232126`, after H3 commit. Advisor mapping approved + at 85% confidence: dedicated no-input `closeView` disposes the original controller; + remove old recovery callbacks, request/response/action types and Retry episodes. A shared + terminal-reason predicate preserves the exact prior terminal/recoverable split. Keep + frontend dirty confirmation and all F/E/H guards unchanged. The automatic RPC event + becomes `...closeView`; `unavailableReason` enrichment is unchanged. + **Blocked (2026-11-30), CONTENT-POLICY:** U2 returned 27 changed files and three + added close-router tests, with no build or runtime validation. Its final inspection + reported organization content exclusions for `src/webviews/`, + `src/webviews/documentdb/`, `documentsViewRouter.test.ts` and + `src/documentdb/connectionBindingRetirement.ts`. No alternate access, reconstruction + or validation that would access excluded code is authorized. U2 remains uncommitted + and unverified; its worker's zero-symbol claim is not an integrated verdict. + Further inspection, integrated/rendered checks, final pre-review and publication are + blocked until the organization policy administrator reviews access. Do not mark the PR + ready or infer a pass from earlier candidate checks. The already committed work through + `c640d447d` and docs commit `1a1c6ceff` remains separate from this unfinished slice. + **Access restored and Done (2026-11-30), commit `6bcf634e7`:** the operator confirmed + administrator restoration; a direct source read succeeded before normal checks resumed. + U2 removes the obsolete recovery/action protocol and supplies dedicated no-input + `closeView` RPCs. Three close-router cases prove disposal does not acquire a client or + revive a retired binding. Decision: advised (`claude-opus-5.5`), final corrections + approved at 90% confidence. Unique retirement IDs prevent test-state pollution, and the + hook retains the prior fire-and-forget callback shape with its existing error/busy guards. + No assertions were weakened. Automatic telemetry uses the new close procedure name. + **Integrated host/unit pass:** at `9222ec8f1` plus final U2 changes, `npm run build` + passed (7 s), all 1,157 tests in the 51 affected suites passed (31.58 s), and the + browser-manifest command passed 47/47 tests (1.30 s). Evidence: runner + `82a22618-e841-49f1-af0c-df4bb76f3613`, corrected integrated run. Rendered and live + results are separate; this is not a packaged or expiry pass. + **Latest endpoint clarification (2026-11-30):** the organization administrator restored + source access before this runbook was written; that updates the access prerequisite, not the + historical fact that U2's earlier inspection was content-restricted. H3 source is committed + at `c640d447d`; U2 remains pending review and integrated validation. Source access is no longer + a blocker. Manual live gates and the missing dedicated environments do not block an + implementation commit, the authorized stacked draft PR, or execution of Case 2; they block + readiness. Do not infer that any such commit, PR, Case 2 run, or manual pass has occurred from + this documentation clarification. +- **P / `mai-code-2` documentation, `mai-code-2-flash` checks:** align only directly affected + docs/contracts, rerun the integrated effects, collect rendered and packaged evidence, and + preserve separate live gates. The authorized order is implementation push and stacked + draft PR, then Case 2, then readiness only if all required gates and pre-review pass. + **Case 1 integrated pass (2026-11-30):** the candidate containing the committed U2 + source passed the build, 1,157 focused runtime tests and 47 fixture-manifest tests. + The exact root focused command follows. Publication is authorized now; Case 2 follows + the implementation push even with manual gates outstanding. The draft must not imply + readiness, final AI pre-review, packaged activation or live evidence that has not run. + + ```sh + npm run build + npx vitest run src/documentdb/ClustersClient.test.ts src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts src/commands/signInAgain/signInAgain.test.ts src/documentdb/shell/ShellSessionManager.test.ts src/documentdb/playground/PlaygroundEvaluator.test.ts src/documentdb/playground/WorkerSessionManager.test.ts src/documentdb/shell/DocumentDBShellPty.test.ts src/commands/playground/executePlaygroundCode.test.ts src/documentdb/connectionTeardown.test.ts src/documentdb/connectionSurfaces.test.ts src/documentdb/connectionBindingRetirement.test.ts src/commands/disconnect/disconnect.test.ts src/commands/updateCredentials src/commands/updateConnectionString src/commands/saveConnectionEdit.test.ts src/commands/runBoundNamespaceCommand.test.ts src/commands/dashboardBoundCommands.test.ts src/commands/importDocuments/importDocuments.test.ts src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts src/services/copilotService.test.ts src/commands/playground/newPlayground.test.ts src/documentdb/playground/PlaygroundService.test.ts src/documentdb/shell/ShellTerminalLinkProvider.test.ts src/commands/openInteractiveShell/openInteractiveShell.test.ts src/webviews/_integration src/webviews/components/DisconnectedOverlay.test.tsx src/webviews/documentdb/useBoundViewRecovery.test.tsx src/webviews/documentdb/documentView src/webviews/documentdb/collectionView/collectionViewController.test.ts src/webviews/documentdb/collectionView/collectionViewRouter.test.ts src/webviews/documentdb/collectionView/indexesTab/indexViewRouter.test.ts src/webviews/documentdb/clusterDashboard + npx vitest run --config build/verification/browser/vitest.config.ts build/verification/browser/scenarios.test.ts + ``` + + **Documentation slice Done (2026-11-30), commit `1a1c6ceff`:** aligned the feature + intent/index, user manual, existing unpublished 1.2 draft and shared cluster skill with + one-way teardown and live same-account repair. Removed Retry-unlock/revival and post-save + Shell-choice instructions; no new release, screenshots or announcement. The feature README + links this ledger instead of duplicating per-slice progress. Telemetry documentation required + no change for this slice. Decisions: leader review, 95% confidence, keep public instructions + concise and verification records here; no design deviation. Docs-only; no checks required. + **Live blocked, operator response (2026-11-30):** an authorized disposable Entra target is + unavailable; the operator will have manual tests performed at a selected candidate checkpoint. + A dedicated physical sleep/wake environment is unavailable. Deterministic implementation + continues; these responses are not live passes or permission to waive required readiness gates. + **Prerequisite evidence:** runner `f2f3b0ec-2762-4135-b213-b7778305f791` verified an + integrated browser page at `about:blank` (`readyState: complete`). Direct cached Chromium + launches failed because `libatk-1.0.so.0` is missing; pinned VS Code 1.109.0 is cached and + the X11 display socket is reachable, but packaged activation is untested. Use the working + integrated browser for U; attempt candidate packaged checks or matching candidate CI for P. + Neither a blank-page check nor an old VSIX is candidate rendered/activation/live evidence. + **Delivery preflight (2026-11-30):** origin's feature branch is still + `1e362403b`; it lacks the two pre-existing baseline commits through `3d66aa937`. + The new implementation branch has not been pushed and has no PR yet. Publish the exact + baseline to the feature ref before opening the stacked PR, so its diff contains only this + work. Parent #1136 uses milestone 1.2.0. Live gates block readiness, not publication + of the authorized draft or Case 2 execution. + Cached Linux VS Code 1.109.0 cannot even report its version: exit 127, missing + `libatk-1.0.so.0`. No system installation was attempted on this shared host. Actual candidate + packaged activation must use a working isolated runtime or matching full CI; a draft's + default fast CI tier is not that evidence. The repository has an explicit full-tier CI + request workflow. Evidence: runner `bb424424-de74-4168-9f05-f12f723fe609`. + Final AI pre-review remains a separate gate; per-item approvals do not pass it. + **Published draft (2026-11-30):** [#1149](https://github.com/microsoft/vscode-documentdb/pull/1149), + base `feature/connection-lifecycle`, milestone 1.2.0, first pushed head + `c4cc00e5663312e0f6a3002d936e13ccf30ad80b`. The feature baseline was safely advanced + to `3d66aa937` separately. All implementation and the detailed manual runbook were committed + before publication. The operator explicitly authorized full CI while retaining draft status; + run [46452303937](https://github.com/microsoft/vscode-documentdb/actions/runs/46452303937) + targets that first head, not later generated changes. + **Case 2 first post-push run:** at `c4cc00e56`, `npm run l10n`, + `npm run prettier-fix`, `npm run l10n:check`, `npm run build`, + `npm run typecheck:tests` and `npm run package` passed. Strict package-test type-checking + passed separately (17.169 s). Lint failed on eleven test-only import-type/unnecessary-cast + findings. Full `npx vitest run` passed 10,448 tests with one skipped, but one of 458 suites + could not load: `ClusterItemBase.test.ts` omitted the `AzureWizardPromptStep` dependency + from its partial azext mock. This is a failing suite, not a full runtime pass. + Formatting and localization output was committed separately as `37917fc74`; the mechanical + lint and mock-load repairs are in progress. Evidence: runner + `241b37a8-7866-4868-805f-274116b2843b`; all eight requested commands ran. + The intermediate VSIX packaged successfully, but is not the final candidate artifact. + **Rendered attempt, not a lifecycle pass:** runner + `45ca6ac4-9aa9-443f-aebb-82f1dd848693` attempted 27 affected routes across three themes + on first pushed head `c4cc00e56` (source hash + `cd5c27f83944864115f422ec1f7463079cbd65218a1f68e8ca41d03e5431a5bc`). + Only Document View default routes completed their layout assertions (3/3). + Collection routes timed out at readiness; dirty/stale Document scenarios timed out replacing + Monaco contents or lost execution context; Dashboard scenarios showed readiness/healthy-status + or held-reply-release mismatches. The lifecycle effect assertions were not established. + Do not attribute every mismatch to the product or environment without evidence, and do not + claim rendered X/copy/no-save or same-tab recovery passed. The runner stopped its own Vite + server and browser page. Keep rendered/workbench verification outstanding in the draft and + use the detailed manual runbook below; deterministic host evidence remains separately valid. + **Case 2 repair review:** the six changed test files replace prohibited inline module types + and unnecessary assertions without changing test expectations. The tree suite now forwards + real azext exports while retaining its custom telemetry/error mocks. Namespace imports that + accidentally included repository-restricted null helpers were replaced with the existing + opaque-export record pattern. The focused six-suite repair run passed 135 tests; a final lint + check and complete post-push Case 2 rerun follow. No production behavior was changed. + **Integrated path walk:** ordinary Collection reads still use `ClusterSession` and the shared + `runWithClient` resolution path. Delayed writes are fenced immediately before the operation + callback; query generation carries the originating lifetime/request signal through sampling + and the post-model-selection send boundary. Playground handoffs validate their captured + origin after document-opening awaits. Same-account client replacement does not retire the + logical lifetime. Intentionally retained safeguards are physical-client generation attribution, + startup/operation epochs, current holds, fingerprint guards, worker Entra pins and cancellation. + Removed mechanisms include the Retry/unlock RPC/action protocol, revival of explicitly ended + views, redundant post-save teardown and the post-save Shell choice. + **Delivery policy:** the final test/format repair commits are pushed before rerunning all eight + Case 2 commands. The draft PR's validation section and linked CI runs carry the exact final + head/VSIX receipt and results. These receipts do not turn unrun manual, rendered or author + pre-review gates into passes; #1149 must remain draft. + **E/H/U pre-edit baseline pass:** at `8c4854f0d` plus F1 working changes, + the command below passed 167 tests in 14 files (12.82 s). The distinct browser-manifest + command passed 47 tests in one file (1.28 s). No missing paths, failures or `TDD:` + failures. Evidence: runner `83db6668-3669-435b-b1a0-76a8ed2c89d0`. + These are host/fixture baselines, not rendered U or candidate P gates. + + ```sh + npx vitest run src/commands/updateCredentials src/commands/updateConnectionString src/services/copilotService.test.ts src/commands/playground/newPlayground.test.ts src/documentdb/playground/PlaygroundService.test.ts src/documentdb/shell/ShellTerminalLinkProvider.test.ts src/webviews/documentdb/useBoundViewRecovery.test.tsx src/webviews/components/DisconnectedOverlay.test.tsx src/webviews/documentdb/documentView/documentView.test.tsx src/webviews/_integration/describeUnavailableConnection.test.ts + npx vitest run --config build/verification/browser/vitest.config.ts build/verification/browser/scenarios.test.ts + ``` + +**F shared boundary:** `retireConnectionBindings(clusterId, generation, reason)` records +an ended lifetime without lowering its cutoff; `getRetiredBindingReason(binding)` preserves +the first end reason; `getBindingLifetimeSignal(binding)` aborts synchronously on teardown. +On failed Remove, correct only the matching latest retirement range to the truthful +`userDisconnected` reason; its lifetime remains permanently ended. +`ClustersClient.assertBindingActive(binding)` rejects ended lifetimes or current holds at +side-effect boundaries. `takeConnectionSurfaces(clusterId)` removes and returns the active +surfaces, so an old frozen snapshot is not closed by the next session's Close all. +Keep the existing internal physical generation and binding guards until replacement coverage +exists; no second general-purpose lifetime framework or worker-pin removal is authorized. For each completed slice update **its row** with status, revision, exact command or test name, observed result and a short evidence pointer. Use `pass`, `fail`, or `blocked: `; @@ -766,10 +1277,89 @@ A rerun on a different revision needs its own result. Report failures, fix and r the smallest reproducible blocker and continue independent rows. The orchestrator owns the integrated verdict; a worker's “done” or a green suite from the pre-change baseline is not it. +#### Manual-test follow-up (2026-11-30, 20:25 UTC) + +The operator reported three follow-ups on the same draft. These are three additional accepted +items, not a reinterpretation of the original seven checkpoints. Baseline `2f704aaad` has the +previously recorded passing Case 1, Case 2 and matching full CI; no tracked edits were present +at this follow-up's intake. The unrelated relay/telemetry directories remain out of scope. + +- **FUP-1 — contextual edit prompt; committed/verified (`mai-code-2`):** explain in the shared + Disconnect-and-update modal that credentials and connection strings can only be updated + while disconnected. Keep the existing heading/button and all teardown/cancellation guards. + Acceptance: both commands use the same explanatory path; ordinary Disconnect is unchanged. + **Done (2026-11-30), commit `e1757115d`:** added the shared modal detail, + "You can only update credentials or the connection string while disconnected." The original + heading, button and teardown guards are unchanged. Decision: operator's requested wording + context, implemented directly; leader review 98% confidence. Existing real-dialog assertions + now include the explanation. +- **FUP-2 — direct clean-view close; committed/verified (`mai-code-2`):** Close view dismisses + Dashboard, Collection View and clean Document View without a confirmation. Preserve the + existing warning, cancel, busy and error handling when Document View is dirty. This is the + operator-approved clarification recorded under decision 0032. + **Done (2026-11-30), commit `dcbf37fd8`:** confirmation runs only with the existing dirty + flag. Default/clean views close directly; dirty confirm, cancel, busy and failure protections + remain. Two focused cases assert zero confirmation RPCs and exactly one close for clean views. + Decision: operator's explicit clean-versus-dirty behavior; leader review 97% confidence. + **Combined focused pass:** at `2f704aaad` plus both follow-ups, the teardown/update/save and + overlay/hook/Document suites passed 170 tests in 11 files (12.29 s). Evidence: runner + `03fdc6df-e172-48e9-82b4-e88d7c893512`. Root build follows the Playground slice. +- **FUP-3 — truthful Playground status; committed/verified (`mai-code-2`):** the CodeLens must + stop claiming Connected after explicit Disconnect without needing a failed Run first. + Preserve file text, selected connection metadata where appropriate, pinned-account recovery, + execution holds and no automatic replay. Advisor diagnosis (`claude-opus-5.5`, 85% + confidence): display used only the selected-connection map, while Run checks a lifecycle hold. + Add a lazy internal latch-change event and reuse the service's existing disposable state-change + notification to refresh CodeLens/status bar. A shared service predicate distinguishes only + explicit `userDisconnected`, without altering selection, saved bindings or other recovery holds. + The existing information action must also describe that state truthfully. This is presentation + synchronization, not new connection or execution policy. + **Done (2026-11-30), commit `39be627c4`:** the lazy host latch event forwards through the + service's existing disposable state notification. CodeLens, status bar and the information action + share the explicit-disconnect predicate. Selection, file text, pins, remembered bindings and Run's + execution guard are unchanged. Ten regressions cover immediate refresh before Run, retained + selection, unlatch recovery, other holds, disposal and truthful information/switch actions. + Decision: advised (`claude-opus-5.5`), implementation reviewed and approved at 88% confidence. + **Combined Case 1 pass:** at `dcbf37fd8` plus the final Playground changes, `npm run build` + passed (44.305 s) and the command below passed 587 tests in 25 files (13.664 s). Evidence: + runner `dbf71ff3-5eeb-4e81-9301-b59b48c73cbe`. No runtime failures or contract changes. + + ```sh + npx vitest run src/documentdb/playground src/commands/playground src/documentdb/ClustersClient.test.ts src/documentdb/connectionTeardown.test.ts src/commands/updateCredentials src/commands/updateConnectionString src/commands/saveConnectionEdit.test.ts src/webviews/components/DisconnectedOverlay.test.tsx src/webviews/documentdb/useBoundViewRecovery.test.tsx src/webviews/documentdb/documentView/documentView.test.tsx + ``` + +The first two slices own disjoint source/tests and run independently of Playground changes. +Focused coding verification is Case 1. The operator subsequently chose to push the follow-up +commits to draft #1149 and rerun Case 2 after that push. Previous-head Case 2 results remain +historical until the new requested full run completes; manual/live readiness gates stay pending. + +**Follow-up post-push Case 2, first run:** on `117e9cce5`, localization, formatting, +localization check, lint, build, strict `typecheck:tests` and packaging passed. The full runtime +suite passed 10,493 tests but failed eight setup-dependent cases in +`TDD: CollectionNameCache`: its automatic client mock omitted the new latch-change subscription. +The operator explicitly approved a **mock-only update, keeping every TDD assertion unchanged**. +No contract expectation or production guard is being weakened. That fixture repair and its +focused verification must be committed/pushed before repeating the full eight-command run. +Final follow-up head, Case 2 outcomes and VSIX receipt are recorded in draft #1149. +The next post-push run on `a9d540c83` passed all 10,501 runtime tests (one skipped), +localization, formatting, lint, strict package-test type checks and packaging, but root build +rejected Vitest's getter-spy overload for a function-valued event getter. The mock fixture uses a +typed property descriptor instead; the event contract and every TDD assertion remain unchanged. +Root build, lint and the focused fixture must pass before publishing that typing correction. + +**Short manual retest for this feedback (not yet run by the agent):** open each update command on +a connected disposable target and verify the shared explanation before accepting or cancelling. +Disconnect with kept views, then Close view on Dashboard, Collection View and a clean Document: +each should close directly. A dirty Document must still allow cancelling the unsaved-changes +warning. With a selected Playground open, invoke Disconnect and do not run it first: both its +connection CodeLens and status bar should show Disconnected while the file and selection remain. +Run must still be blocked; tree Reconnect should refresh the label without automatically executing +the script. These observations supplement, not replace, the longer A–H live verification below. + #### Evidence the agent collects directly - **Host/race evidence:** run the affected suites with `npx vitest run `. Use deferred - promises at real production boundaries, fake timers only for timers, and spies at the *effect* + promises at real production boundaries, fake timers only for timers, and spies at the _effect_ (driver write, prompt, worker reply, model send). Don't infer “nothing happened” from an empty screen or a cancelled return value. Never try to undo an operation already sent. - **Rendered UI evidence:** adapt the checked-in [`disconnected-dirty`, `stale-save-after-reconnect` @@ -798,6 +1388,447 @@ integrated verdict; a worker's “done” or a green suite from the pre-change b traffic on the idle target. Capture elapsed time, sanitized callback evidence, prompt count, operation count and observed outcome per surface. Follow the existing telemetry gate for ingestion; local emission is not proof of ingestion. + + ##### Manual OP-6 / CP-5 execution runbook — NOT RUN for the candidate + + **Gate status and scope:** every group below is **NOT RUN** until a tester returns the evidence + requested in that group for the candidate identified in A. Pending manual evidence blocks + readiness only; it does not block publication of the authorized draft PR or the Case 2 checks. + Never copy a pass from another revision, package, profile, machine or account. Fake clocks, + mocked tokens, socket interruption or screenshots of a completed UI do not satisfy an expiry + gate; VM/simulated suspend does not satisfy the physical sleep/wake gate; local telemetry + emission does not satisfy ingestion. + + **Common safety boundary:** use only an authorized, disposable, non-production Entra-backed + DocumentDB test database and collection. The authorized administrator supplies two harmless + test documents and the normal test connection; do not request or record passwords, tokens, + access-token contents, tenant secrets or a complete connection string. Keep screenshots, + notes and logs free of account details, host names, resource IDs and database contents beyond + synthetic manual-test markers. Use the test ID instead of a person's name or email address. + Stop on a wrong target before saving, creating or deleting anything. + + Run A–H in the order below, but use a fresh session for each runtime group as stated. A is + common candidate preflight, B is continuous use, C is an independent first-write-after-idle + run, D is an independent physical sleep/wake run, E is an independent forced-repair run, F is + an independent teardown matrix, G is independent worker/workbench verification and H is + receipt/ingestion verification. A candidate may have mixed results; each group has its own + `pass`, `fail` or `blocked` result. + + ###### A. Isolated candidate and safe baseline (NOT RUN) + + **Prerequisites** + - The leader has supplied, for the candidate only: the candidate ID, exact commit SHA, VSIX + file name/version and expected SHA-256. Blank fields remain blocked; do not invent them. + - The operator is authorized to use a disposable Entra test database and collection containing + two synthetic documents. The account used to establish the connection is recorded under a + neutral alias such as `account-A`; use the same underlying account throughout A–G. + - A separate VS Code user-data directory or isolated VS Code Profile is available. It must not + inherit credentials, extensions, settings or synced state from the tester's normal profile. + + **Ordered steps** + 1. Assign `A---01` as the run's test ID. Record UTC start time, OS and + OS build, VS Code version, hardware class, and authentication path (`interactive Entra`, + `silent cached Entra`, or another candidate-supported path). Record `Entra account alias A` + only; do not record the sign-in address. + 2. Calculate the VSIX SHA-256 with the operator's local hashing tool. Record the result, VSIX + file name/version, candidate ID and commit SHA. Mismatch against the supplied tuple means + `fail`; a missing expected value means `blocked`. + 3. Install that VSIX into the isolated profile and enable only the extensions needed for the + test. Reload once and record the installed extension version. Do not continue if it differs + from the candidate tuple. + 4. Establish the named, disposable connection with the approved account. In the collection, + verify that the two expected synthetic documents are present, then record their count + without copying document IDs or real field values. + 5. Open a Collection View. Enter the synthetic filter for the two documents and select + **Find Query**. Open a Cluster Dashboard. Open one document, make a synthetic local-only + marker change and keep it dirty; capture the text without saving. Open an Interactive + Shell and run one read-only command, for example + `db..findOne({ manualRun: "" })`. Open a Query Playground, use the + same read-only shape in one block and select **Run** or press `Ctrl+Enter`. + 6. Before saving anything, confirm that the Collection query, Dashboard, dirty Document draft, + Shell result and Playground result retain the expected state. Record one prompt counter + (zero is expected) and one database-operation counter for the baseline. Count only explicit + user operations plus any clearly attributable database callback observed in sanitized logs; + do not count UI redraws or keystrokes as database operations. + + **Pass / fail / uncertain** + - **Pass:** one matching candidate is installed in an isolated profile; all five surfaces are + usable; the draft is still dirty and unchanged; the baseline has no background sign-in prompt; + records contain no secret or personal data. + - **Fail:** candidate mismatch, wrong target, unexpected prompt, lost dirty text, an operation + unexpectedly writes, or a surface cannot use the same account alias and target. + - **Uncertain:** any result depends on a blank profile check, unidentified server, missing + operation counter or sensitive value removal. Mark `blocked` and preserve only the safe + observation; do not turn uncertainty into `pass`. + + **Evidence and independence:** return the candidate tuple; sanitized environment/profile record; + baseline prompt and operation counts; and one observation line per surface. Baseline A is not + evidence for B–E elapsed or environmental prerequisites. + + ###### B. Continuous real-token-expiry use for about 90 minutes (NOT RUN) + + **Prerequisites** + - Use a fresh isolated run after A. The authorized tenant/test administrator confirms that the + normal issued Entra token has a real expiry inside the roughly 90-minute window and supplies + a safe way to record the expiry and renewal callback timestamps. The confirmation must not + contain the token or reveal its claims. If expiry cannot be demonstrated, the result is + `blocked: real expiry timestamp unavailable`. + - Prepare one read-only Collection query, a dirty Document draft, one Interactive Shell and one + Playground block as in A. Keep all four open. This is active use, not the idle-first-write + session in C. + + **Ordered steps** + 1. At `T0`, record UTC time, expected real-token expiry time, account alias, extension candidate + and the marker count. Establish the periodic query cadence: at `T0` and every 10 minutes + thereafter, select **Find Query** for the same filter or **Refresh** to rerun the last query. + Do not use an invented command palette action, script or other client. + 2. After each query, record the time, success/failure, result count, interactive prompt count and + explicit database-operation count. Keep the dirty Document draft open and do not save it; + record that its text remains unchanged. + 3. Continue this cadence through the observed real expiry and for at least one full post-expiry + interval. Capture only a sanitized callback outcome and timestamp proving that expiry/renewal + handling was crossed; never capture the callback payload or token. + 4. After confirmed expiry, issue a separate explicit read-only Interactive Shell command and + select **Run** once for the prepared Playground block. Record each command's visible result, + timestamp and prompt count. Do not type **Run All** or use more than the single prepared block. + 5. End only after at least about 90 real minutes have elapsed and after all Collection, + Shell and Playground post-expiry operations have completed. Record UTC end time and exact + elapsed duration; then compare the collection count/markers with the initial server-side + baseline. + + **Pass / fail / uncertain** + - **Pass:** elapsed time is about 90 minutes, real expiry is evidenced, post-expiry Collection, + Shell and Playground reads succeed, prompt count is zero, operation count equals the explicit + query/command attempts (no duplicate replay), server-side markers/counts did not change, and + the original query and dirty draft remain available. + - **Fail:** any interactive background prompt, wrong-account use, automatic command replay, + unexplained database write, lost query/draft, post-expiry operation failure, or duplicate + operation submission. + - **Uncertain:** no timestamped expiry proof, incomplete operation accounting or missing + server-side final count. Record `blocked`/`uncertain`, not a silent-renewal pass. + + **Evidence and independence:** return the cadence log, start/end/expiry times, sanitized callback + summary, per-surface prompt/operation counts and before/after marker counts. B must not be + reused as C: B intentionally creates database traffic and is not an idle-first-write test. + + ###### C. Independent idle first-write for at least two hours (NOT RUN) + + **Prerequisites** + - Start a new, non-sleeping session after A. The named disposable connection must be configured + with `retryWrites=false`. To configure the existing connection without exposing its value: + first end any live session through **Update Connection String…** → **Disconnect and update**, + edit the connection-string input locally, add `retryWrites=false` to the URI option portion + (after `?` when it has no options, or after `&` when it already has options), then save through + the existing flow. Do not paste, print, quote, screenshot or copy the full string into the + evidence. Reconnect and sanitize any log that contains it. If the operator cannot prove this + named connection uses `retryWrites=false`, the group is `blocked`. + - Close the Dashboard. Close Shell and Playground surfaces. Stop copy/export/import tasks and + all other database clients. Do not leave another VS Code window, polling tab or tree refresh + targeting the same collection. + - Create a unique, local-only marker in an existing test document and leave the Document View + dirty. The marker identifies this run and changes exactly one harmless field. + + **Ordered steps** + 1. Record `idle-start` immediately after the last connection operation. From this point, do not + expand/collapse the tree, open another surface, refresh, query, connect, diagnose or perform + a server-side check. Keep the machine awake; do not suspend it. + 2. Leave the one dirty Document View untouched for at least 7,200 real seconds. Record + `idle-end` and exact elapsed time. Keep the marker text visible; a screenshot is not required + and must exclude connection/account details. + 3. Select **Save** once. This Save must be the first database operation after the idle start; + there is no warm-up read, Find Query, tree expansion or Shell command. Start capturing the + sanitized host/driver observation before clicking, and stop when Save reaches a definite + acknowledged or failed result. Count matching submissions sent to the driver/server. + 4. Do not click Save again if the result is delayed, canceled or uncertain. Do not rely on a UI + spinner disappearing as an acknowledgement. Preserve the dirty draft text on an uncertain + result and record the visible outcome; never accept or initiate automatic replay. + 5. Only after the submission capture is complete, perform a separate explicit server-side check + through the authorized test method. Verify one target document has the exact marker and that + no second document or duplicate field update appeared. Record the check's time, marker + equality and resulting count. + + **Pass / fail / uncertain** + - **Pass:** real idle time is at least two hours; the first post-idle database operation is one + Save; exactly one driver/server submit is observed; the post-capture server result matches the + unique marker once; there was no automatic replay or warm-up; and the draft remained available + and its text was not replaced throughout any acknowledgement uncertainty. After a definite + acknowledgement the editor may show its normal saved state, but the exact draft text remains + captured until the post-ack server check; an uncertain result retains the dirty editor draft + and is not a zero-write pass. + - **Fail:** any pre-Save operation, more than one submit, duplicate write, wrong target, lost + draft, unexplained prompt, automatic retry, or a different server result. + - **Uncertain:** missing before-Save request capture, unavailable server-side result, inability + to distinguish acknowledgement from timeout, or inability to prove `retryWrites=false`. + Do not claim zero writes; retain the draft and report the exact unknown. + + **Evidence and independence:** return start/end/elapsed, configuration proof without the + connection string, the marker identifier, first-operation observation, submit count, final + dirty/saved state and post-capture server result. C must be separate from B and D. + + ###### D. Dedicated physical sleep/wake across real expiry (NOT RUN) + + **Prerequisites** + - Use a dedicated physical machine assigned to this test. A shared host, remote/shared VM, + container, VM save state, fake clock or simulated sleep is not an allowed substitute. Record + the machine assignment and confirm it has no unrelated users or workloads. + - A is complete on the machine and the approved test path can provide a real token expiry + timestamp without exposing a token. Prepare Collection, dirty Document, Shell and Playground + surfaces while still connected. + + **Ordered steps** + 1. Record `suspend-start` UTC, token expiry UTC, system uptime/power state and account alias. + Put the physical machine into its actual suspend/sleep mode. Do not perform network or + database traffic after that point. + 2. Leave it suspended until after the real token expiry. Record the physical `resume` UTC, power + event and elapsed suspended time. Do not inspect the token. + 3. Do not refresh the tree or open a new client. Explicitly, in this order, record the first + post-resume action and outcome on each existing surface: + 1. Collection View: select **Find Query** for the same read-only query. + 2. Document View: select **Save** once for its one unique dirty marker. + 3. Interactive Shell: press Enter for one prepared read-only command. + 4. Query Playground: select **Run** once for the one prepared read-only block. + 4. After each action, record prompts, operation count and visible result. A failed action must + remain failed unless the tester explicitly reruns it once for the tested account; no worker, + view or timer may replay it. + 5. Verify the Document draft/text state and perform the server marker/count check only after all + four submissions have been captured. Record account alias again to prove it was unchanged. + + **Pass / fail / uncertain** + - **Pass:** actual physical suspend/resume is evidenced, the resume follows real token expiry, + each first explicit action either succeeds silently or gives the documented explicit-repair + path, prompt count is zero for the silent path, no action is replayed, the Document text is + preserved, no duplicate write occurs and the account alias is unchanged. + - **Fail:** a shared/virtual/fake sleep substitute; unexplained interactive sign-in during + otherwise-silent renewal; lost text/query; automatic command replay; duplicate write; or + post-resume action binding to another account. + - **Uncertain:** missing physical power/resume evidence or proof that expiry occurred while + suspended. Record `blocked`; a resume before expiry is not the sleep gate. + + **Evidence and independence:** return machine description, suspend/expiry/resume timestamps, + elapsed duration, first-action log per surface, prompt/replay counts, account alias check and + final server result. D is one physical run separate from B and C. + + If manual sign-in is actually required on any D step, record `manual sign-in required` with the + timestamp and affected surface; do not label D a silent-recovery pass even if the operation + succeeds after signing in. Continue only as directed for E's explicit-repair gate. + + ###### E. Approved real renewal failure and same-tab sign-in repair (NOT RUN) + + **Prerequisites** + - An authorized tenant administrator has intentionally established a real test condition in + which silent renewal cannot complete and interactive sign-in is required. Obtain the + administrator's safe confirmation and test window, not instructions to revoke an arbitrary + account or token. If that condition is unavailable or not authorized, the result is + `blocked: real Sign-in condition unavailable`; do not fabricate it with mocks, a deleted + profile, a network break or token revocation instructions. + - Start with one live Collection View under account alias A and a prepared read-only query. + A Shell/Playground may be opened separately for their own explicit-repair observations. + + **Ordered steps** + 1. At the approved condition, run the read-only Collection query once. Capture its failure and + the Document/Collection state. Confirm no failed write or query result is replayed. + 2. In the tree, select **Retry sign-in**. First have the operator choose a different, authorized + test account alias B. Expected result: the repair is rejected; alias A remains pinned; + the view stays on the same tab and no database write occurs. + 3. Select **Retry sign-in** again and choose alias A, the account that established the + connection. Capture only the outcome, not the account address. Keep the same tab open; do + not use a separate unlock or reopen flow. + 4. Return to the same Collection tab and rerun the failed query exactly once through **Find + Query**. Repeat the same one-explicit-rerun rule for a Shell **Sign in again** and a + Playground **Sign in again** in their separate surfaces; never let a held command or code + block replay by itself. + 5. Verify server counts and markers did not change. Record prompt count and the number of + explicit repair/rerun operations. Close the approved condition only through the tenant + administrator's normal cleanup process. + + **Pass / fail / uncertain** + - **Pass:** the real Sign-in condition is observed; alias B is rejected without changing the + pin; alias A repairs the same tab; the tester explicitly reruns once; failed operations are + not replayed; no duplicate/automatic write occurs; and Shell/Playground retain their local text. + - **Fail:** alias B repairs or rebinds the old tab, a failed write/command automatically runs, + the same tab is permanently disabled despite an unchanged-account repair, or a connection + operation changes server data. + - **Uncertain:** setup is synthetic, callback/failure reason is unavailable, the same account + cannot be demonstrated under the alias record, or outcome cannot be separated from a manual + reopen. Mark `blocked` or `fail` according to the missing evidence; never infer repair. + + **Evidence and independence:** return the approved condition window/confirmation reference, + account-alias rejection and acceptance results, same-tab rerun counts, per-surface prompt counts + and unchanged marker/count check. E is separate from the silent paths in B and D. + + ###### F. Explicit end, edit, retained-view and fresh-view matrix (NOT RUN) + + **Prerequisites** + - The target is a disposable named connection. Prepare unique markers for: one dirty document, + one harmless document to create, one harmless document to delete, and one small copy/export or + import task. Keep all within the authorized collection and record baseline counts. + - Open Collection View, Document View and Cluster Dashboard. Set + `documentDB.connections.openTabsOnDisconnect` to `ask` for the choice matrix so the dialog + labels from the user manual are visible. + - Use distinct runs for **Disconnect**, **Remove**, and **Disconnect and update** so deletion + of the saved connection and edits do not contaminate later observations. + + **Ordered steps** + 1. For **Disconnect**, exercise: + 1. **Cancel** by closing the **Disconnect?** modal: connection and all views remain live, + and no database write or removal occurs. + 2. **Close all** with a dirty Document: at the unsaved confirmation choose the refusal/cancel + path, proving teardown does not continue. Repeat, choose **Discard changes**, and prove + the old views close only after teardown. + 3. **Keep open** with a fresh dirty local marker: old Collection/Document/Dashboard contents + remain copyable snapshots; dismiss the notice with **X**, copy loaded text and continue + with the negative/positive test below. + 2. Repeat the three choice paths for **Remove** in a disposable saved-connection run. A refused + dirty close or Cancel must leave the saved connection and cached account path intact; Close + all or Keep open removes only after ordinary teardown succeeds. + 3. Repeat the choice/cancel paths for **Disconnect and update**: + Cancel, a dirty-close refusal or teardown failure writes no connection-string/credential + change. A successful teardown alone opens the edit wizard. Cancel that wizard after teardown + and verify the connection remains disconnected and no partial setting was saved. + 4. Hold a small, safe copy/export/import long enough to invoke Disconnect. The extension must + report the active-transfer conflict and leave both task and live connection running. + Never kill the extension/host to create a race. After the task ends normally, perform a + new explicit Disconnect to complete the test. + 5. For a retained old session, complete this precise negative/positive sequence: + 1. Choose **Keep open**, reconnect the named connection and open fresh Collection, + Document and Dashboard views. Record the server baseline and the unique markers. + 2. In the old snapshot after X, attempt the enabled old Document **Save**, Collection create, + Collection delete and the Dashboard's existing native safe delete action. Use only + visible product controls. If a control is unavailable/disabled, record that the manual + run did not reach the host boundary; do not use DevTools, crafted requests or a claimed + manual RPC pass. + 3. Check actual database state: the old marker must not be saved, old create marker must + not appear, delete target must still exist, and Dashboard target/count must be unchanged. + A disabled appearance by itself is not evidence of zero database writes. + 4. In the newly opened fresh views, perform equivalent disposable Save/create/delete actions + with fresh unique markers and verify positive server-side changes. This positive control + proves the server and test permissions can observe writes. + 6. Start another old-session/fresh-session sequence, retain the old snapshot, then Disconnect + the replacement connection and choose **Close all**. The replacement session's views close; + the older retained snapshot and its dirty/copyable contents must remain open and read-only. + + **Pass / fail / uncertain** + - **Pass:** every selected choice follows the user-manual labels; Cancel/dirty refusal makes no + change; active transfer blocks teardown safely; edits start only after successful teardown; + kept tabs cannot change the database after replacement; fresh views prove positive writes; + old snapshots survive the second Close all; and no old view adopts the new settings. + - **Fail:** any zero-write claim lacks a server check; an old action changes data or binds to + the replacement client; a fresh action cannot make its positive control; Cancel/refusal + partially edits/removes; or the second Close all closes an older snapshot. + - **Uncertain:** manual controls cannot exercise an old host boundary. Record the UI limitation + and pair it with the deterministic host-race evidence; manual workbench evidence alone must + not be described as old-RPC coverage. + + **Evidence and independence:** return one matrix row per entry action/choice, transfer outcome, + the four-step old/fresh server checks, prompt/operation counts, and a second-Disconnect tab + inventory. Each entry action is a new connection/session; do not combine F with B/C/D timing. + + ###### G. Shell, Playground and retained-link workbench (NOT RUN) + + **Prerequisites** + - Start a fresh, independent real-expiry session after A; do not reuse B or D's operation counts + as G evidence. Keep terminal scrollback and the Playground file text. The deterministic host + race gate (holding a token reply or evaluation across Disconnect and releasing it after + reconnect) belongs to automated tests; the manual operator must not kill, pause or inject it + and must not rerun that suite. + + **Ordered steps** + 1. After real expiry, run one visible, read-only Shell command and one Playground **Run** in a + normal, non-held flow. Record result, prompt count, explicit operation count and retained + terminal/file text. Do not claim coverage from the command merely appearing in the editor. + 2. Explicitly Disconnect the connection. The Shell worker and Playground worker must stop; the + terminal scrollback and file text remain. Record that the interrupted command/evaluation is + not replayed after Disconnect or a later Reconnect. + 3. From a retained Shell result produced **before** the explicit end, click its Shell result/link + while the same-account recoverable connection is still live: it may recover/use that same + pinned account. After explicit end and reconnect, repeat with a retained old link: it opens + an unbound Shell, does not silently adopt the replacement worker, and requests an explicit + selection when a database operation is attempted. + 4. Use a retained Playground file after explicit end. Choosing a database/connection again must + be explicit; an allowed repick may open a fresh worker, but no old evaluation automatically + runs and no new account is adopted. + + **Pass / fail / uncertain** + - **Pass:** both normal post-expiry paths work once; text survives teardown; no command/evaluation + replays; pre-end same-account recovery remains usable; post-end links/files remain unbound + until explicit repick. + - **Fail:** a worker rebinds silently, a stopped command/evaluation replays, text disappears, a + post-end link uses the new connection without a user choice, or a different account is used. + - **Uncertain:** a held token/evaluation race was attempted manually or no worker identity/state + can be observed. Report automated host-race coverage separately and do not call the manual + run a race pass. + + **Evidence and independence:** return per-surface explicit operation/replay counts, preserved + text observations, pre-end versus post-end link behavior and repick choice. G is a workbench + complement to, not a replacement for, the automated worker-race tests. + + ###### H. Packaged candidate receipt and telemetry ingestion (NOT RUN) + + **Prerequisites** + - The leader supplies a candidate-matched package/activation receipt tying the candidate ID, + commit, VSIX version and SHA-256 to packaged contents and successful activation. A generic + fast-CI receipt or baseline VSIX is insufficient. The operator does not rerun automated checks + already performed by the implementation/handoff process. + - An authorized workspace viewer can query the extension's Application Insights workspace for + the exact UTC windows from A–G. If workspace/ingestion access is absent, record + `blocked: telemetry workspace access unavailable`. + + **Ordered steps** + 1. Verify and transcribe the supplied receipt fields into the H result; do not rebuild, + repackage or claim a successful Case 2 from local activation. A missing or mismatched receipt + is `blocked` until the leader supplies the matching one. + 2. Ask the authorized viewer for aggregate counts only, using the candidate version (including + prerelease suffix), each test's start/end UTC window and the existing queries in + [`telemetry.md`](../telemetry.md). Request `connection.tokenRenewal` by surface/outcome, + operations by family/result/failure class, and the other candidate-relevant lifecycle event + classes represented in that document. Do not request user IDs, event rows, raw properties, + host names, tenant/account IDs, tokens or connection values. + 3. Return one count table per run window showing event class, surface, outcome/result and count, + plus explicit `0`, `missing` or `not queryable` where applicable. Compare B–G observed + operations with the ingested aggregates. Local log emission alone is not ingestion proof. + 4. Reconcile any expected event count mismatch with the receipt/candidate version/time window. + If the candidate, window or identity of the event class cannot be established, mark the + telemetry gate `uncertain`/`blocked` rather than passing on a nonzero total. + + **Pass / fail / uncertain** + - **Pass:** the packaged receipt matches the candidate tuple and aggregate ingestion covers the + relevant test windows/classes for the matching extension version. + - **Fail:** package/hash/commit/version mismatch, activation receipt failure or an ingested + count/class proving a prohibited failure path that the manual report did not explain. + - **Uncertain:** no authorized ingestion query, wrong/missing candidate version/window, local + emission only, or counts that cannot be tied safely to this test. + + **Evidence and independence:** return the matched receipt reference, candidate tuple, UTC query + windows and aggregate-only class counts. H is not a substitute for B–G observations. + + ###### Copyable manual result template + + Return one block per group/run; never combine unrelated runs to hide a failure or missing + prerequisite. + + ```text + Candidate ID: + Commit SHA: + VSIX version/file: + SHA-256: + Group (A-H): + Test ID / independent run ID: + Start UTC: + End UTC: + Elapsed: + Environment (OS/build, VS Code, profile, physical/shared): + Auth path / account alias: + Token expiry, suspend/resume or idle timestamps (if applicable): + Preconditions completed (including target and retryWrites=false where applicable): + Ordered observations (timestamp | surface | explicit action | outcome | prompt count): + Operation counts (expected / submitted / replayed / writes / duplicates): + Database marker/count check and when it was performed: + Draft/query/terminal/file retention: + Sanitized evidence references (no tokens, secrets, personal IDs or connection strings): + Result: PASS | FAIL | BLOCKED | UNCERTAIN + Failure/uncertainty and exact remaining prerequisite: + ``` + - **Operator exception, not the default:** the agent sets up, drives and records everything its authorized environment permits. Request only the missing input/action (e.g. MFA, a disposable live target, genuine suspend/resume on a dedicated machine, or access to ingested telemetry). @@ -839,25 +1870,25 @@ strong. A2 approval and B2 acceptance do not authorize stale writes or unintende ## 9. Decisions this would change -| Decision | Revised effect | -| --- | --- | -| 0002 | C-balanced keeps internal generation; surface lifetime representation may change | -| 0003 | Keep no implicit identity switch; enforce through edit preconditions **and** lifetime cancellation | -| 0004/0007 | Keep Close/Keep and the existing setting under B2 | -| 0011 | Keep credentials/pin on Disconnect; avoid stale cached auth after an edit write | -| 0012/0013 | Simplify representations, but retain startup, save exclusion and handoff guards | -| 0016/0017 | B2 ends revival after explicit Disconnect; D2 removes recoverable-view Retry as well | -| 0018 | Live-edit policy superseded by disconnected editing; its risks still require coverage | -| 0019 | Keep no stale Dashboard delete; consolidate its guard if equivalent | -| 0021 | Remains relevant until fingerprint callers are actually removed | -| 0022 | Worker/anonymous Shell policy unchanged in this package | -| 0023 | D2 removes recoverable-view Retry episodes; B2 is Close-only after explicit Disconnect | -| 0024/0025 | Retain tree/worker stale-click and origin-specific feedback contracts | -| 0026 | A1 selection modified by 0030; pinned-account requirement retained | -| 0027 | B2 reaffirmed by 0031 | -| 0028 | Broad deletion rejected by 0031; section 5C's C-balanced replacement chosen | -| 0029 | Before 1.2.0, inside #1136, unchanged | -| 0030 | A2 approved on 2026-11-30 | +| Decision | Revised effect | +| --------- | ------------------------------------------------------------------------------------------------------------------------------ | +| 0002 | C-balanced keeps internal generation; surface lifetime representation may change | +| 0003 | Keep no implicit identity switch; enforce through edit preconditions **and** lifetime cancellation | +| 0004/0007 | Keep Close/Keep and the existing setting under B2 | +| 0011 | Keep credentials/pin on Disconnect; avoid stale cached auth after an edit write | +| 0012/0013 | Simplify representations, but retain startup, save exclusion and handoff guards | +| 0016/0017 | B2 ends revival after explicit Disconnect; D2 removes recoverable-view Retry as well | +| 0018 | Live-edit policy superseded by disconnected editing; its risks still require coverage | +| 0019 | Keep no stale Dashboard delete; consolidate its guard if equivalent | +| 0021 | Remains relevant until fingerprint callers are actually removed | +| 0022 | Worker/anonymous Shell policy unchanged in this package | +| 0023 | D2 removes recoverable-view Retry episodes; B2 is Close-only after explicit Disconnect | +| 0024/0025 | Retain tree/worker stale-click and origin-specific feedback contracts | +| 0026 | A1 selection modified by 0030; pinned-account requirement retained | +| 0027 | B2 reaffirmed by 0031 | +| 0028 | Broad deletion rejected by 0031; section 5C's C-balanced replacement chosen | +| 0029 | Before 1.2.0, inside #1136, unchanged | +| 0030 | A2 approved on 2026-11-30 | | 0031/0032 | Package P chosen; same-account repair keeps tabs live, explicit session end freezes kept tabs, and X only dismisses the notice | Decisions are immutable: record each reversal as a new entry plus a status change in the index. @@ -897,13 +1928,13 @@ Limits of this analysis: The operator answered the questions of section 10 and asked to record the direction. Recorded in [decisions.md](../decisions.md) as 0026 to 0029. -| Question | Answer | Differs from the recommendation? | -| ------------------------------ | ------------------------------------------------------------- | -------------------------------- | -| 1. A1 or A2 | **A1**: refuse and tell the user to Disconnect first (0026) | Yes (recommended A2) | -| 2. B1 or B2 | **B2**, "but still ask the user": the Close or Keep open modal stays; kept views are permanently disabled (0027) | Yes (recommended B1) | -| 3. Overlay (D) | Not answered. The in-view Retry overlay (0016, 0017, 0023, 0024) stays in force until decided | Open | -| 4. Sign in again, pinned only | **Yes** (0026) | No | -| 5. Before or after 1.2.0 | **Before 1.2.0, inside #1136** (0029) | No | +| Question | Answer | Differs from the recommendation? | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------- | +| 1. A1 or A2 | **A1**: refuse and tell the user to Disconnect first (0026) | Yes (recommended A2) | +| 2. B1 or B2 | **B2**, "but still ask the user": the Close or Keep open modal stays; kept views are permanently disabled (0027) | Yes (recommended B1) | +| 3. Overlay (D) | Not answered. The in-view Retry overlay (0016, 0017, 0023, 0024) stays in force until decided | Open | +| 4. Sign in again, pinned only | **Yes** (0026) | No | +| 5. Before or after 1.2.0 | **Before 1.2.0, inside #1136** (0029) | No | The original package shorthand was "M with A1". It is historical; section 6 above is the revised recommendation, and the earlier broad deletion estimate is withdrawn. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/03-pr1149-copilot-review.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-pr1149-copilot-review.md new file mode 100644 index 000000000..56645d03f --- /dev/null +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/03-pr1149-copilot-review.md @@ -0,0 +1,1022 @@ +--- +feature: connection-lifecycle +kind: review +status: active +prs: [1149, 1154] +created: 2026-12-01 +verified: 2026-12-01 +code: + - src/documentdb/connectionTeardown.ts + - src/commands/saveConnectionEdit.ts + - src/commands/playground/newPlayground.ts + - src/documentdb/shell/DocumentDBShellPty.ts + - src/commands/openCollectionView/openCollectionView.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts + - src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts + - src/commands/llmEnhancedCommands/queryGenerationCommands.ts + - src/documentdb/playground/PlaygroundService.ts + - src/documentdb/connectionFailures.ts + - src/webviews/_integration/connectionUnavailable.ts + - src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx + - src/webviews/documentdb/useBoundViewRecovery.ts + - src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.ts + - src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx + - src/webviews/documentdb/documentView/documentView.tsx +--- + +# PR #1149: Copilot review evaluation + +## Approved dispositions and implementation ledger + +**Operator-approved on 2026-12-01; see inline progress for implementation status.** The operator approved the +recommended options except for C01, C06, C08 and C10, as recorded below and in +[decision 0033](../decisions.md#0033-approve-the-pr1149-review-dispositions-with-explicit-complexity-tradeoffs). +These dispositions take precedence over the original recommendations and acceptance criteria +later in this document. The original findings and evidence are retained, not reclassified. + +| Item | Approved disposition | Scope | +| ---- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------- | +| C01 | Option 3: retain the existing latch/idle check | Accepted edge case; no completion-tracking fix | +| C02 | Option 1 | Retire the prior lifetime at the common edit boundary, including idle edits | +| C03 | Option 1 | Reject closed Shell origins, including previously captured callbacks | +| C04 | Option 1 | Carry the Dashboard origin through bound session creation and panel publication | +| C05 | Option 1 | Defer the full binding guard until after client resolution | +| C06 | Option 2 direction | Clear a removed connection's Playground selection; reuse the existing Connect path | +| C07 | Option 1 | Treat rejected Entra accounts as explicit same-account sign-in recovery, not binding retirement | +| C08 | Won't fix | Keep the overlay and database guards; accept local query editing after dismissal | +| C09 | Option 1 | Settle an invalidated current collections read as interrupted; enable manual Refresh | +| C10 | Option 2 | Stop polling after a recoverable failure; only explicit manual Refresh can resume it | +| C11 | Option 1 | Send localized title and detail through the existing notification contract | +| C12 | Option 1 | No standalone retained-state refactor | + +This authorizes **nine code fixes**: C02, C03, C04, C05, C06, C07, C09, C10 and C11. +C01, C08 and C12 are approved no-code dispositions. All twelve still need their original +discussion thread answered. Record implementation progress, advisor acceptance, commit, push, +checks and reply URL inline under the corresponding item; approval alone is not completion. + +**Execution:** [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154) targets +`feature/connection-lifecycle`. The `claude-opus-5.5` advisor confirmed the handoff order and found +no new decision to escalate. Recommended implementation models: `gpt-6.1-sol` for C04's +cross-module startup and publication race; `mai-code-2` for C02, C03, C05, C06, C07, C09, C10 +and C11. C04 and C07 share a client test file; the C11 notification-contract change follows the +C09 and C10 hook changes. The final workbench and live checks are separate from Case 1 and Case 2. + +## Scope and verdict + +Evaluated [Copilot's 2026-12-01 review](https://github.com/microsoft/vscode-documentdb/pull/1149#pullrequestreview-6128681886) +against PR head `f8da433c084d298bdecfe09a8003408dd7dcd708`. Local HEAD matched GitHub. All **12** +inline threads were unresolved and not outdated; a second GitHub read confirmed the same head, +review and thread inventory. The PR remains a draft. + +This follows the [previous comment-evaluation workflow](./02-pr1136-copilot-review.md): +collect the comments with discussion links, verify each claim, independently assess severity, +compare solutions and recommend one with reasons. **The following is the original technical +evaluation. The approved dispositions above now govern implementation; no fixes, GitHub replies +or thread resolutions have been performed by this document update.** + +**Result: 11 confirmed findings and one optional refactoring suggestion.** Copilot assigned four +High, seven Medium and one Low ratings. This assessment assigns **one High, six Medium, four Low +and one non-blocking optional item**: + +| Item | Finding | Copilot | Reassessed | Verdict | +| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------- | ------------- | ---------- | ----------------------------------------- | +| [C01](#c01-editing-can-start-before-teardown-finishes-or-after-it-fails) | Edit admitted before teardown succeeds | High | Medium | Confirmed | +| [C02](#c02-idle-edits-do-not-retire-pending-playground-origins) | Idle edit leaves a pending Playground origin valid | High | Medium | Confirmed | +| [C03](#c03-closing-a-shell-does-not-invalidate-its-captured-handoff-origin) | Closed Shell origin remains current | High | Medium | Confirmed | +| [C04](#c04-dashboard-navigation-can-create-a-session-for-a-replacement-identity) | Dashboard opens a view on a replacement identity | High | High | Confirmed | +| [C05](#c05-query-generation-cannot-be-the-first-operation-to-recover-an-evicted-client) | Generate Query cancels before client recovery | Medium | Medium | Confirmed | +| [C06](#c06-removed-playground-connections-are-presented-as-connected) | Removed Playground connection shown as connected | Medium | Low | Confirmed | +| [C07](#c07-a-rejected-entra-account-is-mistaken-for-a-permanently-ended-binding) | Wrong-account token freezes an otherwise recoverable tab | Medium | Medium | Confirmed | +| [C08](#c08-retained-collection-queries-remain-editable-after-notice-dismissal) | Copy-only Collection View still permits query edits | Medium | Low | Confirmed | +| [C09](#c09-a-recoverable-failure-can-leave-an-independent-dashboard-read-loading-forever) | Invalidated Dashboard read never settles its loading state | Medium | Medium | Confirmed | +| [C10](#c10-index-build-polling-can-repeat-recoverable-error-notifications) | Background index poll repeats notifications | Medium | Low | Confirmed | +| [C11](#c11-recovery-notifications-display-an-internal-reason-and-omit-the-title) | Notification exposes reason code instead of localized context | Medium | Low | Confirmed | +| [C12](#c12-persistent-retained-state-would-clarify-rendering-but-no-rendering-defect-was-demonstrated) | Render persistent retention from state rather than a ref | Low, optional | Optional | No current functional defect demonstrated | + +Severity reflects demonstrated impact, not just the presence of a race: + +- **High:** an old-origin action can create a live view for a different connection identity. +- **Medium:** a lifecycle safety precondition is violated, a delayed action survives the intended + session boundary, or a supported recovery workflow becomes unusable. +- **Low:** local retained-content editing or misleading/noisy presentation, without a demonstrated + database-access or identity bypass. +- **Optional:** a maintainability improvement without an identified failing behavior. + +The behavioral baseline for the original evaluation was [decisions 0030-0032](../decisions.md#0030-offer-disconnect-and-update-performing-the-ordinary-disconnect-flow-before-editing): +successful teardown before editing, guarded handoffs, permanently read-only retained views, and +usable existing tabs after same-account recovery. Decision 0033 qualifies the teardown guarantee +for C01's accepted edge case and the local Collection View editing policy for C08. It also selects +the simpler C06 and C10 alternatives. No additional general-purpose identity/lease framework is +approved. + +## C01. Editing can start before teardown finishes or after it fails + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752057973). +**Copilot: High. Assessment: confirmed, Medium.** + +**Approved disposition: option 3; no code fix.** The operator considers this an edge case and +rejects option 1's additional complexity. Keep the existing latch/idle eligibility check; do not +add teardown-completion tracking or claim this race has been fixed. The original option 1 +acceptance criteria below are not requirements for this round. + +**Done (2026-12-01), decision commit [`1b98521`](https://github.com/microsoft/vscode-documentdb/commit/1b985210362510facc41862314b712b785161fae):** +operator approved option 3 in Decision 0033; the edit/teardown race remains an accepted edge case. +No implementation or new tests. The checkpoint was pushed to draft #1154 after `npm run build` +passed. [Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757117308). + +> The `userDisconnected` latch is set before `commitTeardown` finishes closing the driver client, +> so another Update command can pass this check and save while Disconnect is still pending. If +> close later fails, editing has already started despite the requirement that teardown must +> succeed first. Track teardown completion separately from the latch, and await it or reject +> edits until it succeeds. + +**Evidence.** [canSaveEdit](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.ts#L66) +treats `userDisconnected` as sufficient. [commitTeardown](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.ts#L173) +sets that latch before awaiting driver close. +[deleteClient](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/ClustersClient.ts#L1274) +also removes the cached client before the close promise settles. A second edit therefore passes +preflight and the [save-time guard](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/saveConnectionEdit.ts#L34). + +An offline probe held driver close, invoked the real second-edit preflight and save helper, and +observed the mocked storage save run before close settled. After close rejected, a fresh edit +check still returned true. The +[existing ordering test](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.test.ts#L619) +covers the edit that initiates Disconnect, not another edit entering while it is pending. + +**Why Medium rather than High:** this concretely violates the approved teardown-success +precondition. It does not by itself demonstrate a database write or cross-identity access; the +probe changed only synthetic storage. + +**Options.** + +1. **Recommended:** track the outcome of an actual teardown attempt at the existing per-cluster + teardown boundary. An edit must await that attempt or fail explicitly while it is pending; + a rejected attempt must not become eligible merely because its latch or empty registries + remain. Recheck the epoch and task guard before saving. **Pros:** distinguishes intent from + completed teardown and covers both pending and failed closes. **Cons:** requires explicit + ownership/cleanup of the completion record and a defined retry path after failure. +2. Refuse an edit while teardown is pending, but discard that record on rejection. + **Pros:** a smaller concurrency fix. **Cons:** fixes only the overlap; subsequent edits can + still mistake failed teardown for safe disconnection. +3. Check only for an absent client or `userDisconnected`. **Pros:** no added state. + **Cons:** those facts become true before close completes; this is the current defect. + +**Why option 1:** the condition being enforced is successful teardown, not a request to +disconnect. Keep this bookkeeping local to teardown rather than building a second session system. + +**Acceptance:** hold driver close and start a second Update command; neither its wizard nor save +may proceed prematurely. Reject close and verify later edits also remain blocked with explicit +failure feedback. A successful close permits editing; cancellation, task conflicts and a genuinely +unused connection retain their intended behavior. + +## C02. Idle edits do not retire pending Playground origins + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058063). +**Copilot: High. Assessment: confirmed, Medium.** + +**Approved disposition: option 1.** Implement existing lifetime retirement at the common edit +boundary, including idle edits, without reintroducing C01's rejected completion-tracking design. +**Done (2026-12-01), commit [`d0132088`](https://github.com/microsoft/vscode-documentdb/commit/d0132088cbcf21ee56333c9668197c8d1409a076):** +the shared save boundary retires the prior lifetime after acquiring the update latch and before +storage changes, including idle edits. Earlier Disconnect retirement keeps its reason; eviction +alone does not retire. The operator approved option 1 in Decision 0033. Advised +(`claude-opus-5.5`), accepted at about 85% confidence based on the latch ordering and idempotent +retirement. Implementation: `mai-code-2`, as recommended. Added two `saveConnectionEdit` cases. +The exact-call assertions now pin both retirement reasons in order and retain the existing +Disconnect-before-prompt assertion; the advisor's optional extra call-count assertion was not needed. +Case 1 (`mai-code-2-flash`): `npm run build` and focused `npx vitest run` on `saveConnectionEdit`, +`updateCredentials`, `updateConnectionString` and `newPlayground` passed (105 tests, four suites). +Pushed to [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757355849). + +> The idle shortcut checks registered resources but does not account for pending handoffs. A +> tree-to-Playground handoff can be waiting when credential rejection evicts the last client; +> this branch then permits a password edit without retiring the old binding, allowing the +> delayed handoff to bind to the edited connection. Retire the previous lifetime even when +> the registries are empty, or track pending handoffs in the edit preflight. + +**Evidence.** [Edit preflight](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionTeardown.ts#L73) +returns immediately for the idle case. The +[save helper](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/saveConnectionEdit.ts#L34) +latches storage writes but does not retire bindings. A +[tree Playground launch](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/newPlayground.ts#L41) +captures a binding before opening the document; its +[late validation](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/newPlayground.ts#L169) +checks retirement and fingerprint, not every intervening epoch. + +The probe paused document creation, reported a native-auth credential rejection through the real +client failure handler, and edited the now-idle connection through the real preflight/save path. +The old binding remained unretired. After a same-fingerprint replacement was published, resuming +the handoff bound the Playground. The +[fingerprint helper](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionFingerprint.ts#L18) +was also checked: changing only the URI authority password preserves the fingerprint. + +**Why Medium rather than High:** a pending old-origin action crosses the intended edit boundary, +but the demonstrated case preserves identity/fingerprint. Creating the Playground does not run +its contents; a later explicit Run is needed for database effects. + +**Options.** + +1. **Recommended:** retire the prior logical lifetime at the common edit boundary, including the + idle shortcut, before storage can change. Reuse the existing idempotent retirement helper and + epoch/task checks. **Pros:** catches pending binding-based handoffs without enumerating every + producer; a password-only edit cannot hide behind fingerprint equality. **Cons:** an empty + registry can no longer be treated as proof that no old logical lifetime needs ending. +2. Register every pending handoff as a resource and include it in preflight. + **Pros:** preflight can enumerate and cancel outstanding handoffs explicitly. + **Cons:** adds registration/disposal obligations to every producer and can miss future ones. + +**Why option 1:** an explicit saved edit is the lifetime boundary. Ordinary credential rejection +or physical-client eviction must remain recoverable and must not itself retire views. + +**Acceptance:** hold a tree handoff, evict its last client, edit only the password, reconnect and +release the handoff. Preserve the document text, but leave the stale handoff unbound with guidance. +An ordinary same-account recovery without an edit must still permit a valid handoff. + +## C03. Closing a Shell does not invalidate its captured handoff origin + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058111). +**Copilot: High. Assessment: confirmed, Medium.** + +**Approved disposition: option 1.** +**Done (2026-12-01), commit [`2e01db69`](https://github.com/microsoft/vscode-documentdb/commit/2e01db6951268337eb3804424bf82b36f2d9f320):** +closed Shells no longer supply a Playground origin, and previously captured callbacks reject +the handoff after closure. Disconnect and authentication behavior are unchanged. The operator +approved option 1 in Decision 0033. Advised (`claude-opus-5.5`), accepted at about 90% confidence +after tracing both close paths and the final handoff guard. Implementation: `mai-code-2`, as +recommended. Added one `DocumentDBShellPty` regression covering both lookups and the captured +callback. Case 1 (`mai-code-2-flash`): `npm run build` and focused `npx vitest run` on +`DocumentDBShellPty`, `ShellTerminalLinkProvider` and `newPlayground` passed (208 tests, three +suites). Pushed to [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757418958). + +> Closing the terminal sets `_closed` and unregisters the Shell, but this captured origin still +> reports itself current. If a Playground handoff is waiting during closure and a later +> Disconnect or password-only edit, teardown cannot reach that Shell and the matching fingerprint +> can let the old handoff bind to the replacement session. Include `_closed` in the validity check +> and cover terminal closure during a pending handoff. + +**Evidence.** [close](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/shell/DocumentDBShellPty.ts#L253) +sets `_closed` and unregisters the terminal, but does not advance `_disconnectRevision`. +[getPlaygroundOrigin](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/shell/DocumentDBShellPty.ts#L329) +checks only the disconnect revision, authentication mode and fingerprint; its captured callback +also ignores closure. The +[handoff consumer](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/newPlayground.ts#L182) +accepts that callback plus expected-fingerprint equality. + +A probe captured an origin, called the real PTY `close()` with mocked terminal/session resources, +and found both `origin.isCurrent() === true` and a newly queried origin still reporting `shell`. +Later teardown cannot call `disconnect()` on an unregistered terminal. + +**Why Medium rather than High:** the demonstrated gap bypasses origin-lifetime validity, not +fingerprint or Entra-pin comparison. The stated password-only/same-identity replacement case is +valid; arbitrary different-identity adoption is not established by this finding. + +**Options.** + +1. **Recommended:** reject a closed PTY when creating an origin and include `!_closed` in the + already-captured `isCurrent` callback. **Pros:** fixes both new and pending handoffs with the + existing source-owned lifetime check. **Cons:** a handoff interrupted by terminal closure + becomes an unbound document and needs explicit re-selection. +2. Increment `_disconnectRevision` during close. **Pros:** reuses the current invalidation test. + **Cons:** conflates terminal closure with the separate Disconnect behavior; directly checking + `_closed` expresses the missing condition more clearly. + +**Why option 1:** a source that has closed cannot authorize delayed navigation. Checking only +future calls to `getPlaygroundOrigin` would leave previously captured callbacks valid. + +**Acceptance:** close a terminal during a held Playground handoff, then Disconnect/edit/reconnect +with the same fingerprint. No stale binding is installed; text remains available. A still-open, +current Shell continues to support the handoff. + +## C04. Dashboard navigation can create a session for a replacement identity + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058182). +**Copilot: High. Assessment: confirmed, High.** + +**Approved disposition: option 1.** +**Done (2026-12-01), commit [`5e39ca70`](https://github.com/microsoft/vscode-documentdb/commit/5e39ca709a59728ef89395bef9575ac9cfbc7f2b):** +both Dashboard paths pass the captured connection binding through session creation and panel +publication. The final guard rejects retired, changed or cancelled origins and closes the +unpublished session; a same-identity replacement within the lifetime can still open the view. +Decision: operator selected option 1 in Decision 0033; advised (`claude-opus-5.5`), accepted at +about 85% confidence based on the bound resolver, final synchronous guard, cleanup and both +entry points. Implementation: `gpt-6.1-sol`, as recommended. Added 15 cases across client, opener, +controller and router tests; updated the host action assertion to include the binding while keeping +the namespace, tab and no-relay assertions. Case 1 (`mai-code-2-flash`): `npm run build` passed; +focused `npx vitest run` on `ClustersClient`, `openCollectionView`, `clusterDashboardController`, +`clusterDashboardRouter`, `vscodeUriHandler` and `collectionViewRouter` passed (319 tests, six suites). +Pushed to [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757276509). + +> Open Collection and Manage Indexes call `openCollectionViewInternal`, which creates a session +> without the Dashboard's captured binding. If client startup spans Disconnect/Reconnect, that +> lookup can retry against the replacement and open a live view from the ended Dashboard. Carry +> the originating binding through session creation and check it before opening the panel; the +> Dashboard toolbar needs the same fix. + +**Evidence.** Both the +[row-action path](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/clusterDashboardController.ts#L281) +and [toolbar procedure](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.ts#L505) +check the Dashboard binding before calling the +[opening helper](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/openCollectionView/openCollectionView.ts#L40), +but do not pass it. [Session creation](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/ClusterSession.ts#L804) +awaits unbound `getClient(clusterId)` and captures whichever client's binding comes back. +[Client acquisition](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/ClustersClient.ts#L1000) +can retry a stale startup after an epoch change. + +The composition probe passed the source Dashboard guard, held client startup, completed explicit +teardown, published a different-fingerprint replacement and released the old startup. The real +acquisition/session/opening helpers created a new, unretired session for the replacement identity. +The originating Dashboard binding was retired. Only driver startup and the panel were mocked; +no database was read. + +**Why High:** unlike C02/C03, the receiving session no longer has the originating fingerprint. +The opened view is live for a different identity, so its subsequent reads and writes are not +protected by the old Dashboard's binding. A pre-await guard or discarding a later RPC result is +too early or too late, respectively. + +**Options.** + +1. **Recommended:** carry the originating binding/lifetime through both Dashboard entry paths + into session creation. Resolve through the existing bound-client mechanism, revalidate before + publishing the panel, and clean up any abandoned session. Keep ordinary tree/deep-link entry + semantics separate where there is no originating bound view. **Pros:** protects the point + that creates the new live surface, including same-fingerprint Disconnect/Reconnect. + **Cons:** changes the internal opening/session API and its directly dependent callers. +2. Check the Dashboard again only after `openCollectionViewInternal` returns. + **Pros:** a small caller change. **Cons:** the replacement-bound panel already exists and can + start its own work; rejecting the original RPC does not undo that side effect. +3. Disable these Dashboard navigation actions. **Pros:** fail-closed mitigation. + **Cons:** removes useful navigation instead of preserving its origin. + +**Why option 1:** this is a guarded-handoff requirement, not a need for more UI blocking. +Preserve the original lifetime across awaits and allow physical-client replacement only within +that still-live, same-identity lifetime. + +**Acceptance:** hold startup for Open Collection, Manage Indexes and toolbar navigation; end the +source session and reconnect with both the same and a different fingerprint. Neither case may +publish a live view from the ended source. Normal navigation and ordinary same-identity recovery +must work, with no orphaned session when opening is cancelled. + +## C05. Query generation cannot be the first operation to recover an evicted client + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058252). +**Copilot: Medium. Assessment: confirmed, Medium.** + +**Approved disposition: option 1.** +**Done (2026-12-01), commit [`94d6287e`](https://github.com/microsoft/vscode-documentdb/commit/94d6287e93d193e40e8fae2419eb7baf26e4e8e0):** +Generate Query checks cancellation before resolving a client, then validates the binding before +sampling or sending. It can recover an evicted same-identity client without another operation +running first. The operator approved option 1 in Decision 0033. Advised (`claude-opus-5.5`), +accepted at about 90% confidence based on the unchanged lifetime and identity checks and the +epoch staying current across same-identity publication. If Copilot is unavailable, its existing +notice can precede a stale-binding error; neither path sends a request. Implementation: +`mai-code-2`, as recommended. Added four `queryGenerationCommands` regressions. +Case 1 (`mai-code-2-flash`): `npm run build` and `npx vitest run +src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts` passed (18 tests). +Pushed to [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757492585). + +> This preflight requires a cached client before the recovery path can resolve one. After a tree +> failure evicts the client without retiring the view, Generate Query repeatedly cancels here +> even after connectivity returns. Check cancellation here and defer the full binding guard +> until after resolution, where `runBoundViewOperation` already performs it. + +**Evidence.** [generateQuery](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/llmEnhancedCommands/queryGenerationCommands.ts#L179) +calls the full guard before `runBoundViewOperation`. That +[guard](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/boundViewOperations.ts#L13) +throws `UserCancelledError` when `getBinding` returns no cached client, even if the binding is +unretired and there is no latch. The subsequent bound-resolution path is therefore never reached. + +A probe supplied an unretired binding and non-aborted request with no cached client: generation +cancelled and made **zero** client-resolution calls. The +[existing replacement test](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts#L120) +has the replacement binding already cached, so its passing result does not cover this case. + +**Impact:** Generate Query cannot initiate this recovery; another operation that repopulates the +client can make it work again. This is not a permanent retirement or an identity bypass. + +**Options.** + +1. **Recommended:** check request cancellation at preflight, then let bound resolution validate + the lifetime/identity and create or recover the client. Keep the full guard after resolution + and before sampling/model sends. **Pros:** restores recovery without weakening the existing + side-effect fences. **Cons:** a request can enter client resolution before discovering that + it cannot proceed, so cancellation and retirement tests remain important. +2. Change the shared guard to accept a missing cached client everywhere. + **Pros:** avoids this particular early cancellation. **Cons:** broadens the guard's contract + for callers that use it immediately before side effects. +3. Require a separate tree action first. **Pros:** no code change. + **Cons:** contradicts the same-tab recovery design and leaves a silent cancellation trap. + +**Why option 1:** the guard is appropriate after acquisition; it is misplaced before the path +that can supply the missing client. + +**Acceptance:** an unretired view with valid connection settings and no cached client can recover, +sample and send once. Abort, explicit retirement and different-identity replacement must still +prevent sampling/model sends. No failed operation is automatically replayed. + +## C06. Removed Playground connections are presented as connected + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058319). +**Copilot: Medium. Assessment: confirmed, Low.** + +**Approved disposition: option 2 direction.** Prefer clearing a removed connection's selected +Playground binding and reusing the existing **Connect** affordance/picker. The operator chose +this because it is simpler than adding shared reason-aware presentation. Keep the file text; +do not clear the selection for ordinary Disconnect or cancelled removal. + +**Approved acceptance:** after successful Remove, the affected Playground has no selected +connection, no connected claim, and the existing Connect path can select another database. +File contents remain intact. This replaces the original option 1 presentation requirements below. +**Done (2026-12-01), commit [`eb57981f`](https://github.com/microsoft/vscode-documentdb/commit/eb57981f01ea3d06d9dfc559cf298ecfaad68844):** +successful connection or folder removal clears matching selections and remembered bindings after +the storage delete. Playground uses the existing Connect picker and keeps the file text. +Disconnect and cancelled or failed removal retain the selection. The operator approved option 2 +in Decision 0033. Advised (`claude-opus-5.5`), accepted with high confidence based on ordering, +target scope, and the single state event. Implementation: `mai-code-2`, as recommended; added two +regressions for selection restoration and batch removal, and extended negative assertions. +Case 1 (`mai-code-2-flash`): `npm run build` and focused `npx vitest run` on `PlaygroundService`, +`connectionTeardown`, `deleteFolder` and `executePlaygroundCode` passed (126 tests, four suites). +Pushed to [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). Workbench +presentation remains unverified. [Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757815667). + +> Remove Connection sets `connectionRemoved` but retains the Playground's selected connection, +> so this predicate returns false after its worker has stopped. The refreshed status bar, CodeLens +> and information action therefore claim that the removed connection is connected. Handle +> removal as an ended connection with guidance to select another database, rather than suggesting +> Reconnect for an item that no longer exists. + +**Evidence.** [isUserDisconnected](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/playground/PlaygroundService.ts#L320) +recognizes only `userDisconnected`. With a retained selection, the +[status bar](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/playground/PlaygroundService.ts#L423), +[CodeLens](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/playground/PlaygroundCodeLensProvider.ts#L84) +and [information action](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/commands/playground/connectDatabase.ts#L35) +fall through to connected wording for `connectionRemoved`. A real-method probe confirmed both +the false predicate and the connected status-bar tooltip after setting that latch. + +**Why Low:** the selection's presentation is wrong, but this predicate does not authorize +execution. Removal's host-side latch and worker teardown remain in place; no database-access +bypass was demonstrated. + +**Options.** + +1. **Recommended:** expose a shared reason-aware ended-connection presentation for these three + consumers. Keep the selected target/text, distinguish Remove from Disconnect, and offer the + existing database picker for a removed connection. **Pros:** truthful and consistent guidance + without changing execution policy. **Cons:** requires coordinated wording and assertions + across the three surfaces. +2. Delete every selected Playground binding when its connection is removed. + **Pros:** existing unbound UI offers Connect. **Cons:** loses the remembered target/context + and changes selection behavior more broadly than this presentation defect. +3. Treat both reasons as a boolean disconnected state with the same Reconnect message. + **Pros:** smallest code edit. **Cons:** Reconnect cannot recover an item that was removed. + +**Why option 1:** absence of a connection and deliberate disconnection need different next +actions, not just the same warning icon. + +**Acceptance:** Remove immediately updates all three surfaces with select-another-database +guidance and preserves file text. Disconnect still gives valid tree-reconnect guidance; ordinary +same-account recovery must not be reported as removal. + +## C07. A rejected Entra account is mistaken for a permanently ended binding + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058391). +**Copilot: Medium. Assessment: confirmed, Medium.** + +**Approved disposition: option 1.** +**Done (2026-12-01), commit [`82723db3`](https://github.com/microsoft/vscode-documentdb/commit/82723db379c3bc89c5d499083b3623d57757593d):** +a rejected Entra account now requires sign-in without retiring the binding. The wrong account is +still rejected, the original account can repair the existing view explicitly, and actual identity +changes remain terminal. No operation replays. The bounded `connectionFailureKind` now records +`signInRequired` for this case. The operator approved option 1 in Decision 0033. Advised +(`claude-opus-5.5`), accepted with high confidence based on the unchanged pin checks and explicit +replacement path. Implementation: `mai-code-2`, as recommended; added one mocked host recovery +regression and updated classifier and host reason assertions without weakening the no-replay +assertion. Case 1 (`mai-code-2-flash`): `npm run build` and focused `npx vitest run` on +`connectionFailures`, `ClustersClient`, `signInAgain`, `startupFailureTelemetry` and diagnostics +`authenticate` passed (253 tests, five suites); live Entra was not exercised. Pushed to +[draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757586804). + +> `identityChanged` also represents an `EntraIdentityMismatchError` from a silent token lookup, +> not just a changed connection binding: `classifyConnectionFailure` maps that error to this +> reason and evicts the client. A provider returning the wrong account therefore permanently +> freezes the tab, even if the user subsequently signs in with the original account; the hook +> never clears its terminal ref. Distinguish a rejected token/account from an actual binding +> change so same-account repair can keep the tab usable without accepting the wrong account. + +**Evidence.** The +[silent token callback](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/auth/MicrosoftEntraIDAuthHandler.ts#L244) +correctly rejects a different account. The +[classifier](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/connectionFailures.ts#L98) +maps that error to `identityChanged` with eviction. +[runWithClient](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/documentdb/runWithClient.ts#L19) +preserves the reason, which the +[webview contract](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/_integration/connectionUnavailable.ts#L20) +classifies as terminal. + +The probe reported a real `EntraIdentityMismatchError` against a synthetic Entra client. Its +logical binding was not retired, but the real recovery hook permanently blocked the view for +the resulting reason. Publishing a same-fingerprint replacement did not clear that block. + +**Impact:** fail-closed behavior is maintained: the wrong account is rejected, not accepted. +The defect is unnecessarily losing same-tab recovery after repairing the original account. + +**Options.** + +1. **Recommended:** classify a typed token/account mismatch as requiring explicit same-account + sign-in recovery, using the existing `signInRequired`/`replaceOnRecovery` path where possible. + Preserve the original pin and error cause. Reserve terminal `identityChanged` for an actual + incompatible binding. **Pros:** separates failed authentication from a changed identity + without adding another general lifecycle state. **Cons:** changes the classifier's expected + outcome and requires checking host/worker recovery consumers and wording. +2. Add a dedicated bounded account-mismatch reason through the host/webview protocol. + **Pros:** can provide more specific original-account guidance. + **Cons:** wider protocol, classifier and UI changes if existing sign-in recovery is sufficient. +3. Make every `identityChanged` response recoverable in the hook. + **Pros:** tiny change. **Cons:** conflates actual binding changes with rejected tokens and + weakens a boundary that must remain terminal. Do not choose this. + +**Why option 1:** rejecting an offered account does not mean the established binding changed. +Retain the refusal and the pinned identity while allowing the approved explicit repair workflow. + +**Acceptance:** a wrong account returned silently is never used. After explicit sign-in with +the original account, the same tab can execute one new user-requested operation. An actually +different fingerprint and explicit Disconnect/Remove remain permanently blocked. Preserve +worker pin checks, fresh-client recovery and the no-automatic-replay rule. + +## C08. Retained Collection queries remain editable after notice dismissal + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058453). +**Copilot: Medium. Assessment: confirmed, Low.** + +**Approved disposition: won't fix.** The operator considers the existing overlay sufficient to +make the disabled connection clear; choosing to edit local query text after dismissing it is the +user's responsibility. Keep the overlay and all database-operation/lifetime guards. Do not add +query-editor read-only gates or treat the original acceptance criteria below as implementation +requirements. This does not authorize database access or relax Document View's existing guards. + +**Done (2026-12-01), decision commit [`1b98521`](https://github.com/microsoft/vscode-documentdb/commit/1b985210362510facc41862314b712b785161fae):** +operator approved local Collection View query editing after notice dismissal in Decision 0033; +the overlay, database guards and Document View protections are unchanged. No implementation or +new tests. The pushed checkpoint passed `npm run build`. +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757120247). + +> Passing the retained unavailable state here does not make the Collection View read-only: +> after dismissing the notice, `QueryEditor` still creates its Monaco editors with +> `readOnly: false`, and its Clear Query and skip/limit inputs remain active. Users can therefore +> overwrite the retained query even though the notice promises a copy-only snapshot. Apply +> this state to the query editors and mutating controls while keeping text selection and +> copying available. + +**Evidence.** [Collection View](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/CollectionView.tsx#L818) +keeps terminal details in its lifecycle context after the dismissible notice is cleared. +However, [QueryEditor options](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx#L274) +hard-code `readOnly: false`; [Clear Query](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx#L688) +still resets values, and [Skip/Limit](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/components/queryEditor/QueryEditor.tsx#L817) +have neither read-only nor disabled state. + +**Why Low:** this breaks the promised retained snapshot and can overwrite local query text, +but the operation/lifetime guards still block database submissions. It is not evidence that a +retained view can write to a replacement connection. This finding was verified by source tracing, +not by rendering production Monaco in VS Code. + +**Options.** + +1. **Recommended:** use persistent retained status to make all query editors and value-mutating + controls read-only/disabled, including programmatic Clear/history replacement paths. Keep + selection, copying and presentation-only navigation available. **Pros:** implements the + accepted copy-only behavior without removing the retained contents. **Cons:** controls need + consistent state and focused UI checks after notice dismissal. +2. Change the notice to allow local query editing while continuing to block execution. + **Pros:** smaller implementation and potentially useful scratch editing. + **Cons:** changes the approved permanent-read-only behavior and would require an explicit + operator decision, not just a wording adjustment. + +**Why option 1:** the existing decision is clear; this is missing application of that state, +not ambiguity about whether database operations should resume. + +**Acceptance:** after Disconnect/Keep and X, typing, Clear Query, query replacement and Skip/Limit +cannot change retained values. Text selection/copy and access to already-loaded query fields work. +Recoverable sign-in/network failures leave the editors usable. + +## C09. A recoverable failure can leave an independent Dashboard read loading forever + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058526). +**Copilot: Medium. Assessment: confirmed, Medium.** + +**Approved disposition: option 1.** +**Done (2026-12-01), commit [`0b81b831`](https://github.com/microsoft/vscode-documentdb/commit/0b81b83199ef0f7f47ae49cdf3ebf9241b65960a):** +invalidated collections reads settle as interrupted without replacing rows. Manual Refresh can +start a new request; background retry and terminal submissions stay blocked. Operator approved +option 1 in Decision 0033. Advised (`claude-opus-5.5`): the first review found a same-key return +navigation defect, and the first focused run exposed an unstable mocked client. `mai-code-2` +corrected the navigation state and test harness and added five focused cases overall. The advisor +accepted the revision at about 85% confidence. Workbench transition timing remains unverified. +Final Case 1 (`mai-code-2-flash`): `npm run build` and focused `npx vitest run` on +`useDatabaseCollections.test.tsx` and `useBoundViewRecovery.test.tsx` passed (14 tests, two suites). +Pushed to [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757735541). + +**Integration follow-up [`269d371f`](https://github.com/microsoft/vscode-documentdb/commit/269d371f7bda21aa828ecd5bf3cee9938c02619b):** +the Dashboard regression now depends on the stable ref objects to satisfy React Compiler lint. +Advised (`claude-opus-5.5`), about 85% confidence in the final correction; implemented by +`mai-code-2`. No runtime or assertion changes. Final lint, test type-check, affected tests and +the full runtime suite passed. + +> A recoverable failure still advances the view-wide revision, so it discards unrelated pending +> reads without blocking submissions. If Dashboard storage refresh fails before its collections +> read returns, `useDatabaseCollections` drops that reply but never settles its request key, +> leaving Refresh disabled even after sign-in repair. Settle invalidated loads as interrupted, +> or use request-scoped invalidation so independent reads can finish. + +**Evidence.** [showUnavailable](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L75) +increments the shared revision even for recoverable failures. +[Storage loading](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L218) +calls it on a typed unavailable result. The independent +[collections hook](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.ts#L81) +then ignores its late success/failure. Its abandonment bookkeeping only notices a submission +block, which recoverable failures no longer create. +[isLoading](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/components/useDatabaseCollections.ts#L131) +stays true for the unsettled key, and +[Dashboard Refresh](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/clusterDashboard/ClusterDashboard.tsx#L831) +is disabled. + +A React probe composed the real recovery and collections hooks, held a collections reply, +reported a recoverable sign-in failure, then resolved the reply and rendered again. It observed +`isLoading=true`, `isInterrupted=false` and no submission block. The operation had finished, but +its UI request remained outstanding. + +**Options.** + +1. **Recommended:** explicitly settle an invalidated current collections request as interrupted, + retaining existing rows and enabling manual Refresh. Do not let an old request settle or + overwrite a newer database/request key. **Pros:** repairs the demonstrated dead end while + preserving existing stale-result guards and the no-replay policy. **Cons:** still discards an + independent read that might otherwise have been useful. +2. Make recoverable failures request-scoped and reserve view-wide invalidation for terminal + transitions. **Pros:** unrelated valid reads can complete normally. + **Cons:** requires auditing pending reads, mutations and loading resets across all hook + consumers; broader than fixing this request's settlement. +3. Automatically reload discarded requests after failure. **Pros:** can clear the spinner. + **Cons:** adds background work/retry policy and may repeatedly fail rather than repairing + request accounting. + +**Why option 1:** no UI request should remain loading after its completion has been deliberately +discarded. This can be fixed without weakening identity fences or automatically replaying work. + +**Acceptance:** with storage and collections reads outstanding, fail storage first and complete +collections afterward. Preserve existing rows or show an interrupted state, stop the spinner and +enable explicit Refresh after repair. Also cover late rejection, database navigation, a newer +request and explicit terminal teardown. + +## C10. Index build polling can repeat recoverable-error notifications + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058577). +**Copilot: Medium. Assessment: confirmed, Low.** + +**Approved disposition: option 2.** Stop index-build polling after a recoverable failure. +Connectivity returning or successful sign-in must not resume it automatically; the user must +explicitly refresh the table. Do not implement option 1's foreground/background callback expansion. + +**Approved acceptance:** after the first recoverable poll failure, no new automatic poll or +repeated notification occurs, including after repair. Explicit manual Refresh is the only resume +action for that paused table; a failed refresh leaves it paused, and a successful one may resume +normal build polling while a row is still building. Terminal teardown still prevents submissions. +This replaces the original option 1 acceptance criteria below. +**Done (2026-12-01), commit [`700c6d1f`](https://github.com/microsoft/vscode-documentdb/commit/700c6d1f91960a4a4f17f3e19ad7d5c287192256):** +the first recoverable poll failure pauses periodic index loads, even through repair and +switching tabs within the same Collection View. Only a successful manual Refresh resumes polling; +failed Refresh and terminal blocking are unchanged. The operator approved option 2 in Decision 0033. Advised (`claude-opus-5.5`): the first review surfaced a pause lost on remount. The advisor +accepted the per-view correction with high confidence. Implementation: `mai-code-2`, as +recommended; five fake-timer regressions include the remount case. Final Case 1 +(`mai-code-2-flash`): `npm run build` and focused `npx vitest run` on `IndexesTab.test.tsx` +passed (five tests). Pushed to [draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +Workbench timing remains unverified. [Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757984995). + +> The Indexes tab's five-second build poll also sends recoverable failures through this +> notification path. Because these failures no longer block submissions, a retained building +> row keeps the poll running and produces another notification every five seconds until repair. +> Carry a foreground/background option through the lifecycle callback so background failures +> stay quiet or inline while explicit operations still show actionable errors. + +**Evidence.** [Index refresh](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx#L289) +already limits ordinary rejected-request notifications to initial/manual loads. Its typed +unavailable branch instead always calls `showUnavailable`, which +[always notifies for recoverable reasons](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L73). +The [build timer](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx#L451) +re-arms while retained rows are building/creating and submissions remain permitted. + +The actual hook produced three notifications for three successive recoverable callbacks, without +a terminal block. The polling route was source-traced, not exercised as a rendered five-second +timer. More precisely, the repetition is once per failed poll cycle: the five-second timer plus +request duration, not necessarily every five seconds of wall-clock time. + +**Why Low:** this is disruptive notification noise and violates the background-presentation +policy, but does not itself execute a write, accept another identity or block explicit repair. + +**Options.** + +1. **Recommended:** carry foreground/background intent into unavailable presentation. Use the + existing initial/manual distinction for index reads; keep background recoverable failures + inline or otherwise quiet. Still apply terminal lifetime invalidation from any source. + **Pros:** preserves actionable explicit-operation errors and quiet polling. + **Cons:** requires propagating intent through the lifecycle callback/context and its callers. +2. Stop build polling after its first recoverable failure and require manual refresh to resume. + **Pros:** prevents repetition and reduces failed requests. + **Cons:** changes automatic build-status recovery and introduces an extra resume policy. +3. Suppress every repeated error globally. **Pros:** fewer notifications. + **Cons:** can hide a later explicit user operation's failure and does not model intent. + +**Why option 1:** the same failure needs different presentation depending on who initiated the +read. The existing rejected-request branch already follows that principle. + +**Acceptance:** retain a building row and return typed recoverable failures over several poll +cycles: no repeated toast. A manual refresh still explains the failure. Explicit Disconnect stops +new polling/submissions, and a background terminal event still freezes the old view. + +## C11. Recovery notifications display an internal reason and omit the title + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058652). +**Copilot: Medium. Assessment: confirmed, Low.** + +**Approved disposition: option 1.** +**Done (2026-12-01), commit [`dc4a95b7`](https://github.com/microsoft/vscode-documentdb/commit/dc4a95b7d2b0c07521354dde51d6572a9f14bb61):** +recoverable notices pass the existing localized title and detail to the non-modal host contract +instead of the internal reason. Terminal and close behavior are unchanged. The operator approved +option 1 in Decision 0033. Advised (`claude-opus-5.5`), accepted with high confidence based on +the host formatting contract and all five recoverable reasons. Implementation: `mai-code-2`, as +recommended. Expanded the hook regression and added a host-formatting test; updated the exact +Document View and browser scenario payloads without changing call counts or modality. +Case 1 (`mai-code-2-flash`): `npm run build`, five focused webview and host suites (35 tests), and +the separately configured static browser-scenario suite (47 tests) passed. This did not render +the journey or the workbench toast. No localization source strings changed. Pushed to +[draft #1154](https://github.com/microsoft/vscode-documentdb/pull/1154). +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4758052211). + +> `common.displayErrorMessage` appends a non-modal `cause` to the message, so this produces text +> such as "Sign in from the connection tree. (signInRequired)". It also drops the localized title +> that explains what failed. Use the localized title and detail instead of the internal reason +> code, and update the exact-payload assertions. + +**Evidence.** The [recovery hook](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L87) +sends `message: failure.detail` and `cause: failure.reason`. +The [host procedure](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/_integration/appRouter.ts#L249) +appends a non-empty non-modal cause in parentheses. The real-hook probe observed that exact +payload for `signInRequired`; the localized `title` was absent. The existing hook test explicitly +asserts this payload, so test success does not establish correct user-facing wording. + +**Why Low:** a bounded internal category is shown, not a credential or private raw error. +The remediation detail is still present, but its context/localization is unnecessarily degraded. + +**Options.** + +1. **Recommended:** send the existing localized title as `message` and localized detail as + `cause`, following the current non-modal display contract. **Pros:** includes both explanation + and action without a transport change or new reason-code prose. **Cons:** uses the existing + parenthesized detail presentation rather than redesigning notification layout. +2. Format title and detail into a single localized message and send an empty cause. + **Pros:** more control over readable sentence structure. + **Cons:** adds a formatting string and changes the payload convention for this caller. +3. Change the shared host procedure to ignore non-modal causes. + **Pros:** hides this enum. **Cons:** removes useful details for unrelated callers and still + does not restore this title. + +**Why option 1:** repair the incorrect caller payload, not a shared renderer that is doing what +its other callers expect. + +**Acceptance:** exact-payload and rendered-message checks contain localized title/detail and no +raw reason token for each recoverable category. Preserve error-display failure reporting. +Update localization only if the chosen implementation adds or changes localization source strings. + +## C12. Persistent retained state would clarify rendering, but no rendering defect was demonstrated + +**Discussion:** [Copilot comment](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4752058722). +**Copilot: Low, explicitly optional. Assessment: optional, not a merge-blocking bug.** + +**Approved disposition: option 1; no standalone refactor.** Keep the current behavior and +terminal/dismissal coverage. Option 2 is not an extra work item authorized by this round. +**Done (2026-12-01), decision commit [`1b98521`](https://github.com/microsoft/vscode-documentdb/commit/1b985210362510facc41862314b712b785161fae):** +operator approved option 1 in Decision 0033; no rendering defect warranted a standalone refactor. +No implementation or new tests. The pushed checkpoint passed `npm run build`. +[Original-thread reply](https://github.com/microsoft/vscode-documentdb/pull/1149#discussion_r4757120153). + +> Optional: Save/Refresh disabled state and Monaco `readOnly` now read a mutable ref during render, +> so their updates depend on the separate dismissible state also triggering a render. Expose a +> persistent `retained` state from `useBoundViewRecovery` for rendering, while keeping the ref for +> synchronous operation guards. + +**Evidence.** [Document View](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/documentView/documentView.tsx#L448) +does read the ref for disabled/read-only props. However, the +[current terminal transition](https://github.com/microsoft/vscode-documentdb/blob/f8da433c084d298bdecfe09a8003408dd7dcd708/src/webviews/documentdb/useBoundViewRecovery.ts#L75) +sets both the ref and `unavailable` state. Dismissing the notice changes that state again while +leaving the ref set. Both transitions schedule the render needed by these props. + +A React probe using the same render-time ref pattern observed editable controls initially, +read-only/disabled controls after the terminal event, and continued read-only/disabled controls +after dismissal. This was not a production-Monaco/workbench test, but it does not support a claim +that these current transitions fail to render. + +**Options.** + +1. **Recommended disposition:** do not make a standalone refactor a requirement for this review. + Keep the existing behavior and its terminal/dismissal coverage. **Pros:** avoids expanding a + bug-fix round without demonstrated impact. **Cons:** the render dependency remains implicit. +2. If the hook is already changing for accepted findings, expose persistent retained state for + rendering and keep the ref only for synchronous guards. **Pros:** expresses the distinction + between retained state and visible notice, and can simplify C08's control wiring. + **Cons:** adds state synchronization obligations and caller changes; must not accidentally + make dismissing the notice restore access. + +**Why option 1:** the observation is a valid maintainability suggestion, not evidence of broken +current behavior. Option 2 is reasonable as a small coordinated implementation choice, not a new +required lifecycle redesign. + +**Acceptance if option 2 is chosen:** terminal event, notice dismissal, repeated notice and +subsequent unrelated renders all preserve disabled/read-only controls and immediate submission +guards. Recoverable errors must not set retained state. + +## Approved execution handoff + +### Branch and pull request + +- Prepared local work branch: `dev/tnaum/connection-lifecycle-pr1149-review-fixes`, starting at + reviewed head `f8da433c084d298bdecfe09a8003408dd7dcd708`. +- **The operator explicitly selected `feature/connection-lifecycle` as the new PR's base.** + Create a separate draft PR; do not push fixes onto the original simplification branch or the + feature branch. At approval time #1149 is still unmerged, so this base choice includes its + simplification changes as well as this follow-up. Do not merge or retarget existing PRs. +- The approval/review documents are uncommitted on the prepared branch. The recovered feature + README link was already staged; preserve it. Commit the decision record as an initial + checkpoint so accepted no-code replies can cite a real pushed commit. +- The earlier stash recovery is complete. Keep stash `ce93e767475777c94dd20c5d49c44cd9413a32c0` + as a backup; do not apply it again. Leave unrelated untracked connection-relay/telemetry + directories out of commits. + +### Authority and model routing + +- **Technical advisor:** `claude-opus-5.5` for implementation judgment, acceptance and difficult + decisions within the approved scope. +- **Implementation:** `mai-code-2` for every task that would normally use Terra and for simpler + Sol-class tasks. Keep genuinely complex Sol-class work on the lead skill's normal Sol routing. +- **CLI/tool execution:** `mai-code-2-flash` for command execution, builds/tests, Git/GitHub + operations and collection of verification evidence. +- The lead orchestrator **trusts the advisor's decisions**. It must not repeat the advisor's + code review, reopen settled options or independently re-verify the same technical judgment. + Mandatory build/test execution still applies. A concrete failing check or new external fact + goes back to the advisor for disposition, rather than prompting a second leader-led review. + Changes to the operator-approved behavior require the operator, not an advisor override. + +### Items, commits and replies + +1. Implement C04, C02 and C03's distinct handoff protections, then C05/C07/C09 recovery fixes + and C06/C10/C11's selected presentation/polling behavior. The advisor may adjust execution + order for real dependencies without changing the approved options. +2. Keep **each of the nine code fixes in its own commit**, including its directly related + regression coverage and documentation. Push each item before reporting it addressed. +3. After the item is accepted and pushed, reply in its original Copilot discussion linked above: + summarize **what changed, why this approved solution was chosen, and the full commit URL**. + Report verification accurately; do not imply that deferred full checks already passed. +4. Reply to C01, C08 and C12 with the approved no-code disposition and rationale, citing the + pushed decision-record commit. Do not fabricate a fix or add code merely to create a commit. +5. Update the item's inline progress immediately with advisor acceptance, commit/push, commands + and results, and reply URL. Keep the lead skill's per-return progress checkpoints. Preserve + all author decisions and the original review evidence. + +### Verification and final iteration + +- Keep the required **Case 1** fast loop for implementation commits/pushes: + `npm run build` and the smallest combined `npx vitest run ` selection covering that + item. Use the Flash runner and reuse its reported evidence; no duplicate leader reruns. +- Defer the expensive **Case 2** suite, global formatting/localization generation and full + runtime suite until all item dispositions are complete. Do not run these between fixes. +- Finish with a distinct integration iteration covering Case 1 and the complete Case 2 list. + Run the integrated focused tests, then the full list below; its build also supplies the final + Case 1 build result, so do not run an identical second build without intervening changes: + + ```bash + npm run l10n # only if localization source strings were added, changed or removed + npm run prettier-fix + npm run l10n:check + npm run lint + npm run build + npm run typecheck:tests + npx vitest run + npm run package + ``` + +- Fix in-scope failures in follow-up commits, push again, and rerun checks affected by the + correction. Every required check must cover the final integrated candidate; separately report + `npm run typecheck:tests`. Do not weaken assertions or silently change `TDD:` contracts. +- Complete the required advisor-led AI pre-review and commit its review record under this + feature's iterations directory. The lead consumes the advisor's verdict without redoing it. +- Keep evidence of mocked, rendered, packaged and live checks separate. Do not claim real + authentication, expiry or sleep/wake passed because unit tests did. Report remaining gates + honestly and do not mark the PR ready while required checks or other handoff gates are blocked. + +## Advisor-led integrated AI pre-review for draft #1154 + +- **Reviewed:** `f8da433c084d298bdecfe09a8003408dd7dcd708..e8479641793bbcc0c5d4910c75c0d335e17c86f0` + (runtime changes). Earlier item sections preserve the initial findings, original Copilot threads, + author decisions, advisor acceptance and exact published fixes. +- **Independent sweep:** `claude-opus-5.5` checked lifetime retirement and publication across + Dashboard, Shell, Playground and Generate Query; and Entra recovery, concurrent request state, + index polling and notifications across webviews. High confidence from source inspection: + no Critical, High or Medium findings. One valid Low finding is recorded below. The advisor + did not rerun checks or reopen the approved C01, C08 or C12 dispositions. +- **Cross-item checks:** retirement is checked after bound startup and before panel publication. + Dashboard interruption and Collection View polling state are scoped to their respective views. + Same-account sign-in recovery does not itself re-arm index polling or replay a failed operation. + +### N01. Creating an index while polling is paused + +**Low, valid; advisor confidence high.** A typed unavailable result can pause index polling, +including on initial load. A later successful Create shows a **Creating** row and relies on the +poll to update it. After repair, that row can stay at **Creating** until the user selects +**Refresh**; the index request itself is not blocked by the pause. The relevant paths are +[`IndexesTab.tsx`](../../../../../src/webviews/documentdb/collectionView/indexesTab/IndexesTab.tsx) +and the per-view pause state in +[`CollectionView.tsx`](../../../../../src/webviews/documentdb/collectionView/CollectionView.tsx). + +**Options considered:** (1) keep manual Refresh and document the workaround; (2) resume polling +after a successful Create (the advisor's recommendation, which changes Decision 0033); (3) keep +manual Refresh and add a localized pause hint. **Author decision (2026-12-01):** option 1, with +no code change. Recorded in [Decision 0034](../decisions.md#0034-keep-manual-refresh-as-the-only-way-to-resume-paused-index-polling-after-create). + +**Still manual/live:** Dashboard navigation and interruption timing; Shell closure during a pending +handoff; Playground removal and file preservation; Generate Query with a genuinely evicted client +and live Copilot; wrong-account Entra rejection and explicit original-account recovery; index poll +pause/resume and Create with polling paused; localized notification in the workbench; token expiry +and sleep/wake. Mocked cases and static scenario tests do not certify these. + +## Final integration evidence + +The Flash runner confirmed all twelve original Copilot discussions have one reply from this round. +Case 1 and Case 2 ran on the integrated candidate. The formatting-only commit was `754098c83`. +Initial Case 2 lint failed on the Dashboard collections test harness; after the test-only +correction, the affected checks passed on `269d371f`. The later changes were the test and review, +decision, and manual documentation; production build, package, and localization inputs did not +change. No new or changed localization source strings required generation. + +| Check | Result | +| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | +| `npm run prettier-fix` | Passed in a detached worktree; round-only formatting applied. Targeted Prettier also passed after the test and author-record updates. | +| `npm run l10n:check` | Passed (3,732 keys); `npm run l10n` not needed. | +| `npm run lint` | Passed after the test-only correction; focused ESLint had zero errors and 20 existing warnings. | +| `npm run build` | Passed; this also supplies the integrated Case 1 build. | +| `npm run typecheck:tests` | Passed on the corrected candidate. | +| Integrated focused Vitest | 939 passed across 26 suites; after correction, 18 passed across the two affected suites. | +| Static browser scenario tests | 47 passed; did not run the rendered journeys. | +| Full `npx vitest run` | 10,541 passed, 1 skipped across 461 files on the corrected candidate. | +| `npm run package` | Passed; generated `vscode-documentdb-1.1.1-alpha.4.vsix` (9,270,193 bytes). The VSIX was not installed or exercised in the workbench. | + +## Approval-update outcome + +The original branch/stash recovery was verified against its saved blob, and the separate follow-up +branch was prepared. All twelve dispositions, their execution contract and the changed feature +intent are recorded. No production fixes, commits, pushes, new PR, replies or thread resolutions +were performed in this approval-recording step. The verification below belongs to the original +evaluation, not to an implementation of the now-approved fixes. + +## Verification and limits + +- Read all 12 Copilot comments, their severity labels and the active design decisions. Traced the + affected production paths at the pinned head, including both Dashboard navigation paths and + all three Playground connection-status consumers. +- Ran offline probes by transpiling the current TypeScript modules and composing the real + lifecycle helpers and React hooks. Driver startup/close, VS Code APIs, panel creation, storage + and RPC responses were mocked with synthetic data. Unexpected dependency use failed the + probe rather than silently invoking infrastructure. +- The probes corroborated C01-C07 and C09 at their relevant host/hook boundaries. C10/C11 were + corroborated by the actual repeated-notification/payload behavior plus the polling/host-renderer + source paths. C08 was source-verified. C12's suspected missed-render behavior was not reproduced. +- **12 existing focused Vitest files passed: 382 tests, zero failures.** The command was: + + ```bash + npx vitest run --maxWorkers=2 \ + src/documentdb/connectionTeardown.test.ts \ + src/commands/saveConnectionEdit.test.ts \ + src/commands/playground/newPlayground.test.ts \ + src/documentdb/shell/DocumentDBShellPty.test.ts \ + src/commands/openCollectionView/openCollectionView.test.ts \ + src/webviews/documentdb/clusterDashboard/clusterDashboardController.test.ts \ + src/webviews/documentdb/clusterDashboard/clusterDashboardRouter.test.ts \ + src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts \ + src/documentdb/playground/PlaygroundService.test.ts \ + src/documentdb/connectionFailures.test.ts \ + src/webviews/documentdb/useBoundViewRecovery.test.tsx \ + src/webviews/documentdb/documentView/documentView.test.tsx + ``` + +- These passing tests preserve evidence of existing covered behavior; they do not disprove the + separately demonstrated gaps. No behavior-contract tests or production files were changed. +- No live database, real authentication provider, Copilot model request, rendered production + Monaco, installed-workbench race, expiry or sleep/wake test was performed. No actual disclosure + or database write was observed. The PR's existing live/rendered gates remain outstanding. +- **Case 1, review/documentation only.** No production code changed, so the build was not rerun. + Full Case 2 checks, including `prettier-fix`, were not rerun in this triage and are deferred to + ready-for-review verification of any follow-up fixes. Earlier PR validation is not represented + as a new pass from this evaluation. +- No GitHub reply, resolution, commit, push or PR-state change was made. diff --git a/docs/release-notes/1.2.md b/docs/release-notes/1.2.md index adbc0ce77..188443648 100644 --- a/docs/release-notes/1.2.md +++ b/docs/release-notes/1.2.md @@ -37,13 +37,15 @@ See [Keep connections usable](https://microsoft.github.io/vscode-documentdb/user 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**. A setting can choose either -behavior in advance, while unsaved document changes still require explicit confirmation. +behavior in advance, while closing the dialog cancels and unsaved document changes still require +explicit confirmation. Retained Collection View, Document View, and Cluster Dashboard contents stay available for -inspection or copying under a connection dialog. If **Reconnect** automatically opens the retained -Dashboard for the same connection, the Dashboard retries on its own. If it stays disabled, select -**Retry**, as you would in other retained webviews. Use **Close view** when the connection changed or -was removed. Retry does not replay the operation that failed. +inspection or copying under a read-only notice. Dismissing the notice does not restore +database access, and **Reconnect** never revives the old tab. Use **Close view** to close it and +open a fresh view from the tree for new work. Ordinary token, sign-in or network recovery is +different: it keeps an unchanged connection's existing view usable, and the user explicitly runs +an operation again after repair. If a tracked copy, export, or import is using the cluster, the task and connection keep running. Select **Disconnect** again after the task finishes or you stop it. The same teardown rules apply @@ -52,27 +54,24 @@ connection and cached credentials. See [#566](https://github.com/microsoft/vscode-documentdb/issues/566) and [#1059](https://github.com/microsoft/vscode-documentdb/issues/1059). -Learn how retained views, shells, and playgrounds resume in the +Learn how retained views, shells, and playgrounds behave in the [connection lifecycle guide](https://microsoft.github.io/vscode-documentdb/user-manual/connecting-to-databases#disconnect-and-reconnect). ### ⭐ Open Work Stays Bound to Its Original Connection -Saving changes with **Update Credentials…** or **Update Connection String…**, even just a password, -permanently disables operations in existing Collection View, Document View, and Cluster Dashboard -tabs. You can still copy their contents. Open a new view from the tree to use the saved settings. - -Shell and Playground are different: a Shell you choose to leave running can keep its previous -settings, and a restarted worker can use a password-only update without a new terminal or connection -pick. A different host, user, or identity requires a new Shell or an explicit Playground connection -pick. +Saving changes with **Update Credentials…** or **Update Connection String…** requires the old +connection to end first. For a connected item, **Disconnect and update** runs the normal +Disconnect checks and tab choice before the editor opens. Kept tabs remain permanently read-only; +open a fresh view from the tree to use the saved settings. Cancelling or a blocked/failed +Disconnect does not start the edit. ## Key Limits and Improvements -- **No replay of uncertain writes.** Reconnecting or clicking Retry never resubmits the failed - operation. Check the server before repeating a write that did not report an outcome. -- **Resume in the same shell or playground.** After reconnecting with unchanged settings, run - again in the existing terminal or file. Scrollback and query text stay, but worker-local state - such as variables is lost. +- **No replay of uncertain writes.** Recovery and reconnect never resubmit a failed operation. + Check the server before repeating a write that did not report an outcome. +- **Keep useful text, not the old worker.** Disconnect stops Shell and Playground workers while + retaining terminal scrollback and file text. An explicitly ended session is not replayed or + silently rebound to a later connection. - **Follow-up network work is outside this release.** Kubernetes tunnel recreation and broader network resilience remain tracked in [#1105](https://github.com/microsoft/vscode-documentdb/issues/1105). diff --git a/docs/user-manual/collection-view-index-management-troubleshooting.md b/docs/user-manual/collection-view-index-management-troubleshooting.md index d61419b4f..08786d328 100644 --- a/docs/user-manual/collection-view-index-management-troubleshooting.md +++ b/docs/user-manual/collection-view-index-management-troubleshooting.md @@ -18,7 +18,13 @@ If the list loads but Size or Usage is unavailable, the server may not provide t The tab shows **Creating** after the extension sends a create request. It shows **Building** while the server reports an active index build. -The tab refreshes while an active build is present. Wait for the status to become **Ready**, or use **Refresh** to request the current server state. +The tab refreshes while an active build is present. Wait for **Ready**, or select **Refresh** to +request the current server state. If automatic refresh paused because of a connection error, select +**Refresh** after restoring the connection; it does not resume automatically. + +If you create an index while automatic refresh is paused, the row can still show **Creating** +after the request succeeds. Select **Refresh** to see its current status and resume automatic +refresh if the index is still building. ## Creating an index fails diff --git a/docs/user-manual/collection-view-index-management.md b/docs/user-manual/collection-view-index-management.md index 4a964a0ea..3e2a655c6 100644 --- a/docs/user-manual/collection-view-index-management.md +++ b/docs/user-manual/collection-view-index-management.md @@ -39,7 +39,8 @@ An index can have one of these states: | Creating | The create request has been sent and the extension is waiting for the server result. | | Building | The server reports that the index build is still in progress. | -The tab refreshes while an index is creating or building. You can also select **Refresh** at any time. +The tab refreshes while an index is creating or building. If a recoverable connection error pauses +automatic refresh, restore the connection and select **Refresh** to resume it. ## Create an index diff --git a/docs/user-manual/connecting-to-databases.md b/docs/user-manual/connecting-to-databases.md index 1de0d385f..4ede820ce 100644 --- a/docs/user-manual/connecting-to-databases.md +++ b/docs/user-manual/connecting-to-databases.md @@ -41,7 +41,9 @@ connection. It does not open a sign-in prompt from a background refresh. If Microsoft sign-in can no longer be renewed, the tree offers **Retry sign-in**. The Interactive Shell and Query Playground can instead offer **Sign in again**. Sign in with the identity originally -used for that connection. The old view is not moved to a different account. +used for that connection. The old view is not moved to a different account. After the repair, +run the operation again in the same view when recovery was for the unchanged connection; failed +commands are not replayed automatically. ## Disconnect and reconnect @@ -54,7 +56,9 @@ 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**, which keeps view contents but prevents database operations. +- **Keep open**, which retains a copyable snapshot but permanently prevents database operations in + those views. +- **Cancel**, by closing the modal, which leaves the connection running. 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,39 +68,32 @@ The setting can use `closeAll` or `keepOpenDisabled` as a default instead of sho time. It never bypasses the unsaved-document confirmation. **Delete Connection…** uses the same choice, but also removes the saved connection and its cached credentials. -A retained Collection View, Document View, or Cluster Dashboard is covered by a dialog that explains -why it is unavailable: +A retained Collection View, Document View, or Cluster Dashboard shows a read-only notice: -- Select **Retry** after repairing or reconnecting the connection. Retry checks the binding and - does not replay the operation that failed. +- Use the **X** to dismiss the notice and inspect or copy the loaded contents. Database operations + remain disabled. - 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 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 start a new session, then open a fresh view. +Neither Reconnect nor same-account sign-in revives a retained view after an explicit Disconnect or +removal. This is different from an ordinary token, authentication or network recovery: those do not +turn a live view into a read-only snapshot. -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. - -After reconnecting to the same connection with unchanged settings, run a command in the existing -Interactive Shell or run the retained Query Playground again. No new terminal or connection pick -is needed. The terminal scrollback and Playground text remain, but worker-local state such as -variables and open cursors is lost. Interrupted commands are not replayed. +Disconnect stops the connection's Shell and Playground workers, but their terminal scrollback or +file text remains. If you delete a saved connection, affected Playground files keep their text but +lose the selection. Use **Connect** in the Playground to select another database. Interrupted +commands and evaluations are not replayed. ## After changing connection details -Saving a change with **Update Credentials…** or **Update Connection String…** permanently disables -database operations in the existing Collection View, Document View, and Cluster Dashboard tabs. -This includes a password-only edit. Their contents remain available for inspection or copying. -Select **Close view** and open a new view from the tree to use the saved settings. - -Shell and Playground follow different rules. If you choose to keep a running Shell connected when -prompted, its worker can continue using the previous settings. After a password-only edit, a new -worker can use the updated password in the existing terminal or Playground without a new connection -pick. To use a different host, user, or sign-in identity, open a new Shell or explicitly select the -connection again in the Playground. Cancelling an edit or saving unchanged settings does not lock -the open views. +**Update Credentials…** and **Update Connection String…** cannot edit a live connection. When it +is connected, choose **Disconnect and update**. The extension performs the ordinary Disconnect +flow first, including its task checks, tab choice and dirty-document confirmation. When you select +**Disconnect and update**, that command waits for its Disconnect to finish before opening the +wizard. Cancelling the flow, a task conflict or a Disconnect failure in that command prevents the edit. + +If you keep tabs during that Disconnect, database operations remain disabled in those tabs, even +after a later reconnect with the same account. Loaded contents remain available for copying, and you +can still edit local query text in Collection View after dismissing the notice. Open fresh views +from the tree to use the updated settings. A cancelled edit leaves the connection disconnected +but does not partially save settings. diff --git a/l10n/bundle.l10n.json b/l10n/bundle.l10n.json index 22b198da1..ddc898930 100644 --- a/l10n/bundle.l10n.json +++ b/l10n/bundle.l10n.json @@ -653,7 +653,7 @@ "Check the kubeconfig source and context, then run the diagnosis again.": "Check the kubeconfig source and context, then run the diagnosis again.", "Check the local database, container or tunnel on this computer, then run the diagnosis again.": "Check the local database, container or tunnel on this computer, then run the diagnosis again.", "Check the network connection and proxy settings, then run the diagnosis again.": "Check the network connection and proxy settings, then run the diagnosis again.", - "Check the network or server, then click Retry.": "Check the network or server, then click Retry.", + "Check the network or server.": "Check the network or server.", "Check the option values in the connection string, such as true or false for switches and numbers for timeouts, then connect again.": "Check the option values in the connection string, such as true or false for switches and numbers for timeouts, then connect again.", "Check the output channel for details.": "Check the output channel for details.", "Check the output channel for details. The cluster may be unreachable or your credentials may need updating.": "Check the output channel for details. The cluster may be unreachable or your credentials may need updating.", @@ -808,7 +808,7 @@ "Connect": "Connect", "Connect another API Key or Service Account to see more organizations and projects.": "Connect another API Key or Service Account to see more organizations and projects.", "Connect database": "Connect database", - "Connect from the connection tree, then click Retry.": "Connect from the connection tree, then click Retry.", + "Connect from the connection tree.": "Connect from the connection tree.", "Connect MongoDB Atlas to browse, open, and manage your clusters without leaving VS Code.": "Connect MongoDB Atlas to browse, open, and manage your clusters without leaving VS Code.", "Connect this playground to a database": "Connect this playground to a database", "Connect to a different database…": "Connect to a different database…", @@ -838,7 +838,6 @@ "Connection": "Connection", "connection \"{0}\"": "connection \"{0}\"", "Connection attempt failed": "Connection attempt failed", - "Connection changed": "Connection changed", "Connection checks": "Connection checks", "Connection configuration": "Connection configuration", "Connection details unavailable": "Connection details unavailable", @@ -858,7 +857,6 @@ "Connection options rejected": "Connection options rejected", "Connection preparation failed": "Connection preparation failed", "Connection refused": "Connection refused", - "Connection removed": "Connection removed", "Connection settings": "Connection settings", "Connection status based on periodic ping commands to this cluster.": "Connection status based on periodic ping commands to this cluster.", "Connection string": "Connection string", @@ -1120,8 +1118,8 @@ "Discard changes": "Discard changes", "Discard the pasted input.": "Discard the pasted input.", "Discard unsaved document changes?": "Discard unsaved document changes?", - "Disconnect": "Disconnect", "Disconnect and connect this playground to a different database?": "Disconnect and connect this playground to a different database?", + "Disconnect and update": "Disconnect and update", "disconnect this connection": "disconnect this connection", "Disconnect?": "Disconnect?", "Disconnected": "Disconnected", @@ -1131,8 +1129,7 @@ "Discovery view": "Discovery view", "DiskANN": "DiskANN", "Dismiss": "Dismiss", - "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.", + "Dismiss notice": "Dismiss notice", "Dissatisfied": "Dissatisfied", "DNS connection options invalid": "DNS connection options invalid", "DNS lookup temporarily failed": "DNS lookup temporarily failed", @@ -2217,7 +2214,6 @@ "Open setup": "Open setup", "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", "Open this query in Interactive Shell": "Open this query in Interactive Shell", @@ -2454,9 +2450,7 @@ "Recommended": "Recommended", "Recommended Index": "Recommended Index", "Reconnect": "Reconnect", - "Reconnect from the connection tree, then click Retry.": "Reconnect from the connection tree, then click Retry.", "Reconnect now with the updated credentials": "Reconnect now with the updated credentials", - "Reconnected": "Reconnected", "Reconnecting...": "Reconnecting...", "Recovery command copied.": "Recovery command copied.", "Recreate container": "Recreate container", @@ -2508,7 +2502,7 @@ "Rename kubeconfig source": "Rename kubeconfig source", "Rename Kubernetes context": "Rename Kubernetes context", "Renamed folder from \"{oldName}\" to \"{newName}\"": "Renamed folder from \"{oldName}\" to \"{newName}\"", - "Repair the connection in the tree, then click Retry.": "Repair the connection in the tree, then click Retry.", + "Repair the connection in the tree.": "Repair the connection in the tree.", "Repairing…": "Repairing…", "Replaced, Start fresh": "Replaced, Start fresh", "Replica set": "Replica set", @@ -2763,7 +2757,7 @@ "Sign in again": "Sign in again", "Sign in again to continue using Microsoft Entra ID.": "Sign in again to continue using Microsoft Entra ID.", "Sign in again to continue using this connection.": "Sign in again to continue using this connection.", - "Sign in from the connection tree, then click Retry.": "Sign in from the connection tree, then click Retry.", + "Sign in from the connection tree.": "Sign in from the connection tree.", "Sign in to": "Sign in to", "Sign in to additional accounts or authenticate with other tenants to see more options.": "Sign in to additional accounts or authenticate with other tenants to see more options.", "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.": "Sign in to additional accounts or authenticate with other tenants to see more subscriptions.", @@ -3280,7 +3274,6 @@ "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 run the script again.": "This connection is unavailable. Reconnect from the tree, then run the script again.", @@ -3350,8 +3343,8 @@ "This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.": "This shell is not allowed to sign in to this connection. Review the trusted server settings, then reconnect from the tree.", "This step did not finish within the time limit. This alone does not show that the server is unreachable.": "This step did not finish within the time limit. This alone does not show that the server is unreachable.", "This stops all running WSL distributions so the new group membership applies when WSL starts again.": "This stops all running WSL distributions so the new group membership applies when WSL starts again.", + "This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.": "This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.", "This table view presents data at the root level by default.": "This table view presents data at the root level by default.", - "This view is tied to the previous connection settings. Close it and reopen it from the tree.": "This view is tied to the previous connection settings. Close it and reopen it from the tree.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround could not read it either.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround could not read it either.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround is turned off.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), and the extension's workaround is turned off.", "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), so the extension read it another way. Nothing needs to change.": "This VS Code version couldn't read your DNS server's reply for the server list (SRV record), so the extension read it another way. Nothing needs to change.", @@ -3410,14 +3403,13 @@ "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 close the view. Try again.": "Unable to close the view. Try again.", "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", @@ -3582,7 +3574,7 @@ "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.": "VS Code is signed in to a custom cloud, and we could not find which Microsoft Entra resource to request a token for. Set \"{setting}\" to the open-source database resource of your cloud, usually \"https://ossrdbms-aad.database.\". Your cloud operator or Azure administrator can tell you the exact value.", "VS Code version: {0}": "VS Code version: {0}", "VS Code: v{0}": "VS Code: v{0}", - "Wait for the update to finish, then click Retry.": "Wait for the update to finish, then click Retry.", + "Wait for the update to finish.": "Wait for the update to finish.", "Wait longer": "Wait longer", "Wait until the service has an external address, then run the diagnosis again.": "Wait until the service has an external address, then run the diagnosis again.", "Waiting {0}": "Waiting {0}", @@ -3688,6 +3680,7 @@ "You asked us to remind you later, so here we are.": "You asked us to remind you later, so here we are.", "You can disable this confirmation by setting \"{0}\" to false.": "You can disable this confirmation by setting \"{0}\" to false.", "You can now close this tab and explore your MongoDB Atlas clusters in the Service Discovery area.": "You can now close this tab and explore your MongoDB Atlas clusters in the Service Discovery area.", + "You can only update credentials or the connection string while disconnected.": "You can only update credentials or the connection string while disconnected.", "You cancelled the diagnosis. The results so far are kept.": "You cancelled the diagnosis. The results so far are kept.", "You closed this invitation a while ago, so we are asking once more.": "You closed this invitation a while ago, so we are asking once more.", "You do not have permission to create a resource group in subscription \"{0}\".": "You do not have permission to create a resource group in subscription \"{0}\".", diff --git a/src/commands/dashboardBoundCommands.test.ts b/src/commands/dashboardBoundCommands.test.ts index 942277ea6..72ab417b2 100644 --- a/src/commands/dashboardBoundCommands.test.ts +++ b/src/commands/dashboardBoundCommands.test.ts @@ -48,6 +48,7 @@ vi.mock('../documentdb/ClustersClient', () => ({ getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), reportFailure: vi.fn(), }, })); diff --git a/src/commands/disconnect/disconnect.test.ts b/src/commands/disconnect/disconnect.test.ts index 3b1bfcc65..234f6b428 100644 --- a/src/commands/disconnect/disconnect.test.ts +++ b/src/commands/disconnect/disconnect.test.ts @@ -7,17 +7,24 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import { beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { getConnectionSurfaces } from '../../documentdb/connectionSurfaces'; import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { type PlaygroundEvaluator } from '../../documentdb/playground/PlaygroundEvaluator'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; import { connectDisconnected, disconnect } from './disconnect'; vi.mock('../../documentdb/ClustersClient', () => ({ - ClustersClient: { exists: vi.fn(), getLatchReason: vi.fn(), unlatch: vi.fn() }, + ClustersClient: { exists: vi.fn(), hasPendingStartup: vi.fn(), getLatchReason: vi.fn(), unlatch: vi.fn() }, })); +vi.mock('../../documentdb/connectionSurfaces', () => ({ getConnectionSurfaces: vi.fn() })); vi.mock('../../documentdb/connectionTeardown', () => ({ teardownConnection: vi.fn() })); +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: vi.fn() })); +vi.mock('../playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators: vi.fn() })); vi.mock('../../extensionVariables', () => ({ ext: { state: { notifyChildrenChanged: vi.fn() } } })); vi.mock('../../tree/documentdb/ClusterItemBase', () => ({ ClusterItemBase: class {} })); vi.mock('../retryAuthentication/retryAuthentication', () => ({ refreshAuthenticationNode: vi.fn() })); @@ -38,7 +45,11 @@ describe('tree disconnect recovery', () => { beforeEach(() => { vi.clearAllMocks(); vi.mocked(ClustersClient.exists).mockReturnValue(true); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + vi.mocked(getConnectionSurfaces).mockReturnValue([]); + vi.mocked(getPlaygroundEvaluators).mockReturnValue(new Map()); + vi.mocked(getRegisteredShellTerminals).mockReturnValue([]); }); it.each([disconnect, connectDisconnected])( @@ -47,6 +58,9 @@ describe('tree disconnect recovery', () => { for (const reason of ['connectionRemoved', 'credentialsChanged', 'identityChanged'] as const) { vi.clearAllMocks(); vi.mocked(ClustersClient.getLatchReason).mockReturnValue(reason); + if (command === disconnect) { + vi.mocked(ClustersClient.exists).mockReturnValue(false); + } const context = actionContext(); const node = clusterNode(); @@ -154,4 +168,70 @@ describe('tree disconnect recovery', () => { expect(refreshAuthenticationNode).not.toHaveBeenCalled(); expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); }); + + it.each(['surface', 'startup', 'evaluator', 'shell', 'heldClient'] as const)( + 'does not bypass ordinary Disconnect for a surviving %s on a rejected or absent client', + async (survivor): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(survivor === 'heldClient'); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(survivor === 'startup'); + if (survivor === 'surface') { + vi.mocked(getConnectionSurfaces).mockReturnValue([ + { clusterId: 'stable-cluster', kind: 'documentView', disable: vi.fn(), dispose: vi.fn() }, + ]); + } + if (survivor === 'evaluator') { + vi.mocked(getPlaygroundEvaluators).mockReturnValue( + new Map([['stable-cluster', {} as PlaygroundEvaluator]]), + ); + } + if (survivor === 'shell') { + const terminal: vscode.Terminal = { + name: 'Test shell', + processId: Promise.resolve(undefined), + creationOptions: {}, + exitStatus: undefined, + state: { isInteractedWith: false, shell: undefined }, + shellIntegration: undefined, + sendText: vi.fn(), + show: vi.fn(), + hide: vi.fn(), + dispose: vi.fn(), + }; + const shell: ReturnType[number] = { + terminal, + info: { + clusterId: 'stable-cluster', + clusterDisplayName: 'Cluster', + activeDatabase: 'database', + isInitialized: true, + isEvaluating: false, + workerState: 'ready', + authMethod: 'NoAuth', + username: undefined, + }, + disconnect: vi.fn(), + }; + vi.mocked(getRegisteredShellTerminals).mockReturnValue([shell]); + } + const node = clusterNode(); + await disconnect(actionContext(), node); + expect(teardownConnection).toHaveBeenCalledExactlyOnceWith( + 'stable-cluster', + 'userDisconnected', + expect.any(Function), + ); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }, + ); + + it('leaves credentialsUpdating safely terminal even with surviving surfaces', async (): Promise => { + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsUpdating'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(true); + const node = clusterNode(); + await disconnect(actionContext(), node); + expect(refreshAuthenticationNode).toHaveBeenCalledExactlyOnceWith(node); + expect(teardownConnection).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); }); diff --git a/src/commands/disconnect/disconnect.ts b/src/commands/disconnect/disconnect.ts index 08296041a..ea0c02eaa 100644 --- a/src/commands/disconnect/disconnect.ts +++ b/src/commands/disconnect/disconnect.ts @@ -6,11 +6,14 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import { l10n, window } from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { getConnectionSurfaces } from '../../documentdb/connectionSurfaces'; import { teardownConnection } from '../../documentdb/connectionTeardown'; +import { getRegisteredShellTerminals } from '../../documentdb/shell/ShellTerminalLinkProvider'; import { Views } from '../../documentdb/Views'; import { ext } from '../../extensionVariables'; import { ClusterItemBase } from '../../tree/documentdb/ClusterItemBase'; import { type TreeElement } from '../../tree/TreeElement'; +import { getPlaygroundEvaluators } from '../playground/executePlaygroundCode'; import { refreshAuthenticationNode } from '../retryAuthentication/retryAuthentication'; function isClusterNode(node: TreeElement | undefined): node is ClusterItemBase { @@ -25,7 +28,16 @@ export async function disconnect(context: IActionContext, node?: TreeElement): P const { clusterId } = node.cluster; const reason = ClustersClient.getLatchReason(clusterId); - if (!ClustersClient.exists(clusterId) || reason) { + if ( + reason === 'userDisconnected' || + reason === 'connectionRemoved' || + reason === 'credentialsUpdating' || + (!ClustersClient.exists(clusterId) && + !ClustersClient.hasPendingStartup(clusterId) && + getConnectionSurfaces(clusterId).length === 0 && + !getPlaygroundEvaluators().has(clusterId) && + !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId)) + ) { if ( node.cluster.viewId !== String(Views.ConnectionsView) && node.cluster.viewId !== String(Views.DiscoveryView) && diff --git a/src/commands/importDocuments/importDocuments.test.ts b/src/commands/importDocuments/importDocuments.test.ts index 46ca5021c..e992196ac 100644 --- a/src/commands/importDocuments/importDocuments.test.ts +++ b/src/commands/importDocuments/importDocuments.test.ts @@ -22,6 +22,7 @@ vi.mock('../../documentdb/ClustersClient', () => ({ getClient: vi.fn(), getLatchReason: vi.fn(), resolveBoundClient: vi.fn(), + assertBindingActive: vi.fn(), reportFailure: vi.fn(), }, isBulkWriteError: vi.fn(() => false), diff --git a/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts new file mode 100644 index 000000000..5f7876887 --- /dev/null +++ b/src/commands/llmEnhancedCommands/queryGenerationCommands.test.ts @@ -0,0 +1,322 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { createTestActionContext, UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { type Document } from 'mongodb'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import type * as vscodeModule from 'vscode'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { getBindingLifetimeSignal, retireConnectionBindings } from '../../documentdb/connectionBindingRetirement'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; +import { CopilotService } from '../../services/copilotService'; +import { PromptTemplateService } from '../../services/promptTemplateService'; +import { generateQuery, QueryGenerationType, type QueryGenerationContext } from './queryGenerationCommands'; + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { trace: vi.fn() } }, +})); +vi.mock('../../services/copilotService', () => ({ + CopilotService: { isAvailable: vi.fn(), sendMessage: vi.fn() }, +})); +vi.mock('../../services/promptTemplateService', () => ({ + PromptTemplateService: { getQueryGenerationPromptTemplate: vi.fn() }, +})); +vi.mock('vscode', async (importOriginal) => ({ + ...(await importOriginal()), + LanguageModelChatMessage: { User: vi.fn((content: string) => ({ role: 1, content })) }, +})); + +interface Deferred { + readonly promise: Promise; + resolve(value: T): void; +} + +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((complete): void => { + resolve = complete; + }); + return { promise, resolve }; +} + +let sequence = 0; +let context: IActionContext; +let binding: ConnectionBinding; +let queryContext: QueryGenerationContext; +let sampleDocuments: ReturnType>; +let listCollections: ReturnType>; +let client: ClustersClient; + +beforeEach(async (): Promise => { + vi.resetAllMocks(); + context = await createTestActionContext(); + binding = { clusterId: `query-generation-${++sequence}`, fingerprint: 'original', generation: 1 }; + queryContext = { + binding, + signal: getBindingLifetimeSignal(binding), + databaseName: 'database', + collectionName: 'collection', + naturalLanguageQuery: 'Find active records', + generationType: QueryGenerationType.SingleCollection, + }; + sampleDocuments = vi.fn().mockResolvedValue([{ active: true }]); + listCollections = vi + .fn() + .mockResolvedValue([{ name: 'first' }, { name: 'second' }]); + client = { binding, getSampleDocuments: sampleDocuments, listCollections } as unknown as ClustersClient; + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(binding); + vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(1); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockResolvedValue(client); + vi.spyOn(ClustersClient, 'reportFailure').mockReturnValue(undefined); + vi.mocked(CopilotService.isAvailable).mockResolvedValue(true); + vi.mocked(CopilotService.sendMessage).mockResolvedValue({ + text: JSON.stringify({ explanation: 'Generated', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + vi.mocked(PromptTemplateService.getQueryGenerationPromptTemplate).mockResolvedValue('Fake prompt'); +}); + +afterEach((): void => { + vi.restoreAllMocks(); +}); + +it.each(['userDisconnected', 'credentialsChanged', 'connectionRemoved'] as const)( + 'does not sample a replacement after %s during availability', + async (reason): Promise => { + const availability = deferred(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, queryContext); + expect(CopilotService.isAvailable).toHaveBeenCalledOnce(); + retireConnectionBindings(binding.clusterId, binding.generation, reason); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, fingerprint: 'replacement', generation: 2 }); + availability.resolve(true); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); + }, +); + +it('preserves request cancellation during availability without sampling', async (): Promise => { + const availability = deferred(); + const controller = new AbortController(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, { ...queryContext, signal: controller.signal }); + controller.abort(); + availability.resolve(true); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('recovers an unretired same-identity binding with no cached client', async (): Promise => { + const recoveredBinding = { ...binding, generation: 2 }; + const recoveredSamples = vi.fn().mockResolvedValue([{ active: true }]); + let currentBinding: ConnectionBinding | undefined; + vi.mocked(ClustersClient.getBinding).mockImplementation(() => currentBinding); + vi.mocked(ClustersClient.resolveBoundClient).mockImplementationOnce(async () => { + currentBinding = recoveredBinding; + return { + binding: recoveredBinding, + getSampleDocuments: recoveredSamples, + } as unknown as ClustersClient; + }); + + await expect(generateQuery(context, queryContext)).resolves.toMatchObject({ explanation: 'Generated' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, { + trigger: 'collectionView', + }); + expect(recoveredSamples).toHaveBeenCalledExactlyOnceWith('database', 'collection', 10); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('does not resolve or sample for a pre-aborted request with no cached client', async (): Promise => { + const controller = new AbortController(); + controller.abort(); + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + + await expect(generateQuery(context, { ...queryContext, signal: controller.signal })).rejects.toBeInstanceOf( + UserCancelledError, + ); + expect(ClustersClient.resolveBoundClient).not.toHaveBeenCalled(); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not sample or send for a retired binding with no cached client', async (): Promise => { + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + + await expect(generateQuery(context, queryContext)).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not sample or send when recovery resolves to a different identity', async (): Promise => { + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + vi.mocked(ClustersClient.resolveBoundClient).mockRejectedValueOnce( + new ConnectionUnavailableError('identityChanged'), + ); + + await expect(generateQuery(context, queryContext)).rejects.toMatchObject({ reason: 'identityChanged' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledExactlyOnceWith(binding, { + trigger: 'collectionView', + }); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('samples and sends once after same-account physical replacement during availability', async (): Promise => { + const availability = deferred(); + vi.mocked(CopilotService.isAvailable).mockReturnValueOnce(availability.promise); + const pending = generateQuery(context, queryContext); + const replacementBinding = { ...binding, generation: 2 }; + const replacementSamples = vi.fn().mockResolvedValue([{ active: true }]); + vi.mocked(ClustersClient.getBinding).mockReturnValue(replacementBinding); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.resolveBoundClient).mockResolvedValue({ + binding: replacementBinding, + getSampleDocuments: replacementSamples, + } as unknown as ClustersClient); + availability.resolve(true); + + await expect(pending).resolves.toMatchObject({ explanation: 'Generated' }); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(replacementSamples).toHaveBeenCalledExactlyOnceWith('database', 'collection', 10); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledWith(binding, { trigger: 'collectionView' }); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledWith(expect.any(Array), { + featureSource: 'queryGeneration', + signal: queryContext.signal, + }); +}); + +it('does not start the second collection sample after invalidation during the first', async (): Promise => { + const firstSample = deferred(); + sampleDocuments.mockReturnValueOnce(firstSample.promise); + const pending = generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }); + await vi.waitFor(() => expect(sampleDocuments).toHaveBeenCalledExactlyOnceWith('database', 'first', 3)); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + firstSample.resolve([{ active: true }]); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not sample after retirement during collection listing', async (): Promise => { + const listing = deferred>>(); + listCollections.mockReturnValueOnce(listing.promise); + const pending = generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }); + await vi.waitFor(() => expect(listCollections).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + listing.resolve([{ name: 'first' }]); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).not.toHaveBeenCalled(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('does not send after retirement during prompt preparation', async (): Promise => { + const template = deferred(); + vi.mocked(PromptTemplateService.getQueryGenerationPromptTemplate).mockReturnValueOnce(template.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(PromptTemplateService.getQueryGenerationPromptTemplate).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + template.resolve('Fake prompt'); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it('returns a successful model response after same-account repair advances the epoch', async (): Promise => { + const modelResponse = deferred>>(); + vi.mocked(CopilotService.sendMessage).mockReturnValueOnce(modelResponse.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(CopilotService.sendMessage).toHaveBeenCalledOnce()); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + modelResponse.resolve({ + text: JSON.stringify({ explanation: 'Generated after repair', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + + await expect(pending).resolves.toMatchObject({ + generatedQuery: JSON.stringify({ filter: '{"active":true}' }, null, 2), + explanation: 'Generated after repair', + }); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('cancels a model response after retirement even when the fake model ignores abort', async (): Promise => { + const modelResponse = deferred>>(); + vi.mocked(CopilotService.sendMessage).mockReturnValueOnce(modelResponse.promise); + const pending = generateQuery(context, queryContext); + await vi.waitFor(() => expect(CopilotService.sendMessage).toHaveBeenCalledOnce()); + retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + expect(vi.mocked(CopilotService.sendMessage).mock.calls[0][1]?.signal?.aborted).toBe(true); + modelResponse.resolve({ + text: JSON.stringify({ explanation: 'Late response', command: { filter: '{"active":true}' } }), + durationMs: 1, + modelId: 'fake-model', + modelFamily: 'fake-family', + modelDisplayName: 'Fake model', + modelVersion: '1', + }); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + await expect(pending).rejects.toHaveProperty('stepName', 'staleBoundViewOperation'); + expect(sampleDocuments).toHaveBeenCalledOnce(); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); + +it('preserves a schema sampling failure as the cause', async (): Promise => { + const cause = new Error('Synthetic sampling failure'); + sampleDocuments.mockRejectedValueOnce(cause); + + await expect(generateQuery(context, queryContext)).rejects.toMatchObject({ + message: expect.stringContaining('Failed to gather schema information'), + cause, + }); + expect(ClustersClient.reportFailure).toHaveBeenCalledWith(binding, expect.objectContaining({ cause })); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); +}); + +it.each([new UserCancelledError('Synthetic cancellation'), new ConnectionUnavailableError('credentialsUpdating')])( + 'rethrows terminal sampling errors unchanged: $name', + async (error): Promise => { + sampleDocuments.mockRejectedValueOnce(error); + + await expect(generateQuery(context, queryContext)).rejects.toBe(error); + expect(CopilotService.sendMessage).not.toHaveBeenCalled(); + }, +); + +it('samples both collections and sends one request in normal cross-collection generation', async (): Promise => { + await expect( + generateQuery(context, { ...queryContext, generationType: QueryGenerationType.CrossCollection }), + ).resolves.toMatchObject({ explanation: 'Generated' }); + + expect(listCollections).toHaveBeenCalledExactlyOnceWith('database'); + expect(sampleDocuments.mock.calls).toEqual([ + ['database', 'first', 3], + ['database', 'second', 3], + ]); + expect(CopilotService.sendMessage).toHaveBeenCalledOnce(); +}); diff --git a/src/commands/llmEnhancedCommands/queryGenerationCommands.ts b/src/commands/llmEnhancedCommands/queryGenerationCommands.ts index bce7621c0..acd52aafd 100644 --- a/src/commands/llmEnhancedCommands/queryGenerationCommands.ts +++ b/src/commands/llmEnhancedCommands/queryGenerationCommands.ts @@ -3,15 +3,17 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type IActionContext } from '@microsoft/vscode-azext-utils'; +import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { type Document } from 'mongodb'; import * as vscode from 'vscode'; -import { ClustersClient } from '../../documentdb/ClustersClient'; +import { type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { ext } from '../../extensionVariables'; import { CopilotService } from '../../services/copilotService'; import { PromptTemplateService } from '../../services/promptTemplateService'; import { generateSchemaDefinition, type SchemaDefinition } from '../../utils/schemaInference'; +import { guardBoundViewOperation, runBoundViewOperation } from '../../webviews/documentdb/boundViewOperations'; import { getQueryTypeConfig, type FilledPromptResult } from './promptTemplates'; /** @@ -26,8 +28,8 @@ export enum QueryGenerationType { * Context information needed for query generation */ export interface QueryGenerationContext { - // The cluster/connection ID - clusterId: string; + readonly binding: ConnectionBinding; + readonly signal: AbortSignal; // Database name databaseName: string; // Collection name (only for single-collection queries) @@ -174,6 +176,10 @@ export async function generateQuery( // Check if Copilot is available const copilotAvailable = await CopilotService.isAvailable(); + const assertCurrent = guardBoundViewOperation(queryContext.binding, queryContext.signal); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } if (!copilotAvailable) { throw new Error( l10n.t( @@ -182,79 +188,96 @@ export async function generateQuery( ); } - // Get the MongoDB client const getClientStart = Date.now(); - const client = await ClustersClient.getClient(queryContext.clusterId); - context.telemetry.measurements.getClientDurationMs = Date.now() - getClientStart; + const schemas = await runBoundViewOperation( + queryContext.binding, + assertCurrent, + async (client) => { + context.telemetry.measurements.getClientDurationMs = Date.now() - getClientStart; + const schemas: Array = []; + const schemaGatheringStart = Date.now(); + try { + if (queryContext.generationType === QueryGenerationType.CrossCollection) { + // Get all collections in the database + const listCollectionsStart = Date.now(); + assertCurrent(); + const collections = await client.listCollections(queryContext.databaseName); + assertCurrent(); + context.telemetry.measurements.listCollectionsDurationMs = Date.now() - listCollectionsStart; + ext.outputChannel.trace( + l10n.t('[Query Generation] listCollections completed in {ms}ms ({count} collections)', { + ms: context.telemetry.measurements.listCollectionsDurationMs.toString(), + count: collections.length.toString(), + }), + ); - // Gather schema information - const schemas: Array = []; - const schemaGatheringStart = Date.now(); + let collectionIndex = 0; + for (const collection of collections) { + collectionIndex++; + const sampleDocsStart = Date.now(); + assertCurrent(); + const sampleDocs = await client.getSampleDocuments( + queryContext.databaseName, + collection.name, + 3, + ); + assertCurrent(); + const sampleDocsDuration = Date.now() - sampleDocsStart; + context.telemetry.measurements[`sampleDocs_${collectionIndex}_DurationMs`] = sampleDocsDuration; + ext.outputChannel.trace( + l10n.t('[Query Generation] Schema sampling for {collection} completed in {ms}ms', { + collection: collection.name, + ms: sampleDocsDuration.toString(), + }), + ); - try { - if (queryContext.generationType === QueryGenerationType.CrossCollection) { - // Get all collections in the database - const listCollectionsStart = Date.now(); - const collections = await client.listCollections(queryContext.databaseName); - context.telemetry.measurements.listCollectionsDurationMs = Date.now() - listCollectionsStart; - ext.outputChannel.trace( - l10n.t('[Query Generation] listCollections completed in {ms}ms ({count} collections)', { - ms: context.telemetry.measurements.listCollectionsDurationMs.toString(), - count: collections.length.toString(), - }), - ); + if (sampleDocs.length > 0) { + const schema = generateSchemaDefinition(sampleDocs, collection.name); + schemas.push(schema); + } else { + schemas.push({ collectionName: collection.name, fields: {} }); + } + } + } else { + if (!queryContext.collectionName) { + throw new Error(l10n.t('Collection name is required for single-collection query generation')); + } - let collectionIndex = 0; - for (const collection of collections) { - collectionIndex++; - const sampleDocsStart = Date.now(); - const sampleDocs = await client.getSampleDocuments(queryContext.databaseName, collection.name, 3); - const sampleDocsDuration = Date.now() - sampleDocsStart; - context.telemetry.measurements[`sampleDocs_${collectionIndex}_DurationMs`] = sampleDocsDuration; - ext.outputChannel.trace( - l10n.t('[Query Generation] Schema sampling for {collection} completed in {ms}ms', { - collection: collection.name, - ms: sampleDocsDuration.toString(), - }), - ); + const sampleDocsStart = Date.now(); + assertCurrent(); + const sampleDocs = await client.getSampleDocuments( + queryContext.databaseName, + queryContext.collectionName, + 10, + ); + assertCurrent(); + context.telemetry.measurements.sampleDocsDurationMs = Date.now() - sampleDocsStart; + ext.outputChannel.trace( + l10n.t('[Query Generation] Schema sampling completed in {ms}ms', { + ms: context.telemetry.measurements.sampleDocsDurationMs.toString(), + }), + ); - if (sampleDocs.length > 0) { - const schema = generateSchemaDefinition(sampleDocs, collection.name); + const schema = generateSchemaDefinition(sampleDocs, queryContext.collectionName); schemas.push(schema); - } else { - schemas.push({ collectionName: collection.name, fields: {} }); } + context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; + return schemas; + } catch (error) { + context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; + if (error instanceof ConnectionUnavailableError || error instanceof UserCancelledError) { + throw error; + } + throw new Error( + l10n.t('Failed to gather schema information: {message}', { + message: error instanceof Error ? error.message : String(error), + }), + { cause: error }, + ); } - } else { - if (!queryContext.collectionName) { - throw new Error(l10n.t('Collection name is required for single-collection query generation')); - } - - const sampleDocsStart = Date.now(); - const sampleDocs = await client.getSampleDocuments( - queryContext.databaseName, - queryContext.collectionName, - 10, - ); - context.telemetry.measurements.sampleDocsDurationMs = Date.now() - sampleDocsStart; - ext.outputChannel.trace( - l10n.t('[Query Generation] Schema sampling completed in {ms}ms', { - ms: context.telemetry.measurements.sampleDocsDurationMs.toString(), - }), - ); - - const schema = generateSchemaDefinition(sampleDocs, queryContext.collectionName); - schemas.push(schema); - } - context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; - } catch (error) { - context.telemetry.measurements.schemaGatheringDurationMs = Date.now() - schemaGatheringStart; - throw new Error( - l10n.t('Failed to gather schema information: {message}', { - message: error instanceof Error ? error.message : String(error), - }), - ); - } + }, + { trigger: 'collectionView' }, + ); // Fill the prompt template const { craftedPrompt, userQuery, contextData } = await fillPromptTemplate( @@ -263,6 +286,9 @@ export async function generateQuery( schemas, ); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } ext.outputChannel.trace(l10n.t('[Query Generation] Calling Copilot...')); const response = await CopilotService.sendMessage( [ @@ -272,8 +298,12 @@ export async function generateQuery( ], { featureSource: 'queryGeneration', + signal: queryContext.signal, }, ); + if (queryContext.signal.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } context.telemetry.measurements.llmCallDurationMs = response.durationMs; ext.outputChannel.trace( l10n.t('[Query Generation] Copilot response received in {ms}ms (model: {model})', { diff --git a/src/commands/openCollectionView/openCollectionView.test.ts b/src/commands/openCollectionView/openCollectionView.test.ts index ff9d6ff11..6b19028ef 100644 --- a/src/commands/openCollectionView/openCollectionView.test.ts +++ b/src/commands/openCollectionView/openCollectionView.test.ts @@ -4,12 +4,24 @@ *--------------------------------------------------------------------------------------------*/ import { type IActionContext } from '@microsoft/vscode-azext-utils'; -import { describe, expect, it, vi } from 'vitest'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { ClusterSession } from '../../documentdb/ClusterSession'; +import { ConnectionUnavailableError } from '../../documentdb/ConnectionUnavailableError'; import { openCollectionWebview } from '../../webviews/documentdb/collectionView/collectionViewController'; import { openCollectionViewInternal } from './openCollectionView'; +const { assertAvailable } = vi.hoisted(() => ({ assertAvailable: vi.fn() })); + +vi.mock('../../documentdb/ClustersClient', () => ({ + ClustersClient: { assertBindingActive: vi.fn() }, +})); vi.mock('../../documentdb/ClusterSession', () => ({ - ClusterSession: { initNewSession: vi.fn().mockResolvedValue('collection-session'), closeSession: vi.fn() }, + ClusterSession: { + initNewSession: vi.fn().mockResolvedValue('collection-session'), + getSession: vi.fn(() => ({ assertAvailable })), + closeSession: vi.fn(), + }, })); vi.mock('../../utils/feedbackPermission', () => ({ isFeedbackPermitted: () => true })); vi.mock('../../webviews/documentdb/collectionView/collectionViewController', () => ({ @@ -40,3 +52,73 @@ describe('URL-driven collection opening', () => { ); }); }); + +describe('bound collection opening', () => { + const origin = { clusterId: 'stable-id', fingerprint: 'dashboard-fingerprint', generation: 1 }; + const props = { + clusterId: origin.clusterId, + clusterDisplayName: 'Cluster', + viewId: 'connectionsView', + databaseName: 'db', + collectionName: 'collection', + }; + let context: IActionContext; + + beforeEach((): void => { + vi.clearAllMocks(); + context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: { issueProperties: {} }, + valuesToMask: [], + ui: {} as IActionContext['ui'], + }; + }); + + it('forwards the origin and cancellation to session creation without serializing them', async (): Promise => { + const signal = new AbortController().signal; + const options = { origin, signal }; + + await openCollectionViewInternal(context, props, options); + + expect(ClusterSession.initNewSession).toHaveBeenCalledExactlyOnceWith(origin.clusterId, options); + expect(ClustersClient.assertBindingActive).toHaveBeenCalledExactlyOnceWith(origin); + expect(ClusterSession.getSession).toHaveBeenCalledExactlyOnceWith('collection-session'); + expect(assertAvailable).toHaveBeenCalledExactlyOnceWith(signal); + expect(openCollectionWebview).toHaveBeenCalledExactlyOnceWith( + { + ...props, + sessionId: 'collection-session', + feedbackPermitted: true, + initialQuery: undefined, + initialTab: undefined, + }, + undefined, + undefined, + ); + }); + + it.each(['origin', 'session'] as const)( + 'closes the new session when the %s guard rejects immediately before publication', + async (guard): Promise => { + const error = new ConnectionUnavailableError('userDisconnected'); + const check = guard === 'origin' ? vi.mocked(ClustersClient.assertBindingActive) : assertAvailable; + check.mockImplementationOnce((): never => { + throw error; + }); + + await expect(openCollectionViewInternal(context, props, { origin })).rejects.toBe(error); + + expect(ClusterSession.closeSession).toHaveBeenCalledExactlyOnceWith('collection-session'); + expect(openCollectionWebview).not.toHaveBeenCalled(); + }, + ); + + it('preserves the unbound one-argument session call without bound guards', async (): Promise => { + await openCollectionViewInternal(context, props); + + expect(ClusterSession.initNewSession).toHaveBeenCalledExactlyOnceWith(props.clusterId); + expect(ClustersClient.assertBindingActive).not.toHaveBeenCalled(); + expect(ClusterSession.getSession).not.toHaveBeenCalled(); + expect(openCollectionWebview).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/commands/openCollectionView/openCollectionView.ts b/src/commands/openCollectionView/openCollectionView.ts index a73700cdc..0b399d7e2 100644 --- a/src/commands/openCollectionView/openCollectionView.ts +++ b/src/commands/openCollectionView/openCollectionView.ts @@ -7,6 +7,7 @@ import { type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { readDeepLinkTelemetry } from '../../deepLinks/deepLinkTelemetry'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; import { ClusterSession } from '../../documentdb/ClusterSession'; import { inferViewIdFromTreeId } from '../../documentdb/Views'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; @@ -59,14 +60,27 @@ export async function openCollectionViewInternal( */ initialTab?: 'tab_result' | 'tab_indexes' | 'tab_queryInsights'; }, + options?: { readonly origin?: ConnectionBinding; readonly signal?: AbortSignal }, ): Promise { /** * We're starting a new "session" using the existing connection. * A session can cache data, handle paging, and convert data. */ - const sessionId = await ClusterSession.initNewSession(props.clusterId); + const sessionId = options + ? await ClusterSession.initNewSession(props.clusterId, options) + : await ClusterSession.initNewSession(props.clusterId); context.telemetry.properties.collectionSessionId = sessionId; + if (options?.origin) { + try { + ClustersClient.assertBindingActive(options.origin); + ClusterSession.getSession(sessionId).assertAvailable(options.signal); + } catch (error) { + ClusterSession.closeSession(sessionId); + throw error; + } + } + const view = openCollectionWebview( { sessionId: sessionId, diff --git a/src/commands/playground/connectDatabase.test.ts b/src/commands/playground/connectDatabase.test.ts new file mode 100644 index 000000000..aa2873403 --- /dev/null +++ b/src/commands/playground/connectDatabase.test.ts @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient } from '../../documentdb/ClustersClient'; +import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; +import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { DatabaseItem } from '../../tree/documentdb/DatabaseItem'; +import { pickTreeNode } from '../../utils/pickItem/pickTreeNode'; +import { showConnectionInfo } from './connectDatabase'; + +vi.mock('../../utils/pickItem/pickTreeNode', () => ({ pickTreeNode: vi.fn() })); + +describe('playground connection information', () => { + let service: PlaygroundService; + let context: IActionContext; + let sequence = 0; + let uri: vscode.Uri; + let clusterId: string; + + beforeEach((): void => { + vi.clearAllMocks(); + clusterId = `playground-connection-info-${++sequence}`; + uri = vscode.Uri.parse(`untitled:connection-info-${sequence}.documentdb.js`); + Object.assign(vscode.window, { + activeTextEditor: { + document: { + uri, + languageId: PLAYGROUND_LANGUAGE_ID, + }, + } as vscode.TextEditor, + }); + context = { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + } as IActionContext; + service = PlaygroundService.getInstance(); + service.setConnection(uri, { + clusterId, + clusterDisplayName: 'Original Cluster', + databaseName: 'original', + }); + }); + + afterEach((): void => { + ClustersClient.unlatch(clusterId); + service.dispose(); + Object.assign(vscode.window, { activeTextEditor: undefined }); + vi.restoreAllMocks(); + }); + + it('explains an explicit disconnect without clearing the selected connection', async () => { + ClustersClient.latch(clusterId, 'userDisconnected'); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + await showConnectionInfo(context); + + expect(vscode.window.showWarningMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + { modal: true }, + 'Connect to a different database…', + ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); + expect(pickTreeNode).not.toHaveBeenCalled(); + expect(context.telemetry.properties.reconnectChoice).toBe('dismissed'); + expect(service.getConnection(uri)).toMatchObject({ + clusterId, + clusterDisplayName: 'Original Cluster', + databaseName: 'original', + }); + }); + + it('keeps the switch action on the normal picker flow', async () => { + const replacement = Object.assign(Object.create(DatabaseItem.prototype) as DatabaseItem, { + cluster: { + clusterId: `replacement-${sequence}`, + name: 'Replacement Cluster', + viewId: 'connectionsView', + }, + databaseInfo: { name: 'replacement' }, + experience: { api: 'DocumentDB' }, + }); + vi.mocked(vscode.window.showWarningMessage).mockResolvedValue('Connect to a different database…' as never); + vi.mocked(pickTreeNode).mockResolvedValue(replacement); + ClustersClient.latch(clusterId, 'userDisconnected'); + + await showConnectionInfo(context); + + expect(pickTreeNode).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + leafContextValue: 'treeItem_database', + telemetrySource: 'playground.connect', + placeHolder: 'Select a database to connect this playground to', + }), + ); + expect(context.telemetry.properties).toMatchObject({ + reconnectChoice: 'switch', + outcome: 'connected', + experience: 'DocumentDB', + }); + expect(service.getConnection(uri)).toMatchObject({ + clusterId: `replacement-${sequence}`, + clusterDisplayName: 'Replacement Cluster', + databaseName: 'replacement', + }); + }); +}); diff --git a/src/commands/playground/connectDatabase.ts b/src/commands/playground/connectDatabase.ts index c2e920099..59a50c497 100644 --- a/src/commands/playground/connectDatabase.ts +++ b/src/commands/playground/connectDatabase.ts @@ -49,6 +49,21 @@ export async function showConnectionInfo(context: IActionContext): Promise } const switchAction = l10n.t('Connect to a different database…'); + if (service.isUserDisconnected(editor.document.uri)) { + const choice = await vscode.window.showWarningMessage( + l10n.t('This connection is disconnected. Reconnect from the tree, then run the script again.'), + { modal: true }, + switchAction, + ); + + context.telemetry.properties.reconnectChoice = choice === switchAction ? 'switch' : 'dismissed'; + + if (choice === switchAction) { + await promptAndConnectPlayground(context, editor.document.uri, 'playground.connect'); + } + return; + } + const choice = await vscode.window.showInformationMessage( l10n.t('This playground is connected to {0} / {1}.', connection.clusterDisplayName, connection.databaseName), { diff --git a/src/commands/playground/executePlaygroundCode.ts b/src/commands/playground/executePlaygroundCode.ts index d150879a9..fc33f8118 100644 --- a/src/commands/playground/executePlaygroundCode.ts +++ b/src/commands/playground/executePlaygroundCode.ts @@ -60,6 +60,10 @@ export function stopPlaygroundEvaluator(clusterId: string): void { evaluator?.dispose(); } +export function clearRemovedPlaygroundConnections(clusterId: string): void { + PlaygroundService.getInstance().removeConnectionsForCluster(clusterId); +} + /** * Shut down all evaluators that have no remaining open playground documents. * Called when playground documents close or state changes. diff --git a/src/commands/playground/newPlayground.test.ts b/src/commands/playground/newPlayground.test.ts index df7710c7f..17ccb453c 100644 --- a/src/commands/playground/newPlayground.test.ts +++ b/src/commands/playground/newPlayground.test.ts @@ -3,11 +3,26 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import type * as vscode from 'vscode'; +import { createTestActionContext, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { createTextDocument } from 'jest-mock-vscode'; +import * as vscode from 'vscode'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../../documentdb/connectionBindingRetirement'; import { PLAYGROUND_LANGUAGE_ID } from '../../documentdb/playground/constants'; -import { createPlaygroundFileName } from './newPlayground'; +import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { type DatabaseItem } from '../../tree/documentdb/DatabaseItem'; +import { + createPlaygroundFileName, + newPlayground, + newPlaygroundWithContent, + type PlaygroundHandoffOrigin, +} from './newPlayground'; + +vi.mock('../../extensionVariables', () => ({ + ext: { outputChannel: { trace: vi.fn() } }, +})); function playgroundDocument(fileName: string): vscode.TextDocument { return { @@ -31,13 +46,232 @@ function javascriptDocument(fileName: string): vscode.TextDocument { } as vscode.TextDocument; } +describe('Playground origin handoffs', () => { + let sequence = 0; + let context: IActionContext; + let binding: ConnectionBinding; + let service: PlaygroundService; + let doc: vscode.TextDocument; + const identity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'original-account', + accountLabel: 'Original account', + tenantId: 'tenant', + } as const; + + beforeEach(async (): Promise => { + context = await createTestActionContext(); + binding = { clusterId: `playground-handoff-${++sequence}`, fingerprint: 'original', generation: 1 }; + const uri = vscode.Uri.parse(`untitled:handoff-${sequence}.documentdb.js`); + doc = createTextDocument(uri, "db.getCollection('records').find({})", PLAYGROUND_LANGUAGE_ID); + vi.spyOn(vscode.Uri, 'file').mockReturnValue(uri); + vi.spyOn(vscode.workspace, 'applyEdit').mockClear().mockResolvedValue(true); + vi.spyOn(vscode.workspace, 'openTextDocument').mockClear().mockResolvedValue(doc); + vi.spyOn(vscode.window, 'showTextDocument') + .mockClear() + .mockResolvedValue({ document: doc } as vscode.TextEditor); + vi.spyOn(vscode.window, 'showWarningMessage').mockClear().mockResolvedValue(undefined); + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(binding); + vi.spyOn(ClustersClient, 'getLastVerifiedIdentity').mockReturnValue(identity); + vi.spyOn(ClustersClient, 'getExpectedFingerprint').mockReturnValue(binding.fingerprint); + vi.spyOn(ClustersClient, 'getEpoch').mockReturnValue(1); + vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue(undefined); + service = PlaygroundService.getInstance(); + vi.spyOn(service, 'setConnectionFromHost'); + vi.spyOn(service, 'removeConnection'); + }); + + afterEach((): void => { + service.dispose(); + vi.restoreAllMocks(); + }); + + function open(origin: PlaygroundHandoffOrigin): Promise { + return newPlaygroundWithContent(context, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + content: "db.getCollection('records').find({})", + origin, + }); + } + + function treeNode(): DatabaseItem { + return { + cluster: { clusterId: binding.clusterId, name: 'Cluster', viewId: 'connectionsView' }, + databaseInfo: { name: 'database' }, + experience: { api: 'DocumentDB' }, + } as unknown as DatabaseItem; + } + + it.each([ + ['binding', 'open', 'different'], + ['binding', 'show', 'same'], + ['tree', 'open', 'same'], + ['tree', 'show', 'different'], + ['shell', 'open', 'different'], + ['shell', 'show', 'same'], + ['binding', 'show', 'disconnect'], + ['saved', 'open', 'same'], + ] as const)( + 'leaves the %s draft unbound when %s pauses across %s explicit session end', + async (source, boundary, replacement): Promise => { + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + if (boundary === 'open') { + vi.mocked(vscode.workspace.openTextDocument).mockImplementationOnce(async () => { + await pause; + return doc; + }); + } else { + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document: doc } as vscode.TextEditor; + }); + } + let shellCurrent = true; + let origin: PlaygroundHandoffOrigin = { kind: 'binding', binding, entraIdentity: identity }; + if (source === 'shell') { + origin = { + kind: 'shell', + fingerprint: binding.fingerprint, + entraIdentity: identity, + isCurrent: () => shellCurrent, + }; + } else if (source === 'saved') { + origin = { kind: 'saved', epoch: 1 }; + } + const pending = source === 'tree' ? newPlayground(context, treeNode()) : open(origin); + await vi.waitFor(() => + expect( + boundary === 'open' ? vscode.workspace.openTextDocument : vscode.window.showTextDocument, + ).toHaveBeenCalledOnce(), + ); + // Simulate the open-document listener restoring a remembered untitled binding. + service.setConnection(doc.uri, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + shellCurrent = false; + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + if (replacement === 'disconnect') { + vi.mocked(ClustersClient.getBinding).mockReturnValue(undefined); + } else { + vi.mocked(ClustersClient.getBinding).mockReturnValue({ + ...binding, + fingerprint: replacement === 'different' ? 'replacement' : binding.fingerprint, + generation: 2, + }); + } + release(); + await pending; + + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(service.removeConnection).toHaveBeenCalledExactlyOnceWith(doc.uri); + expect(service.getConnection(doc.uri)).toBeUndefined(); + expect(vscode.workspace.applyEdit).toHaveBeenCalledOnce(); + expect(vscode.window.showTextDocument).toHaveBeenCalledWith(doc, { preview: true }); + expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce(); + }, + ); + + it.each(['binding', 'shell'] as const)( + 'preserves the original %s pin across same-account repair during document display', + async (source): Promise => { + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document: doc } as vscode.TextEditor; + }); + const pending = open( + source === 'binding' + ? { kind: 'binding', binding, entraIdentity: identity } + : { + kind: 'shell', + fingerprint: binding.fingerprint, + entraIdentity: identity, + isCurrent: () => true, + }, + ); + await vi.waitFor(() => expect(vscode.window.showTextDocument).toHaveBeenCalledOnce()); + vi.mocked(ClustersClient.getEpoch).mockReturnValue(2); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ ...binding, generation: 2 }); + vi.mocked(ClustersClient.getLatchReason).mockReturnValue('signInRequired'); + release(); + await pending; + + expect(service.setConnectionFromHost).toHaveBeenCalledOnce(); + expect(service.getConnection(doc.uri)).toMatchObject({ + fingerprint: binding.fingerprint, + entraIdentity: identity, + }); + expect(service.removeConnection).not.toHaveBeenCalled(); + }, + ); + + it('never binds an anonymous handoff or retains its restored authenticated binding', async (): Promise => { + service.setConnection(doc.uri, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + await open({ kind: 'none' }); + + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(service.getConnection(doc.uri)).toBeUndefined(); + expect(ClustersClient.getExpectedFingerprint).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + }); + + it('binds a normal saved tree selection once through the existing host capture API', async (): Promise => { + vi.mocked(ClustersClient.getBinding).mockReturnValueOnce(undefined); + await newPlayground(context, treeNode()); + + expect(service.setConnectionFromHost).toHaveBeenCalledOnce(); + expect(service.getConnection(doc.uri)?.fingerprint).toBe(binding.fingerprint); + }); + + it('still permits an explicit connection re-pick after rejecting an old handoff', async (): Promise => { + retireConnectionBindings(binding.clusterId, binding.generation, 'userDisconnected'); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ + ...binding, + fingerprint: 'replacement', + generation: 2, + }); + await open({ kind: 'binding', binding, entraIdentity: identity }); + expect(service.getConnection(doc.uri)).toBeUndefined(); + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + + const replacementIdentity = { ...identity, accountId: 'replacement-account' }; + vi.mocked(ClustersClient.getLastVerifiedIdentity).mockReturnValue(replacementIdentity); + service.setConnectionFromHost(doc.uri, { + clusterId: binding.clusterId, + clusterDisplayName: 'Cluster', + databaseName: 'database', + }); + + expect(service.setConnectionFromHost).toHaveBeenCalledOnce(); + expect(service.getConnection(doc.uri)).toMatchObject({ + fingerprint: 'replacement', + entraIdentity: replacementIdentity, + }); + }); +}); + describe('createPlaygroundFileName', () => { it('uses cluster and collection context when provided', () => { const fileName = createPlaygroundFileName([], { clusterDisplayName: 'my-cluster', databaseOrCollectionName: 'users', }); - expect(fileName).toBe('my-cluster_users.documentdb.js'); }); diff --git a/src/commands/playground/newPlayground.ts b/src/commands/playground/newPlayground.ts index 9e07f55cc..6e08b5cca 100644 --- a/src/commands/playground/newPlayground.ts +++ b/src/commands/playground/newPlayground.ts @@ -9,8 +9,11 @@ import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import { modifierKey } from '../../constants'; -import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; +import { type VerifiedEntraIdentity } from '../../documentdb/auth/AuthHandler'; +import { ClustersClient, type ConnectionBinding } from '../../documentdb/ClustersClient'; +import { isRetiredConnectionBinding } from '../../documentdb/connectionBindingRetirement'; import { PLAYGROUND_FILE_EXTENSION } from '../../documentdb/playground/constants'; +import { PlaygroundService } from '../../documentdb/playground/PlaygroundService'; import { type PlaygroundConnection } from '../../documentdb/playground/types'; import { type CollectionItem } from '../../tree/documentdb/CollectionItem'; import { type DatabaseItem } from '../../tree/documentdb/DatabaseItem'; @@ -21,6 +24,12 @@ interface PlaygroundFileNameContext { readonly databaseOrCollectionName: string; } +export type PlaygroundHandoffOrigin = + | { kind: 'binding'; binding: ConnectionBinding; entraIdentity?: VerifiedEntraIdentity; signal?: AbortSignal } + | { kind: 'shell'; fingerprint: string; entraIdentity?: VerifiedEntraIdentity; isCurrent: () => boolean } + | { kind: 'saved'; epoch: number } + | { kind: 'none' }; + /** * Creates a new Query Playground file. * @@ -36,6 +45,11 @@ export async function newPlayground(context: IActionContext, node?: DatabaseItem ); return; } + const binding = ClustersClient.getBinding(node.cluster.clusterId); + const identity = binding ? ClustersClient.getLastVerifiedIdentity(node.cluster.clusterId) : undefined; + const origin: PlaygroundHandoffOrigin = binding + ? { kind: 'binding', binding, entraIdentity: identity?.kind === 'entra' ? identity : undefined } + : { kind: 'saved', epoch: ClustersClient.getEpoch(node.cluster.clusterId) }; // ── Telemetry: activation source & context ─────────────────────── context.telemetry.properties.activationSource ??= 'treeNode'; @@ -65,6 +79,7 @@ export async function newPlayground(context: IActionContext, node?: DatabaseItem databaseName: node.databaseInfo.name, viewId: node.cluster.viewId, }, + origin, isCollectionItem(node) ? node.collectionInfo.name : undefined, ); } @@ -74,6 +89,7 @@ export async function newPlayground(context: IActionContext, node?: DatabaseItem * Used by cross-feature navigation links (Collection View → Playground, Shell → Playground). */ export interface NewPlaygroundWithContentParams { + readonly origin: PlaygroundHandoffOrigin; readonly clusterId: string; readonly clusterDisplayName: string; readonly databaseName: string; @@ -109,12 +125,16 @@ export async function newPlaygroundWithContent( '', ].join('\n'); - await createPlaygroundWithContent(template, { - clusterId: params.clusterId, - clusterDisplayName: params.clusterDisplayName, - databaseName: params.databaseName, - viewId: params.viewId, - }); + await createPlaygroundWithContent( + template, + { + clusterId: params.clusterId, + clusterDisplayName: params.clusterDisplayName, + databaseName: params.databaseName, + viewId: params.viewId, + }, + params.origin, + ); } /** @@ -123,6 +143,7 @@ export async function newPlaygroundWithContent( async function createPlaygroundWithContent( content: string, connection: PlaygroundConnection, + origin: PlaygroundHandoffOrigin, collectionName?: string, ): Promise { const service = PlaygroundService.getInstance(); @@ -143,7 +164,45 @@ async function createPlaygroundWithContent( const doc = await vscode.workspace.openTextDocument(uri); await vscode.window.showTextDocument(doc, { preview: true }); - // Bind connection to this specific document + let current = false; + switch (origin.kind) { + case 'binding': { + const hostBinding = ClustersClient.getBinding(connection.clusterId); + current = + !origin.signal?.aborted && + !isRetiredConnectionBinding(origin.binding) && + (!hostBinding || hostBinding.fingerprint === origin.binding.fingerprint); + connection = { + ...connection, + fingerprint: origin.binding.fingerprint, + entraIdentity: origin.entraIdentity, + }; + break; + } + case 'shell': + current = + origin.isCurrent() && + ClustersClient.getExpectedFingerprint(connection.clusterId, origin.entraIdentity) === + origin.fingerprint; + connection = { ...connection, fingerprint: origin.fingerprint, entraIdentity: origin.entraIdentity }; + break; + case 'saved': + current = + ClustersClient.getEpoch(connection.clusterId) === origin.epoch && + !ClustersClient.getLatchReason(connection.clusterId); + break; + case 'none': + break; + } + if (!current) { + service.removeConnection(doc.uri); + if (origin.kind !== 'none') { + void vscode.window.showWarningMessage( + l10n.t('This playground is bound to the previous connection. Re-pick its connection from the tree.'), + ); + } + return; + } service.setConnectionFromHost(doc.uri, connection); } diff --git a/src/commands/runBoundNamespaceCommand.test.ts b/src/commands/runBoundNamespaceCommand.test.ts new file mode 100644 index 000000000..ea58caab2 --- /dev/null +++ b/src/commands/runBoundNamespaceCommand.test.ts @@ -0,0 +1,181 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; +import { afterEach, expect, it, vi } from 'vitest'; +import { ClustersClient, type ConnectionBinding } from '../documentdb/ClustersClient'; +import { retireConnectionBindings } from '../documentdb/connectionBindingRetirement'; +import { runBoundNamespaceCommand } from './runBoundNamespaceCommand'; + +interface Deferred { + readonly promise: Promise; + resolve(value: T): void; +} + +interface CreateClientFixture { + readonly client: ClustersClient; + readonly createDatabase: ClustersClient['createDatabase']; + readonly createCollection: ClustersClient['createCollection']; + readonly dropDatabase: ClustersClient['dropDatabase']; +} + +interface CreateEffect { + readonly name: string; + readonly method: 'createDatabase' | 'createCollection'; + readonly run: (client: ClustersClient) => Promise; +} + +const createEffects: readonly CreateEffect[] = [ + { + name: 'database', + method: 'createDatabase', + run: async (client) => client.createDatabase('database'), + }, + { + name: 'collection', + method: 'createCollection', + run: async (client) => client.createCollection('database', 'collection'), + }, +]; + +let clusterSequence = 0; + +function deferred(): Deferred { + let resolve!: (value: T) => void; + const promise = new Promise((resolvePromise): void => { + resolve = resolvePromise; + }); + return { promise, resolve }; +} + +function createBinding(): ConnectionBinding { + return { + clusterId: `run-bound-namespace-${++clusterSequence}`, + fingerprint: 'original', + generation: 0, + }; +} + +function createClient(binding: ConnectionBinding): CreateClientFixture { + const createDatabase = vi.fn().mockResolvedValue(undefined); + const createCollection = vi + .fn() + .mockResolvedValue({} as Awaited>); + const dropDatabase = vi.fn().mockResolvedValue(true); + return { + client: { + binding, + generation: binding.generation, + fingerprint: binding.fingerprint, + createDatabase, + createCollection, + dropDatabase, + } as unknown as ClustersClient, + createDatabase, + createCollection, + dropDatabase, + }; +} + +afterEach((): void => { + vi.restoreAllMocks(); +}); + +it.each(createEffects)('does not create a $name after its binding lifetime ends during resolution', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + ClustersClient._clients.set(binding.clusterId, replacement.client); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + resolution.resolve(replacement.client); + + await expect(pending).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); + ClustersClient._clients.delete(binding.clusterId); +}); + +it.each(createEffects)('does not create a $name when a current latch starts during resolution', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + ClustersClient.latch(binding.clusterId, 'credentialsUpdating'); + resolution.resolve(replacement.client); + + try { + await expect(pending).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + } finally { + ClustersClient.unlatch(binding.clusterId); + } +}); + +it.each(createEffects)('does not revive a retired $name binding when its teardown latch clears', async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + ClustersClient._clients.set(binding.clusterId, replacement.client); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + ClustersClient.latch(binding.clusterId, 'credentialsChanged'); + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + ClustersClient.unlatch(binding.clusterId); + resolution.resolve(replacement.client); + + await expect(pending).rejects.toMatchObject({ reason: 'credentialsChanged' }); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).not.toHaveBeenCalled(); + expect(ClustersClient.getExistingClient(binding.clusterId)).toBe(replacement.client); + ClustersClient._clients.delete(binding.clusterId); +}); + +it.each(createEffects)( + 'creates a $name once when the resolved client is a live same-identity replacement', + async (effect) => { + const binding = createBinding(); + const replacement = createClient({ ...binding, generation: binding.generation + 1 }); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + + const pending = runBoundNamespaceCommand(binding.clusterId, binding, effect.run); + resolution.resolve(replacement.client); + await pending; + + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(replacement[effect.method]).toHaveBeenCalledOnce(); + }, +); + +it('preserves stale delete-confirmation cancellation while resolution is pending', async (): Promise => { + const binding = createBinding(); + const client = createClient(binding); + const resolution = deferred(); + vi.spyOn(ClustersClient, 'resolveBoundClient').mockReturnValue(resolution.promise); + const confirmationEpoch = ClustersClient.getEpoch(binding.clusterId); + + const pending = runBoundNamespaceCommand( + binding.clusterId, + binding, + async (resolved) => resolved.dropDatabase('database'), + confirmationEpoch, + ); + ClustersClient.invalidate(binding.clusterId); + resolution.resolve(client.client); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(ClustersClient.resolveBoundClient).toHaveBeenCalledOnce(); + expect(client.dropDatabase).not.toHaveBeenCalled(); +}); diff --git a/src/commands/saveConnectionEdit.test.ts b/src/commands/saveConnectionEdit.test.ts new file mode 100644 index 000000000..f3e65d963 --- /dev/null +++ b/src/commands/saveConnectionEdit.test.ts @@ -0,0 +1,584 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { UserCancelledError, type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; +import type * as mongoModule from 'mongodb'; +import { MongoClient, MongoServerError, type MongoClientOptions } from 'mongodb'; +import { EventEmitter } from 'node:events'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { AuthMethodId } from '../documentdb/auth/AuthMethod'; +import { ClustersClient } from '../documentdb/ClustersClient'; +import { + getBindingLifetimeSignal, + getRetiredBindingReason, + isRetiredConnectionBinding, +} from '../documentdb/connectionBindingRetirement'; +import { registerConnectionSurface } from '../documentdb/connectionSurfaces'; +import { canSaveEdit, teardownConnection } from '../documentdb/connectionTeardown'; +import { CredentialCache } from '../documentdb/CredentialCache'; +import { API } from '../DocumentDBExperiences'; +import { ext } from '../extensionVariables'; +import type * as storageModule from '../services/connectionStorageService'; +import { + ConnectionStorageService, + ConnectionType, + ItemType, + type ConnectionItem, +} from '../services/connectionStorageService'; +import { type DocumentDBClusterItem } from '../tree/connections-view/DocumentDBClusterItem'; +import { showConfirmationAsInSettings } from '../utils/dialogs/showConfirmation'; +import { refreshView } from './refreshView/refreshView'; +import { saveConnectionEdit } from './saveConnectionEdit'; +import { ExecuteStep as UpdateStringExecuteStep } from './updateConnectionString/ExecuteStep'; +import { updateConnectionString } from './updateConnectionString/updateConnectionString'; +import { type UpdateCSWizardContext } from './updateConnectionString/UpdateCSWizardContext'; +import { ExecuteStep as UpdateCredentialsExecuteStep } from './updateCredentials/ExecuteStep'; +import { updateCredentials } from './updateCredentials/updateCredentials'; +import { type UpdateCredentialsWizardContext } from './updateCredentials/UpdateCredentialsWizardContext'; + +type EditContext = UpdateCredentialsWizardContext | UpdateCSWizardContext; +const capturedContexts: EditContext[] = []; +const driverConnect = vi.fn(); +const driverClose = vi.fn(); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const { wizardPrompt, getPlaygroundEvaluators, getRegisteredShellTerminals } = vi.hoisted(() => ({ + wizardPrompt: vi.fn<(context: EditContext) => Promise>(), + getPlaygroundEvaluators: vi.fn(), + getRegisteredShellTerminals: vi.fn(), +})); +const registrations: vscode.Disposable[] = []; + +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal<{ AzureWizard: typeof AzureWizard; UserCancelledError: typeof UserCancelledError }>()), + // Match the client-suite fixture: the shared VS Code stub has no CancellationError. + parseError: (error: unknown): { message: string; errorType: string } => ({ + message: error instanceof Error ? error.message : String(error), + errorType: + typeof error === 'object' && + error !== null && + 'code' in error && + (typeof error.code === 'string' || typeof error.code === 'number') + ? String(error.code) + : error instanceof Error + ? error.constructor.name + : typeof error, + }), + AzureWizard: class { + constructor(private readonly context: EditContext) { + capturedContexts.push(context); + } + public async prompt(): Promise { + if ('originalConnectionString' in this.context) { + this.context.newConnectionString = 'mongodb://new.example.com/'; + } else { + this.context.selectedAuthenticationMethod = AuthMethodId.NativeAuth; + this.context.nativeAuthConfig = { connectionUser: 'new-user', connectionPassword: 'new-password' }; + } + await wizardPrompt(this.context); + } + public async execute(): Promise { + if ('originalConnectionString' in this.context) { + await new UpdateStringExecuteStep().execute(this.context); + } else { + await new UpdateCredentialsExecuteStep().execute(this.context); + } + } + }, + callWithTelemetryAndErrorHandling: async ( + _name: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + const context = makeContext(); + try { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow && !(error instanceof UserCancelledError)) { + throw error; + } + return undefined; + } + }, +})); +vi.mock('mongodb', async (importOriginal) => ({ + ...(await importOriginal()), + MongoClient: vi.fn(), +})); +vi.mock('../documentdb/LlmEnhancedFeatureApis', () => ({ llmEnhancedFeatureApis: vi.fn() })); +vi.mock('../documentdb/client/QueryInsightsApis', () => ({ QueryInsightsApis: vi.fn() })); +vi.mock('../documentdb/utils/getClusterMetadata', () => ({ + getClusterMetadata: vi.fn().mockResolvedValue({}), + getDomainMetadata: vi.fn().mockReturnValue({}), +})); +vi.mock('../documentdb/srv/prepareDriverConnectionString', () => ({ + prepareDriverConnectionString: async (input: { + connectionString: string; + options: MongoClientOptions; + }): Promise<{ connectionString: string; options: MongoClientOptions }> => ({ + connectionString: input.connectionString, + options: input.options, + }), +})); +vi.mock('../services/connectionStorageService', async (importOriginal) => ({ + ...(await importOriginal()), + ConnectionStorageService: { get: vi.fn(), save: vi.fn() }, +})); +vi.mock('../services/SettingsService', () => ({ + SettingsService: { getSetting: (): undefined => undefined }, +})); +vi.mock('../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: (): readonly unknown[] => [] }, +})); +vi.mock('./playground/executePlaygroundCode', () => ({ + getPlaygroundEvaluators, + stopPlaygroundEvaluator: vi.fn(), +})); +vi.mock('../documentdb/shell/ShellTerminalLinkProvider', () => ({ + getRegisteredShellTerminals, +})); +vi.mock('./refreshView/refreshView', () => ({ refreshView: vi.fn() })); +vi.mock('../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../extensionVariables', () => ({ + ext: { + connectionsBranchDataProvider: { + hasNodeErrorState: vi.fn(), + resetNodeErrorState: vi.fn(), + refresh: vi.fn(), + }, + outputChannel: { debug: vi.fn(), info: vi.fn(), trace: vi.fn(), warn: vi.fn(), error: vi.fn() }, + }, +})); + +function makeContext(): IActionContext { + return { + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + valuesToMask: [], + } as unknown as IActionContext; +} + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((finish) => { + resolve = finish; + }); + return { promise, resolve }; +} + +describe('disconnected connection edits', () => { + let clusterId: string; + let number = 0; + let node: DocumentDBClusterItem; + let stored: ConnectionItem; + + function cacheStoredCredentials(): void { + const method = + stored.properties.selectedAuthMethod === AuthMethodId.NativeAuth + ? AuthMethodId.NativeAuth + : AuthMethodId.NoAuth; + CredentialCache.setAuthCredentials( + clusterId, + method, + stored.secrets.connectionString, + stored.secrets.nativeAuthConfig, + ); + } + + beforeEach((): void => { + vi.clearAllMocks(); + clusterId = `disconnected-edit-${number++}`; + node = { + id: `folder/${clusterId}`, + storageId: clusterId, + cluster: { clusterId, storageZone: ConnectionType.Clusters, treeId: `folder/${clusterId}` }, + } as unknown as DocumentDBClusterItem; + stored = { + id: clusterId, + name: 'Saved connection', + properties: { + type: ItemType.Connection, + api: API.DocumentDB, + selectedAuthMethod: AuthMethodId.NoAuth, + availableAuthMethods: [AuthMethodId.NativeAuth, AuthMethodId.NoAuth], + }, + secrets: { connectionString: 'mongodb://old.example.com/' }, + }; + capturedContexts.length = 0; + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(false); + vi.mocked(refreshView).mockReset().mockResolvedValue(undefined); + wizardPrompt.mockReset().mockResolvedValue(undefined); + getPlaygroundEvaluators.mockReturnValue(new Map()); + getRegisteredShellTerminals.mockReturnValue([]); + cacheStoredCredentials(); + vi.mocked(ConnectionStorageService.get).mockImplementation(async () => structuredClone(stored)); + vi.mocked(ConnectionStorageService.save) + .mockReset() + .mockImplementation(async (_zone, item): Promise => { + stored = structuredClone(item); + }); + driverConnect.mockReset().mockResolvedValue(undefined); + driverClose.mockResolvedValue(undefined); + vi.mocked(MongoClient).mockImplementation(function () { + return Object.assign(new EventEmitter(), { + connect: driverConnect, + close: driverClose, + }) as unknown as MongoClient; + }); + showWarning.mockImplementation( + async (_message, _options, ...items) => items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); + }); + + afterEach(async (): Promise => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } + await ClustersClient.deleteClient(clusterId); + CredentialCache.deleteCredentials(clusterId); + ClustersClient.clearLastVerifiedIdentity(clusterId); + ClustersClient.unlatch(clusterId); + }); + + it('retires an evicted binding before a password-only edit reaches storage', async (): Promise => { + stored.properties.selectedAuthMethod = AuthMethodId.NativeAuth; + stored.secrets.nativeAuthConfig = { + connectionUser: 'old-user', + connectionPassword: 'old-password', + }; + cacheStoredCredentials(); + const original = await ClustersClient.getClient(clusterId); + + expect(ClustersClient.reportFailure(original.binding, new MongoServerError({ code: 18 }))).toBe( + 'credentialsRejected', + ); + expect(ClustersClient.exists(clusterId)).toBe(false); + expect(isRetiredConnectionBinding(original.binding)).toBe(false); + + const changed = await saveConnectionEdit(node, async (): Promise => { + expect(isRetiredConnectionBinding(original.binding)).toBe(true); + stored.secrets.nativeAuthConfig = { + connectionUser: 'old-user', + connectionPassword: 'new-password', + }; + await ConnectionStorageService.save(ConnectionType.Clusters, structuredClone(stored), true); + return true; + }); + + expect(changed).toBe(true); + expect(getRetiredBindingReason(original.binding)).toBe('credentialsChanged'); + }); + + it('preserves an explicit Disconnect retirement when the edit boundary is reached', async (): Promise => { + const original = await ClustersClient.getClient(clusterId); + await teardownConnection(clusterId, 'userDisconnected', vi.fn()); + + await saveConnectionEdit(node, async (): Promise => false); + + expect(getRetiredBindingReason(original.binding)).toBe('userDisconnected'); + }); + + it.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)( + 'excludes real client startup between both %s writes, including a metadata failure', + async (_commandName, update): Promise => { + const original = await ClustersClient.getClient(clusterId); + expect(original.binding.clusterId).toBe(clusterId); + expect(driverConnect).toHaveBeenCalledOnce(); + const secretWritten = deferred(); + const finishMetadata = deferred(); + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored.secrets = structuredClone(item.secrets); + secretWritten.resolve(); + await finishMetadata.promise; + throw new Error('Metadata write failed'); + }); + + const updating = update(makeContext(), node); + await secretWritten.promise; + expect(driverClose).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsUpdating'); + expect(ClustersClient.exists(clusterId)).toBe(false); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'credentialsUpdating' }); + await expect(ClustersClient.connectInteractive(clusterId)).rejects.toMatchObject({ + reason: 'credentialsUpdating', + }); + expect(driverConnect).toHaveBeenCalledOnce(); + finishMetadata.resolve(); + await updating; + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + const edited = capturedContexts[0]; + if ('originalConnectionString' in edited) { + expect(edited.connectionStringSaved).toBe(false); + } else { + expect(edited.credentialsSaved).not.toBe(true); + } + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); + expect(driverConnect).toHaveBeenCalledOnce(); + }, + ); + + it.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)( + 'allows a fresh client using the fully saved %s after explicit reconnect', + async (_name, update): Promise => { + const original = await ClustersClient.getClient(clusterId); + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored = structuredClone(item); + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + expect(driverConnect).toHaveBeenCalledOnce(); + cacheStoredCredentials(); + ClustersClient.unlatch(clusterId); + const current = await ClustersClient.getClient(clusterId); + expect(current).not.toBe(original); + expect(current.generation).toBeGreaterThan(original.generation); + expect(driverConnect).toHaveBeenCalledTimes(2); + expect(driverClose).toHaveBeenCalledOnce(); + }, + ); + + it('does not start saving after its wizard epoch was superseded', async (): Promise => { + const save = vi.fn<() => Promise>(); + const epoch = ClustersClient.getEpoch(clusterId); + ClustersClient.invalidate(clusterId); + + await expect( + saveConnectionEdit(node, save, { canStart: (): boolean => canSaveEdit(clusterId, epoch) }), + ).rejects.toBeInstanceOf(UserCancelledError); + + expect(ConnectionStorageService.get).not.toHaveBeenCalled(); + expect(save).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + }); + + it('does not save or restore a hold superseded during the storage read', async (): Promise => { + const readStarted = deferred(); + const finishRead = deferred(); + ClustersClient.latch(clusterId, 'userDisconnected'); + vi.mocked(ConnectionStorageService.get).mockImplementationOnce(async () => { + readStarted.resolve(); + await finishRead.promise; + return structuredClone(stored); + }); + const save = vi.fn<() => Promise>(); + const saving = saveConnectionEdit(node, save); + await readStarted.promise; + ClustersClient.latch(clusterId, 'connectionRemoved'); + finishRead.resolve(); + + await expect(saving).rejects.toBeInstanceOf(UserCancelledError); + + expect(save).not.toHaveBeenCalled(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('connectionRemoved'); + }); + + it('reconnects after Yes with a fresh session while the kept old tab remains read-only', async (): Promise => { + const original = await ClustersClient.getClient(clusterId); + const lifetime = getBindingLifetimeSignal(original.binding); + const draft = { + clusterId, + kind: 'documentView' as const, + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + registrations.push(registerConnectionSurface(draft)); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + wizardPrompt.mockImplementationOnce(async (context): Promise => { + if ('isErrorState' in context) { + context.reconnectAfterError = true; + } + }); + let connected: ClustersClient | undefined; + vi.mocked(refreshView).mockImplementationOnce(async (): Promise => { + connected = await ClustersClient.getClient(clusterId); + }); + const unlatch = vi.spyOn(ClustersClient, 'unlatch'); + try { + await updateCredentials(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(unlatch).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(unlatch).toHaveBeenCalledBefore(vi.mocked(ext.connectionsBranchDataProvider.resetNodeErrorState)); + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).toHaveBeenCalledBefore( + vi.mocked(refreshView), + ); + expect(connected).toBeDefined(); + expect(connected).not.toBe(original); + expect(connected?.generation).toBeGreaterThan(original.generation); + expect(driverConnect).toHaveBeenCalledTimes(2); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(draft.isDirty()).toBe(true); + expect(lifetime.aborted).toBe(true); + await expect(ClustersClient.resolveBoundClient(original.binding)).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + if (!connected) { + throw new Error('Expected refresh to open a fresh connection.'); + } + await expect(ClustersClient.resolveBoundClient(connected.binding)).resolves.toBe(connected); + expect(driverConnect).toHaveBeenCalledTimes(2); + } finally { + unlatch.mockRestore(); + } + }); + + it.each(['No', 'failed save', 'connectionRemoved'] as const)( + 'does not unlatch or start another session after %s', + async (outcome): Promise => { + await ClustersClient.getClient(clusterId); + vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); + wizardPrompt.mockImplementationOnce(async (context): Promise => { + if ('isErrorState' in context) { + context.reconnectAfterError = outcome !== 'No'; + } + }); + if (outcome === 'failed save') { + vi.mocked(ConnectionStorageService.save).mockRejectedValueOnce(new Error('Save failed')); + } else if (outcome === 'connectionRemoved') { + vi.mocked(ConnectionStorageService.save).mockImplementationOnce(async (_zone, item): Promise => { + stored = structuredClone(item); + ClustersClient.latch(clusterId, 'connectionRemoved'); + }); + } + const unlatch = vi.spyOn(ClustersClient, 'unlatch'); + try { + await updateCredentials(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(unlatch).not.toHaveBeenCalled(); + const reason = outcome === 'connectionRemoved' ? 'connectionRemoved' : 'userDisconnected'; + expect(ClustersClient.getLatchReason(clusterId)).toBe(reason); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason }); + expect(driverConnect).toHaveBeenCalledOnce(); + if (outcome !== 'connectionRemoved') { + expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); + } + } finally { + unlatch.mockRestore(); + } + }, + ); + + describe.each([ + ['credentials', updateCredentials], + ['connection string', updateConnectionString], + ] as const)('%s idle-wizard exclusion', (_name, update): void => { + it.each(['client', 'pending startup', 'surface', 'shell', 'evaluator'] as const)( + 'does not save when a %s appears during the wizard without changing the epoch', + async (work): Promise => { + const epoch = ClustersClient.getEpoch(clusterId); + const original = structuredClone(stored); + const started = deferred(); + const finishStartup = deferred(); + let startup: Promise | undefined; + const disconnect = vi.fn(); + const surface = { + clusterId, + kind: 'documentView' as const, + disable: vi.fn(), + dispose: vi.fn(), + }; + wizardPrompt.mockImplementationOnce(async (): Promise => { + if (work === 'client') { + await ClustersClient.getClient(clusterId); + } else if (work === 'pending startup') { + driverConnect.mockImplementationOnce(async (): Promise => { + started.resolve(); + await finishStartup.promise; + }); + startup = ClustersClient.getClient(clusterId); + await started.promise; + } else if (work === 'surface') { + registrations.push(registerConnectionSurface(surface)); + } else if (work === 'shell') { + getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + } else { + getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + } + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(stored).toEqual(original); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); + expect(driverConnect).toHaveBeenCalledTimes(work === 'client' || work === 'pending startup' ? 1 : 0); + expect(driverClose).not.toHaveBeenCalled(); + expect(disconnect).not.toHaveBeenCalled(); + expect(surface.disable).not.toHaveBeenCalled(); + expect(surface.dispose).not.toHaveBeenCalled(); + finishStartup.resolve(); + if (startup) { + await startup; + expect(ClustersClient.exists(clusterId)).toBe(true); + } + }, + ); + + it('saves a user-disconnected connection with a still-registered old shell', async (): Promise => { + ClustersClient.latch(clusterId, 'userDisconnected'); + const disconnect = vi.fn(); + getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('userDisconnected'); + expect(disconnect).not.toHaveBeenCalled(); + expect(driverConnect).not.toHaveBeenCalled(); + expect(driverClose).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + + it('allows saving when a startup attempted during the wizard has failed and disappeared', async (): Promise => { + const epoch = ClustersClient.getEpoch(clusterId); + wizardPrompt.mockImplementationOnce(async (): Promise => { + driverConnect.mockRejectedValueOnce(new Error('Startup failed')); + await expect(ClustersClient.getClient(clusterId)).rejects.toThrow('Startup failed'); + expect(ClustersClient.hasPendingStartup(clusterId)).toBe(false); + expect(ClustersClient.exists(clusterId)).toBe(false); + expect(ClustersClient.getEpoch(clusterId)).toBe(epoch); + }); + + await update(makeContext(), node); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + expect(showConfirmationAsInSettings).toHaveBeenCalledOnce(); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/src/commands/saveConnectionEdit.ts b/src/commands/saveConnectionEdit.ts index 4cd90a3c1..0a81abaca 100644 --- a/src/commands/saveConnectionEdit.ts +++ b/src/commands/saveConnectionEdit.ts @@ -8,16 +8,13 @@ import { isDeepStrictEqual } from 'node:util'; import * as vscode from 'vscode'; import { clearEntraTokenFailure } from '../documentdb/auth/entraErrors/entraTokenFailures'; import { ClustersClient } from '../documentdb/ClustersClient'; -import { getConnectionSurfaces } from '../documentdb/connectionSurfaces'; -import { confirmTeardown, latchForTeardown } from '../documentdb/connectionTeardown'; +import { latchForTeardown } from '../documentdb/connectionTeardown'; import { CredentialCache } from '../documentdb/CredentialCache'; -import { getRegisteredShellTerminals } from '../documentdb/shell/ShellTerminalLinkProvider'; import { ext } from '../extensionVariables'; import { ConnectionStorageService, isConnection, type StoredItem } from '../services/connectionStorageService'; import { checkCanProceedAndInformUser } from '../services/taskService/resourceUsageHelper'; import { type DocumentDBClusterItem } from '../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../tree/connections-view/models/ConnectionClusterModel'; -import { stopPlaygroundEvaluator } from './playground/executePlaygroundCode'; function storedSettings(item: StoredItem | undefined): object | undefined { if (!item || !isConnection(item)) { @@ -31,8 +28,8 @@ function storedSettings(item: StoredItem | undefined): object | undefined { } /** - * Hold the existing latch across storage writes, then use what actually persisted to decide - * whether to retire views. Secret storage and metadata are not written atomically. + * Exclude startup across both storage writes and verify what actually persisted. + * The old session has already ended; secret storage and metadata are not written atomically. */ export async function saveConnectionEdit( node: DocumentDBClusterItem, @@ -44,10 +41,6 @@ export async function saveConnectionEdit( ): Promise { const { clusterId } = node.cluster; const zone = resolveStorageZone(node.cluster); - if ((await confirmTeardown(clusterId, 'credentialsChanged')).outcome !== 'confirmed') { - throw new UserCancelledError(); - } - if (options?.canStart?.() === false) { throw new UserCancelledError(); } @@ -60,6 +53,7 @@ export async function saveConnectionEdit( throw new UserCancelledError(); } + ClustersClient.retireBoundViews(clusterId, 'credentialsChanged'); const epoch = ClustersClient.getEpoch(clusterId); const isCurrent = (): boolean => ClustersClient.getEpoch(clusterId) === epoch; let changed = false; @@ -85,12 +79,6 @@ export async function saveConnectionEdit( } if (isCurrent() && !isDeepStrictEqual(originalSettings, storedSettings(after))) { changed = true; - ClustersClient.retireBoundViews(clusterId); - for (const surface of getConnectionSurfaces(clusterId)) { - surface.disable('credentialsChanged'); - } - stopPlaygroundEvaluator(clusterId); - const closing = ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); CredentialCache.deleteCredentials(clusterId); clearEntraTokenFailure(clusterId); if ( @@ -114,7 +102,6 @@ export async function saveConnectionEdit( ), ); } - await closing; if (isCurrent()) { options?.publishCredentials?.(after); } @@ -132,21 +119,3 @@ export async function saveConnectionEdit( } return changed; } - -export async function offerShellDisconnect(node: DocumentDBClusterItem): Promise { - const shells = getRegisteredShellTerminals().filter(({ info }) => info.clusterId === node.cluster.clusterId); - if (!shells.length) { - return; - } - const disconnect = vscode.l10n.t('Disconnect'); - const selected = await vscode.window.showInformationMessage( - vscode.l10n.t('Open shells are still using the previous connection settings.'), - { modal: true }, - disconnect, - ); - if (selected === disconnect) { - for (const shell of shells) { - shell.disconnect?.(); - } - } -} diff --git a/src/commands/signInAgain/signInAgain.test.ts b/src/commands/signInAgain/signInAgain.test.ts index d5c465bcd..d75989a1f 100644 --- a/src/commands/signInAgain/signInAgain.test.ts +++ b/src/commands/signInAgain/signInAgain.test.ts @@ -95,11 +95,10 @@ describe('signInAgain', () => { ); }); - it.each([ - { id: pin.accountId, label: pin.accountLabel }, - { id: 'different-account', label: 'Explicitly selected in VS Code' }, - ])('requests one pinned forced session and forwards the accepted account', async (account): Promise => { - vi.mocked(getEntraSession).mockResolvedValueOnce({ account } as vscode.AuthenticationSession); + it('requests one pinned forced session and forwards the repaired account', async (): Promise => { + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: pin.accountId, label: pin.accountLabel }, + } as vscode.AuthenticationSession); vi.mocked(ClustersClient.startAfterSignIn).mockResolvedValueOnce({} as ClustersClient); await signInAgain(actionContext(), { clusterId }); @@ -116,10 +115,40 @@ describe('signInAgain', () => { clusterId, 1, CredentialCache.getCredentials(clusterId), - { verifiedIdentity: expect.objectContaining({ accountId: account.id }) }, + { verifiedIdentity: pin }, ); }); + it.each([pin.accountLabel, 'Explicitly selected in VS Code'])( + 'rejects a different account with label %s without changing the repair pin or hold', + async (label): Promise => { + const credentials = CredentialCache.getCredentials(clusterId); + vi.mocked(getEntraSession).mockResolvedValueOnce({ + account: { id: 'different-account', label }, + } as vscode.AuthenticationSession); + + await expect(signInAgain(actionContext(), { clusterId })).rejects.toBeInstanceOf( + EntraIdentityMismatchError, + ); + + expect(getEntraSession).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + mode: 'forceNew', + tenantId: pin.tenantId, + providerId: pin.providerId, + account: { id: pin.accountId, label: pin.accountLabel }, + }), + ); + expect(ClustersClient.startAfterSignIn).not.toHaveBeenCalled(); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + expect(showClusterConnectFailure).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ error: expect.any(EntraIdentityMismatchError) }), + ); + }, + ); + it('observes renewal only for the client established by this sign-in', async (): Promise => { vi.mocked(getEntraSession).mockResolvedValueOnce({ account: { id: pin.accountId, label: pin.accountLabel }, diff --git a/src/commands/signInAgain/signInAgain.ts b/src/commands/signInAgain/signInAgain.ts index db777d794..f7be417d2 100644 --- a/src/commands/signInAgain/signInAgain.ts +++ b/src/commands/signInAgain/signInAgain.ts @@ -184,17 +184,7 @@ async function signInAgainInternal( throw new UserCancelledError('signInAgain'); } if (session.account.id !== identity.accountId) { - if (expectedIdentity) { - throw new EntraIdentityMismatchError(); - } - // VS Code only confirms account changes when the account *label* is different. - // A same-label/different-ID session is not an explicit user choice. - if ( - session.account.label === identity.accountLabel || - (identity.providerId !== 'microsoft' && identity.providerId !== 'microsoft-sovereign-cloud') - ) { - throw new EntraIdentityMismatchError(); - } + throw new EntraIdentityMismatchError(); } return session; }); diff --git a/src/commands/updateConnectionString/updateConnectionString.test.ts b/src/commands/updateConnectionString/updateConnectionString.test.ts index 4b6703005..535c168ae 100644 --- a/src/commands/updateConnectionString/updateConnectionString.test.ts +++ b/src/commands/updateConnectionString/updateConnectionString.test.ts @@ -9,13 +9,14 @@ import { type IActionContext, type callWithTelemetryAndErrorHandling, } from '@microsoft/vscode-azext-utils'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { API, DocumentDBExperience } from '../../DocumentDBExperiences'; import { ClustersClient } from '../../documentdb/ClustersClient'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { EntraDestinationRejectedError } from '../../documentdb/auth/oidcAllowedHosts'; +import { registerConnectionSurface } from '../../documentdb/connectionSurfaces'; import { type AuthenticateWizardContext } from '../../documentdb/wizards/authenticate/AuthenticateWizardContext'; import { ChooseAuthMethodStep } from '../../documentdb/wizards/authenticate/ChooseAuthMethodStep'; import { ext } from '../../extensionVariables'; @@ -36,10 +37,22 @@ import { ExecuteStep } from './ExecuteStep'; import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; import { updateConnectionString } from './updateConnectionString'; -const { capturedContexts, showInputBox, showQuickPick } = vi.hoisted(() => ({ +const { + capturedContexts, + showInputBox, + showQuickPick, + getConflictingTasks, + getPlaygroundEvaluators, + getRegisteredShellTerminals, + stopPlaygroundEvaluator, +} = vi.hoisted(() => ({ capturedContexts: [] as UpdateCSWizardContext[], showInputBox: vi.fn(), showQuickPick: vi.fn(), + getConflictingTasks: vi.fn(), + getPlaygroundEvaluators: vi.fn(), + getRegisteredShellTerminals: vi.fn(), + stopPlaygroundEvaluator: vi.fn(), })); vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ @@ -73,9 +86,13 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ _name: string, callback: (context: IActionContext) => Promise, ): Promise => { + const context = makeContext(); try { - return await callback(makeContext()); - } catch { + return await callback(context); + } catch (error) { + if (context.errorHandling.rethrow && !(error instanceof UserCancelledError)) { + throw error; + } return undefined; } }, @@ -90,6 +107,7 @@ vi.mock('../../documentdb/ClustersClient', () => ({ connectInteractive: vi.fn(), deleteClient: vi.fn(), exists: vi.fn(), + hasPendingStartup: vi.fn(), getEpoch: vi.fn(() => 0), getLatchReason: vi.fn(), getExistingClient: vi.fn(), @@ -107,6 +125,9 @@ vi.mock('../../services/SettingsService', () => ({ SettingsService: { getSetting: vi.fn(() => false) }, })); vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../../services/taskService/taskService', () => ({ TaskService: { getConflictingTasks } })); +vi.mock('../playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators, stopPlaygroundEvaluator })); +vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals })); vi.mock('../../extensionVariables', () => ({ ext: { outputChannel: { appendLine: vi.fn(), append: vi.fn(), debug: vi.fn(), info: vi.fn(), error: vi.fn() }, @@ -119,6 +140,13 @@ vi.mock('../../tree/connections-view/LocalQuickStart/LocalQuickStartItem', () => const originalUri = 'mongodb://old.example.com/'; const approvedUri = 'mongodb://new.mongocluster.cosmos.azure.com/'; const deleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const registrations: vscode.Disposable[] = []; function makeContext(): IActionContext { return { @@ -158,10 +186,35 @@ describe('updateConnectionString rejected-destination recovery', () => { let provider: ConnectionsBranchDataProvider; let storedConnection: ConnectionItem; let item: DocumentDBClusterItem; + let epoch: number; + let latch: ReturnType; beforeEach((): void => { CredentialCache.deleteCredentials('stable-id'); vi.resetAllMocks(); + epoch = 0; + latch = undefined; + vi.mocked(ClustersClient.getEpoch).mockImplementation(() => epoch); + vi.mocked(ClustersClient.getLatchReason).mockImplementation(() => latch); + vi.mocked(ClustersClient.latch).mockImplementation((_id, reason): void => { + latch = reason; + epoch++; + }); + vi.mocked(ClustersClient.unlatch).mockImplementation((): void => { + latch = undefined; + epoch++; + }); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); + getConflictingTasks.mockReturnValue([]); + getPlaygroundEvaluators.mockReturnValue(new Map()); + getRegisteredShellTerminals.mockReturnValue([]); + showWarning.mockImplementation( + async (_message, _options, ...items) => items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); capturedContexts.length = 0; provider = new ConnectionsBranchDataProvider(); ext.connectionsBranchDataProvider = provider; @@ -184,6 +237,12 @@ describe('updateConnectionString rejected-destination recovery', () => { ); }); + afterEach((): void => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } + }); + it.each([ [approvedUri, AuthMethodId.ManagedIdentity], ['mongodb://new.example.com/', AuthMethodId.NoAuth], @@ -193,11 +252,12 @@ describe('updateConnectionString rejected-destination recovery', () => { const failedChildren = await provider.getChildren(item); expect(provider.hasNodeErrorState(item.id)).toBe(true); expect(item.lastConnectionFailureReason).toBe('entraDestinationRejected'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(true); const resetError = vi.spyOn(provider, 'resetNodeErrorState'); const refresh = vi.spyOn(provider, 'refresh'); showInputBox.mockResolvedValue(newUri); vi.mocked(ClustersClient.deleteClient).mockImplementation(async (): Promise => { - expect(storedConnection.secrets.connectionString).toBe(newUri); + expect(storedConnection.secrets.connectionString).toBe(originalUri); expect(provider.hasNodeErrorState(item.id)).toBe(true); expect(CredentialCache.hasCredentials('stable-id')).toBe(true); }); @@ -214,11 +274,12 @@ describe('updateConnectionString rejected-destination recovery', () => { expect(CredentialCache.hasCredentials('stable-id')).toBe(false); expect(item.lastConnectionFailureReason).toBeUndefined(); expect(item.lastConnectionOutcome).toBeUndefined(); - expect(vi.mocked(ConnectionStorageService.save).mock.invocationCallOrder[0]).toBeLessThan( - vi.mocked(ClustersClient.deleteClient).mock.invocationCallOrder[0], - ); + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(showInputBox); + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(vi.mocked(ConnectionStorageService.save)); expect(deleteCredentials.mock.invocationCallOrder[0]).toBeLessThan(resetError.mock.invocationCallOrder[0]); - expect(resetError.mock.invocationCallOrder[0]).toBeLessThan(refresh.mock.invocationCallOrder[0]); + expect(resetError.mock.invocationCallOrder[0]).toBeLessThan( + refresh.mock.invocationCallOrder[refresh.mock.invocationCallOrder.length - 1], + ); const client = { listDatabases: vi.fn().mockResolvedValue([]), connectionCorrelationId: 'retry' }; vi.mocked(ClustersClient.connectInteractive).mockImplementation( async (clusterId): Promise => { @@ -231,6 +292,7 @@ describe('updateConnectionString rejected-destination recovery', () => { }, ); + ClustersClient.unlatch('stable-id'); const retriedChildren = await provider.getChildren(item); expect(retriedChildren).not.toEqual(failedChildren); @@ -280,38 +342,142 @@ describe('updateConnectionString rejected-destination recovery', () => { }, ); - it('retires the old client and bindings after an ordinary saved edit', async (): Promise => { + it('ends the old session before an ordinary saved edit', async (): Promise => { const resetError = vi.spyOn(provider, 'resetNodeErrorState'); const refresh = vi.spyOn(provider, 'refresh'); item.lastConnectionOutcome = 'connected'; + vi.mocked(ClustersClient.exists).mockReturnValue(true); await updateConnectionString(makeContext(), item); expect(capturedContexts[0].connectionStringSaved).toBe(true); expect(storedConnection.secrets.connectionString).toBe(approvedUri); - expect(ClustersClient.retireBoundViews).toHaveBeenCalledExactlyOnceWith('stable-id'); + expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(1, 'stable-id', 'userDisconnected'); + expect(ClustersClient.retireBoundViews).toHaveBeenNthCalledWith(2, 'stable-id', 'credentialsChanged'); expect(ClustersClient.deleteClient).toHaveBeenCalledExactlyOnceWith('stable-id', { alreadyInvalidated: true }); expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); expect(resetError).not.toHaveBeenCalled(); expect(CredentialCache.getCredentials('stable-id')).toBeUndefined(); expect(item.lastConnectionOutcome).toBe('connected'); - expect(refresh).toHaveBeenCalledOnce(); + expect(refresh).toHaveBeenCalledTimes(2); + expect(latch).toBe('userDisconnected'); }); - it('saves an ordinary edit when the epoch changes while the input is open', async (): Promise => { + it('does not save an ordinary edit superseded while the input is open', async (): Promise => { const refresh = vi.spyOn(provider, 'refresh'); item.lastConnectionOutcome = 'connected'; showInputBox.mockImplementationOnce(async (): Promise => { - vi.mocked(ClustersClient.getEpoch).mockReturnValue(1); + epoch++; return approvedUri; }); await updateConnectionString(makeContext(), item); - expect(storedConnection.secrets.connectionString).toBe(approvedUri); - expect(capturedContexts[0].connectionStringSaved).toBe(true); - expect(ClustersClient.retireBoundViews).toHaveBeenCalledExactlyOnceWith('stable-id'); - expect(deleteCredentials).toHaveBeenCalledExactlyOnceWith('stable-id'); - expect(refresh).toHaveBeenCalledOnce(); + expect(storedConnection.secrets.connectionString).toBe(originalUri); + expect(capturedContexts[0].connectionStringSaved).toBe(false); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(deleteCredentials).not.toHaveBeenCalled(); + expect(refresh).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); }); + + it.each(['cancel offer', 'cancel tabs', 'active transfer', 'dirty close refusal', 'close failure'] as const)( + 'does not begin the wizard or save after %s', + async (outcome): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + const draft = { + clusterId: 'stable-id', + kind: 'documentView' as const, + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + registrations.push(registerConnectionSurface(draft)); + const task = { taskName: 'Copy orders', taskType: 'copy', cancel: vi.fn() }; + if (outcome === 'active transfer') { + getConflictingTasks.mockReturnValue([task]); + } else if (outcome === 'cancel offer') { + showWarning.mockResolvedValueOnce(undefined); + } else if (outcome === 'cancel tabs') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else if (outcome === 'dirty close refusal') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else { + vi.mocked(ClustersClient.deleteClient).mockRejectedValueOnce( + new Error('private driver connection details'), + ); + } + + const pending = updateConnectionString(makeContext(), item); + if (outcome === 'close failure') { + await expect(pending).rejects.toThrow('Could not finish closing the connection.'); + expect(latch).toBe('userDisconnected'); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(draft.disable).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(stopPlaygroundEvaluator).not.toHaveBeenCalled(); + } + expect(showInputBox).not.toHaveBeenCalled(); + expect(ConnectionStorageService.get).not.toHaveBeenCalled(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(task.cancel).not.toHaveBeenCalled(); + }, + ); + + it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + showInputBox.mockRejectedValueOnce(new UserCancelledError()); + + await expect(updateConnectionString(makeContext(), item)).rejects.toBeInstanceOf(UserCancelledError); + + expect(latch).toBe('userDisconnected'); + expect(ClustersClient.deleteClient).toHaveBeenCalledOnce(); + expect(ConnectionStorageService.save).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }); + + it.each(['idle', 'userDisconnected', 'held client', 'evicted surface', 'pending startup'] as const)( + 'edits %s without overlooking surviving connection work', + async (state): Promise => { + latch = state === 'userDisconnected' ? 'userDisconnected' : 'credentialsRejected'; + vi.mocked(ClustersClient.exists).mockReturnValue(state === 'held client'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(state === 'pending startup'); + const draft = { + clusterId: 'stable-id', + kind: 'documentView' as const, + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + if (state === 'evicted surface') { + registrations.push(registerConnectionSurface(draft)); + } + + await updateConnectionString(makeContext(), item); + + expect(ConnectionStorageService.save).toHaveBeenCalledOnce(); + if (state === 'idle' || state === 'userDisconnected') { + expect(ClustersClient.deleteClient).not.toHaveBeenCalled(); + expect(stopPlaygroundEvaluator).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + } else { + expect(ClustersClient.deleteClient).toHaveBeenCalledBefore(showInputBox); + expect(stopPlaygroundEvaluator).toHaveBeenCalledBefore(showInputBox); + expect(latch).toBe('userDisconnected'); + } + if (state === 'evicted surface') { + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.dispose).not.toHaveBeenCalled(); + } + }, + ); }); diff --git a/src/commands/updateConnectionString/updateConnectionString.ts b/src/commands/updateConnectionString/updateConnectionString.ts index 27229623a..2734435d8 100644 --- a/src/commands/updateConnectionString/updateConnectionString.ts +++ b/src/commands/updateConnectionString/updateConnectionString.ts @@ -5,7 +5,9 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; +import { window } from 'vscode'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { canSaveEdit, ensureDisconnectedForEdit } from '../../documentdb/connectionTeardown'; import { maskSensitiveValuesInTelemetry } from '../../documentdb/utils/connectionStringHelpers'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; @@ -14,7 +16,7 @@ import { ConnectionStorageService } from '../../services/connectionStorageServic import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; import { refreshView } from '../refreshView/refreshView'; -import { offerShellDisconnect, saveConnectionEdit } from '../saveConnectionEdit'; +import { saveConnectionEdit } from '../saveConnectionEdit'; import { ConnectionStringStep } from './ConnectionStringStep'; import { ExecuteStep } from './ExecuteStep'; import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; @@ -23,13 +25,13 @@ import { type UpdateCSWizardContext } from './UpdateCSWizardContext'; * Updates the connection string (hosts, ports, etc.) for a cluster connection. * * Architecture: - * 1. Loads the current connection string with credentials masked + * 1. Ends the old session, then loads the current connection string with credentials masked * 2. Runs wizard to collect new connection string: * - ConnectionStringStep: Enter new connection string * 3. ExecuteStep: Saves updated connection string to storage * 4. Post-wizard: Refreshes the view * - * A changed value retires views tied to the previous settings. + * Tabs kept during Disconnect remain read-only, even if the edit is cancelled. */ export async function updateConnectionString(context: IActionContext, node: DocumentDBClusterItem): Promise { if (!node) { @@ -37,8 +39,8 @@ export async function updateConnectionString(context: IActionContext, node: Docu } const recoveringRejectedDestination = node.lastConnectionFailureReason === 'entraDestinationRejected'; const clusterId = node.cluster.clusterId; - const epoch = ClustersClient.getEpoch(clusterId); const recoveringRejectedCredentials = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const epoch = await ensureDisconnectedForEdit(clusterId, () => ext.connectionsBranchDataProvider.refresh()); const recovering = recoveringRejectedDestination || recoveringRejectedCredentials; const isRecoveryCurrent = recovering ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; @@ -50,7 +52,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu const resourceType = resolveStorageZone(node.cluster); const connection = await ConnectionStorageService.get(node.storageId, resourceType); - if (isRecoveryCurrent?.() === false) { + if (ClustersClient.getEpoch(clusterId) !== epoch) { return; } const connectionString = connection?.secrets?.connectionString || ''; @@ -80,7 +82,8 @@ export async function updateConnectionString(context: IActionContext, node: Docu }); await wizard.prompt(); - if (isRecoveryCurrent?.() === false) { + if (!canSaveEdit(clusterId, epoch)) { + void window.showErrorMessage(l10n.t('This connection changed. Refresh the tree and try again.')); return; } const changed = @@ -93,7 +96,7 @@ export async function updateConnectionString(context: IActionContext, node: Docu await wizard.execute(); return wizardContext.connectionStringSaved === true; }, - { canStart: isRecoveryCurrent }, + { canStart: () => canSaveEdit(clusterId, epoch) }, ) : false; if (recovering && changed && wizardContext.connectionStringSaved) { @@ -103,7 +106,4 @@ export async function updateConnectionString(context: IActionContext, node: Docu } await refreshView(context, Views.ConnectionsView); - if (changed) { - await offerShellDisconnect(node); - } } diff --git a/src/commands/updateCredentials/updateCredentials.test.ts b/src/commands/updateCredentials/updateCredentials.test.ts index 0e9d59238..87e5701b8 100644 --- a/src/commands/updateCredentials/updateCredentials.test.ts +++ b/src/commands/updateCredentials/updateCredentials.test.ts @@ -3,11 +3,12 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; -import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { UserCancelledError, type AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; import { AuthMethodId } from '../../documentdb/auth/AuthMethod'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { registerConnectionSurface, type ConnectionSurface } from '../../documentdb/connectionSurfaces'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { SelectEntraTokenSourceStep } from '../../documentdb/wizards/authenticate/SelectEntraTokenSourceStep'; import { API } from '../../DocumentDBExperiences'; @@ -15,12 +16,14 @@ import { ext } from '../../extensionVariables'; import type * as storageModule from '../../services/connectionStorageService'; import { ItemType } from '../../services/connectionStorageService'; import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; +import { showConfirmationAsInSettings } from '../../utils/dialogs/showConfirmation'; import { ExecuteStep } from './ExecuteStep'; import { updateCredentials } from './updateCredentials'; import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardContext'; const capturedContexts: UpdateCredentialsWizardContext[] = []; const mockExecute = vi.fn<(context: UpdateCredentialsWizardContext) => Promise>().mockResolvedValue(undefined); +const mockPrompt = vi.fn<() => Promise>(); const mockGet = vi.fn(); const mockSave = vi.fn(); const mockGetEpoch = vi.fn(() => 0); @@ -29,6 +32,17 @@ const mockRetireBoundViews = vi.hoisted(() => vi.fn()); const mockDeleteCredentials = vi.spyOn(CredentialCache, 'deleteCredentials'); const mockShutdownEvaluator = vi.fn(); const mockGetRegisteredShellTerminals = vi.fn(); +const mockGetPlaygroundEvaluators = vi.fn(); +const mockGetConflictingTasks = vi.fn(); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); +const registrations: vscode.Disposable[] = []; +let epoch = 0; +let latch: ReturnType; vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ ...(await importOriginal<{ AzureWizard: typeof AzureWizard }>()), @@ -37,12 +51,27 @@ vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ capturedContexts.push(context); } public prompt(): Promise { - return Promise.resolve(); + return mockPrompt(); } public execute(): Promise { return mockExecute(this.context); } }, + callWithTelemetryAndErrorHandling: async ( + _name: string, + callback: (context: IActionContext) => Promise, + ): Promise => { + try { + await callback({ + telemetry: { properties: {}, measurements: {} }, + errorHandling: {}, + } as unknown as IActionContext); + } catch (error) { + if (!(error instanceof UserCancelledError)) { + throw error; + } + } + }, })); vi.mock('../../services/connectionStorageService', async (importOriginal) => ({ @@ -58,6 +87,8 @@ vi.mock('../../documentdb/ClustersClient', () => ({ getLastFailedStartupCorrelationId: (): undefined => undefined, getEpoch: (): number => mockGetEpoch(), getLatchReason: vi.fn(), + exists: vi.fn(), + hasPendingStartup: vi.fn(), latch: vi.fn(), unlatch: vi.fn(), retireBoundViews: mockRetireBoundViews, @@ -67,15 +98,20 @@ vi.mock('../../documentdb/ClustersClient', () => ({ })); vi.mock('../playground/executePlaygroundCode', () => ({ stopPlaygroundEvaluator: (...args: unknown[]): unknown => mockShutdownEvaluator(...args), + getPlaygroundEvaluators: (): unknown => mockGetPlaygroundEvaluators(), })); vi.mock('../../documentdb/shell/ShellTerminalLinkProvider', () => ({ getRegisteredShellTerminals: (): unknown => mockGetRegisteredShellTerminals(), })); vi.mock('../refreshView/refreshView', () => ({ refreshView: vi.fn() })); vi.mock('../../utils/dialogs/showConfirmation', () => ({ showConfirmationAsInSettings: vi.fn() })); +vi.mock('../../services/SettingsService', () => ({ SettingsService: { getSetting: (): undefined => undefined } })); +vi.mock('../../services/taskService/taskService', () => ({ + TaskService: { getConflictingTasks: (...args: unknown[]): unknown => mockGetConflictingTasks(...args) }, +})); vi.mock('../../extensionVariables', () => ({ ext: { - connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(), resetNodeErrorState: vi.fn() }, + connectionsBranchDataProvider: { hasNodeErrorState: vi.fn(), resetNodeErrorState: vi.fn(), refresh: vi.fn() }, outputChannel: { error: vi.fn(), warn: vi.fn() }, }, })); @@ -83,13 +119,42 @@ vi.mock('../../extensionVariables', () => ({ beforeEach(() => { CredentialCache.deleteCredentials('stable-cluster-id'); vi.clearAllMocks(); - mockGetEpoch.mockReturnValue(0); - vi.mocked(ClustersClient.getLatchReason).mockReturnValue(undefined); + epoch = 0; + latch = undefined; + mockGetEpoch.mockImplementation((): number => epoch); + vi.mocked(ClustersClient.getLatchReason).mockImplementation(() => latch); + vi.mocked(ClustersClient.latch).mockImplementation((_id, reason): void => { + latch = reason; + epoch++; + }); + vi.mocked(ClustersClient.unlatch).mockImplementation((): void => { + latch = undefined; + epoch++; + }); + vi.mocked(ClustersClient.exists).mockReturnValue(false); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(false); + mockDeleteClient.mockReset().mockResolvedValue(undefined); + mockPrompt.mockReset().mockResolvedValue(undefined); + mockExecute.mockReset().mockResolvedValue(undefined); + mockGetConflictingTasks.mockReturnValue([]); + mockGetPlaygroundEvaluators.mockReturnValue(new Map()); vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(false); mockGetRegisteredShellTerminals.mockReturnValue([]); + showWarning.mockImplementation( + async (_message, _options, ...items) => items.find((item) => item === 'Keep open') ?? items[0], + ); + vi.spyOn(vscode.l10n, 't').mockImplementation((message) => + typeof message === 'string' ? message : message.message, + ); capturedContexts.length = 0; }); +afterEach((): void => { + for (const registration of registrations.splice(0)) { + registration.dispose(); + } +}); + async function inferMethods( host: string, suffix?: string, @@ -232,7 +297,8 @@ describe('updateCredentials post-wizard updates', () => { ); }); - it('retires old views after a saved password-only edit', async (): Promise => { + it('disconnects before prompting and saving a password-only edit', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); let storedConnection: storageModule.ConnectionItem = originalConnection; const newCredentials = { connectionUser: 'old-user', connectionPassword: 'new-password' }; mockGet.mockImplementation(async () => structuredClone(storedConnection)); @@ -251,15 +317,20 @@ describe('updateCredentials post-wizard updates', () => { expect(storedConnection.secrets.nativeAuthConfig).toEqual(newCredentials); expect(CredentialCache.getCredentials(node.cluster.clusterId)?.nativeAuthConfig).toEqual(newCredentials); expect(capturedContexts[0].credentialsSaved).toBe(true); - expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId, 'userDisconnected'); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId, 'credentialsChanged'); expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { alreadyInvalidated: true }); expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).toHaveBeenCalledBefore(mockPrompt); + expect(mockDeleteClient).toHaveBeenCalledBefore(mockSave); + expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'userDisconnected'); }); it.each([true, false])( 'only clears rejection and refreshes the recovery node when an unchanged edit saves (%s)', async (saved) => { - vi.mocked(ClustersClient.getLatchReason).mockReturnValue('credentialsRejected'); + latch = 'credentialsRejected'; + vi.mocked(ClustersClient.exists).mockReturnValue(true); vi.mocked(ext.connectionsBranchDataProvider.hasNodeErrorState).mockReturnValue(true); mockExecute.mockImplementationOnce((wizardContext) => { wizardContext.reconnectAfterError = true; @@ -269,19 +340,24 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); - expect(mockRetireBoundViews).not.toHaveBeenCalled(); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId, 'userDisconnected'); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId, 'credentialsChanged'); + expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'userDisconnected'); if (saved) { expect(ClustersClient.unlatch).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(ClustersClient.unlatch).toHaveBeenCalledBefore( + vi.mocked(ext.connectionsBranchDataProvider.resetNodeErrorState), + ); expect(ext.connectionsBranchDataProvider.resetNodeErrorState).toHaveBeenCalledExactlyOnceWith(node.id); } else { - expect(ClustersClient.latch).toHaveBeenLastCalledWith(node.cluster.clusterId, 'credentialsRejected'); expect(ClustersClient.unlatch).not.toHaveBeenCalled(); expect(ext.connectionsBranchDataProvider.resetNodeErrorState).not.toHaveBeenCalled(); } }, ); - it('retires old views if the secret write persisted but the edit reported failure', async (): Promise => { + it('keeps the ended session disconnected if a secret write persists but metadata fails', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); const stored = structuredClone(originalConnection); mockGet.mockImplementation(async () => structuredClone(stored)); mockExecute.mockImplementationOnce(async (wizardContext): Promise => { @@ -298,8 +374,12 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); expect(capturedContexts[0].credentialsSaved).not.toBe(true); - expect(mockRetireBoundViews).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); - expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce(); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(1, node.cluster.clusterId, 'userDisconnected'); + expect(mockRetireBoundViews).toHaveBeenNthCalledWith(2, node.cluster.clusterId, 'credentialsChanged'); + expect(vscode.window.showWarningMessage).toHaveBeenCalledWith( + 'The connection update may be incomplete. Check the saved settings before reconnecting.', + ); + expect(showConfirmationAsInSettings).not.toHaveBeenCalled(); }); it.each<{ authMethod: AuthMethodId; secrets: Partial }>([ @@ -318,7 +398,7 @@ describe('updateCredentials post-wizard updates', () => { }, { authMethod: AuthMethodId.NoAuth, secrets: {} }, ])( - 'caches the saved $authMethod credentials and shuts down the old client and playground', + 'caches the saved $authMethod credentials without redundantly tearing down an idle connection', async ({ authMethod, secrets }) => { const savedConnection: storageModule.ConnectionItemInput = { ...originalConnection, @@ -352,10 +432,8 @@ describe('updateCredentials post-wizard updates', () => { }); expect(CredentialCache.hasCredentials(node.cluster.treeId)).toBe(false); expect(mockDeleteCredentials).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); - expect(mockDeleteClient).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId, { - alreadyInvalidated: true, - }); - expect(mockShutdownEvaluator).toHaveBeenCalledExactlyOnceWith(node.cluster.clusterId); + expect(mockDeleteClient).not.toHaveBeenCalled(); + expect(mockShutdownEvaluator).not.toHaveBeenCalled(); }, ); @@ -392,7 +470,7 @@ describe('updateCredentials post-wizard updates', () => { expect(CredentialCache.getCredentials(node.cluster.clusterId)).toBeUndefined(); }); - it('offers to disconnect only shells using the previous connection settings', async () => { + it('stops only matching shells before editing without a post-save shell modal', async () => { const disconnect = vi.fn(); const disconnectOther = vi.fn(); mockGet @@ -408,15 +486,6 @@ describe('updateCredentials post-wizard updates', () => { mockExecute.mockImplementationOnce(async (wizardContext) => { wizardContext.credentialsSaved = true; }); - vi.spyOn(vscode.l10n, 't').mockImplementation((message) => - typeof message === 'string' ? message : message.message, - ); - const showInformation: ( - message: string, - options: vscode.MessageOptions, - ...items: string[] - ) => Thenable = vscode.window.showInformationMessage; - vi.mocked(showInformation).mockResolvedValueOnce('Disconnect'); mockGetRegisteredShellTerminals.mockReturnValue([ { info: { clusterId: 'another-cluster-id' }, disconnect: disconnectOther }, { info: { clusterId: node.cluster.clusterId }, disconnect }, @@ -424,16 +493,11 @@ describe('updateCredentials post-wizard updates', () => { await updateCredentials(context, node); - expect(vscode.window.showInformationMessage).toHaveBeenCalledExactlyOnceWith( - 'Open shells are still using the previous connection settings.', - { modal: true }, - 'Disconnect', - ); + expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); expect(disconnect).toHaveBeenCalledOnce(); expect(disconnectOther).not.toHaveBeenCalled(); - const modalCallOrder = vi.mocked(vscode.window.showInformationMessage).mock.invocationCallOrder[0]; - expect(mockDeleteClient.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); - expect(mockShutdownEvaluator.mock.invocationCallOrder[0]).toBeLessThan(modalCallOrder); + expect(disconnect).toHaveBeenCalledBefore(mockPrompt); + expect(mockShutdownEvaluator).toHaveBeenCalledBefore(mockPrompt); }); it.each([ @@ -450,4 +514,119 @@ describe('updateCredentials post-wizard updates', () => { expect(vscode.window.showInformationMessage).not.toHaveBeenCalled(); }); + + it.each(['cancel offer', 'cancel tabs', 'active transfer', 'dirty close refusal', 'close failure'] as const)( + 'does not begin the wizard or save after %s', + async (outcome): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + const draft: ConnectionSurface = { + clusterId: node.cluster.clusterId, + kind: 'documentView', + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + registrations.push(registerConnectionSurface(draft)); + const task = { taskName: 'Copy orders', taskType: 'copy', cancel: vi.fn() }; + if (outcome === 'active transfer') { + mockGetConflictingTasks.mockReturnValue([task]); + } else if (outcome === 'cancel offer') { + showWarning.mockResolvedValueOnce(undefined); + } else if (outcome === 'cancel tabs') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else if (outcome === 'dirty close refusal') { + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockResolvedValueOnce(undefined); + } else { + mockDeleteClient.mockRejectedValueOnce(new Error('private driver connection details')); + } + + const pending = updateCredentials(context, node); + if (outcome === 'close failure') { + await expect(pending).rejects.toThrow('Could not finish closing the connection.'); + expect(latch).toBe('userDisconnected'); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(draft.disable).not.toHaveBeenCalled(); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(mockDeleteClient).not.toHaveBeenCalled(); + expect(mockShutdownEvaluator).not.toHaveBeenCalled(); + } + expect(mockPrompt).not.toHaveBeenCalled(); + expect(mockGet).not.toHaveBeenCalled(); + expect(mockSave).not.toHaveBeenCalled(); + expect(task.cancel).not.toHaveBeenCalled(); + }, + ); + + it('keeps the connection disconnected when the edit wizard is cancelled', async (): Promise => { + vi.mocked(ClustersClient.exists).mockReturnValue(true); + mockPrompt.mockRejectedValueOnce(new UserCancelledError()); + + await expect(updateCredentials(context, node)).rejects.toBeInstanceOf(UserCancelledError); + + expect(latch).toBe('userDisconnected'); + expect(mockDeleteClient).toHaveBeenCalledOnce(); + expect(mockSave).not.toHaveBeenCalled(); + expect(ClustersClient.unlatch).not.toHaveBeenCalled(); + }); + + it.each(['idle', 'userDisconnected', 'held client', 'evicted surface', 'pending startup'] as const)( + 'edits %s without overlooking surviving connection work', + async (state): Promise => { + latch = state === 'userDisconnected' ? 'userDisconnected' : 'credentialsRejected'; + vi.mocked(ClustersClient.exists).mockReturnValue(state === 'held client'); + vi.mocked(ClustersClient.hasPendingStartup).mockReturnValue(state === 'pending startup'); + const draft: ConnectionSurface = { + clusterId: node.cluster.clusterId, + kind: 'documentView', + isDirty: (): boolean => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + if (state === 'evicted surface') { + registrations.push(registerConnectionSurface(draft)); + } + mockExecute.mockImplementationOnce(async (wizardContext): Promise => { + wizardContext.nativeAuthConfig = { connectionUser: 'old-user', connectionPassword: 'new-password' }; + await new ExecuteStep().execute(wizardContext); + }); + + await updateCredentials(context, node); + + expect(mockSave).toHaveBeenCalledOnce(); + if (state === 'idle' || state === 'userDisconnected') { + expect(mockDeleteClient).not.toHaveBeenCalled(); + expect(mockShutdownEvaluator).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + } else { + expect(mockDeleteClient).toHaveBeenCalledBefore(mockPrompt); + expect(mockShutdownEvaluator).toHaveBeenCalledBefore(mockPrompt); + expect(latch).toBe('userDisconnected'); + } + if (state === 'evicted surface') { + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.dispose).not.toHaveBeenCalled(); + } + }, + ); + + it('does not save an ordinary edit superseded while the wizard is open', async (): Promise => { + mockPrompt.mockImplementationOnce(async (): Promise => { + epoch++; + }); + + await updateCredentials(context, node); + + expect(mockExecute).not.toHaveBeenCalled(); + expect(mockSave).not.toHaveBeenCalled(); + expect(mockDeleteCredentials).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'This connection changed. Refresh the tree and try again.', + ); + }); }); diff --git a/src/commands/updateCredentials/updateCredentials.ts b/src/commands/updateCredentials/updateCredentials.ts index 72b703ab8..543ace0d9 100644 --- a/src/commands/updateCredentials/updateCredentials.ts +++ b/src/commands/updateCredentials/updateCredentials.ts @@ -5,6 +5,7 @@ import { AzureWizard, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; +import { window } from 'vscode'; import { AuthMethodId, authMethodFromString, @@ -13,6 +14,7 @@ import { } from '../../documentdb/auth/AuthMethod'; import { evaluateEntraDestinationFromSettings } from '../../documentdb/auth/entraDestinationSettings'; import { ClustersClient } from '../../documentdb/ClustersClient'; +import { canSaveEdit, ensureDisconnectedForEdit } from '../../documentdb/connectionTeardown'; import { CredentialCache } from '../../documentdb/CredentialCache'; import { DocumentDBConnectionString } from '../../documentdb/utils/DocumentDBConnectionString'; import { Views } from '../../documentdb/Views'; @@ -22,7 +24,7 @@ import { ConnectionStorageService, isConnection } from '../../services/connectio import { type DocumentDBClusterItem } from '../../tree/connections-view/DocumentDBClusterItem'; import { resolveStorageZone } from '../../tree/connections-view/models/ConnectionClusterModel'; import { refreshView } from '../refreshView/refreshView'; -import { offerShellDisconnect, saveConnectionEdit } from '../saveConnectionEdit'; +import { saveConnectionEdit } from '../saveConnectionEdit'; import { PromptAuthMethodStep } from '../updateCredentials/PromptAuthMethodStep'; import { ExecuteStep } from './ExecuteStep'; import { PromptPasswordStep } from './PromptPasswordStep'; @@ -35,7 +37,7 @@ import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardCo * Updates the authentication credentials for a cluster connection. * * Architecture: - * 1. Loads stored credentials and determines available authentication methods + * 1. Ends the old session, then loads stored credentials and available authentication methods * 2. Runs wizard to collect new credentials from user: * - PromptAuthMethodStep: Select authentication method * - SelectEntraTokenSourceStep: Select account sign-in or a managed identity (if needed) @@ -44,8 +46,7 @@ import { type UpdateCredentialsWizardContext } from './UpdateCredentialsWizardCo * - PromptPasswordStep: Enter password (if needed) * - PromptReconnectStepForErrorNodes: Ask to reconnect (only for error nodes) * 3. ExecuteStep: Saves updated credentials to storage - * 4. Post-wizard: Refreshes cached credentials, drops the client and playground worker, - * warns about open shells, and optionally resets error state for reconnection + * 4. Post-wizard: Refreshes cached credentials and optionally resets error state for reconnection * * For error recovery nodes, prompts whether to reconnect immediately. If user chooses * not to reconnect, the error state is preserved and the node remains as an error node. @@ -56,8 +57,8 @@ export async function updateCredentials(context: IActionContext, node: DocumentD throw new Error(l10n.t('No node selected.')); } const clusterId = node.cluster.clusterId; - const epoch = ClustersClient.getEpoch(clusterId); const recoveringRejection = ClustersClient.getLatchReason(clusterId) === 'credentialsRejected'; + const epoch = await ensureDisconnectedForEdit(clusterId, () => ext.connectionsBranchDataProvider.refresh()); const isRecoveryCurrent = recoveringRejection ? (): boolean => ClustersClient.getEpoch(clusterId) === epoch : undefined; @@ -76,7 +77,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD const resourceType = resolveStorageZone(node.cluster); const storedItem = await ConnectionStorageService.get(node.storageId, resourceType); - if (isRecoveryCurrent?.() === false) { + if (ClustersClient.getEpoch(clusterId) !== epoch) { return; } // Type guard ensures we have connection properties (not a folder) @@ -145,10 +146,11 @@ export async function updateCredentials(context: IActionContext, node: DocumentD }); await wizard.prompt(); - if (isRecoveryCurrent?.() === false) { + if (!canSaveEdit(clusterId, epoch)) { + void window.showErrorMessage(l10n.t('This connection changed. Refresh the tree and try again.')); return; } - const changed = await saveConnectionEdit( + await saveConnectionEdit( node, async (isCurrent) => { wizardContext.isRecoveryCurrent = isCurrent; @@ -156,7 +158,7 @@ export async function updateCredentials(context: IActionContext, node: DocumentD return wizardContext.credentialsSaved === true; }, { - canStart: isRecoveryCurrent, + canStart: () => canSaveEdit(clusterId, epoch), publishCredentials: (updated): void => { if (!updated || !isConnection(updated)) { return; @@ -186,13 +188,13 @@ export async function updateCredentials(context: IActionContext, node: DocumentD // Clearing the error state triggers a fresh connection attempt on refresh. if (wizardContext.credentialsSaved && node.id && wizardContext.isErrorState) { if (wizardContext.reconnectAfterError) { + if (ClustersClient.getLatchReason(clusterId) === 'userDisconnected') { + ClustersClient.unlatch(clusterId); + } ext.connectionsBranchDataProvider.resetNodeErrorState(node.id); context.telemetry.properties.reconnected = 'true'; } } await refreshView(context, Views.ConnectionsView); - if (changed) { - await offerShellDisconnect(node); - } } diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index c665e3f4b..c3d195236 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -14,7 +14,7 @@ import { getDataAtPath } from '../utils/slickgrid/mongo/toSlickGridTable'; import { toSlickGridTree, type TreeData } from '../utils/slickgrid/mongo/toSlickGridTree'; import { type QueryInsightsStage2Response } from '../webviews/documentdb/collectionView/types/queryInsights'; import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; -import { isRetiredConnectionBinding } from './connectionBindingRetirement'; +import { getRetiredBindingReason, isRetiredConnectionBinding } from './connectionBindingRetirement'; import { classifyConnectionFailure } from './connectionFailures'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { runWithClient } from './runWithClient'; @@ -109,9 +109,7 @@ export class ClusterSession { if (signal?.aborted) { throw new UserCancelledError('staleCollectionViewOperation'); } - const reason = isRetiredConnectionBinding(this.binding) - ? 'credentialsChanged' - : ClustersClient.getLatchReason(this.binding.clusterId); + const reason = getRetiredBindingReason(this.binding) ?? ClustersClient.getLatchReason(this.binding.clusterId); if (reason) { throw new ConnectionUnavailableError(reason); } @@ -803,8 +801,17 @@ export class ClusterSession { * * @throws Will throw an error if the client cannot be obtained using the provided cluster ID. */ - public static async initNewSession(clusterId: string): Promise { - const client = await ClustersClient.getClient(clusterId, undefined, undefined, 'collectionView'); + public static async initNewSession( + clusterId: string, + options?: { readonly origin?: ConnectionBinding; readonly signal?: AbortSignal }, + ): Promise { + const client = options?.origin + ? await ClustersClient.resolveBoundClient(options.origin, { trigger: 'collectionView' }) + : await ClustersClient.getClient(clusterId, undefined, undefined, 'collectionView'); + + if (options?.signal?.aborted) { + throw new UserCancelledError('staleBoundViewOperation'); + } const sessionId = Math.random().toString(16).substring(2, 15) + Math.random().toString(36).substring(2, 15); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index ad78c6845..c2d63c9e5 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -376,6 +376,90 @@ describe('regular connection startup diagnostics', () => { await expect(ClustersClient.resolveBoundClient(current.binding)).resolves.toBe(current); }); + it.each([false, true])( + 'does not create a bound session after Disconnect during startup (changed identity: %s)', + async (changedIdentity): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(original.binding, new MongoNotConnectedError('idle connection closed')); + const handshake = pauseNextConnect(); + const opening = ClusterSession.initNewSession(clusterId, { origin: original.binding }); + await handshake.started; + + ClustersClient.latch(clusterId, 'userDisconnected'); + ClustersClient.retireBoundViews(clusterId, 'userDisconnected'); + await ClustersClient.deleteClient(clusterId, { alreadyInvalidated: true }); + if (changedIdentity) { + CredentialCache.setAuthCredentials( + clusterId, + AuthMethodId.MicrosoftEntraID, + 'mongodb://different.test/', + ); + } + ClustersClient.unlatch(clusterId); + const replacement = await ClustersClient.getClient(clusterId); + expect(replacement.fingerprint === original.fingerprint).toBe(!changedIdentity); + + handshake.resolve(); + await expect(opening).rejects.toMatchObject({ + reason: changedIdentity ? 'identityChanged' : 'userDisconnected', + }); + expect(ClusterSession._sessions.size).toBe(0); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + }, + ); + + it('does not create a bound session while the origin is latched', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + + await expect(ClusterSession.initNewSession(clusterId, { origin: original.binding })).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + expect(ClusterSession._sessions.size).toBe(0); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + + it('does not create a bound session against a replacement identity', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + const replacement = await ClustersClient.getClient(clusterId); + + await expect(ClusterSession.initNewSession(clusterId, { origin: original.binding })).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(ClusterSession._sessions.size).toBe(0); + expect(ClustersClient.getBinding(clusterId)).toBe(replacement.binding); + }); + + it('creates a bound session after ordinary same-identity client replacement', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + ClustersClient.reportFailure(original.binding, new MongoNotConnectedError('idle connection closed')); + + const sessionId = await ClusterSession.initNewSession(clusterId, { origin: original.binding }); + const session = ClusterSession.getSession(sessionId); + expect(session.getBinding()).toEqual({ ...original.binding, generation: original.generation + 1 }); + expect(() => session.assertAvailable()).not.toThrow(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('does not store a bound session when cancelled during client startup', async (): Promise => { + const original = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + const handshake = pauseNextConnect(); + const controller = new AbortController(); + const opening = ClusterSession.initNewSession(clusterId, { + origin: original.binding, + signal: controller.signal, + }); + await handshake.started; + controller.abort(); + handshake.resolve(); + + await expect(opening).rejects.toBeInstanceOf(UserCancelledError); + expect(ClusterSession._sessions.size).toBe(0); + }); + it('keeps session paging and schema accumulation on a same-identity replacement', async (): Promise => { const original = await ClustersClient.connectInteractive(clusterId); const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); @@ -971,6 +1055,133 @@ describe('regular connection startup diagnostics', () => { await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'userDisconnected' }); }); + it('recovers a rejected Entra account without retiring or replaying its binding', async (): Promise => { + const wrongAccountId = 'private-other-account-id'; + const callback = vi.fn(async (): Promise => { + if (wrongAccountId !== verifiedIdentity.accountId) { + throw new EntraIdentityMismatchError(); + } + throw new Error('The wrong account must not be used'); + }); + vi.mocked(MicrosoftEntraIDAuthHandler.prototype.configureAuth).mockResolvedValueOnce({ + connectionString: 'mongodb://private-host:27017', + options: { authMechanismProperties: { OIDC_CALLBACK: callback } }, + verifiedIdentity, + }); + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + const driverCallback = vi.mocked(MongoClient).mock.lastCall?.[1]?.authMechanismProperties?.OIDC_CALLBACK; + const pin = ClustersClient.getLastVerifiedIdentity(clusterId); + const rejectedOperation = vi.fn(async (): Promise => { + await driverCallback!({ version: 1, timeoutContext: new AbortController().signal }); + throw new Error('The wrong account operation must not continue'); + }); + + await expect(runWithClient(old.binding, rejectedOperation)).resolves.toEqual({ + unavailable: { reason: 'signInRequired' }, + }); + expect(ClustersClient.getBinding(clusterId)).toBe(old.binding); + expect(() => ClustersClient.assertBindingActive(old.binding)).not.toThrow(); + expect(ClustersClient.getLastVerifiedIdentity(clusterId)).toBe(pin); + expect(CredentialCache.getCredentials(clusterId)).toBe(credentials); + expect(rejectedOperation).toHaveBeenCalledExactlyOnceWith(old); + expect(mockConnect).toHaveBeenCalledOnce(); + expect(mockClose).not.toHaveBeenCalled(); + + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'signInRequired' }); + await expect(runWithClient(old.binding, rejectedOperation)).resolves.toEqual({ + unavailable: { reason: 'signInRequired' }, + }); + expect(rejectedOperation).toHaveBeenCalledOnce(); + expect(mockConnect).toHaveBeenCalledOnce(); + + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const operation = vi.fn(async (client: ClustersClient) => client); + + await expect(runWithClient(old.binding, operation)).resolves.toBe(repaired); + + expect(repaired.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(operation).toHaveBeenCalledExactlyOnceWith(repaired); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('serves the next explicit operation once on a repaired same-account generation', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + ClustersClient.reportFailure(old.binding, new MongoServerError({ code: 18 })); + + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const operation = vi.fn(async (client: ClustersClient) => client); + + await expect(runWithClient(old.binding, operation)).resolves.toBe(repaired); + + expect(repaired.binding).toEqual({ ...old.binding, generation: old.generation + 1 }); + expect(operation).toHaveBeenCalledExactlyOnceWith(repaired); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockConnect).toHaveBeenCalledTimes(2); + }); + + it('ignores a late failure from the generation replaced by same-account repair', async (): Promise => { + const old = await ClustersClient.connectInteractive(clusterId); + const credentials = CredentialCache.getCredentials(clusterId)!; + ClustersClient.reportFailure(old.binding, new MongoServerError({ code: 18 })); + const repaired = await ClustersClient.startAfterSignIn( + clusterId, + ClustersClient.getEpoch(clusterId), + credentials, + { + connectionString: 'mongodb://private-host:27017', + options: {}, + verifiedIdentity, + }, + ); + if (!repaired) { + throw new Error('Expected same-account repair to publish a client'); + } + const closes = mockClose.mock.calls.length; + const lateFailure = new MongoServerError({ code: 18 }); + + expect(ClustersClient.reportFailure(old.binding, lateFailure)).toBeUndefined(); + expect(ClustersClient.getExistingClient(clusterId)).toBe(repaired); + expect(ClustersClient.getBinding(clusterId)).toBe(repaired.binding); + expect(ClustersClient.getLatchReason(clusterId)).toBeUndefined(); + expect(mockClose).toHaveBeenCalledTimes(closes); + expect(await ClustersClient.getClient(clusterId)).toBe(repaired); + expect(mockConnect).toHaveBeenCalledTimes(2); + + expect(ClustersClient.reportFailure(repaired.binding, lateFailure)).toBe('credentialsRejected'); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(ClustersClient.getLatchReason(clusterId)).toBe('credentialsRejected'); + expect(mockClose).toHaveBeenCalledTimes(closes + 1); + }); + it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { const old = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('topologyClosed'); @@ -989,10 +1200,12 @@ describe('regular connection startup diagnostics', () => { op.mockRejectedValueOnce(new EntraIdentityMismatchError()); await expect(runWithClient(old.binding, op)).resolves.toEqual({ - unavailable: { reason: 'identityChanged' }, + unavailable: { reason: 'signInRequired' }, }); - expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + expect(ClustersClient.getBinding(clusterId)).toBe(client.binding); + await expect(ClustersClient.getClient(clusterId)).rejects.toMatchObject({ reason: 'signInRequired' }); expect(op).toHaveBeenCalledTimes(2); + expect(mockConnect).toHaveBeenCalledTimes(2); }); it('reports a startup credential rejection without submitting the bound operation', async (): Promise => { diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index 90f361f25..78642b3a5 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -40,6 +40,7 @@ import { type WithId, type WithoutId, } from 'mongodb'; +import * as vscode from 'vscode'; import { Links } from '../constants'; import { ext } from '../extensionVariables'; import { meterSilentCatch } from '../utils/accumulatingTelemetry'; @@ -53,7 +54,11 @@ import { getAzureHostSuffix } from './auth/oidcAllowedHosts'; import { readJwtTimes } from './auth/tokenExpiry'; import { emitTokenRenewal } from './auth/tokenRenewalTelemetry'; import { QueryInsightsApis, type ExplainVerbosity } from './client/QueryInsightsApis'; -import { isRetiredConnectionBinding, retireConnectionBindings } from './connectionBindingRetirement'; +import { + getRetiredBindingReason, + retireConnectionBindings, + type EndedLifetimeReason, +} from './connectionBindingRetirement'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { computeConnectionFingerprint, type ConnectionPrincipal } from './connectionFingerprint'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; @@ -290,6 +295,7 @@ export class ClustersClient { private static readonly _generations = new Map(); private static readonly _epochs = new Map(); private static readonly _latches = new Map(); + private static _onDidChangeLatch: vscode.EventEmitter | undefined; private static readonly _pendingStartups = new Map(); private static readonly _lastVerifiedIdentities = new Map>(); @@ -352,11 +358,18 @@ export class ClustersClient { public static latch(clusterId: string, reason: ConnectionUnavailableReason): void { ClustersClient._latches.set(clusterId, reason); ClustersClient.invalidate(clusterId); + ClustersClient._onDidChangeLatch?.fire(clusterId); } public static unlatch(clusterId: string): void { ClustersClient._latches.delete(clusterId); ClustersClient.invalidate(clusterId); + ClustersClient._onDidChangeLatch?.fire(clusterId); + } + + public static get onDidChangeLatch(): vscode.Event { + ClustersClient._onDidChangeLatch ??= new vscode.EventEmitter(); + return ClustersClient._onDidChangeLatch.event; } public static getLatchReason(clusterId: string): ConnectionUnavailableReason | undefined { @@ -890,9 +903,7 @@ export class ClustersClient { binding: ConnectionBinding, options?: { readonly background?: boolean; readonly trigger?: ClientStartupTrigger }, ): Promise { - if (isRetiredConnectionBinding(binding)) { - throw new ConnectionUnavailableError('credentialsChanged'); - } + ClustersClient.assertBindingActive(binding); const client = await ClustersClient.acquireClient( binding.clusterId, undefined, @@ -902,14 +913,25 @@ export class ClustersClient { options?.background === true, binding.fingerprint, ); - if (isRetiredConnectionBinding(binding)) { - throw new ConnectionUnavailableError('credentialsChanged'); - } + ClustersClient.assertBindingActive(binding); return client; } - public static retireBoundViews(clusterId: string): void { - retireConnectionBindings(clusterId, ClustersClient._generations.get(clusterId) ?? 0); + public static retireBoundViews(clusterId: string, reason: EndedLifetimeReason = 'credentialsChanged'): number { + const generation = ClustersClient._generations.get(clusterId) ?? 0; + retireConnectionBindings(clusterId, generation, reason); + return generation; + } + + public static assertBindingActive(binding: ConnectionBinding): void { + const reason = getRetiredBindingReason(binding) ?? ClustersClient.getLatchReason(binding.clusterId); + if (reason) { + throw new ConnectionUnavailableError(reason); + } + } + + public static hasPendingStartup(clusterId: string): boolean { + return ClustersClient._pendingStartups.has(clusterId); } /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ diff --git a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts index b8bd10338..7236d00ed 100644 --- a/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts +++ b/src/documentdb/auth/MicrosoftEntraIDAuthHandler.test.ts @@ -1133,6 +1133,56 @@ describe('MicrosoftEntraIDAuthHandler', () => { expect(output).not.toContain('access-token'); }); + it.each(['success', 'noSession', 'rejection'] as const)( + 'keeps a non-interactive callback silent on %s', + async (outcome): Promise => { + const cause = new Error('provider rejected silent lookup'); + const { options } = await new MicrosoftEntraIDAuthHandler( + buildCredentials('mongodb://cluster.mongocluster.cosmos.azure.com/'), + { interactive: false, pinnedEntraIdentity }, + ).configureAuth(); + if (outcome === 'noSession') { + getSessionFromVSCode.mockResolvedValueOnce(undefined); + } else if (outcome === 'rejection') { + getSessionFromVSCode.mockRejectedValueOnce(cause); + } + + const result = options.authMechanismProperties!.OIDC_CALLBACK!({ + version: 1, + timeoutContext: new AbortController().signal, + }); + + if (outcome === 'success') { + await expect(result).resolves.toEqual({ accessToken: session.accessToken }); + } else if (outcome === 'noSession') { + await expect(result).rejects.toMatchObject({ + name: 'EntraSignInRequiredError', + reason: 'noSession', + }); + } else { + await expect(result).rejects.toBeInstanceOf(TokenCallbackError); + } + expect(getSessionFromVSCode.mock.calls).toEqual([ + [ + 'microsoft', + [ + 'https://ossrdbms-aad.database.windows.net/.default', + `VSCODE_TENANT:${pinnedEntraIdentity.tenantId}`, + ], + { silent: true, account }, + ], + [ + 'microsoft', + [ + 'https://ossrdbms-aad.database.windows.net/.default', + `VSCODE_TENANT:${pinnedEntraIdentity.tenantId}`, + ], + { silent: true, account }, + ], + ]); + }, + ); + it('reports a missing silent session as unavailable input without recording a token failure', async () => { getSessionFromVSCode.mockResolvedValueOnce(undefined); const events: string[] = []; diff --git a/src/documentdb/connectionBindingRetirement.test.ts b/src/documentdb/connectionBindingRetirement.test.ts new file mode 100644 index 000000000..b1e446832 --- /dev/null +++ b/src/documentdb/connectionBindingRetirement.test.ts @@ -0,0 +1,172 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import * as vscode from 'vscode'; +import { ClustersClient, type ConnectionBinding } from './ClustersClient'; +import { + correctFailedRemovalRetirement, + getBindingLifetimeSignal, + getRetiredBindingReason, + isRetiredConnectionBinding, + retireConnectionBindings, +} from './connectionBindingRetirement'; +import { runWithClient } from './runWithClient'; + +beforeEach((): void => { + vi.clearAllMocks(); +}); + +afterEach((): void => { + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +it('keeps same-account physical replacements in one lifetime and aborts it synchronously on session end', (): void => { + const binding = { clusterId: 'lifetime-signal', fingerprint: 'same-account', generation: 1 }; + const replacement = { ...binding, generation: 2 }; + const signal = getBindingLifetimeSignal(binding); + const abort = vi.fn(); + signal.addEventListener('abort', abort); + + expect(getBindingLifetimeSignal(replacement)).toBe(signal); + expect(isRetiredConnectionBinding(binding)).toBe(false); + expect(signal.aborted).toBe(false); + + retireConnectionBindings(binding.clusterId, replacement.generation, 'userDisconnected'); + + expect(abort).toHaveBeenCalledOnce(); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + expect(getBindingLifetimeSignal(replacement).aborted).toBe(true); + const fresh = getBindingLifetimeSignal({ ...binding, generation: 3 }); + expect(fresh).not.toBe(signal); + expect(fresh.aborted).toBe(false); +}); + +it('preserves the first reason per ended range without lowering the cutoff or ending the fresh lifetime twice', (): void => { + const binding = { clusterId: 'lifetime-reasons', fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 2, 'userDisconnected'); + const freshSignal = getBindingLifetimeSignal({ ...binding, generation: 3 }); + retireConnectionBindings(binding.clusterId, 1, 'connectionRemoved'); + retireConnectionBindings(binding.clusterId, 2, 'credentialsChanged'); + expect(freshSignal.aborted).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('userDisconnected'); + + retireConnectionBindings(binding.clusterId, 4, 'connectionRemoved'); + expect(freshSignal.aborted).toBe(true); + expect(getRetiredBindingReason({ ...binding, generation: 2 })).toBe('userDisconnected'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('connectionRemoved'); + expect(isRetiredConnectionBinding({ ...binding, generation: 4 })).toBe(true); + expect(getRetiredBindingReason({ ...binding, generation: 5 })).toBeUndefined(); +}); + +it('corrects only the last failed removal without reviving signals or changing an earlier disconnected range', (): void => { + const first = { clusterId: 'failed-removal-reasons', fingerprint: 'same-account', generation: 1 }; + const firstSignal = getBindingLifetimeSignal(first); + retireConnectionBindings(first.clusterId, 1, 'userDisconnected'); + const second = { ...first, generation: 2 }; + const secondSignal = getBindingLifetimeSignal(second); + retireConnectionBindings(first.clusterId, 2, 'connectionRemoved'); + const freshSignal = getBindingLifetimeSignal({ ...first, generation: 3 }); + + expect(correctFailedRemovalRetirement(first.clusterId, 2)).toBe(true); + expect(getRetiredBindingReason(first)).toBe('userDisconnected'); + expect(getRetiredBindingReason(second)).toBe('userDisconnected'); + expect(firstSignal.aborted).toBe(true); + expect(secondSignal.aborted).toBe(true); + expect(getBindingLifetimeSignal(second).aborted).toBe(true); + expect(freshSignal.aborted).toBe(false); + expect(() => ClustersClient.assertBindingActive(second)).toThrow( + expect.objectContaining({ reason: 'userDisconnected' }), + ); + expect(correctFailedRemovalRetirement(first.clusterId, 2)).toBe(true); +}); + +it('does not correct a missing, wrong or superseded removal generation', (): void => { + const binding = { clusterId: 'superseded-removal-reasons', fingerprint: 'same-account', generation: 2 }; + expect(correctFailedRemovalRetirement(binding.clusterId, 2)).toBe(false); + retireConnectionBindings(binding.clusterId, 2, 'connectionRemoved'); + expect(correctFailedRemovalRetirement(binding.clusterId, 1)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + retireConnectionBindings(binding.clusterId, 3, 'connectionRemoved'); + expect(correctFailedRemovalRetirement(binding.clusterId, 2)).toBe(false); + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + expect(getRetiredBindingReason({ ...binding, generation: 3 })).toBe('connectionRemoved'); +}); + +it.each(['userDisconnected', 'credentialsChanged'] as const)( + 'accepts the matching last generation without changing a range ended for %s', + (reason): void => { + const binding = { clusterId: `non-removal-reasons-${reason}`, fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 1, reason); + expect(correctFailedRemovalRetirement(binding.clusterId, 1)).toBe(true); + expect(getRetiredBindingReason(binding)).toBe(reason); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + }, +); + +it('checks stored lifetime reasons before a later hold, while live bindings obey the current hold', (): void => { + const binding = { clusterId: 'lifetime-hold', fingerprint: 'same-account', generation: 1 }; + retireConnectionBindings(binding.clusterId, 1, 'userDisconnected'); + vi.spyOn(ClustersClient, 'getLatchReason').mockReturnValue('credentialsRejected'); + expect(() => ClustersClient.assertBindingActive(binding)).toThrow( + expect.objectContaining({ reason: 'userDisconnected' }), + ); + expect(() => ClustersClient.assertBindingActive({ ...binding, generation: 2 })).toThrow( + expect.objectContaining({ reason: 'credentialsRejected' }), + ); +}); + +it('rejects a client resolved across retirement before it can reach a driver operation', async (): Promise => { + const binding = { clusterId: 'lifetime-pending-resolution', fingerprint: 'same-account', generation: 1 }; + let release!: (client: ClustersClient) => void; + const pending = new Promise((resolve) => { + release = resolve; + }); + const acquisition = vi + .spyOn(ClustersClient as unknown as { acquireClient: () => Promise }, 'acquireClient') + .mockReturnValue(pending); + const effect = vi.fn(); + const operation = runWithClient(binding, effect); + expect(acquisition).toHaveBeenCalledOnce(); + retireConnectionBindings(binding.clusterId, 1, 'connectionRemoved'); + release({ binding: { ...binding, generation: 2 } } as ClustersClient); + await expect(operation).resolves.toEqual({ unavailable: { reason: 'connectionRemoved' } }); + expect(effect).not.toHaveBeenCalled(); +}); + +it('never acquires, polls the database or prompts for an ended binding; a fresh background operation works once', async (): Promise => { + vi.useFakeTimers(); + const binding: ConnectionBinding = { + clusterId: 'lifetime-background', + fingerprint: 'same-account', + generation: 1, + }; + const replacement = { binding: { ...binding, generation: 2 } } as ClustersClient; + const acquisition = vi + .spyOn(ClustersClient as unknown as { acquireClient: () => Promise }, 'acquireClient') + .mockResolvedValue(replacement); + const database = vi.fn(async (): Promise => {}); + retireConnectionBindings(binding.clusterId, 1, 'userDisconnected'); + const poll = vi.fn(async (): Promise => { + await runWithClient(binding, database, { background: true }); + }); + const timer = setInterval(() => void poll(), 100); + try { + await vi.advanceTimersByTimeAsync(500); + } finally { + clearInterval(timer); + } + expect(poll).toHaveBeenCalledTimes(5); + expect(acquisition).not.toHaveBeenCalled(); + expect(database).not.toHaveBeenCalled(); + expect(vscode.window.showErrorMessage).not.toHaveBeenCalled(); + expect(vscode.window.showWarningMessage).not.toHaveBeenCalled(); + + await runWithClient(replacement.binding, database, { background: true }); + expect(acquisition).toHaveBeenCalledOnce(); + expect(database).toHaveBeenCalledExactlyOnceWith(replacement); +}); diff --git a/src/documentdb/connectionBindingRetirement.ts b/src/documentdb/connectionBindingRetirement.ts index cedb5ba99..46f778b63 100644 --- a/src/documentdb/connectionBindingRetirement.ts +++ b/src/documentdb/connectionBindingRetirement.ts @@ -5,13 +5,56 @@ import { type ConnectionBinding } from './ClustersClient'; -const retiredThroughGeneration = new Map(); +export type EndedLifetimeReason = 'userDisconnected' | 'connectionRemoved' | 'credentialsChanged'; -export function retireConnectionBindings(clusterId: string, generation: number): void { - retiredThroughGeneration.set(clusterId, Math.max(retiredThroughGeneration.get(clusterId) ?? 0, generation)); +interface BindingLifetime { + readonly ended: { readonly generation: number; readonly reason: EndedLifetimeReason }[]; + controller: AbortController; } -export function isRetiredConnectionBinding({ clusterId, generation }: ConnectionBinding): boolean { - const retiredThrough = retiredThroughGeneration.get(clusterId); - return retiredThrough !== undefined && generation <= retiredThrough; +const lifetimes = new Map(); +const endedSignal = AbortSignal.abort(); + +export function retireConnectionBindings(clusterId: string, generation: number, reason: EndedLifetimeReason): void { + const lifetime: BindingLifetime = lifetimes.get(clusterId) ?? { ended: [], controller: new AbortController() }; + if (generation <= (lifetime.ended.at(-1)?.generation ?? -1)) { + return; + } + lifetime.ended.push({ generation, reason }); + const controller = lifetime.controller; + lifetime.controller = new AbortController(); + lifetimes.set(clusterId, lifetime); + controller.abort(); +} + +export function getRetiredBindingReason({ clusterId, generation }: ConnectionBinding): EndedLifetimeReason | undefined { + return lifetimes.get(clusterId)?.ended.find((range) => generation <= range.generation)?.reason; +} + +export function correctFailedRemovalRetirement(clusterId: string, generation: number): boolean { + const lifetime = lifetimes.get(clusterId); + const last = lifetime?.ended.at(-1); + if (!lifetime || !last || last.generation !== generation) { + return false; + } + if (last.reason === 'connectionRemoved') { + lifetime.ended[lifetime.ended.length - 1] = { generation, reason: 'userDisconnected' }; + } + return true; +} + +export function isRetiredConnectionBinding(binding: ConnectionBinding): boolean { + return getRetiredBindingReason(binding) !== undefined; +} + +export function getBindingLifetimeSignal(binding: ConnectionBinding): AbortSignal { + if (isRetiredConnectionBinding(binding)) { + return endedSignal; + } + let lifetime = lifetimes.get(binding.clusterId); + if (!lifetime) { + lifetime = { ended: [], controller: new AbortController() }; + lifetimes.set(binding.clusterId, lifetime); + } + return lifetime.controller.signal; } diff --git a/src/documentdb/connectionFailures.test.ts b/src/documentdb/connectionFailures.test.ts index 32dd83c98..4c55e2331 100644 --- a/src/documentdb/connectionFailures.test.ts +++ b/src/documentdb/connectionFailures.test.ts @@ -67,15 +67,30 @@ describe('classifyConnectionFailure', (): void => { expect(classifyConnectionFailure(error, native)).toEqual({ kind: 'other', generation: 'keep' }); }); - it.each([new EntraIdentityMismatchError(), new ConnectionUnavailableError('identityChanged')])( - 'requires a rebind for %s', - (error): void => { - expect(classifyConnectionFailure(new Error('Wrapper', { cause: error }))).toEqual({ - kind: 'identityChanged', - generation: 'evict', + it('requires explicit recovery for a rejected Entra account without an auth-method gate', (): void => { + for (const authMethod of [undefined, entra, native, AuthMethodId.ManagedIdentity]) { + expect( + classifyConnectionFailure( + new Error('Wrapper', { cause: new EntraIdentityMismatchError() }), + authMethod, + ), + ).toEqual({ + kind: 'signInRequired', + generation: 'replaceOnRecovery', }); - }, - ); + } + }); + + it('evicts a typed unavailable binding whose identity changed', (): void => { + expect( + classifyConnectionFailure( + new Error('Wrapper', { cause: new ConnectionUnavailableError('identityChanged') }), + ), + ).toEqual({ + kind: 'identityChanged', + generation: 'evict', + }); + }); it('reports missing credentials without inventing a generation to evict', (): void => { expect(classifyConnectionFailure(new ConnectionUnavailableError('credentialsMissing'))).toEqual({ diff --git a/src/documentdb/connectionFailures.ts b/src/documentdb/connectionFailures.ts index a3ec10797..3c7643554 100644 --- a/src/documentdb/connectionFailures.ts +++ b/src/documentdb/connectionFailures.ts @@ -96,7 +96,7 @@ export function classifyConnectionFailure(error: unknown, authMethod?: AuthMetho ? { kind: 'signInRequired', generation: 'replaceOnRecovery' } : OTHER; case 'EntraIdentityMismatchError': - return { kind: 'identityChanged', generation: 'evict' }; + return { kind: 'signInRequired', generation: 'replaceOnRecovery' }; case 'TokenCallbackError': return { kind: 'transient', generation: 'replaceOnNextForeground' }; case 'MongoOIDCError': diff --git a/src/documentdb/connectionSurfaces.test.ts b/src/documentdb/connectionSurfaces.test.ts index 23957e479..47d039f63 100644 --- a/src/documentdb/connectionSurfaces.test.ts +++ b/src/documentdb/connectionSurfaces.test.ts @@ -4,7 +4,12 @@ *--------------------------------------------------------------------------------------------*/ import { expect, it, vi } from 'vitest'; -import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; +import { + getConnectionSurfaces, + registerConnectionSurface, + takeConnectionSurfaces, + type ConnectionSurface, +} from './connectionSurfaces'; it('keeps teardown scoped to the current registered surfaces for one cluster', (): void => { const makeSurface = (clusterId: string, kind: ConnectionSurface['kind']): ConnectionSurface => ({ @@ -13,6 +18,7 @@ it('keeps teardown scoped to the current registered surfaces for one cluster', ( disable: vi.fn(), dispose: vi.fn(), }); + const document = makeSurface('cluster-a', 'documentView'); const dashboard = makeSurface('cluster-a', 'clusterDashboard'); const otherCluster = makeSurface('cluster-b', 'collectionView'); @@ -34,3 +40,29 @@ it('keeps teardown scoped to the current registered surfaces for one cluster', ( expect(getConnectionSurfaces('cluster-a')).toEqual([]); expect(getConnectionSurfaces('cluster-b')).toEqual([]); }); + +it('detaches ended surfaces without disposing snapshots or letting their registrations remove fresh surfaces', (): void => { + const old: ConnectionSurface = { + clusterId: 'detached-cluster', + kind: 'documentView', + isDirty: () => true, + disable: vi.fn(), + dispose: vi.fn(), + }; + const fresh: ConnectionSurface = { ...old, dispose: vi.fn() }; + const oldRegistration = registerConnectionSurface(old); + expect(takeConnectionSurfaces(old.clusterId)).toEqual([old]); + expect(getConnectionSurfaces(old.clusterId)).toEqual([]); + expect(takeConnectionSurfaces(old.clusterId)).toEqual([]); + const freshRegistration = registerConnectionSurface(fresh); + try { + oldRegistration.dispose(); + expect(getConnectionSurfaces(old.clusterId)).toEqual([fresh]); + expect(old.isDirty?.()).toBe(true); + expect(old.dispose).not.toHaveBeenCalled(); + expect(old.disable).not.toHaveBeenCalled(); + } finally { + oldRegistration.dispose(); + freshRegistration.dispose(); + } +}); diff --git a/src/documentdb/connectionSurfaces.ts b/src/documentdb/connectionSurfaces.ts index f48f199fd..c65125aec 100644 --- a/src/documentdb/connectionSurfaces.ts +++ b/src/documentdb/connectionSurfaces.ts @@ -27,7 +27,7 @@ export function registerConnectionSurface(surface: ConnectionSurface): Disposabl surfaces.add(surface); return { dispose(): void { - if (surfaces.delete(surface) && surfaces.size === 0) { + if (surfaces.delete(surface) && surfaces.size === 0 && surfacesByCluster.get(clusterId) === surfaces) { surfacesByCluster.delete(clusterId); } }, @@ -37,3 +37,9 @@ export function registerConnectionSurface(surface: ConnectionSurface): Disposabl export function getConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { return [...(surfacesByCluster.get(clusterId) ?? [])]; } + +export function takeConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { + const surfaces = getConnectionSurfaces(clusterId); + surfacesByCluster.delete(clusterId); + return surfaces; +} diff --git a/src/documentdb/connectionTeardown.test.ts b/src/documentdb/connectionTeardown.test.ts index 03bc04070..89945a27b 100644 --- a/src/documentdb/connectionTeardown.test.ts +++ b/src/documentdb/connectionTeardown.test.ts @@ -7,14 +7,22 @@ import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import * as vscode from 'vscode'; -import { registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; +import { + getBindingLifetimeSignal, + getRetiredBindingReason, + retireConnectionBindings, + type EndedLifetimeReason, +} from './connectionBindingRetirement'; +import { getConnectionSurfaces, registerConnectionSurface, type ConnectionSurface } from './connectionSurfaces'; import { commitTeardown, confirmTeardown, + ensureDisconnectedForEdit, latchForTeardown, teardownConnection, withConnectionRemoval, } from './connectionTeardown'; +import { type ConnectionUnavailableReason } from './ConnectionUnavailableError'; const mocks = vi.hoisted(() => ({ getSetting: vi.fn(), @@ -24,12 +32,16 @@ const mocks = vi.hoisted(() => ({ latch: vi.fn(), unlatch: vi.fn(), deleteClient: vi.fn(), + exists: vi.fn(), + hasPendingStartup: vi.fn(), + retireBoundViews: vi.fn(), clearLastVerifiedIdentity: vi.fn(), deleteCredentials: vi.fn(), clearEntraTokenFailure: vi.fn(), getRegisteredShellTerminals: vi.fn(), getPlaygroundEvaluators: vi.fn(), stopPlaygroundEvaluator: vi.fn(), + clearRemovedPlaygroundConnections: vi.fn(), event: vi.fn(), })); @@ -55,7 +67,7 @@ vi.mock('../services/SettingsService', () => ({ SettingsService: { getSetting: m vi.mock('../services/taskService/taskService', () => ({ TaskService: { getConflictingTasks: mocks.getConflictingTasks }, })); -vi.mock('./ClustersClient', () => ({ ClustersClient: { ...mocks, exists: () => true } })); +vi.mock('./ClustersClient', () => ({ ClustersClient: mocks })); vi.mock('./CredentialCache', () => ({ CredentialCache: { deleteCredentials: mocks.deleteCredentials } })); vi.mock('./auth/entraErrors/entraTokenFailures', () => ({ clearEntraTokenFailure: mocks.clearEntraTokenFailure })); vi.mock('./shell/ShellTerminalLinkProvider', () => ({ @@ -64,12 +76,18 @@ vi.mock('./shell/ShellTerminalLinkProvider', () => ({ vi.mock('../commands/playground/executePlaygroundCode', () => ({ getPlaygroundEvaluators: mocks.getPlaygroundEvaluators, stopPlaygroundEvaluator: mocks.stopPlaygroundEvaluator, + clearRemovedPlaygroundConnections: mocks.clearRemovedPlaygroundConnections, })); const clusterId = 'example-cluster'; const otherId = 'other-cluster'; const refreshTree = vi.fn(); -const showWarning = vi.mocked(vscode.window.showWarningMessage); +const showWarningMessage: ( + message: string, + options: vscode.MessageOptions, + ...items: string[] +) => Thenable = vscode.window.showWarningMessage; +const showWarning = vi.mocked(showWarningMessage); const showError = vi.mocked(vscode.window.showErrorMessage); const registrations: vscode.Disposable[] = []; @@ -83,6 +101,9 @@ describe('connection teardown', () => { beforeEach(() => { vi.resetAllMocks(); mocks.getConflictingTasks.mockReturnValue([]); + mocks.exists.mockReturnValue(true); + mocks.hasPendingStartup.mockReturnValue(false); + mocks.retireBoundViews.mockReturnValue(1); mocks.getRegisteredShellTerminals.mockReturnValue([]); mocks.getPlaygroundEvaluators.mockReturnValue(new Map()); vi.spyOn(vscode.l10n, 't').mockImplementation(l10n.t); @@ -113,6 +134,7 @@ describe('connection teardown', () => { expect(draft.dispose).not.toHaveBeenCalled(); expect(draft.disable).not.toHaveBeenCalled(); expect(remove).not.toHaveBeenCalled(); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); }, ); @@ -130,24 +152,40 @@ describe('connection teardown', () => { }); mocks.getSetting.mockReturnValue('keepOpenDisabled'); const draft = register('documentView', true); + const binding = { clusterId, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, binding.generation, reason); + return binding.generation; + }); const untouchedView = register('documentView', true, otherId); const failedDelete = new Error('Storage write failed'); + let fresh: ConnectionSurface | undefined; await expect( withConnectionRemoval([clusterId, otherId], async (remove) => { await remove(clusterId, async () => { expect(latches.get(otherId)).toBe('connectionRemoved'); expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + fresh = register('collectionView'); throw failedDelete; }); }), ).rejects.toBe(failedDelete); expect(latches.get(clusterId)).toBe('userDisconnected'); - expect(draft.disable).toHaveBeenLastCalledWith('userDisconnected'); + expect(vi.mocked(draft.disable).mock.calls).toEqual([['connectionRemoved'], ['userDisconnected']]); + expect(getRetiredBindingReason(binding)).toBe('userDisconnected'); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + expect(getBindingLifetimeSignal({ ...binding, generation: 2 }).aborted).toBe(false); + expect(getConnectionSurfaces(clusterId)).toEqual([fresh]); + expect(fresh?.disable).not.toHaveBeenCalled(); + expect(draft.isDirty?.()).toBe(true); expect(draft.dispose).not.toHaveBeenCalled(); expect(latches.has(otherId)).toBe(false); expect(untouchedView.disable).not.toHaveBeenCalled(); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); }); it('skips the choice modal when there are no surfaces and leaves preflight read-only', async () => { @@ -223,6 +261,7 @@ describe('connection teardown', () => { expect(mocks.stopPlaygroundEvaluator).not.toHaveBeenCalled(); expect(mocks.deleteClient).not.toHaveBeenCalled(); expect(refreshTree).not.toHaveBeenCalled(); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); expect(mocks.event).toHaveBeenCalledExactlyOnceWith( 'connection.disconnect', expect.objectContaining({ properties: expect.objectContaining({ blockedByTask: 'true' }) }), @@ -258,6 +297,7 @@ describe('connection teardown', () => { expect(mocks.deleteCredentials).not.toHaveBeenCalled(); expect(mocks.clearLastVerifiedIdentity).not.toHaveBeenCalled(); expect(mocks.clearEntraTokenFailure).toHaveBeenCalledExactlyOnceWith(clusterId); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); expect(refreshTree).toHaveBeenCalledOnce(); expect(mocks.event).toHaveBeenCalledExactlyOnceWith('connection.disconnect', { properties: { source: 'command', surfacesChoice: 'keepOpenDisabled', blockedByTask: 'false' }, @@ -292,4 +332,397 @@ describe('connection teardown', () => { expect(latchForTeardown([clusterId, otherId], 'connectionRemoved')).toBe(false); expect(mocks.latch).not.toHaveBeenCalled(); }); + + it.each([false, true])( + 'retires and detaches the lifetime before any surface, worker or asynchronous close (already latched: %s)', + async (alreadyLatched): Promise => { + const target = `ordered-teardown-${alreadyLatched}`; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + if (alreadyLatched) { + mocks.getLatchReason.mockReturnValue('connectionRemoved'); + } + mocks.retireBoundViews.mockImplementation((id: string, reason: 'connectionRemoved'): number => { + expect(alreadyLatched || mocks.latch.mock.calls.length === 1).toBe(true); + retireConnectionBindings(id, 1, reason); + return 1; + }); + const onRetired = vi.fn((generation: number, surfaces: readonly ConnectionSurface[]): void => { + expect(generation).toBe(1); + expect(surfaces).toEqual([draft]); + expect(signal.aborted).toBe(true); + expect(getConnectionSurfaces(target)).toEqual([]); + expect(draft.disable).not.toHaveBeenCalled(); + }); + vi.mocked(draft.disable).mockImplementation((): void => { + expect(signal.aborted).toBe(true); + expect(getConnectionSurfaces(target)).toEqual([]); + }); + const disconnect = vi.fn((): void => { + expect(signal.aborted).toBe(true); + expect(draft.disable).toHaveBeenCalledOnce(); + }); + mocks.getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId: target }, disconnect }]); + let finishClose!: () => void; + mocks.deleteClient.mockImplementation((): Promise => { + expect(signal.aborted).toBe(true); + return new Promise((resolve) => { + finishClose = resolve; + }); + }); + const teardown = commitTeardown(target, { + reason: 'connectionRemoved', + choice: 'keepOpenDisabled', + alreadyLatched, + onRetired, + refreshTree, + }); + expect(signal.aborted).toBe(true); + expect(onRetired).toHaveBeenCalledOnce(); + expect(disconnect).toHaveBeenCalledOnce(); + expect(refreshTree).not.toHaveBeenCalled(); + finishClose(); + await expect(teardown).resolves.toBe('committed'); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(draft.isDirty?.()).toBe(true); + }, + ); + + it.each(['userDisconnected', 'connectionRemoved'] as const)( + 'keeps an old dirty snapshot out of the next session %s Close all, dirty confirmation and counts', + async (reason): Promise => { + const draft = register('documentView', true); + const collection = register('collectionView'); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + const fresh = register('collectionView'); + mocks.getSetting.mockReturnValue('closeAll'); + await teardownConnection(clusterId, reason, refreshTree); + + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + expect(draft.isDirty?.()).toBe(true); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(collection.dispose).not.toHaveBeenCalled(); + expect(fresh.dispose).toHaveBeenCalledOnce(); + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.event).toHaveBeenLastCalledWith( + 'connection.disconnect', + expect.objectContaining({ measurements: expect.objectContaining({ surfaceCount: 1 }) }), + ); + }, + ); + + it.each(['surface', 'startup', 'evaluator', 'shell', 'heldClient'] as const)( + 'tears down surviving %s even when the cached connection is absent or credentials are rejected', + async (survivor): Promise => { + mocks.exists.mockReturnValue(survivor === 'heldClient'); + mocks.getLatchReason.mockReturnValue('credentialsRejected'); + const draft = survivor === 'surface' ? register('documentView', true) : undefined; + const disconnect = vi.fn(); + mocks.hasPendingStartup.mockReturnValue(survivor === 'startup'); + if (survivor === 'evaluator') { + mocks.getPlaygroundEvaluators.mockReturnValue(new Map([[clusterId, {}]])); + } + if (survivor === 'shell') { + mocks.getRegisteredShellTerminals.mockReturnValue([{ info: { clusterId }, disconnect }]); + } + await expect( + commitTeardown(clusterId, { reason: 'userDisconnected', choice: 'keepOpenDisabled', refreshTree }), + ).resolves.toBe('committed'); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); + expect(mocks.retireBoundViews).toHaveBeenCalledExactlyOnceWith(clusterId, 'userDisconnected'); + expect(mocks.deleteClient).toHaveBeenCalledOnce(); + if (draft) { + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + } + if (survivor === 'shell') { + expect(disconnect).toHaveBeenCalledOnce(); + } + }, + ); + + it.each(['userDisconnected', 'connectionRemoved', 'credentialsUpdating', undefined] as const)( + 'skips only terminal %s or a fully idle target', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + if (reason) { + register('collectionView'); + mocks.hasPendingStartup.mockReturnValue(true); + } + await expect( + commitTeardown(clusterId, { reason: 'userDisconnected', choice: 'close', refreshTree }), + ).resolves.toBe('superseded'); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.retireBoundViews).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); + + it.each(['epoch', 'laterGeneration'] as const)( + 'does not correct a failed Remove superseded by %s during storage deletion', + async (superseding): Promise => { + const target = `superseded-removal-${superseding}`; + const old = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const later = { ...old, generation: 2 }; + let epoch = 0; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation(() => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, old.generation, reason); + return old.generation; + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + const draft = register('documentView', true, target); + const oldSignal = getBindingLifetimeSignal(old); + let fresh: ConnectionSurface | undefined; + const failedDelete = new Error('Storage write failed'); + + await expect( + withConnectionRemoval([target], async (remove) => { + await remove(target, async () => { + fresh = register('collectionView', false, target); + if (superseding === 'epoch') { + epoch++; + } + retireConnectionBindings(target, later.generation, 'connectionRemoved'); + throw failedDelete; + }); + }), + ).rejects.toBe(failedDelete); + + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(latch).toBe('connectionRemoved'); + expect(getRetiredBindingReason(old)).toBe('connectionRemoved'); + expect(getRetiredBindingReason(later)).toBe('connectionRemoved'); + expect(oldSignal.aborted).toBe(true); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + expect(fresh?.disable).not.toHaveBeenCalled(); + expect(getConnectionSurfaces(target)).toEqual([fresh]); + }, + ); + + it.each(['disconnect', 'failedRemove', 'credentialsChanged'] as const)( + 'restores the still-stored connection after repeated same-generation failed Removes following %s', + async (preceding): Promise => { + const target = `repeated-removal-${preceding}`; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + let epoch = 0; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation((): ConnectionUnavailableReason | undefined => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, binding.generation, reason); + return binding.generation; + }); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + if (preceding !== 'failedRemove') { + await expect( + commitTeardown(target, { + reason: preceding === 'disconnect' ? 'userDisconnected' : 'credentialsChanged', + choice: 'keepOpenDisabled', + refreshTree, + }), + ).resolves.toBe('committed'); + } + let nextSignal: AbortSignal | undefined; + for (let attempt = 0; attempt < 2; attempt++) { + const captured = register('documentView', true, target); + const fresh: ConnectionSurface = { + clusterId: target, + kind: 'collectionView', + disable: vi.fn(), + dispose: vi.fn(), + }; + let freshRegistration: vscode.Disposable | undefined; + const failedDelete = new Error('Storage write failed'); + const deleteStored = vi.fn(async (): Promise => { + freshRegistration = registerConnectionSurface(fresh); + throw failedDelete; + }); + try { + await expect( + withConnectionRemoval([target], async (remove) => { + await remove(target, deleteStored); + }), + ).rejects.toBe(failedDelete); + + expect(deleteStored).toHaveBeenCalledOnce(); + expect(latch).toBe('userDisconnected'); + expect(getRetiredBindingReason(binding)).toBe( + preceding === 'credentialsChanged' ? 'credentialsChanged' : 'userDisconnected', + ); + expect(signal.aborted).toBe(true); + expect(getBindingLifetimeSignal(binding).aborted).toBe(true); + const currentNextSignal = getBindingLifetimeSignal({ ...binding, generation: 2 }); + expect(currentNextSignal.aborted).toBe(false); + if (nextSignal) { + expect(currentNextSignal).toBe(nextSignal); + } + nextSignal = currentNextSignal; + expect(vi.mocked(captured.disable).mock.calls).toEqual([ + ['connectionRemoved'], + ['userDisconnected'], + ]); + expect(captured.isDirty?.()).toBe(true); + expect(captured.dispose).not.toHaveBeenCalled(); + expect(fresh.disable).not.toHaveBeenCalled(); + expect(getConnectionSurfaces(target)).toEqual([fresh]); + } finally { + freshRegistration?.dispose(); + } + } + expect(draft.isDirty?.()).toBe(true); + expect(draft.dispose).not.toHaveBeenCalled(); + expect(vi.mocked(draft.disable).mock.calls).toEqual( + preceding === 'failedRemove' + ? [['connectionRemoved'], ['userDisconnected']] + : [[preceding === 'disconnect' ? 'userDisconnected' : 'credentialsChanged']], + ); + }, + ); + + it('leaves a successful Remove retirement unchanged and reports storage success only after deletion', async (): Promise => { + const target = 'successful-removal'; + const binding = { clusterId: target, fingerprint: 'same-account', generation: 1 }; + const signal = getBindingLifetimeSignal(binding); + const draft = register('documentView', true, target); + mocks.getSetting.mockReturnValue('keepOpenDisabled'); + mocks.getEpoch.mockReturnValue(1); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + mocks.getLatchReason.mockReturnValue(reason); + }); + mocks.retireBoundViews.mockImplementation((id: string, reason: EndedLifetimeReason): number => { + retireConnectionBindings(id, binding.generation, reason); + return binding.generation; + }); + const deleteStored = vi.fn(async (): Promise => { + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + expect(signal.aborted).toBe(true); + expect(mocks.clearRemovedPlaygroundConnections).not.toHaveBeenCalled(); + }); + await withConnectionRemoval([target], async (remove) => { + await remove(target, deleteStored); + }); + + expect(deleteStored).toHaveBeenCalledOnce(); + expect(getRetiredBindingReason(binding)).toBe('connectionRemoved'); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('connectionRemoved'); + expect(mocks.latch).toHaveBeenCalledExactlyOnceWith(target, 'connectionRemoved'); + expect(mocks.clearRemovedPlaygroundConnections).toHaveBeenCalledExactlyOnceWith(target); + }); + + it('clears Playground selections once per successfully deleted connection', async (): Promise => { + const targets = ['successful-removal-1', 'successful-removal-2']; + const latches = new Map(); + mocks.getEpoch.mockReturnValue(1); + mocks.getLatchReason.mockImplementation((id: string) => latches.get(id)); + mocks.latch.mockImplementation((id: string, reason: ConnectionUnavailableReason): void => { + latches.set(id, reason); + }); + mocks.getSetting.mockReturnValue('closeAll'); + const deleteStored = targets.map((_, index) => + vi.fn(async (): Promise => { + expect(mocks.clearRemovedPlaygroundConnections).toHaveBeenCalledTimes(index); + }), + ); + + await withConnectionRemoval(targets, async (remove) => { + for (const [index, target] of targets.entries()) { + await remove(target, deleteStored[index]); + } + }); + + expect(mocks.clearRemovedPlaygroundConnections.mock.calls).toEqual(targets.map((target) => [target])); + for (const storedDelete of deleteStored) { + expect(storedDelete).toHaveBeenCalledOnce(); + } + }); + + it('returns the post-Disconnect epoch only after ordinary teardown finishes', async (): Promise => { + let epoch = 7; + let latch: ConnectionUnavailableReason | undefined; + mocks.getEpoch.mockImplementation((): number => epoch); + mocks.getLatchReason.mockImplementation(() => latch); + mocks.latch.mockImplementation((_id: string, reason: ConnectionUnavailableReason): void => { + latch = reason; + epoch++; + }); + const draft = register('documentView', true); + showWarning + .mockImplementationOnce(async (_message, _options, ...items) => items[0]) + .mockImplementationOnce(async (_message, _options, ...items) => items[1]); + let finishClose!: () => void; + const closingStarted = new Promise((resolve) => { + mocks.deleteClient.mockImplementationOnce((): Promise => { + resolve(); + return new Promise((finish) => { + finishClose = finish; + }); + }); + }); + const edited = vi.fn(); + const disconnecting = ensureDisconnectedForEdit(clusterId, refreshTree); + void disconnecting.then(edited); + await closingStarted; + expect(edited).not.toHaveBeenCalled(); + expect(draft.disable).toHaveBeenCalledExactlyOnceWith('userDisconnected'); + finishClose(); + await expect(disconnecting).resolves.toBe(8); + expect(showWarning).toHaveBeenNthCalledWith( + 1, + 'Disconnect?', + { + modal: true, + detail: 'You can only update credentials or the connection string while disconnected.', + }, + 'Disconnect and update', + ); + expect(refreshTree).toHaveBeenCalledOnce(); + expect(mocks.deleteCredentials).not.toHaveBeenCalled(); + expect(mocks.clearLastVerifiedIdentity).not.toHaveBeenCalled(); + }); + + it.each(['userDisconnected', 'credentialsRejected', undefined] as const)( + 'captures the safe-idle epoch without another teardown for %s', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + mocks.getEpoch.mockReturnValue(7); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).resolves.toBe(7); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); + + it.each(['connectionRemoved', 'credentialsUpdating'] as const)( + 'does not edit a %s target even without a client', + async (reason): Promise => { + mocks.exists.mockReturnValue(false); + mocks.getLatchReason.mockReturnValue(reason); + + await expect(ensureDisconnectedForEdit(clusterId, refreshTree)).rejects.toThrow( + 'A connection is already being updated or removed. Try again when it finishes.', + ); + + expect(showWarning).not.toHaveBeenCalled(); + expect(mocks.latch).not.toHaveBeenCalled(); + expect(mocks.deleteClient).not.toHaveBeenCalled(); + }, + ); }); diff --git a/src/documentdb/connectionTeardown.ts b/src/documentdb/connectionTeardown.ts index b52147385..f6f2b86bf 100644 --- a/src/documentdb/connectionTeardown.ts +++ b/src/documentdb/connectionTeardown.ts @@ -9,14 +9,19 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; -import { getPlaygroundEvaluators, stopPlaygroundEvaluator } from '../commands/playground/executePlaygroundCode'; +import { + clearRemovedPlaygroundConnections, + getPlaygroundEvaluators, + stopPlaygroundEvaluator, +} from '../commands/playground/executePlaygroundCode'; import { SettingsService } from '../services/SettingsService'; import { checkCanProceedAndInformUser } from '../services/taskService/resourceUsageHelper'; import { TaskService } from '../services/taskService/taskService'; import { settingsKeys } from '../settingsKeys'; import { clearEntraTokenFailure } from './auth/entraErrors/entraTokenFailures'; import { ClustersClient } from './ClustersClient'; -import { getConnectionSurfaces } from './connectionSurfaces'; +import { correctFailedRemovalRetirement } from './connectionBindingRetirement'; +import { getConnectionSurfaces, takeConnectionSurfaces, type ConnectionSurface } from './connectionSurfaces'; import { CredentialCache } from './CredentialCache'; import { getRegisteredShellTerminals } from './shell/ShellTerminalLinkProvider'; @@ -33,6 +38,7 @@ export interface TeardownOptions { readonly dropCredentials?: boolean; /** A caller that fenced a batch or a save must still hold the matching latch. */ readonly alreadyLatched?: boolean; + readonly onRetired?: (generation: number, surfaces: readonly ConnectionSurface[]) => void; readonly refreshTree: () => void; } @@ -51,6 +57,56 @@ function operationName(intent: TeardownReason): string { } } +function isConnectionIdle(clusterId: string): boolean { + return ( + !ClustersClient.exists(clusterId) && + !ClustersClient.hasPendingStartup(clusterId) && + getConnectionSurfaces(clusterId).length === 0 && + !getPlaygroundEvaluators().has(clusterId) && + !getRegisteredShellTerminals().some((shell) => shell.info.clusterId === clusterId) + ); +} + +export function canSaveEdit(clusterId: string, epoch: number): boolean { + return ( + ClustersClient.getEpoch(clusterId) === epoch && + (ClustersClient.getLatchReason(clusterId) === 'userDisconnected' || isConnectionIdle(clusterId)) + ); +} + +export async function ensureDisconnectedForEdit(clusterId: string, refreshTree: () => void): Promise { + const reason = ClustersClient.getLatchReason(clusterId); + if (reason === 'connectionRemoved' || reason === 'credentialsUpdating') { + throw new Error(vscode.l10n.t('A connection is already being updated or removed. Try again when it finishes.')); + } + if (TaskService.getConflictingTasks({ clusterId }).length > 0) { + await checkCanProceedAndInformUser({ clusterId }, operationName('userDisconnected')); + throw new UserCancelledError(); + } + const epoch = ClustersClient.getEpoch(clusterId); + if (canSaveEdit(clusterId, epoch)) { + return epoch; + } + + const disconnectAndUpdate = vscode.l10n.t('Disconnect and update'); + const selected = await vscode.window.showWarningMessage( + vscode.l10n.t('Disconnect?'), + { + modal: true, + detail: vscode.l10n.t('You can only update credentials or the connection string while disconnected.'), + }, + disconnectAndUpdate, + ); + if (selected !== disconnectAndUpdate || ClustersClient.getEpoch(clusterId) !== epoch) { + throw new UserCancelledError(); + } + await teardownConnection(clusterId, 'userDisconnected', refreshTree); + if (ClustersClient.getLatchReason(clusterId) !== 'userDisconnected') { + throw new UserCancelledError(); + } + return ClustersClient.getEpoch(clusterId); +} + /** Read-only preflight. A folder can ask once for all its descendants. */ export async function confirmTeardown( target: string | readonly string[], @@ -122,15 +178,19 @@ export async function commitTeardown( clusterId: string, options: TeardownOptions, ): Promise<'committed' | 'blockedByTask' | 'superseded'> { - const { reason, choice, dropCredentials, alreadyLatched, refreshTree } = options; + const { reason, choice, dropCredentials, alreadyLatched, onRetired, refreshTree } = options; if (alreadyLatched) { if (ClustersClient.getLatchReason(clusterId) !== reason) { return 'superseded'; } } else { + const latch = ClustersClient.getLatchReason(clusterId); if ( reason === 'userDisconnected' && - (!ClustersClient.exists(clusterId) || ClustersClient.getLatchReason(clusterId)) + (latch === 'userDisconnected' || + latch === 'connectionRemoved' || + latch === 'credentialsUpdating' || + isConnectionIdle(clusterId)) ) { return 'superseded'; } @@ -141,7 +201,10 @@ export async function commitTeardown( } try { - for (const surface of getConnectionSurfaces(clusterId)) { + const generation = ClustersClient.retireBoundViews(clusterId, reason); + const surfaces = takeConnectionSurfaces(clusterId); + onRetired?.(generation, surfaces); + for (const surface of surfaces) { if (choice === 'close') { surface.dispose(); } else { @@ -195,7 +258,16 @@ async function removeConnections( properties.surfacesChoice = confirmed.choice; const targets = new Map( - clusterIds(ids).map((id) => [id, { previous: ClustersClient.getLatchReason(id), epoch: 0, started: false }]), + clusterIds(ids).map((id) => [ + id, + { + previous: ClustersClient.getLatchReason(id), + epoch: 0, + started: false, + generation: undefined as number | undefined, + surfaces: [] as readonly ConnectionSurface[], + }, + ]), ); if ( [...targets.values()].some( @@ -229,12 +301,17 @@ async function removeConnections( choice: confirmed.choice, dropCredentials: true, alreadyLatched: true, + onRetired: (generation, surfaces): void => { + target.generation = generation; + target.surfaces = surfaces; + }, refreshTree: () => {}, }); if (result !== 'committed' || ClustersClient.getEpoch(id) !== target.epoch) { throw new Error(vscode.l10n.t('The connections to remove changed. Refresh the tree and try again.')); } await deleteStored(); + clearRemovedPlaygroundConnections(id); targets.delete(id); }); } finally { @@ -247,10 +324,12 @@ async function removeConnections( } if (target.started) { // A failed storage delete must not leave the surviving connection locked as removed. - ClustersClient.latch(id, 'userDisconnected'); - if (confirmed.choice === 'keepOpenDisabled') { - for (const surface of getConnectionSurfaces(id)) { - surface.disable('userDisconnected'); + if (target.generation !== undefined && correctFailedRemovalRetirement(id, target.generation)) { + ClustersClient.latch(id, 'userDisconnected'); + if (confirmed.choice === 'keepOpenDisabled') { + for (const surface of target.surfaces) { + surface.disable('userDisconnected'); + } } } } else if (target.previous) { diff --git a/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts b/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts index 8533bd27e..5b5402a36 100644 --- a/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts +++ b/src/documentdb/playground/PlaygroundCodeLensProvider.test.ts @@ -3,9 +3,10 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import type * as vscode from 'vscode'; +import { ClustersClient } from '../ClustersClient'; import { PlaygroundCodeLensProvider } from './PlaygroundCodeLensProvider'; import { PlaygroundService } from './PlaygroundService'; import { PlaygroundCommandIds } from './constants'; @@ -31,6 +32,12 @@ function mockDocument(text: string): vscode.TextDocument { describe('PlaygroundCodeLensProvider', () => { let provider: PlaygroundCodeLensProvider; let service: PlaygroundService; + let latchTestSequence = 0; + const latchedClusterIds = new Set(); + + function uniqueLatchClusterId(prefix: string): string { + return `${prefix}-${++latchTestSequence}`; + } beforeEach(() => { service = PlaygroundService.getInstance(); @@ -38,6 +45,10 @@ describe('PlaygroundCodeLensProvider', () => { }); afterEach(() => { + for (const clusterId of latchedClusterIds) { + ClustersClient.unlatch(clusterId); + } + latchedClusterIds.clear(); provider.dispose(); service.dispose(); }); @@ -67,6 +78,62 @@ describe('PlaygroundCodeLensProvider', () => { expect(connectionLens.command?.title).toContain('MyCluster / orders'); }); + it('refreshes the connection lens immediately for an explicit disconnect and unlatch', () => { + const doc = mockDocument('db.test.find({})'); + const clusterId = uniqueLatchClusterId('playground-lens-disconnect'); + const connection = { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }; + service.setConnection(doc.uri, connection); + const refreshed = vi.fn(); + provider.onDidChangeCodeLenses(refreshed); + + latchedClusterIds.add(clusterId); + ClustersClient.latch(clusterId, 'userDisconnected'); + + expect(refreshed).toHaveBeenCalledTimes(1); + const disconnected = provider.provideCodeLenses(doc)[0]; + expect(disconnected.command).toMatchObject({ + title: '$(warning) Disconnected', + command: PlaygroundCommandIds.showConnectionInfo, + tooltip: 'This connection is disconnected. Reconnect from the tree, then run the script again.', + }); + expect(service.getConnection(doc.uri)).toBe(connection); + expect(service.isExecuting()).toBe(false); + + ClustersClient.unlatch(clusterId); + + expect(refreshed).toHaveBeenCalledTimes(2); + const reconnected = provider.provideCodeLenses(doc)[0]; + expect(reconnected.command).toMatchObject({ + title: '$(plug) MyCluster / orders', + command: PlaygroundCommandIds.showConnectionInfo, + tooltip: 'Connected to MyCluster / orders', + }); + expect(service.getConnection(doc.uri)).toBe(connection); + expect(service.isExecuting()).toBe(false); + }); + + it.each(['signInRequired', 'unreachable', 'identityChanged'] as const)( + 'keeps the normal connection lens for the %s hold', + (reason) => { + const doc = mockDocument('db.test.find({})'); + const clusterId = uniqueLatchClusterId(`playground-lens-${reason}`); + service.setConnection(doc.uri, { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }); + latchedClusterIds.add(clusterId); + + ClustersClient.latch(clusterId, reason); + + expect(provider.provideCodeLenses(doc)[0].command?.title).toBe('$(plug) MyCluster / orders'); + }, + ); + it('provides Run All lens at line 0', () => { const doc = mockDocument('db.test.find({})'); const lenses = provider.provideCodeLenses(doc); diff --git a/src/documentdb/playground/PlaygroundCodeLensProvider.ts b/src/documentdb/playground/PlaygroundCodeLensProvider.ts index 86b5b53a0..3d49ea42a 100644 --- a/src/documentdb/playground/PlaygroundCodeLensProvider.ts +++ b/src/documentdb/playground/PlaygroundCodeLensProvider.ts @@ -88,7 +88,17 @@ export class PlaygroundCodeLensProvider implements vscode.CodeLensProvider, vsco // 1. Connection status lens const displayName = service.getDisplayName(document.uri); - if (displayName) { + if (service.isUserDisconnected(document.uri)) { + lenses.push( + new vscode.CodeLens(topRange, { + title: `$(warning) ${l10n.t('Disconnected')}`, + command: PlaygroundCommandIds.showConnectionInfo, + tooltip: l10n.t( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + ), + }), + ); + } else if (displayName) { lenses.push( new vscode.CodeLens(topRange, { title: `$(plug) ${displayName}`, diff --git a/src/documentdb/playground/PlaygroundEvaluator.test.ts b/src/documentdb/playground/PlaygroundEvaluator.test.ts index ca56a3536..73ee534b4 100644 --- a/src/documentdb/playground/PlaygroundEvaluator.test.ts +++ b/src/documentdb/playground/PlaygroundEvaluator.test.ts @@ -523,6 +523,63 @@ describe('PlaygroundEvaluator token relay lifecycle', () => { }, ); + it('does not replay or rebind an old evaluation after Disconnect replaces its worker', async (): Promise => { + await initializeSession(AuthMethodId.MicrosoftEntraID); + await requestToken({ type: 'tokenRequest', requestId: 'pin' }); + mocks.worker.isConnectedTo.mockReturnValue(true); + const capture = vi.fn(); + await evaluator.evaluate(connection, 'bind', undefined, capture); + const binding = capture.mock.calls[0][0] as PlaygroundWorkerBinding; + const bound = { ...connection, ...binding }; + + let rejectOld!: (error: Error) => void; + mocks.worker.sendEval.mockImplementationOnce( + () => + new Promise((_resolve, reject) => { + rejectOld = reject; + }), + ); + const oldRun = evaluator.evaluate(bound, 'old'); + const oldOutcome = expect(oldRun).rejects.toThrow('Worker terminated'); + await vi.waitFor(() => + expect(mocks.worker.sendEval.mock.calls.at(-1)?.[0]).toMatchObject({ type: 'eval', code: 'old' }), + ); + + try { + ClustersClient.latch(clusterId, 'userDisconnected'); + evaluator.killWorker(); + ClustersClient.unlatch(clusterId); + mocks.worker.isConnectedTo.mockReturnValue(false); + mocks.getCredentials.mockReturnValue({ + clusterId, + connectionString: originalConnection, + authMechanism: AuthMethodId.MicrosoftEntraID, + entraIdConfig: { tenantId: 'interactive-tenant' }, + }); + await evaluator.evaluate(bound, 'new'); + mocks.worker.isConnectedTo.mockReturnValue(true); + + rejectOld(new Error('Worker terminated')); + await oldOutcome; + const response = await requestToken({ type: 'tokenRequest', requestId: 'replacement-token' }); + expect(response).toHaveBeenCalledExactlyOnceWith({ + type: 'tokenResponse', + requestId: 'replacement-token', + accessToken, + }); + expect( + mocks.worker.sendEval.mock.calls.map(([message]) => message.type === 'eval' && message.code), + ).toEqual(['1', 'bind', 'old', 'new']); + expect(mocks.interactiveToken.mock.calls.at(-1)?.[2]).toEqual({ + silent: true, + account: { id: 'private-account', label: accountLabel }, + }); + } finally { + ClustersClient.unlatch(clusterId); + mocks.getCredentials.mockClear(); + } + }); + it.each([AuthMethodId.MicrosoftEntraID, AuthMethodId.ManagedIdentity])( 'uses the captured %s identity and original connection despite forged request fields', async (authMethod): Promise => { diff --git a/src/documentdb/playground/PlaygroundService.test.ts b/src/documentdb/playground/PlaygroundService.test.ts index b6c6de60d..868587a0a 100644 --- a/src/documentdb/playground/PlaygroundService.test.ts +++ b/src/documentdb/playground/PlaygroundService.test.ts @@ -13,6 +13,7 @@ import * as vscode from 'vscode'; import { ClustersClient } from '../ClustersClient'; import { CredentialCache } from '../CredentialCache'; +import { PLAYGROUND_LANGUAGE_ID, PlaygroundCommandIds } from './constants'; vi.mock('../CredentialCache', () => ({ CredentialCache: { hasCredentials: vi.fn() }, @@ -22,9 +23,20 @@ const hasCredentialsMock = CredentialCache.hasCredentials as Mock; describe('PlaygroundService', () => { let service: PlaygroundService; + let latchTestSequence = 0; + const latchedClusterIds = new Set(); const mockUri = { toString: () => 'untitled:playground-1.documentdb.js' } as vscode.Uri; + function latch(clusterId: string, reason: Parameters[1]): void { + latchedClusterIds.add(clusterId); + ClustersClient.latch(clusterId, reason); + } + + function uniqueLatchClusterId(prefix: string): string { + return `${prefix}-${++latchTestSequence}`; + } + function getCloseDocHandler(): (doc: Partial) => void { const calls = vi.mocked(vscode.workspace.onDidCloseTextDocument).mock.calls; return calls[calls.length - 1][0]; @@ -41,7 +53,12 @@ describe('PlaygroundService', () => { }); afterEach(() => { + for (const clusterId of latchedClusterIds) { + ClustersClient.unlatch(clusterId); + } + latchedClusterIds.clear(); service.dispose(); + Object.assign(vscode.window, { activeTextEditor: undefined }); vi.restoreAllMocks(); }); @@ -90,6 +107,48 @@ describe('PlaygroundService', () => { expect(service.getConnection(mockUri)).toBeUndefined(); }); + it('clears only removed-cluster selections and remembered bindings with one state change', () => { + const matchingUri = { toString: () => 'untitled:playground-2.documentdb.js' } as vscode.Uri; + const otherUri = { toString: () => 'untitled:playground-3.documentdb.js' } as vscode.Uri; + const otherConnection: PlaygroundConnection = { + clusterId: 'cluster-456', + clusterDisplayName: 'OtherCluster', + databaseName: 'products', + }; + const doc = { + uri: mockUri, + languageId: PLAYGROUND_LANGUAGE_ID, + getText: () => 'db.orders.find({})', + } as vscode.TextDocument; + Object.assign(vscode.window, { activeTextEditor: { document: doc } as vscode.TextEditor }); + service.setConnection(mockUri, connection); + service.setConnection(matchingUri, connection); + service.setConnection(otherUri, otherConnection); + getCloseDocHandler()({ uri: matchingUri, languageId: PLAYGROUND_LANGUAGE_ID }); + const listener = vi.fn(); + service.onDidChangeState(listener); + const statusBar = vi.mocked(vscode.window.createStatusBarItem).mock.results.at(-1) + ?.value as vscode.StatusBarItem; + hasCredentialsMock.mockReturnValue(true); + hasCredentialsMock.mockClear(); + + service.removeConnectionsForCluster(connection.clusterId); + + expect(service.getConnection(mockUri)).toBeUndefined(); + expect(service.getConnection(matchingUri)).toBeUndefined(); + expect(service.getConnection(otherUri)).toBe(otherConnection); + expect(listener).toHaveBeenCalledTimes(1); + expect(statusBar.command).toBe(PlaygroundCommandIds.connect); + expect(statusBar.text).toBe('$(warning) Connect database'); + expect(statusBar.tooltip).toBe('This playground has no connection. Click to connect it to a database.'); + expect(doc.getText()).toBe('db.orders.find({})'); + + getOpenDocHandler()({ uri: matchingUri, languageId: PLAYGROUND_LANGUAGE_ID }); + + expect(service.getConnection(matchingUri)).toBeUndefined(); + expect(hasCredentialsMock).not.toHaveBeenCalled(); + }); + it('fires onDidChangeState on setConnection', () => { const listener = vi.fn(); service.onDidChangeState(listener); @@ -260,6 +319,73 @@ describe('PlaygroundService', () => { // The StatusBarItem is created in the constructor; verify it was configured expect(vscode.window.createStatusBarItem).toHaveBeenCalledWith(vscode.StatusBarAlignment.Left, 100); }); + + it('immediately presents an explicit disconnect and restores the normal display on unlatch', () => { + const clusterId = uniqueLatchClusterId('playground-status-disconnect'); + const connection: PlaygroundConnection = { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }; + const doc = { + uri: mockUri, + languageId: PLAYGROUND_LANGUAGE_ID, + getText: () => 'db.orders.find({})', + } as vscode.TextDocument; + Object.assign(vscode.window, { activeTextEditor: { document: doc } as vscode.TextEditor }); + const statusBar = vi.mocked(vscode.window.createStatusBarItem).mock.results.at(-1) + ?.value as vscode.StatusBarItem; + service.setConnection(mockUri, connection); + const stateChanged = vi.fn(); + service.onDidChangeState(stateChanged); + + latch(clusterId, 'userDisconnected'); + + expect(stateChanged).toHaveBeenCalledTimes(1); + expect(statusBar.text).toBe('$(warning) Disconnected'); + expect(statusBar.tooltip).toBe( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + ); + expect(statusBar.command).toBe(PlaygroundCommandIds.showConnectionInfo); + expect(service.getConnection(mockUri)).toBe(connection); + expect(service.isConnected(mockUri)).toBe(true); + expect(service.isExecuting()).toBe(false); + expect(doc.getText()).toBe('db.orders.find({})'); + + ClustersClient.unlatch(clusterId); + + expect(stateChanged).toHaveBeenCalledTimes(2); + expect(statusBar.text).toBe('$(plug) MyCluster / orders'); + expect(statusBar.tooltip).toBe('Query Playground connected to MyCluster / orders'); + expect(service.getConnection(mockUri)).toBe(connection); + expect(service.isExecuting()).toBe(false); + }); + + it.each(['signInRequired', 'unreachable', 'identityChanged'] as const)( + 'does not label the %s hold as an explicit disconnect', + (reason) => { + const clusterId = uniqueLatchClusterId(`playground-status-${reason}`); + const connection: PlaygroundConnection = { + clusterId, + clusterDisplayName: 'MyCluster', + databaseName: 'orders', + }; + Object.assign(vscode.window, { + activeTextEditor: { + document: { uri: mockUri, languageId: PLAYGROUND_LANGUAGE_ID }, + } as vscode.TextEditor, + }); + const statusBar = vi.mocked(vscode.window.createStatusBarItem).mock.results.at(-1) + ?.value as vscode.StatusBarItem; + service.setConnection(mockUri, connection); + + latch(clusterId, reason); + + expect(service.isUserDisconnected(mockUri)).toBe(false); + expect(statusBar.text).toBe('$(plug) MyCluster / orders'); + expect(statusBar.tooltip).toBe('Query Playground connected to MyCluster / orders'); + }, + ); }); describe('onDidCloseTextDocument cleanup', () => { diff --git a/src/documentdb/playground/PlaygroundService.ts b/src/documentdb/playground/PlaygroundService.ts index 814123b4a..1c88efe7c 100644 --- a/src/documentdb/playground/PlaygroundService.ts +++ b/src/documentdb/playground/PlaygroundService.ts @@ -94,6 +94,12 @@ export class PlaygroundService implements vscode.Disposable { }), ); + this._disposables.push( + ClustersClient.onDidChangeLatch(() => { + this._onDidChangeState.fire(); + }), + ); + // Clean up connection when a playground document is closed. this._disposables.push( vscode.workspace.onDidCloseTextDocument((doc) => { @@ -233,6 +239,24 @@ export class PlaygroundService implements vscode.Disposable { this._onDidChangeState.fire(); } + public removeConnectionsForCluster(clusterId: string): void { + let clearedSelection = false; + for (const [key, connection] of this._connections) { + if (connection.clusterId === clusterId) { + this._connections.delete(key); + clearedSelection = true; + } + } + for (const [key, connection] of this._lastBindingByPath) { + if (connection.clusterId === clusterId) { + this._lastBindingByPath.delete(key); + } + } + if (clearedSelection) { + this._onDidChangeState.fire(); + } + } + /** * Re-key a connection onto a freshly saved `file:` playground. * @@ -311,6 +335,11 @@ export class PlaygroundService implements vscode.Disposable { return this._connections.get(uri.toString()); } + isUserDisconnected(uri: vscode.Uri): boolean { + const connection = this.getConnection(uri); + return connection !== undefined && ClustersClient.getLatchReason(connection.clusterId) === 'userDisconnected'; + } + /** * Attempt a silent, in-session restore of a previously remembered binding for * a reopened playground. No-ops unless: the document is currently unbound, @@ -416,7 +445,13 @@ export class PlaygroundService implements vscode.Disposable { } const displayName = this.getDisplayName(editor.document.uri); - if (displayName) { + if (this.isUserDisconnected(editor.document.uri)) { + this._statusBarItem.command = PlaygroundCommandIds.showConnectionInfo; + this._statusBarItem.text = `$(warning) ${l10n.t('Disconnected')}`; + this._statusBarItem.tooltip = l10n.t( + 'This connection is disconnected. Reconnect from the tree, then run the script again.', + ); + } else if (displayName) { this._statusBarItem.command = PlaygroundCommandIds.showConnectionInfo; this._statusBarItem.text = `$(plug) ${displayName}`; this._statusBarItem.tooltip = l10n.t('Query Playground connected to {0}', displayName); diff --git a/src/documentdb/playground/WorkerSessionManager.test.ts b/src/documentdb/playground/WorkerSessionManager.test.ts index cdfdfdf30..fe9695267 100644 --- a/src/documentdb/playground/WorkerSessionManager.test.ts +++ b/src/documentdb/playground/WorkerSessionManager.test.ts @@ -1375,6 +1375,81 @@ describe('WorkerSessionManager', () => { }, ); + it('does not deliver a held token reply after Disconnect replaces the worker', async (): Promise => { + let releaseOldReply!: () => void; + const oldReply = new Promise((resolve) => { + releaseOldReply = resolve; + }); + const onTokenRequest = vi.fn>( + async (message, postResponse) => { + if (message.requestId === 'old-token') { + await oldReply; + } + postResponse({ + type: 'tokenResponse', + requestId: message.requestId, + accessToken: `${message.requestId}-access-token`, + }); + }, + ); + callbacks.onTokenRequest = onTokenRequest; + const manager = new WorkerSessionManager(callbacks); + try { + const old = await startWorker(true, {}, manager); + old.worker._emit('message', { + type: 'initResult', + requestId: old.requestId, + success: true, + }); + await old.initPromise; + + old.worker._emit('message', { type: 'tokenRequest', requestId: 'old-token' }); + await vi.waitFor(() => expect(onTokenRequest).toHaveBeenCalledTimes(1)); + + ClustersClient.latch('test-cluster', 'userDisconnected'); + manager.killWorker(); + ClustersClient.unlatch('test-cluster'); + + const replacement = await startWorker(true, {}, manager); + replacement.worker._emit('message', { + type: 'initResult', + requestId: replacement.requestId, + success: true, + }); + await replacement.initPromise; + + releaseOldReply(); + await onTokenRequest.mock.results[0].value; + const postMessage = ( + workerThreads as unknown as { + _mockPostMessage: Mock; + } + )._mockPostMessage; + const tokenReplies = (): MainToWorkerMessage[] => + postMessage.mock.calls + .map(([message]) => message as MainToWorkerMessage) + .filter((message) => message.type === 'tokenResponse'); + expect(tokenReplies()).toEqual([]); + + replacement.worker._emit('message', { + type: 'tokenRequest', + requestId: 'replacement-token', + }); + await onTokenRequest.mock.results[1].value; + expect(tokenReplies()).toEqual([ + { + type: 'tokenResponse', + requestId: 'replacement-token', + accessToken: 'replacement-token-access-token', + }, + ]); + expect(manager.isAlive).toBe(true); + } finally { + ClustersClient.unlatch('test-cluster'); + manager.dispose(); + } + }); + it.each(['returned', 'failed'] as const)( 'cancels a still-attached worker when an invalidated token lookup %s', async (outcome): Promise => { diff --git a/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts b/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts index 3c3f070b6..2585791fe 100644 --- a/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts +++ b/src/documentdb/query-language/playground-completions/tdd/dynamicSchemaIntegration.test.ts @@ -3,7 +3,8 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { afterAll, beforeEach, describe, expect, test, vi, type Mock } from 'vitest'; +import { afterAll, beforeAll, beforeEach, describe, expect, test, vi, type Mock } from 'vitest'; +import { type Disposable, type Event } from 'vscode'; /** * TDD Behavior Tests — Dynamic Schema Integration (WI-3) @@ -39,6 +40,10 @@ const TEST_CONNECTION = { databaseName: 'testdb', }; +const onDidChangeLatch: Event = (_listener: (event: string) => unknown): Disposable => ({ + dispose: vi.fn(), +}); + // ===================================================================== // Tests: CollectionNameCache // ===================================================================== @@ -46,6 +51,13 @@ const TEST_CONNECTION = { describe('TDD: CollectionNameCache', () => { let cache: CollectionNameCache; + beforeAll(() => { + Object.defineProperty(ClustersClient, 'onDidChangeLatch', { + configurable: true, + get: (): Event => onDidChangeLatch, + }); + }); + beforeEach(() => { // Reset singleton for isolation CollectionNameCache.getInstance().dispose(); diff --git a/src/documentdb/runWithClient.ts b/src/documentdb/runWithClient.ts index 30c370542..70906fb25 100644 --- a/src/documentdb/runWithClient.ts +++ b/src/documentdb/runWithClient.ts @@ -54,6 +54,7 @@ export async function runWithClient( } try { + ClustersClient.assertBindingActive(binding); return await op(client); } catch (error) { // Resolution can advance the generation without changing the surface's identity. diff --git a/src/documentdb/shell/DocumentDBShellPty.test.ts b/src/documentdb/shell/DocumentDBShellPty.test.ts index a6d58338c..a07d9daa6 100644 --- a/src/documentdb/shell/DocumentDBShellPty.test.ts +++ b/src/documentdb/shell/DocumentDBShellPty.test.ts @@ -29,6 +29,7 @@ const mockSessionTelemetry: Record[] = []; const workerSignIn = vi.hoisted(() => ({ canRecover: vi.fn(), recover: vi.fn(), + fingerprint: undefined as string | undefined, pin: undefined as | { kind: 'entra'; @@ -132,6 +133,9 @@ vi.mock('./ShellSessionManager', () => ({ setActiveDatabase: mockSetActiveDatabase, resetAfterSignIn: mockResetAfterSignIn, pinnedEntraIdentity: workerSignIn.pin, + get fingerprint(): string | undefined { + return workerSignIn.fingerprint; + }, isInitialized: true, getBlockingLatchReason: (): ReturnType => { const reason = ClustersClient.getLatchReason(connectionInfo.clusterId); @@ -165,6 +169,7 @@ describe('DocumentDBShellPty', () => { vi.clearAllMocks(); mockSessionTelemetry.length = 0; workerSignIn.pin = undefined; + workerSignIn.fingerprint = undefined; workerSignIn.canRecover.mockReturnValue(false); written = ''; closeCode = undefined; @@ -216,6 +221,70 @@ describe('DocumentDBShellPty', () => { vi.restoreAllMocks(); }); + describe('Playground handoff origins', () => { + it('has no origin before the shell learns its fingerprint', (): void => { + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + }); + + it('keeps the original pin and live origin through host-only same-account repair', (): void => { + pty.close(); + workerSignIn.pin = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'original-account', + accountLabel: 'Original account', + tenantId: 'tenant', + }; + workerSignIn.fingerprint = 'original-fingerprint'; + pty = new DocumentDBShellPty(defaultOptions); + const origin = pty.getPlaygroundOrigin(); + expect(origin).toMatchObject({ + kind: 'shell', + fingerprint: 'original-fingerprint', + entraIdentity: workerSignIn.pin, + }); + ClustersClient.invalidate(defaultOptions.connectionInfo.clusterId); + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(true); + expect(pty.getTerminalInfo().getPlaygroundOrigin?.()).toMatchObject({ + kind: 'shell', + fingerprint: 'original-fingerprint', + }); + }); + + it('retires captured origins and terminal-info callbacks when the shell closes', (): void => { + workerSignIn.fingerprint = 'current-fingerprint'; + const origin = pty.getPlaygroundOrigin(); + const getPlaygroundOrigin = pty.getTerminalInfo().getPlaygroundOrigin; + + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(true); + expect(getPlaygroundOrigin?.()).toMatchObject({ + kind: 'shell', + fingerprint: 'current-fingerprint', + }); + + pty.close(); + + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(false); + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + expect(getPlaygroundOrigin?.()).toEqual({ kind: 'none' }); + }); + + it('permanently retires old and newly rescanned origins after explicit disconnect without a host client', (): void => { + workerSignIn.fingerprint = 'password-identity-fingerprint'; + const host = vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(undefined); + const origin = pty.getPlaygroundOrigin(); + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(true); + pty.disconnect(); + expect(origin.kind === 'shell' && origin.isCurrent()).toBe(false); + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + // Restarting the worker cannot make this old terminal's scrollback a new origin. + workerSignIn.fingerprint = 'password-identity-fingerprint'; + expect(pty.getTerminalInfo().getPlaygroundOrigin?.()).toEqual({ kind: 'none' }); + expect(host).not.toHaveBeenCalled(); + expect(mockKillWorker).toHaveBeenCalledOnce(); + }); + }); + describe('unauthenticated isolation', () => { const unauthenticated: UnauthenticatedShellEndpoint = { connectionString: 'mongodb://anonymous-host/', @@ -260,6 +329,12 @@ describe('DocumentDBShellPty', () => { written = ''; } + it('never exposes a saved-auth Playground origin from the diagnostic shell', (): void => { + workerSignIn.fingerprint = 'saved-auth-fingerprint'; + expect(pty.getPlaygroundOrigin()).toEqual({ kind: 'none' }); + expect(pty.getTerminalInfo().getPlaygroundOrigin?.()).toEqual({ kind: 'none' }); + }); + 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(); diff --git a/src/documentdb/shell/DocumentDBShellPty.ts b/src/documentdb/shell/DocumentDBShellPty.ts index 24689d7a4..0fa3d60ba 100644 --- a/src/documentdb/shell/DocumentDBShellPty.ts +++ b/src/documentdb/shell/DocumentDBShellPty.ts @@ -7,6 +7,7 @@ import { callWithTelemetryAndErrorHandling, UserCancelledError } from '@microsof import * as l10n from '@vscode/l10n'; import { randomUUID } from 'crypto'; import * as vscode from 'vscode'; +import { type PlaygroundHandoffOrigin } from '../../commands/playground/newPlayground'; import { canSignInAgainForWorker, signInAgainForWorker } from '../../commands/signInAgain/signInAgain'; import { type DeepLinkTelemetry, trackDeepLinkTelemetry } from '../../deepLinks/deepLinkTelemetry'; import { ext } from '../../extensionVariables'; @@ -325,6 +326,19 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { /** * Returns current shell metadata for the terminal link provider and debug stats. */ + getPlaygroundOrigin(): PlaygroundHandoffOrigin { + const fingerprint = this._sessionManager.fingerprint; + if (this._closed || this._unauthenticated || !fingerprint || this._disconnectRevision > 0) { + return { kind: 'none' }; + } + return { + kind: 'shell', + fingerprint, + entraIdentity: this._sessionManager.pinnedEntraIdentity, + isCurrent: () => !this._closed && this._disconnectRevision === 0, + }; + } + getTerminalInfo(): ShellTerminalInfo { return { clusterId: this._connectionInfo.clusterId, @@ -335,6 +349,7 @@ export class DocumentDBShellPty implements vscode.Pseudoterminal { workerState: this._sessionManager.workerState, authMethod: this._sessionManager.authMethod, username: this._username, + getPlaygroundOrigin: () => this.getPlaygroundOrigin(), }; } diff --git a/src/documentdb/shell/ShellSessionManager.test.ts b/src/documentdb/shell/ShellSessionManager.test.ts index d486e86b2..33cd2c9fc 100644 --- a/src/documentdb/shell/ShellSessionManager.test.ts +++ b/src/documentdb/shell/ShellSessionManager.test.ts @@ -513,6 +513,29 @@ describe('ShellSessionManager', () => { manager.dispose(); }); + it('retains the worker-learned fingerprint and Entra pin across a worker restart', async (): Promise => { + const manager = new ShellSessionManager({ clusterId, clusterDisplayName: 'Cluster', databaseName: 'test' }); + requestTokenOnInit = true; + mockGetSessionFromVSCode.mockResolvedValue({ + accessToken: 'private-token', + account: { id: 'account-a', label: 'Account A' }, + }); + try { + await manager.initialize(); + const fingerprint = manager.fingerprint; + const pin = manager.pinnedEntraIdentity; + expect(fingerprint).toEqual(expect.any(String)); + expect(pin).toMatchObject({ accountId: 'account-a' }); + manager.killWorker(); + ClustersClient.invalidate(clusterId); + await manager.initialize(); + expect(manager.fingerprint).toBe(fingerprint); + expect(manager.pinnedEntraIdentity).toEqual(pin); + } finally { + manager.dispose(); + } + }); + async function initializeSession( manager: ShellSessionManager | PlaygroundEvaluator, source?: 'vscode' | 'managedIdentity', diff --git a/src/documentdb/shell/ShellSessionManager.ts b/src/documentdb/shell/ShellSessionManager.ts index 88cccc227..233728a6a 100644 --- a/src/documentdb/shell/ShellSessionManager.ts +++ b/src/documentdb/shell/ShellSessionManager.ts @@ -216,6 +216,10 @@ export class ShellSessionManager implements vscode.Disposable { return this._pin; } + get fingerprint(): string | undefined { + return this._fingerprint; + } + /** Accept only the same verified account; the next command reconnects and runs once. */ public resetAfterSignIn(identity: VerifiedEntraIdentity, epoch: number): void { this.assertConnectionAvailable(); diff --git a/src/documentdb/shell/ShellTerminalLinkProvider.test.ts b/src/documentdb/shell/ShellTerminalLinkProvider.test.ts index dbd2a065a..413ce94f4 100644 --- a/src/documentdb/shell/ShellTerminalLinkProvider.test.ts +++ b/src/documentdb/shell/ShellTerminalLinkProvider.test.ts @@ -5,9 +5,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { createTestActionContext } from '@microsoft/vscode-azext-utils'; import { EJSON } from 'bson'; +import { createTextDocument } from 'jest-mock-vscode'; import * as vscode from 'vscode'; import { HelpProvider } from '../../../packages/documentdb-js-shell-runtime/src/HelpProvider'; +import { newPlaygroundWithContent, type NewPlaygroundWithContentParams } from '../../commands/playground/newPlayground'; +import { ClustersClient } from '../ClustersClient'; +import { PlaygroundService } from '../playground/PlaygroundService'; +import { PLAYGROUND_LANGUAGE_ID } from '../playground/constants'; import { ShellOutputFormatter } from './ShellOutputFormatter'; import { ACTION_LINE_PREFIX, @@ -495,6 +501,7 @@ describe('ShellTerminalLinkProvider', () => { clusterId: 'my-cluster', databaseName: 'mydb', content: "db.getCollection('users').find({ })", + origin: { kind: 'none' }, }), ); spy.mockRestore(); @@ -504,6 +511,165 @@ describe('ShellTerminalLinkProvider', () => { }); }); + describe('Playground origin effects', () => { + let sequence = 0; + let service: PlaygroundService; + let document: vscode.TextDocument; + const identity = { + kind: 'entra', + providerId: 'microsoft', + accountId: 'original-account', + accountLabel: 'Original account', + tenantId: 'tenant', + } as const; + + beforeEach((): void => { + sequence++; + const uri = vscode.Uri.parse(`untitled:shell-handoff-${sequence}.documentdb.js`); + document = createTextDocument(uri, "db.getCollection('users').find({})", PLAYGROUND_LANGUAGE_ID); + vi.spyOn(vscode.Uri, 'file').mockReturnValue(uri); + vi.spyOn(vscode.workspace, 'applyEdit').mockClear().mockResolvedValue(true); + vi.spyOn(vscode.workspace, 'openTextDocument').mockClear().mockResolvedValue(document); + vi.spyOn(vscode.window, 'showTextDocument') + .mockClear() + .mockResolvedValue({ document } as vscode.TextEditor); + vi.spyOn(vscode.window, 'showWarningMessage').mockClear().mockResolvedValue(undefined); + vi.spyOn(ClustersClient, 'getBinding').mockReturnValue(undefined); + vi.spyOn(ClustersClient, 'getExpectedFingerprint').mockReturnValue('original'); + service = PlaygroundService.getInstance(); + vi.spyOn(service, 'setConnectionFromHost'); + vi.spyOn(service, 'removeConnection'); + vi.spyOn(vscode.commands, 'executeCommand') + .mockClear() + .mockImplementation(async (_command, ...args) => { + await newPlaygroundWithContent( + await createTestActionContext(), + args[0] as NewPlaygroundWithContentParams, + ); + return undefined; + }); + }); + + afterEach((): void => { + service.dispose(); + vi.restoreAllMocks(); + }); + + it.each(['open', 'show'] as const)( + 'leaves a retained Shell draft unbound when %s pauses across password-only teardown', + async (boundary): Promise => { + let current = true; + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + if (boundary === 'open') { + vi.mocked(vscode.workspace.openTextDocument).mockImplementationOnce(async () => { + await pause; + return document; + }); + } else { + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document } as vscode.TextEditor; + }); + } + const getOrigin = vi.fn(() => ({ + kind: 'shell' as const, + fingerprint: 'original', + entraIdentity: identity, + isCurrent: () => current, + })); + registerShellTerminal(mockTerminal, () => ({ + ...mockShellInfo('shell-cluster'), + getPlaygroundOrigin: getOrigin, + })); + const [link] = provider.provideTerminalLinks({ + terminal: mockTerminal, + line: `${PLAYGROUND_ACTION_PREFIX}[mydb.users]`, + } as vscode.TerminalLinkContext); + expect(getOrigin).not.toHaveBeenCalled(); + provider.handleTerminalLink(link); + expect(getOrigin).toHaveBeenCalledOnce(); + await vi.waitFor(() => + expect( + boundary === 'open' ? vscode.workspace.openTextDocument : vscode.window.showTextDocument, + ).toHaveBeenCalledOnce(), + ); + current = false; + release(); + await vi.waitFor(() => expect(vscode.window.showWarningMessage).toHaveBeenCalledOnce()); + + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(service.getConnection(document.uri)).toBeUndefined(); + expect(vscode.window.showTextDocument).toHaveBeenCalledWith(document, { preview: true }); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + }, + ); + + it('captures an old link at click time and never falls back to saved authentication', async (): Promise => { + let ended = false; + registerShellTerminal(mockTerminal, () => ({ + ...mockShellInfo('shell-cluster'), + getPlaygroundOrigin: () => + ended + ? { kind: 'none' } + : { kind: 'shell', fingerprint: 'original', entraIdentity: identity, isCurrent: () => !ended }, + })); + const [link] = provider.provideTerminalLinks({ + terminal: mockTerminal, + line: `${PLAYGROUND_ACTION_PREFIX}[mydb.users]`, + } as vscode.TerminalLinkContext); + ended = true; + provider.handleTerminalLink(link); + await vi.waitFor(() => expect(vscode.window.showTextDocument).toHaveBeenCalledOnce()); + await vi.waitFor(() => expect(service.removeConnection).toHaveBeenCalledExactlyOnceWith(document.uri)); + expect(service.getConnection(document.uri)).toBeUndefined(); + expect(service.setConnectionFromHost).not.toHaveBeenCalled(); + expect(ClustersClient.getExpectedFingerprint).not.toHaveBeenCalled(); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + }); + + it('preserves the original Shell pin through host-only repair during display', async (): Promise => { + let release!: () => void; + const pause = new Promise((resolve): void => { + release = resolve; + }); + vi.mocked(vscode.window.showTextDocument).mockImplementationOnce(async () => { + await pause; + return { document } as vscode.TextEditor; + }); + registerShellTerminal(mockTerminal, () => ({ + ...mockShellInfo('shell-cluster'), + getPlaygroundOrigin: () => ({ + kind: 'shell', + fingerprint: 'original', + entraIdentity: identity, + isCurrent: () => true, + }), + })); + const [link] = provider.provideTerminalLinks({ + terminal: mockTerminal, + line: `${PLAYGROUND_ACTION_PREFIX}[mydb.users]`, + } as vscode.TerminalLinkContext); + provider.handleTerminalLink(link); + await vi.waitFor(() => expect(vscode.window.showTextDocument).toHaveBeenCalledOnce()); + ClustersClient.invalidate('shell-cluster'); + vi.mocked(ClustersClient.getBinding).mockReturnValue({ + clusterId: 'shell-cluster', + fingerprint: 'original', + generation: 2, + }); + release(); + await vi.waitFor(() => expect(service.setConnectionFromHost).toHaveBeenCalledOnce()); + expect(service.getConnection(document.uri)).toMatchObject({ + fingerprint: 'original', + entraIdentity: identity, + }); + expect(vscode.commands.executeCommand).toHaveBeenCalledOnce(); + }); + }); + describe('registry', () => { it('should not match after terminal is unregistered', () => { registerShellTerminal(mockTerminal, () => mockShellInfo('test-id')); diff --git a/src/documentdb/shell/ShellTerminalLinkProvider.ts b/src/documentdb/shell/ShellTerminalLinkProvider.ts index 0a404eca1..60c8d8cdc 100644 --- a/src/documentdb/shell/ShellTerminalLinkProvider.ts +++ b/src/documentdb/shell/ShellTerminalLinkProvider.ts @@ -5,6 +5,7 @@ import { callWithTelemetryAndErrorHandling, type IActionContext } from '@microsoft/vscode-azext-utils'; import * as vscode from 'vscode'; +import { type PlaygroundHandoffOrigin } from '../../commands/playground/newPlayground'; import { settingsKeys } from '../../settingsKeys'; import { escapeJsString } from '../../utils/escapeJsString'; import { PlaygroundCommandIds } from '../playground/constants'; @@ -15,6 +16,7 @@ import { Views } from '../Views'; * for the link provider and debug stats command. */ export interface ShellTerminalInfo { + readonly getPlaygroundOrigin?: () => PlaygroundHandoffOrigin; /** Stable cluster ID for CredentialCache and session lookups. */ readonly clusterId: string; /** Human-readable cluster display name. */ @@ -184,6 +186,7 @@ interface CollectionViewTerminalLink extends vscode.TerminalLink { * Terminal link that opens a Query Playground. */ interface PlaygroundTerminalLink extends vscode.TerminalLink { + readonly terminal?: vscode.Terminal; readonly linkType: 'playground'; /** Cluster ID for the playground connection. */ readonly clusterId: string; @@ -256,6 +259,7 @@ export class ShellTerminalLinkProvider implements vscode.TerminalLinkProvider { @@ -320,6 +326,7 @@ export class ShellTerminalLinkProvider implements vscode.TerminalLinkProvider { selectChatModelsMock.mockReset(); }); + describe('CopilotService.sendMessage cancellation during model selection', () => { + it.each(['request-abort', 'host-retirement', 'live-control'] as const)( + 'fences the actual model sendRequest across paused model selection: %s', + async (cancellation): Promise => { + selectChatModelsMock.mockReset(); + let releaseSelection!: (models: unknown[]) => void; + selectChatModelsMock.mockReturnValueOnce( + new Promise((resolve): void => { + releaseSelection = resolve; + }), + ); + const binding = { + clusterId: `copilot-model-selection-${cancellation}`, + fingerprint: 'original', + generation: 1, + }; + const controller = new AbortController(); + const signal = AbortSignal.any([getBindingLifetimeSignal(binding), controller.signal]); + const sendRequest = vi.fn().mockResolvedValue({ + text: (async function* (): AsyncGenerator { + yield 'Synthetic response'; + })(), + }); + const model = { ...(makeFakeModel([]) as object), sendRequest }; + const pending = CopilotService.sendMessage([makeUserMessage('Synthetic query context') as never], { + featureSource: 'queryGeneration', + signal, + }); + expect(selectChatModelsMock).toHaveBeenCalledExactlyOnceWith({ + vendor: 'copilot', + family: 'copilot-utility', + }); + if (cancellation === 'request-abort') { + controller.abort(); + } else if (cancellation === 'host-retirement') { + retireConnectionBindings(binding.clusterId, binding.generation, 'credentialsChanged'); + } + releaseSelection([model]); + + if (cancellation === 'live-control') { + await expect(pending).resolves.toMatchObject({ text: 'Synthetic response' }); + expect(sendRequest).toHaveBeenCalledOnce(); + } else { + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(sendRequest).not.toHaveBeenCalled(); + } + }, + ); + }); + it('yields fragments in order and resolves completion with the full text + usage', async () => { const fragments = ['Hello, ', 'world', '!']; selectChatModelsMock.mockResolvedValueOnce([makeFakeModel(fragments)]); diff --git a/src/tree/documentdb/ClusterItemBase.test.ts b/src/tree/documentdb/ClusterItemBase.test.ts index 3c507c1a0..a313f7ff4 100644 --- a/src/tree/documentdb/ClusterItemBase.test.ts +++ b/src/tree/documentdb/ClusterItemBase.test.ts @@ -32,7 +32,8 @@ import { ClusterItemBase, type EphemeralClusterCredentials } from './ClusterItem const mockTelemetryEvents: Array<{ eventName: string; properties: Record; suppressDisplay?: boolean }> = []; -vi.mock('@microsoft/vscode-azext-utils', () => ({ +vi.mock('@microsoft/vscode-azext-utils', async (importOriginal) => ({ + ...(await importOriginal>()), UserCancelledError: class UserCancelledError extends Error {}, callWithTelemetryAndErrorHandling: vi.fn( async ( diff --git a/src/webviews/_integration/commonDialogs.test.ts b/src/webviews/_integration/commonDialogs.test.ts index da2cf8ccf..1d0ba86af 100644 --- a/src/webviews/_integration/commonDialogs.test.ts +++ b/src/webviews/_integration/commonDialogs.test.ts @@ -77,3 +77,24 @@ describe('common.confirm', () => { ); }); }); + +describe('common.displayErrorMessage', () => { + beforeEach(() => { + vi.mocked(vscode.window.showErrorMessage).mockReset(); + }); + + it('renders non-modal title and detail without host call-site formatting', async () => { + await expect( + caller.common.displayErrorMessage({ + message: 'Sign-in required', + modal: false, + cause: 'Sign in from the connection tree.', + }), + ).resolves.toEqual({ action: undefined }); + + expect(vscode.window.showErrorMessage).toHaveBeenCalledExactlyOnceWith( + 'Sign-in required (Sign in from the connection tree.)', + { modal: false, detail: undefined }, + ); + }); +}); diff --git a/src/webviews/_integration/connectionUnavailable.ts b/src/webviews/_integration/connectionUnavailable.ts index c2044eccb..3886337a2 100644 --- a/src/webviews/_integration/connectionUnavailable.ts +++ b/src/webviews/_integration/connectionUnavailable.ts @@ -5,9 +5,6 @@ import { type ConnectionUnavailableReason } from '../../documentdb/ConnectionUnavailableError'; -export const connectionRecoveryActions = ['retry', 'close'] as const; -export type ConnectionRecoveryAction = (typeof connectionRecoveryActions)[number]; - export const connectionUnavailableReasons = [ 'signInRequired', 'credentialsRejected', @@ -20,27 +17,23 @@ export const connectionUnavailableReasons = [ 'unreachable', ] as const satisfies readonly ConnectionUnavailableReason[]; +export const terminalUnavailableReasons = [ + 'userDisconnected', + 'connectionRemoved', + 'credentialsChanged', + 'identityChanged', +] as const satisfies readonly ConnectionUnavailableReason[]; + export interface ConnectionUnavailableDetails { readonly reason: ConnectionUnavailableReason; readonly title: string; readonly detail: string; - readonly action: ConnectionRecoveryAction; } export interface ConnectionUnavailableResponse { readonly unavailable: ConnectionUnavailableDetails; } -export interface ConnectionRecoveryRequest { - readonly action: ConnectionRecoveryAction; -} - -export interface ConnectionRecoveryResponse { - readonly recovered: { - readonly text: string; - }; -} - export interface ConnectionUnavailableMessage { readonly type: | 'documentView.connectionUnavailable' @@ -58,11 +51,14 @@ function isConnectionUnavailableDetails(value: unknown): value is ConnectionUnav return ( connectionUnavailableReasons.some((reason) => reason === candidate.reason) && typeof candidate.title === 'string' && - typeof candidate.detail === 'string' && - connectionRecoveryActions.some((action) => action === candidate.action) + typeof candidate.detail === 'string' ); } +export function isTerminalUnavailable(details: ConnectionUnavailableDetails): boolean { + return terminalUnavailableReasons.some((reason) => reason === details.reason); +} + export function isConnectionUnavailableResponse(value: unknown): value is ConnectionUnavailableResponse { if (typeof value !== 'object' || value === null || !('unavailable' in value)) { return false; diff --git a/src/webviews/_integration/describeUnavailableConnection.test.ts b/src/webviews/_integration/describeUnavailableConnection.test.ts index 875b5b7ad..84f4bff83 100644 --- a/src/webviews/_integration/describeUnavailableConnection.test.ts +++ b/src/webviews/_integration/describeUnavailableConnection.test.ts @@ -6,18 +6,22 @@ import { expect, it } from 'vitest'; import { describeUnavailableConnection } from './describeUnavailableConnection'; -it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing'] as const)( - 'directs credential repair to the tree before retrying %s', +it.each(['signInRequired', 'credentialsRejected', 'credentialsMissing', 'credentialsUpdating', 'unreachable'] as const)( + 'directs repair without a Retry workflow for %s', (reason): void => { const { unavailable } = describeUnavailableConnection(reason); - expect(unavailable).toMatchObject({ reason, action: 'retry' }); - expect(unavailable.detail).toContain('tree'); + expect(unavailable).toMatchObject({ reason }); + expect(unavailable.detail).not.toContain('then click Retry'); }, ); -it.each(['identityChanged', 'credentialsChanged', 'connectionRemoved'] as const)( - 'offers only Close view for %s', +it.each(['userDisconnected', 'identityChanged', 'credentialsChanged', 'connectionRemoved'] as const)( + 'permanently describes ended sessions for %s', (reason): void => { - expect(describeUnavailableConnection(reason).unavailable.action).toBe('close'); + expect(describeUnavailableConnection(reason).unavailable).toEqual({ + reason, + title: 'Disconnected', + detail: 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', + }); }, ); diff --git a/src/webviews/_integration/describeUnavailableConnection.ts b/src/webviews/_integration/describeUnavailableConnection.ts index f7491ad32..a90f7c365 100644 --- a/src/webviews/_integration/describeUnavailableConnection.ts +++ b/src/webviews/_integration/describeUnavailableConnection.ts @@ -14,8 +14,7 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso unavailable: { reason, title: l10n.t('Sign-in required'), - detail: l10n.t('Sign in from the connection tree, then click Retry.'), - action: 'retry', + detail: l10n.t('Sign in from the connection tree.'), }, }; case 'credentialsRejected': @@ -23,21 +22,15 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso unavailable: { reason, title: l10n.t('Authentication failed'), - detail: l10n.t('Repair the connection in the tree, then click Retry.'), - action: 'retry', + detail: l10n.t('Repair the connection in the tree.'), }, }; case 'credentialsMissing': - case 'userDisconnected': return { unavailable: { reason, title: l10n.t('Disconnected'), - detail: - reason === 'userDisconnected' - ? l10n.t('Reconnect from the connection tree, then click Retry.') - : l10n.t('Connect from the connection tree, then click Retry.'), - action: 'retry', + detail: l10n.t('Connect from the connection tree.'), }, }; case 'credentialsUpdating': @@ -45,29 +38,20 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso unavailable: { reason, title: l10n.t('Connection update in progress'), - detail: l10n.t('Wait for the update to finish, then click Retry.'), - action: 'retry', + detail: l10n.t('Wait for the update to finish.'), }, }; + case 'userDisconnected': case 'identityChanged': case 'credentialsChanged': + case 'connectionRemoved': return { unavailable: { reason, - title: l10n.t('Connection changed'), + title: l10n.t('Disconnected'), detail: l10n.t( - 'This view is tied to the previous connection settings. Close it and reopen it from the tree.', + 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', ), - action: 'close', - }, - }; - case 'connectionRemoved': - return { - unavailable: { - reason, - title: l10n.t('Connection removed'), - detail: l10n.t('This connection is no longer in the tree. Close this view.'), - action: 'close', }, }; case 'unreachable': @@ -75,8 +59,7 @@ export function describeUnavailableConnection(reason: ConnectionUnavailableReaso unavailable: { reason, title: l10n.t('Connection lost'), - detail: l10n.t('Check the network or server, then click Retry.'), - action: 'retry', + detail: l10n.t('Check the network or server.'), }, }; } diff --git a/src/webviews/_integration/trpc.test.ts b/src/webviews/_integration/trpc.test.ts index 39b33ff85..3aeddab7c 100644 --- a/src/webviews/_integration/trpc.test.ts +++ b/src/webviews/_integration/trpc.test.ts @@ -77,7 +77,6 @@ const unavailableResponse = { reason: 'credentialsRejected', title: 'Reconnect', detail: 'The saved credentials were rejected.', - action: 'retry', }, } as const; const ordinaryResponse = { value: 'loaded' } as const; @@ -86,7 +85,6 @@ const malformedUnavailableResponse = { reason: 'tokenExpired', title: 'Reconnect', detail: 'The connection token expired.', - action: 'retry', }, } as const; diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx index 099ad97c1..fd5b007f0 100644 --- a/src/webviews/components/DisconnectedOverlay.test.tsx +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -18,177 +18,166 @@ vi.mock('../_integration/useTrpcClient', () => ({ useTrpcClient: () => ({ common: { confirm: { mutate: confirm } } }), })); +const unavailable: ConnectionUnavailableDetails = { + reason: 'userDisconnected', + title: 'Disconnected', + detail: 'This tab is disconnected and read-only. You can copy its contents. Open a new tab to run commands.', +}; + beforeEach((): void => { confirm.mockReset(); }); -it('dismisses without closing, and only closes a dirty view after confirmation', async (): Promise => { - const unavailable: ConnectionUnavailableDetails = { - reason: 'signInRequired', - title: 'Sign-in required', - detail: 'Sign in from the connection tree, then click Retry.', - action: 'retry', - }; - const onAction = vi.fn(); +it('dismisses only the notice and never enables terminal content actions', async (): Promise => { + const onClose = vi.fn(); const onDismiss = vi.fn(); - confirm.mockResolvedValueOnce({ confirmed: false }).mockResolvedValueOnce({ confirmed: true }); const host = document.createElement('div'); document.body.appendChild(host); const root = createRoot(host); + const render = async (failure?: ConnectionUnavailableDetails): Promise => { + await act(async () => + root.render( + +