From f139b1e89d82462c7a07061e7e7ac371c3e43717 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:53:04 +0000 Subject: [PATCH 01/44] feat: register open surfaces by connection identity (WI-6) Give planned teardown a cluster-scoped list without introducing shared surface state or changing panel behavior yet. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 5 +++ src/documentdb/connectionSurfaces.test.ts | 36 +++++++++++++++++ src/documentdb/connectionSurfaces.ts | 39 +++++++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 src/documentdb/connectionSurfaces.test.ts create mode 100644 src/documentdb/connectionSurfaces.ts diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index 93f7d4c37..eb718df2f 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1515,6 +1515,11 @@ behave as today. **Progress:** +- **Host foundation:** Started PR5 from verified PR4 `d422d065b` while the independent + packaged-worker smoke test is pending. Added the disposable, cluster-scoped registry. + Build and its focused test passed. Panels are not yet wired to it; next is binding + resolution and the startup-rejection carry-forward from the PR4 review. + --- ## WI-7: Teardown, Disconnect, Remove and Update Credentials (PR 6) diff --git a/src/documentdb/connectionSurfaces.test.ts b/src/documentdb/connectionSurfaces.test.ts new file mode 100644 index 000000000..23957e479 --- /dev/null +++ b/src/documentdb/connectionSurfaces.test.ts @@ -0,0 +1,36 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { expect, it, vi } from 'vitest'; +import { getConnectionSurfaces, registerConnectionSurface, 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 => ({ + clusterId, + kind, + disable: vi.fn(), + dispose: vi.fn(), + }); + const document = makeSurface('cluster-a', 'documentView'); + const dashboard = makeSurface('cluster-a', 'clusterDashboard'); + const otherCluster = makeSurface('cluster-b', 'collectionView'); + const registrations = [document, dashboard, otherCluster].map(registerConnectionSurface); + + try { + expect(getConnectionSurfaces('cluster-a')).toEqual([document, dashboard]); + registrations[0].dispose(); + expect(getConnectionSurfaces('cluster-a')).toEqual([dashboard]); + expect(getConnectionSurfaces('cluster-b')).toEqual([otherCluster]); + expect(document.dispose).not.toHaveBeenCalled(); + expect(document.disable).not.toHaveBeenCalled(); + } finally { + for (const registration of registrations) { + registration.dispose(); + } + } + + expect(getConnectionSurfaces('cluster-a')).toEqual([]); + expect(getConnectionSurfaces('cluster-b')).toEqual([]); +}); diff --git a/src/documentdb/connectionSurfaces.ts b/src/documentdb/connectionSurfaces.ts new file mode 100644 index 000000000..f48f199fd --- /dev/null +++ b/src/documentdb/connectionSurfaces.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type Disposable } from 'vscode'; +import { type ConnectionUnavailableReason } from './ConnectionUnavailableError'; + +export interface ConnectionSurface { + readonly clusterId: string; + readonly kind: 'collectionView' | 'documentView' | 'clusterDashboard'; + disable(reason: ConnectionUnavailableReason): void; + dispose(): void; + isDirty?(): boolean; +} + +const surfacesByCluster = new Map>(); + +export function registerConnectionSurface(surface: ConnectionSurface): Disposable { + const { clusterId } = surface; + let surfaces = surfacesByCluster.get(clusterId); + if (!surfaces) { + surfaces = new Set(); + surfacesByCluster.set(clusterId, surfaces); + } + + surfaces.add(surface); + return { + dispose(): void { + if (surfaces.delete(surface) && surfaces.size === 0) { + surfacesByCluster.delete(clusterId); + } + }, + }; +} + +export function getConnectionSurfaces(clusterId: string): readonly ConnectionSurface[] { + return [...(surfacesByCluster.get(clusterId) ?? [])]; +} From b45e5798043a7be2331b55e58b599a51b7079a9e Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 19:56:15 +0000 Subject: [PATCH 02/44] feat: resolve surface clients without changing identity (WI-6) Use the existing startup fingerprint guard and return typed startup rejections before sending operations. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 7 ++- src/documentdb/ClustersClient.test.ts | 62 ++++++++++++++++--- src/documentdb/ClustersClient.ts | 25 +++++++- src/documentdb/runWithClient.ts | 19 +++--- 4 files changed, 94 insertions(+), 19 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index eb718df2f..f861ec592 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1517,8 +1517,11 @@ behave as today. - **Host foundation:** Started PR5 from verified PR4 `d422d065b` while the independent packaged-worker smoke test is pending. Added the disposable, cluster-scoped registry. - Build and its focused test passed. Panels are not yet wired to it; next is binding - resolution and the startup-rejection carry-forward from the PR4 review. + The bound resolver permits a new generation of the same identity and refuses to start + or use a client for a changed identity. `runWithClient` uses that resolver and reports + startup credential rejection without submitting the operation (PR4 review N1). Build and + 86 focused tests passed. Panels are not yet wired; next migrate `ClusterSession` and its + host callers. --- diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 3fe3353a3..3b352cec4 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -271,6 +271,42 @@ describe('regular connection startup diagnostics', () => { expect(mockClose).not.toHaveBeenCalled(); }); + it('lets a surface follow a same-identity generation but does not redial while latched', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + const replacement = await ClustersClient.resolveBoundClient(client.binding); + expect(replacement.binding).toEqual({ ...client.binding, generation: client.generation + 1 }); + expect(mockConnect).toHaveBeenCalledTimes(2); + + ClustersClient.latch(clusterId, 'userDisconnected'); + try { + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'userDisconnected', + }); + expect(mockConnect).toHaveBeenCalledTimes(2); + } finally { + ClustersClient.unlatch(clusterId); + } + }); + + it('does not open a changed connection for an old surface, even with no cached client', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(MongoClient).toHaveBeenCalledOnce(); + expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); + + const current = await ClustersClient.getClient(clusterId); + await expect(ClustersClient.resolveBoundClient(client.binding)).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(ClustersClient.getBinding(clusterId)).toBe(current.binding); + }); + it('reports only the expiry of the last Entra token supplied to the driver', async (): Promise => { const firstExpiry = 1_800_000_000; const renewedExpiry = firstExpiry + 3600; @@ -676,29 +712,41 @@ describe('regular connection startup diagnostics', () => { it('uses the resolved binding, preserves nonterminal errors and returns terminal unavailability without replay', async () => { const old = await ClustersClient.connectInteractive(clusterId); poolEvents.emit('topologyClosed'); - const client = await ClustersClient.getClient(clusterId); - const resolveClient = vi.fn(async (): Promise => client); const network = Object.freeze(new MongoNetworkError('tunnel refused')); const op = vi.fn<() => Promise>().mockRejectedValueOnce(network); - resolveClient.mockRejectedValueOnce(new ConnectionUnavailableError('unreachable')); - await expect(runWithClient(old.binding, op, { resolveClient, background: true })).resolves.toEqual({ + await expect(runWithClient(old.binding, op, { background: true })).resolves.toEqual({ unavailable: { reason: 'unreachable' }, }); + expect(mockConnect).toHaveBeenCalledOnce(); expect(op).not.toHaveBeenCalled(); - await expect(runWithClient(old.binding, op, { resolveClient, background: true })).rejects.toBe(network); - expect(resolveClient).toHaveBeenLastCalledWith(old.binding, { background: true }); + const client = await ClustersClient.getClient(clusterId); + await expect(runWithClient(old.binding, op, { background: true })).rejects.toBe(network); expect(op).toHaveBeenCalledExactlyOnceWith(client); expect(await ClustersClient.getClient(clusterId)).toBe(client); op.mockRejectedValueOnce(new EntraIdentityMismatchError()); - await expect(runWithClient(old.binding, op, { resolveClient })).resolves.toEqual({ + await expect(runWithClient(old.binding, op)).resolves.toEqual({ unavailable: { reason: 'identityChanged' }, }); expect(ClustersClient.getBinding(clusterId)).toBeUndefined(); expect(op).toHaveBeenCalledTimes(2); }); + it('reports a startup credential rejection without submitting the bound operation', async (): Promise => { + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.NativeAuth, 'mongodb://private-host:27017'); + const client = await ClustersClient.getClient(clusterId); + await ClustersClient.deleteClient(clusterId); + mockConnect.mockRejectedValueOnce(new MongoServerError({ code: 18 })); + const op = vi.fn<() => Promise>(); + + await expect(runWithClient(client.binding, op)).resolves.toEqual({ + unavailable: { reason: 'credentialsRejected' }, + }); + expect(mockConnect).toHaveBeenCalledTimes(2); + expect(op).not.toHaveBeenCalled(); + }); + it('binds Entra to the original cached URI and the verified identity, even if credentials change during startup', async () => { const originalUri = 'mongodb+srv://original.example.com/database?authSource=admin'; const driverUri = 'mongodb://localhost:27018/database'; diff --git a/src/documentdb/ClustersClient.ts b/src/documentdb/ClustersClient.ts index bba86d893..dd72e7759 100644 --- a/src/documentdb/ClustersClient.ts +++ b/src/documentdb/ClustersClient.ts @@ -838,6 +838,22 @@ export class ClustersClient { return ClustersClient.acquireClient(clusterId, abortSignal, onStartup, trigger, true, false); } + /** A surface can follow new generations, but never start or use a client for a different identity. */ + public static resolveBoundClient( + binding: ConnectionBinding, + options?: { readonly background?: boolean; readonly trigger?: ClientStartupTrigger }, + ): Promise { + return ClustersClient.acquireClient( + binding.clusterId, + undefined, + undefined, + options?.trigger ?? 'other', + false, + options?.background === true, + binding.fingerprint, + ); + } + /** Publish only after explicit sign-in and database startup succeed. The prior pin stays intact until then. */ public static async startAfterSignIn( clusterId: string, @@ -894,6 +910,7 @@ export class ClustersClient { trigger: ClientStartupTrigger, allowInteractive: boolean, background: boolean, + boundFingerprint?: string, ): Promise { for (let attempt = 0; ; attempt++) { const reason = ClustersClient.getLatchReason(clusterId); @@ -909,6 +926,9 @@ export class ClustersClient { const epoch = ClustersClient.getEpoch(clusterId); const cached = ClustersClient._clients.get(clusterId); + if (cached && boundFingerprint !== undefined && cached.fingerprint !== boundFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } if (cached?._replacement === 'replaceOnRecovery') { throw new ConnectionUnavailableError('signInRequired'); } @@ -936,12 +956,15 @@ export class ClustersClient { trigger, allowInteractive, background, - cached?.fingerprint, + boundFingerprint ?? cached?.fingerprint, ); onStartup?.(id); try { const client = await waitForClient(promise, abortSignal, id); if (epoch === ClustersClient.getEpoch(clusterId) && client.canReuse()) { + if (boundFingerprint !== undefined && client.fingerprint !== boundFingerprint) { + throw new ConnectionUnavailableError('identityChanged'); + } return client; } } catch (error) { diff --git a/src/documentdb/runWithClient.ts b/src/documentdb/runWithClient.ts index 5bcf53a7b..30c370542 100644 --- a/src/documentdb/runWithClient.ts +++ b/src/documentdb/runWithClient.ts @@ -3,16 +3,16 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { AuthMethodId } from './auth/AuthMethodId'; import { ClustersClient, type ConnectionBinding } from './ClustersClient'; import { classifyConnectionFailure, type ConnectionFailure } from './connectionFailures'; import { ConnectionUnavailableError, type ConnectionUnavailableReason } from './ConnectionUnavailableError'; +import { CredentialCache } from './CredentialCache'; +import { type ClientStartupTrigger } from './utils/startupFailureTelemetry'; -interface ResolveOptions { +interface RunOptions { readonly background?: boolean; -} - -interface RunOptions extends ResolveOptions { - resolveClient(binding: ConnectionBinding, options: ResolveOptions): Promise; + readonly trigger?: ClientStartupTrigger; } interface Unavailable { @@ -31,21 +31,22 @@ function unavailableFor(kind: ConnectionFailure['kind'] | undefined): Unavailabl } } -/** @internal The bound resolver and conversion to a surface response are supplied by WI-6. */ export async function runWithClient( binding: ConnectionBinding, op: (client: ClustersClient) => Promise, - { resolveClient, background }: RunOptions, + options?: RunOptions, ): Promise { + const credentials = CredentialCache.getCredentials(binding.clusterId); + const authMethod = credentials ? (credentials.authMechanism ?? AuthMethodId.NativeAuth) : undefined; let client: ClustersClient; try { - client = await resolveClient(binding, { background }); + client = await ClustersClient.resolveBoundClient(binding, options); } catch (error) { // No operation ran, so there is no client generation to report against. const unavailable = error instanceof ConnectionUnavailableError ? { unavailable: { reason: error.reason } } - : unavailableFor(classifyConnectionFailure(error).kind); + : unavailableFor(classifyConnectionFailure(error, authMethod).kind); if (unavailable) { return unavailable; } From 95dd27be4f3a6fc5a05922f8d75d9c5bfca72055 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 20:04:24 +0000 Subject: [PATCH 03/44] feat: bind Collection View sessions to connection identity (WI-6) Resolve clients per operation and fence cache writes without changing procedure responses yet. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 8 +- .../indexAdvisorCommands.ts | 29 ++- src/documentdb/ClusterSession.ts | 154 +++++++++---- src/documentdb/ClustersClient.test.ts | 125 ++++++++++- src/services/ai/QueryInsightsAIService.ts | 44 ++-- .../collectionView/collectionViewRouter.ts | 8 +- .../queryInsightsEventsRouter.ts | 11 +- .../queryInsights/queryInsightsRouter.ts | 212 ++++++++---------- 8 files changed, 390 insertions(+), 201 deletions(-) diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index f861ec592..b29f8f488 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1520,8 +1520,12 @@ behave as today. The bound resolver permits a new generation of the same identity and refuses to start or use a client for a changed identity. `runWithClient` uses that resolver and reports startup credential rejection without submitting the operation (PR4 review N1). Build and - 86 focused tests passed. Panels are not yet wired; next migrate `ClusterSession` and its - host callers. + 86 focused tests passed. +- **Collection View host slice:** `ClusterSession` holds a binding instead of a client. + Collection View, Query Insights, and the index advisor resolve the client per operation. + Check the epoch, latch, and identity before applying results to session caches. Build + and 193 focused tests passed. Procedure response shapes are unchanged for now; structured + unavailable results and the remaining panels are subsequent WI-6 slices. --- diff --git a/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts b/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts index cdaf10e8c..297d7ceca 100644 --- a/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts +++ b/src/commands/llmEnhancedCommands/indexAdvisorCommands.ts @@ -7,7 +7,7 @@ import { UserCancelledError, type IActionContext } from '@microsoft/vscode-azext import * as l10n from '@vscode/l10n'; import { type Document, type Filter } from 'mongodb'; import * as vscode from 'vscode'; -import { type IndexItemModel } from '../../documentdb/ClustersClient'; +import { ClustersClient, type IndexItemModel } from '../../documentdb/ClustersClient'; import { ClusterSession } from '../../documentdb/ClusterSession'; import { type CollectionStats, type IndexStats } from '../../documentdb/LlmEnhancedFeatureApis'; import { type ClusterMetadata } from '../../documentdb/utils/getClusterMetadata'; @@ -469,6 +469,13 @@ async function prepareOptimizationRequest( throw new UserCancelledError('AbortSignal'); } + // TODO: allow null sessionId for testing framework + if (!queryContext.sessionId) { + throw new Error(l10n.t('sessionId is required for query optimization')); + } + const session = ClusterSession.getSession(queryContext.sessionId); + const epoch = session.getEpoch(); + // Check if Copilot is available const copilotAvailable = await CopilotService.isAvailable(); if (!copilotAvailable) { @@ -479,16 +486,22 @@ async function prepareOptimizationRequest( ); } + return session.runWithClient(async (client) => { + const prepared = await prepareBoundOptimizationRequest(context, queryContext, client); + session.assertCurrent(epoch, queryContext.signal); + return prepared; + }, epoch); +} + +async function prepareBoundOptimizationRequest( + context: IActionContext, + queryContext: QueryOptimizationContext, + client: ClustersClient, +): Promise { let explainResult: unknown; let collectionStats: CollectionStats | undefined; let indexes: IndexStats[] | undefined; - // TODO: allow null sessionId for testing framework - if (!queryContext.sessionId) { - throw new Error(l10n.t('sessionId is required for query optimization')); - } - const session = ClusterSession.getSession(queryContext.sessionId); - const client = session.getClient(); const clusterInfo = await client.getClusterMetadata(); // Track cluster information in telemetry @@ -589,6 +602,7 @@ async function prepareOptimizationRequest( l10n.t('Failed to gather query optimization data: {message}', { message: error instanceof Error ? error.message : String(error), }), + { cause: error }, ); } } @@ -674,6 +688,7 @@ async function prepareOptimizationRequest( if (error instanceof UserCancelledError) { throw error; } + ClustersClient.reportFailure(client.binding, error); // They are not critical errors, we can continue without index stats and collection stats // If the API calls failed, collectionStats and indexes remain undefined (safe to continue) diff --git a/src/documentdb/ClusterSession.ts b/src/documentdb/ClusterSession.ts index 2a7ed1ed9..7d8f1809f 100644 --- a/src/documentdb/ClusterSession.ts +++ b/src/documentdb/ClusterSession.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { type FieldEntry } from '@documentdb-js/schema-analyzer'; +import { UserCancelledError } from '@microsoft/vscode-azext-utils'; import { ParseMode, parse as parseShellBSON } from '@mongodb-js/shell-bson-parser'; import * as l10n from '@vscode/l10n'; import { EJSON } from 'bson'; @@ -12,7 +13,9 @@ import { ext } from '../extensionVariables'; 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 FindQueryParams } from './ClustersClient'; +import { ClustersClient, type ConnectionBinding, type FindQueryParams } from './ClustersClient'; +import { ConnectionUnavailableError } from './ConnectionUnavailableError'; +import { runWithClient } from './runWithClient'; import { SchemaStore } from './SchemaStore'; import { fixupDocumentDbExplain } from './utils/fixupDocumentDbExplain'; import { parseDocumentId } from './utils/parseDocumentId'; @@ -70,15 +73,48 @@ export class ClusterSession { * Private constructor to enforce the use of `initNewSession` for creating new sessions. * This ensures that sessions are properly initialized and managed. */ - private constructor( - private _client: ClustersClient, - private readonly _clusterId: string, - ) { - return; + private constructor(private readonly binding: ConnectionBinding) {} + + public async getClient(): Promise { + return ClustersClient.resolveBoundClient(this.binding, { trigger: 'collectionView' }); + } + + public getEpoch(): number { + return ClustersClient.getEpoch(this.binding.clusterId); + } + + private isCurrent(epoch: number): boolean { + const { clusterId, fingerprint } = this.binding; + return ( + epoch === ClustersClient.getEpoch(clusterId) && + ClustersClient.getLatchReason(clusterId) === undefined && + ClustersClient.getBinding(clusterId)?.fingerprint === fingerprint + ); } - public getClient(): ClustersClient { - return this._client; + public assertCurrent(epoch: number, signal?: AbortSignal): void { + if (signal?.aborted || !this.isCurrent(epoch)) { + throw new UserCancelledError('staleCollectionViewOperation'); + } + } + + // Keep the existing procedure return types until the routers map unavailable results. + public async runWithClient( + operation: (client: ClustersClient, epoch: number) => Promise, + epoch = this.getEpoch(), + ): Promise { + const result = await runWithClient( + this.binding, + async (client) => { + this.assertCurrent(epoch); + return { value: await operation(client, epoch) }; + }, + { trigger: 'collectionView' }, + ); + if ('unavailable' in result) { + throw new ConnectionUnavailableError(result.unavailable.reason); + } + return result.value; } /** @@ -114,7 +150,6 @@ export class ClusterSession { /** * Query Insights caching - * Note: QueryInsightsApis instance is accessed via this._client.queryInsightsApis * * Timestamps are included for potential future features: * - Time-based cache invalidation (e.g., expire after N seconds) @@ -248,6 +283,7 @@ export class ClusterSession { pageNumber: number, pageSize: number, executionIntent: 'initial' | 'refresh' | 'pagination' = 'pagination', + signal?: AbortSignal, ): Promise { const querySkip = queryParams.skip ?? 0; const queryLimit = queryParams.limit ?? 0; @@ -261,9 +297,11 @@ export class ClusterSession { // Early return if trying to skip beyond the query limit // Note: queryLimit=0 means no limit, so only check when queryLimit > 0 if (queryLimit > 0 && pageOffset >= queryLimit) { - // We're trying to page beyond the query's limit - return empty results - this._currentRawDocuments = []; - return 0; + return this.runWithClient((_client, epoch) => { + this.assertCurrent(epoch, signal); + this._currentRawDocuments = []; + return Promise.resolve(0); + }); } // Calculate effective limit: @@ -275,18 +313,6 @@ export class ClusterSession { dbLimit = Math.min(pageSize, remainingInWindow); } - // Check if the user's query has changed (not pagination, just the actual query) - this.resetCachesIfUserQueryChanged(queryParams); - - // Check if page size has changed (invalidates accumulation strategy) - this.resetAccumulationIfPageSizeChanged(pageSize); - - // Force clear query insights caches for initial/refresh operations - // This ensures fresh performance data when user explicitly requests it - if (executionIntent === 'initial' || executionIntent === 'refresh') { - this.clearQueryInsightsCaches(); - } - // Build final query parameters with computed skip/limit const paginatedQueryParams: FindQueryParams = { ...queryParams, @@ -294,14 +320,21 @@ export class ClusterSession { limit: dbLimit, }; - // Track execution time for query insights - const startTime = performance.now(); - const documents: WithId[] = await this._client.runFindQuery( - databaseName, - collectionName, - paginatedQueryParams, - ); - this._lastExecutionTimeMs = performance.now() - startTime; + const epoch = this.getEpoch(); + const { documents, executionTimeMs } = await this.runWithClient(async (client) => { + this.assertCurrent(epoch, signal); + const startTime = performance.now(); + const documents = await client.runFindQuery(databaseName, collectionName, paginatedQueryParams); + return { documents, executionTimeMs: performance.now() - startTime }; + }, epoch); + + this.assertCurrent(epoch, signal); + this.resetCachesIfUserQueryChanged(queryParams); + this.resetAccumulationIfPageSizeChanged(pageSize); + if (executionIntent === 'initial' || executionIntent === 'refresh') { + this.clearQueryInsightsCaches(); + } + this._lastExecutionTimeMs = executionTimeMs; // Update current page documents (always replace, not accumulate) this._currentRawDocuments = documents; @@ -313,10 +346,11 @@ export class ClusterSession { // Feed documents to the shared SchemaStore if (documents.length > 0) { const store = SchemaStore.getInstance(); - store.addDocuments(this._clusterId, databaseName, collectionName, documents); + const { clusterId } = this.binding; + store.addDocuments(clusterId, databaseName, collectionName, documents); ext.outputChannel.trace( - `[SchemaStore] Fed ${String(documents.length)} documents, ${String(store.getDocumentCount(this._clusterId, databaseName, collectionName))} total, ${String(store.getKnownFields(this._clusterId, databaseName, collectionName).length)} known fields`, + `[SchemaStore] Fed ${String(documents.length)} documents, ${String(store.getDocumentCount(clusterId, databaseName, collectionName))} total, ${String(store.getKnownFields(clusterId, databaseName, collectionName).length)} known fields`, ); } @@ -331,10 +365,19 @@ export class ClusterSession { return toSlickGridTree(this._currentRawDocuments); } - async deleteDocuments(databaseName: string, collectionName: string, documentIds: string[]): Promise { - const acknowledged = await this._client.deleteDocuments(databaseName, collectionName, documentIds); + public async deleteDocuments( + databaseName: string, + collectionName: string, + documentIds: string[], + epoch = this.getEpoch(), + ): Promise { + const acknowledged = await this.runWithClient( + (client) => client.deleteDocuments(databaseName, collectionName, documentIds), + epoch, + ); - if (acknowledged) { + // Acknowledge a completed write, but don't update the page from an old operation. + if (acknowledged && this.isCurrent(epoch)) { this._currentRawDocuments = this._currentRawDocuments.filter((doc) => { return !documentIds.some((id) => { const parsedId = parseDocumentId(id); @@ -356,7 +399,7 @@ export class ClusterSession { path: path, headers: this._databaseName && this._collectionName - ? store.getPropertyNamesAtLevel(this._clusterId, this._databaseName, this._collectionName, path) + ? store.getPropertyNamesAtLevel(this.binding.clusterId, this._databaseName, this._collectionName, path) : [], data: getDataAtPath(this._currentRawDocuments, path), }; @@ -372,7 +415,7 @@ export class ClusterSession { if (!this._databaseName || !this._collectionName) { return []; } - return SchemaStore.getInstance().getKnownFields(this._clusterId, this._databaseName, this._collectionName); + return SchemaStore.getInstance().getKnownFields(this.binding.clusterId, this._databaseName, this._collectionName); } // ============================================================================ @@ -393,6 +436,8 @@ export class ClusterSession { * @returns Explain output from queryPlanner verbosity */ public async getQueryPlannerInfo( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -402,14 +447,16 @@ export class ClusterSession { skip?: number; limit?: number; }, + signal?: AbortSignal, ): Promise { + this.assertCurrent(epoch, signal); // Check cache if (this._queryPlannerCache) { return this._queryPlannerCache.result; } // Execute explain("queryPlanner") using QueryInsightsApis from ClustersClient - const rawResult = await this._client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { + const rawResult = await client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { verbosity: 'queryPlanner', sort: options?.sort, projection: options?.projection, @@ -418,10 +465,11 @@ export class ClusterSession { }); // Apply Azure DocumentDB explain fixup (see fixupDocumentDbExplain for details) - const clusterMetadata = await this._client.getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); const explainResult = fixupDocumentDbExplain(rawResult, clusterMetadata) ?? rawResult; // Cache result + this.assertCurrent(epoch, signal); this._queryPlannerCache = { result: explainResult, timestamp: Date.now(), @@ -447,6 +495,8 @@ export class ClusterSession { * @returns Explain output with executionStats */ public async getExecutionStats( + client: ClustersClient, + epoch: number, databaseName: string, collectionName: string, filter: Document, @@ -456,7 +506,9 @@ export class ClusterSession { skip?: number; limit?: number; }, + signal?: AbortSignal, ): Promise { + this.assertCurrent(epoch, signal); // Check cache if (this._executionStatsCache) { return this._executionStatsCache.result; @@ -464,7 +516,7 @@ export class ClusterSession { // Determine verbosity based on cluster type // Azure DocumentDB clusters support allPlansExecution for richer plan data - const clusterMetadata = await this._client.getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); const verbosity = clusterMetadata.domainInfo_isAzure === 'true' && clusterMetadata.domainInfo_api === 'vCore' ? 'allPlansExecution' @@ -472,7 +524,8 @@ export class ClusterSession { // Execute explain using QueryInsightsApis from ClustersClient // This re-runs the query to get authoritative execution metrics - const rawResult = await this._client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { + this.assertCurrent(epoch, signal); + const rawResult = await client.queryInsightsApis.explainFind(databaseName, collectionName, filter, { verbosity, sort: options?.sort, projection: options?.projection, @@ -484,6 +537,7 @@ export class ClusterSession { const explainResult = fixupDocumentDbExplain(rawResult, clusterMetadata) ?? rawResult; // Cache result + this.assertCurrent(epoch, signal); this._executionStatsCache = { result: explainResult, timestamp: Date.now(), @@ -606,7 +660,13 @@ export class ClusterSession { * Caches the transformed Stage 2 response and total collection docs * for use by Stage 3 when building the static analysis summary. */ - public setStage2Response(response: QueryInsightsStage2Response, totalCollectionDocs?: number): void { + public setStage2Response( + epoch: number, + response: QueryInsightsStage2Response, + totalCollectionDocs?: number, + signal?: AbortSignal, + ): void { + this.assertCurrent(epoch, signal); this._stage2ResponseCache = { response, totalCollectionDocs }; } @@ -635,7 +695,7 @@ export class ClusterSession { * * @remarks * This method will be implemented in Phase 3. The AI service is accessed via - * this._client.queryInsightsAIService (similar to queryInsightsApis pattern). + * the resolved client's Query Insights service. */ public getAIRecommendations( _databaseName: string, @@ -649,7 +709,7 @@ export class ClusterSession { } // TODO: Phase 3 implementation - // const recommendations = await this._client.queryInsightsAIService.generateRecommendations( + // const recommendations = await client.queryInsightsAIService.generateRecommendations( // databaseName, // collectionName, // filter, @@ -692,7 +752,7 @@ export class ClusterSession { const sessionId = Math.random().toString(16).substring(2, 15) + Math.random().toString(36).substring(2, 15); - const session = new ClusterSession(client, clusterId); + const session = new ClusterSession(client.binding); ClusterSession._sessions.set(sessionId, session); diff --git a/src/documentdb/ClustersClient.test.ts b/src/documentdb/ClustersClient.test.ts index 3b352cec4..13d74a04e 100644 --- a/src/documentdb/ClustersClient.test.ts +++ b/src/documentdb/ClustersClient.test.ts @@ -29,6 +29,7 @@ import { ManagedIdentityAuthHandler } from './auth/ManagedIdentityAuthHandler'; import { MicrosoftEntraIDAuthHandler } from './auth/MicrosoftEntraIDAuthHandler'; import { NativeAuthHandler } from './auth/NativeAuthHandler'; import { NoAuthHandler } from './auth/NoAuthHandler'; +import { ClusterSession } from './ClusterSession'; import { addEstablishedConnectionContext, ClustersClient, @@ -39,6 +40,7 @@ import { computeConnectionFingerprint } from './connectionFingerprint'; import { ConnectionUnavailableError } from './ConnectionUnavailableError'; import { CredentialCache } from './CredentialCache'; import { runWithClient } from './runWithClient'; +import { SchemaStore } from './SchemaStore'; import { prepareDriverConnectionString } from './srv/prepareDriverConnectionString'; import { type SrvResolutionSummary } from './srv/srvResolutionSummary'; import { getClusterMetadata, getDomainMetadata } from './utils/getClusterMetadata'; @@ -130,7 +132,11 @@ vi.mock('./utils/getClusterMetadata', () => ({ })); vi.mock('./LlmEnhancedFeatureApis', () => ({ llmEnhancedFeatureApis: vi.fn() })); -vi.mock('./client/QueryInsightsApis', () => ({ QueryInsightsApis: vi.fn() })); +vi.mock('./client/QueryInsightsApis', () => ({ + QueryInsightsApis: vi.fn(function () { + return { explainFind: vi.fn() }; + }), +})); vi.mock('./srv/prepareDriverConnectionString', () => ({ prepareDriverConnectionString: vi.fn() })); vi.mock('./auth/createAuthHandler', async () => { const actual = await vi.importActual('./auth/createAuthHandler'); @@ -160,6 +166,9 @@ describe('regular connection startup diagnostics', () => { const mockConnect = vi.fn(); const mockClose = vi.fn(); const mockListDatabases = vi.fn<() => Promise>(); + const mockFind = vi.fn(); + const mockToArray = vi.fn<() => Promise[]>>(); + const mockDeleteMany = vi.fn<() => Promise>(); let poolEvents: EventEmitter; function pauseNextConnect(): { started: Promise; resolve: () => void; reject: (error: Error) => void } { @@ -193,12 +202,18 @@ describe('regular connection startup diagnostics', () => { }); mockClose.mockResolvedValue(undefined); mockListDatabases.mockReset(); + mockFind.mockReset().mockReturnValue({ toArray: mockToArray }); + mockToArray.mockReset(); + mockDeleteMany.mockReset(); vi.mocked(MongoClient).mockImplementation(function () { poolEvents = new EventEmitter(); return Object.assign(poolEvents, { connect: mockConnect, close: mockClose, - db: () => ({ admin: () => ({ listDatabases: mockListDatabases }) }), + db: () => ({ + admin: () => ({ listDatabases: mockListDatabases }), + collection: () => ({ find: mockFind, deleteMany: mockDeleteMany }), + }), }) as unknown as MongoClient; }); for (const handler of [ @@ -307,6 +322,110 @@ describe('regular connection startup diagnostics', () => { expect(ClustersClient.getBinding(clusterId)).toBe(current.binding); }); + 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)); + const query = { filter: '{}', skip: 2, limit: 3 }; + mockToArray.mockResolvedValueOnce([{ _id: 'first', previousField: true }]); + await session.runFindQueryWithCache('db', 'items', query, 1, 2); + + ClustersClient.reportFailure(original.binding, new MongoNotConnectedError('idle connection closed')); + const replacement = await session.getClient(); + expect(replacement.generation).toBe(original.generation + 1); + expect(replacement.fingerprint).toBe(original.fingerprint); + const runFind = vi.spyOn(replacement, 'runFindQuery'); + + mockToArray.mockResolvedValueOnce([{ _id: 'last', nextField: true }]); + await expect(session.runFindQueryWithCache('db', 'items', query, 2, 2)).resolves.toBe(1); + expect(runFind).toHaveBeenCalledExactlyOnceWith('db', 'items', { ...query, skip: 4, limit: 1 }); + expect(session.getCurrentPageAsJson().map((page) => JSON.parse(page) as unknown)).toEqual([ + { _id: 'last', nextField: true }, + ]); + expect(SchemaStore.getInstance().getDocumentCount(clusterId, 'db', 'items')).toBe(2); + await expect(session.runFindQueryWithCache('db', 'items', query, 3, 2)).resolves.toBe(0); + expect(session.getCurrentPageAsJson()).toEqual([]); + expect(runFind).toHaveBeenCalledOnce(); + }); + + it('rejects a changed identity before a session can submit a write', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + await ClustersClient.deleteClient(clusterId); + CredentialCache.setAuthCredentials(clusterId, AuthMethodId.MicrosoftEntraID, 'mongodb://different.test/'); + await ClustersClient.getClient(clusterId); + + await expect(session.getClient()).rejects.toMatchObject({ reason: 'identityChanged' }); + await expect(session.deleteDocuments('db', 'items', ['"one"'])).rejects.toMatchObject({ + reason: 'identityChanged', + }); + expect(mockDeleteMany).not.toHaveBeenCalled(); + }); + + it('drops a find completed after reconnect without changing the query, page, or schema', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const query = { filter: '{}' }; + mockToArray.mockResolvedValueOnce([{ _id: 'current' }]); + await session.runFindQueryWithCache('db', 'items', query, 1, 10); + const page = session.getCurrentPageAsJson(); + + const started = deferred(); + const finish = deferred(); + mockToArray.mockImplementationOnce(async () => { + started.resolve(); + await finish.promise; + return [{ _id: 'stale', staleField: true }]; + }); + const pending = session.runFindQueryWithCache('db', 'items', { filter: '{ staleField: true }' }, 1, 10); + await started.promise; + ClustersClient.latch(clusterId, 'userDisconnected'); + await ClustersClient.deleteClient(clusterId); + ClustersClient.unlatch(clusterId); + await session.getClient(); + finish.resolve(); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(session.getCurrentFindQueryParams()).toEqual(query); + expect(session.getCurrentPageAsJson()).toEqual(page); + expect(SchemaStore.getInstance().getDocumentCount(clusterId, 'db', 'items')).toBe(0); + }); + + it('does not cache execution stats that complete while the session is latched', async (): Promise => { + const client = await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + const started = deferred(); + const finish = deferred(); + vi.spyOn(client.queryInsightsApis, 'explainFind').mockImplementationOnce(async () => { + started.resolve(); + await finish.promise; + return { executionStats: { nReturned: 1 } }; + }); + const pending = session.runWithClient((resolved, epoch) => + session.getExecutionStats(resolved, epoch, 'db', 'items', {}), + ); + await started.promise; + ClustersClient.latch(clusterId, 'userDisconnected'); + finish.resolve(); + + await expect(pending).rejects.toBeInstanceOf(UserCancelledError); + expect(session.getRawExplainOutput('db', 'items')).toBeNull(); + }); + + it('does not replay a failed delete or remove the cached document', async (): Promise => { + await ClustersClient.connectInteractive(clusterId); + const session = ClusterSession.getSession(await ClusterSession.initNewSession(clusterId)); + mockToArray.mockResolvedValueOnce([{ _id: 'one' }]); + await session.runFindQueryWithCache('db', 'items', {}, 1, 10); + const page = session.getCurrentPageAsJson(); + const failure = new MongoNotConnectedError('connection closed during delete'); + mockDeleteMany.mockRejectedValueOnce(failure); + + await expect(session.deleteDocuments('db', 'items', ['"one"'])).rejects.toBe(failure); + expect(mockDeleteMany).toHaveBeenCalledExactlyOnceWith({ _id: { $in: ['one'] } }); + expect(session.getCurrentPageAsJson()).toEqual(page); + expect(mockConnect).toHaveBeenCalledOnce(); + }); + it('reports only the expiry of the last Entra token supplied to the driver', async (): Promise => { const firstExpiry = 1_800_000_000; const renewedExpiry = firstExpiry + 3600; @@ -1027,6 +1146,8 @@ describe('regular connection startup diagnostics', () => { }); afterEach(() => { + ClusterSession._sessions.clear(); + SchemaStore.getInstance().clearCluster(clusterId); if (ClustersClient.getLatchReason(clusterId)) { ClustersClient.unlatch(clusterId); } diff --git a/src/services/ai/QueryInsightsAIService.ts b/src/services/ai/QueryInsightsAIService.ts index dbd19776d..dbe39d338 100644 --- a/src/services/ai/QueryInsightsAIService.ts +++ b/src/services/ai/QueryInsightsAIService.ts @@ -9,7 +9,6 @@ import { type IActionContext, } from '@microsoft/vscode-azext-utils'; import * as l10n from '@vscode/l10n'; -import { type Document } from 'mongodb'; import { CommandType, optimizeQuery, @@ -509,6 +508,9 @@ export class QueryInsightsAIService { }), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before creating the index const confirmed = await getConfirmationWithClick( l10n.t('Create index?'), @@ -529,10 +531,10 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - const result = await client.createIndex(payload.databaseName, payload.collectionName, payload.indexSpec); + const result = await session.runWithClient( + (client) => client.createIndex(payload.databaseName, payload.collectionName, payload.indexSpec), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available @@ -630,6 +632,9 @@ export class QueryInsightsAIService { ), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before dropping the index (destructive action) const confirmed = await getConfirmationAsInSettings( l10n.t('Delete index?'), @@ -653,10 +658,10 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - const result = await client.dropIndex(payload.databaseName, payload.collectionName, payload.indexName); + const result = await session.runWithClient( + (client) => client.dropIndex(payload.databaseName, payload.collectionName, payload.indexName), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available @@ -774,6 +779,9 @@ export class QueryInsightsAIService { ), ); + const session = ClusterSession.getSession(actualSessionId); + const epoch = session.getEpoch(); + // Ask for confirmation before modifying the index const operationText = operation === 'hideIndex' ? l10n.t('hide') : l10n.t('unhide'); const confirmed = await getConfirmationWithClick( @@ -797,17 +805,13 @@ export class QueryInsightsAIService { }; } - const session = ClusterSession.getSession(actualSessionId); - const client = session.getClient(); - - // Execute the operation - let result: Document; - if (operation === 'hideIndex') { - result = await client.hideIndex(payload.databaseName, payload.collectionName, indexName); - } else { - // unhideIndex - result = await client.unhideIndex(payload.databaseName, payload.collectionName, indexName); - } + const result = await session.runWithClient( + (client) => + operation === 'hideIndex' + ? client.hideIndex(payload.databaseName, payload.collectionName, indexName) + : client.unhideIndex(payload.databaseName, payload.collectionName, indexName), + epoch, + ); if (result.ok === 1) { // Provide positive feedback with additional context from result.note if available diff --git a/src/webviews/documentdb/collectionView/collectionViewRouter.ts b/src/webviews/documentdb/collectionView/collectionViewRouter.ts index 4950e3778..aebe487f7 100644 --- a/src/webviews/documentdb/collectionView/collectionViewRouter.ts +++ b/src/webviews/documentdb/collectionView/collectionViewRouter.ts @@ -246,6 +246,7 @@ export const collectionsViewRouter = router({ input.pageNumber, input.pageSize, executionIntent, + myCtx.signal, ); // Report execution intent for analytics @@ -355,6 +356,8 @@ export const collectionsViewRouter = router({ // procedure type .mutation(async ({ input, ctx }) => { const myCtx = ctx as RouterContext; + const session = ClusterSession.getSession(myCtx.sessionId); + const epoch = session.getEpoch(); const confirmed = await getConfirmationAsInSettings( l10n.t('Are you sure?'), @@ -362,12 +365,11 @@ export const collectionsViewRouter = router({ 'delete', ); - if (!confirmed) { + if (!confirmed || myCtx.signal?.aborted) { return false; } - const session: ClusterSession = ClusterSession.getSession(myCtx.sessionId); - const acknowledged = await session.deleteDocuments(myCtx.databaseName, myCtx.collectionName, input); + const acknowledged = await session.deleteDocuments(myCtx.databaseName, myCtx.collectionName, input, epoch); if (acknowledged) { showConfirmationAsInSettings( diff --git a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts index 00015a9d6..ec8ef5137 100644 --- a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts +++ b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsEventsRouter.ts @@ -204,6 +204,8 @@ export const queryInsightsEventsRouter = router({ }; try { + const session = ClusterSession.getSession(sessionId); + const epoch = session.getEpoch(); ext.outputChannel.trace( l10n.t('[Query Insights Stage 3 stream] Started for {db}.{collection} (requestKey: {key})', { db: databaseName, @@ -229,19 +231,22 @@ export const queryInsightsEventsRouter = router({ // the (now-deleted) buffered Stage 3 procedure used to build. // Kept structurally identical so the dedicated completion // telemetry (§7) records the same shape of inputs. - const session: ClusterSession = ClusterSession.getSession(sessionId); - // Record the platform on the dedicated completion event so // it lines up with the buffered procedure's rpc event. Best // effort — a metadata fetch failure here must not abort // Stage 3 streaming (the buffered procedure has the same // contract). + const client = await session.getClient(); try { - const clusterMetadata = await session.getClient().getClusterMetadata(); + const clusterMetadata = await client.getClusterMetadata(); completionTelemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; } catch { completionTelemetry.properties.platform = 'unknown'; } + if (abortController.signal.aborted) { + return; + } + session.assertCurrent(epoch); const parsedQueryParams = session.getCurrentFindQueryParamsWithObjects(); const queryObject: QueryObject = { diff --git a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts index 0ade16c31..49c26a197 100644 --- a/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts +++ b/src/webviews/documentdb/collectionView/queryInsights/queryInsightsRouter.ts @@ -31,6 +31,7 @@ import { z } from 'zod'; import * as l10n from '@vscode/l10n'; import { ClusterSession } from '../../../../documentdb/ClusterSession'; +import { ClustersClient } from '../../../../documentdb/ClustersClient'; import { ExplainPlanAnalyzer, type ExecutionStatsAnalysis, @@ -116,82 +117,57 @@ export const queryInsightsQueriesRouter = router({ }), ); - let analyzed: QueryPlannerAnalysis; - let executionTime: number; - - // Platform compatibility check: - // Query Insights requires the MongoDB API explain() command with specific verbosity modes - // (queryPlanner and executionStats). Currently, only DocumentDB supports these features. - // - // Supported platforms: - // - Azure Cosmos DB for MongoDB vCore (domainInfo_api !== 'RU') - // - Native MongoDB clusters - const session: ClusterSession = ClusterSession.getSession(sessionId); - const clusterMetadata = await session.getClient().getClusterMetadata(); - - myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; - if (clusterMetadata?.domainInfo_api === 'RU') { - // TODO: Platform identification improvements needed - // 1. Create a centralized platform detection service (ClusterSession.getPlatformType()) - // 2. Define platform capabilities enum (SupportsExplain, SupportsAggregation, etc.) - // 3. Check capabilities instead of platform names for better maintainability - // 4. Consider adding feature detection (try explain() and handle gracefully) - // 5. Update UI to show platform-specific feature availability - ext.outputChannel.trace( - l10n.t( - '[Query Insights Stage 1] Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.', - ), - ); - - // Create error with code for UI-specific handling - const error = new Error( - l10n.t('Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.'), - ); - // Add error code as a custom property for UI pattern matching - (error as Error & { code?: string }).code = 'QUERY_INSIGHTS_PLATFORM_NOT_SUPPORTED_RU'; - throw error; - } - - // Check for debug override file first - const debugData = readQueryInsightsDebugFile('query-insights-stage1.json'); - if (debugData) { - ext.outputChannel.trace(l10n.t('[Query Insights Stage 1] Using debug data file')); - // Use debug data - analyze it the same way as real data - analyzed = ExplainPlanAnalyzer.analyzeQueryPlanner(debugData); - // Use a default execution time for debug mode - executionTime = 2.5; - } else { - // Get ClusterSession - const session: ClusterSession = ClusterSession.getSession(sessionId); - - // Get execution time from session (tracked during last query execution) - executionTime = session.getLastExecutionTimeMs(); - - // Get query parameters from session with parsed BSON objects - const queryParams = session.getCurrentFindQueryParamsWithObjects(); - - // Get query planner info (cached or fetch) without skip/limit for full query insights - const queryPlannerStart = Date.now(); - const queryPlannerResult = await session.getQueryPlannerInfo( - databaseName, - collectionName, - queryParams.filterObj, - { - sort: queryParams.sortObj, - projection: queryParams.projectionObj, - // Intentionally omit skip/limit for full query insights - }, - ); - const queryPlannerDuration = Date.now() - queryPlannerStart; - ext.outputChannel.trace( - l10n.t('[Query Insights Stage 1] explain(queryPlanner) completed in {ms}ms', { - ms: queryPlannerDuration.toString(), - }), - ); - - // Analyze with ExplainPlanAnalyzer - analyzed = ExplainPlanAnalyzer.analyzeQueryPlanner(queryPlannerResult); - } + const session = ClusterSession.getSession(sessionId); + const { analyzed, executionTime } = await session.runWithClient( + async (client, epoch): Promise<{ analyzed: QueryPlannerAnalysis; executionTime: number }> => { + const clusterMetadata = await client.getClusterMetadata(); + session.assertCurrent(epoch, myCtx.signal); + myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; + if (clusterMetadata?.domainInfo_api === 'RU') { + ext.outputChannel.trace( + l10n.t( + '[Query Insights Stage 1] Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.', + ), + ); + + const error = new Error( + l10n.t('Query Insights is not supported on Azure Cosmos DB for MongoDB (RU) clusters.'), + ); + (error as Error & { code?: string }).code = 'QUERY_INSIGHTS_PLATFORM_NOT_SUPPORTED_RU'; + throw error; + } + + const debugData = readQueryInsightsDebugFile('query-insights-stage1.json'); + if (debugData) { + ext.outputChannel.trace(l10n.t('[Query Insights Stage 1] Using debug data file')); + return { analyzed: ExplainPlanAnalyzer.analyzeQueryPlanner(debugData), executionTime: 2.5 }; + } + + const executionTime = session.getLastExecutionTimeMs(); + const queryParams = session.getCurrentFindQueryParamsWithObjects(); + const queryPlannerStart = Date.now(); + const queryPlannerResult = await session.getQueryPlannerInfo( + client, + epoch, + databaseName, + collectionName, + queryParams.filterObj, + { + sort: queryParams.sortObj, + projection: queryParams.projectionObj, + // Intentionally omit skip/limit for full query insights + }, + myCtx.signal, + ); + ext.outputChannel.trace( + l10n.t('[Query Insights Stage 1] explain(queryPlanner) completed in {ms}ms', { + ms: (Date.now() - queryPlannerStart).toString(), + }), + ); + + return { analyzed: ExplainPlanAnalyzer.analyzeQueryPlanner(queryPlannerResult), executionTime }; + }, + ); // Transform to UI format const transformed = transformStage1Response(analyzed, executionTime); @@ -231,6 +207,8 @@ export const queryInsightsQueriesRouter = router({ let analyzed: ExecutionStatsAnalysis; let explainResult: Document | undefined; let totalCollectionDocs: number | undefined; + const session = ClusterSession.getSession(sessionId); + const epoch = session.getEpoch(); // Check for debug override file first const debugData = readQueryInsightsDebugFile('query-insights-stage2.json'); @@ -242,46 +220,47 @@ export const queryInsightsQueriesRouter = router({ explainResult = debugData; // totalCollectionDocs not available in debug mode — advisories will simply not fire } else { - // Get ClusterSession - const session: ClusterSession = ClusterSession.getSession(sessionId); - - const clusterMetadata = await session.getClient().getClusterMetadata(); - myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; - - // Get query parameters from session with parsed BSON objects - const queryParams = session.getCurrentFindQueryParamsWithObjects(); - - // Get execution stats (cached or fetch) without skip/limit for full query insights - const executionStatsStart = Date.now(); - const executionStatsResult = await session.getExecutionStats( - databaseName, - collectionName, - queryParams.filterObj, - { - sort: queryParams.sortObj, - projection: queryParams.projectionObj, - // Intentionally omit skip/limit for full query insights + ({ explainResult, queryFilter, totalCollectionDocs } = await session.runWithClient( + async (client) => { + const clusterMetadata = await client.getClusterMetadata(); + session.assertCurrent(epoch, myCtx.signal); + myCtx.actionContext.telemetry.properties.platform = clusterMetadata?.domainInfo_api ?? 'unknown'; + + const queryParams = session.getCurrentFindQueryParamsWithObjects(); + const executionStatsStart = Date.now(); + const explainResult = await session.getExecutionStats( + client, + epoch, + databaseName, + collectionName, + queryParams.filterObj, + { + sort: queryParams.sortObj, + projection: queryParams.projectionObj, + // Intentionally omit skip/limit for full query insights + }, + myCtx.signal, + ); + ext.outputChannel.trace( + l10n.t('[Query Insights Stage 2] explain completed in {ms}ms', { + ms: (Date.now() - executionStatsStart).toString(), + }), + ); + + session.assertCurrent(epoch, myCtx.signal); + let totalCollectionDocs: number | undefined; + try { + totalCollectionDocs = await client.estimateDocumentCount(databaseName, collectionName); + } catch (error) { + // Non-critical — advisories and selectivity can be omitted. + ClustersClient.reportFailure(client.binding, error); + } + return { explainResult, queryFilter: queryParams.filterObj, totalCollectionDocs }; }, - ); - const executionStatsDuration = Date.now() - executionStatsStart; - ext.outputChannel.trace( - l10n.t('[Query Insights Stage 2] explain completed in {ms}ms', { - ms: executionStatsDuration.toString(), - }), - ); - - // Analyze with ExplainPlanAnalyzer (pass the user's actual filter for empty-query detection) - analyzed = ExplainPlanAnalyzer.analyzeExecutionStats(executionStatsResult, queryParams.filterObj); - explainResult = executionStatsResult; - queryFilter = queryParams.filterObj as Document | undefined; - - // Fetch total collection docs for index-strategy advisories and selectivity cell - try { - totalCollectionDocs = await session.getClient().estimateDocumentCount(databaseName, collectionName); - } catch { - // Non-critical — advisories and selectivity will simply not fire/display - totalCollectionDocs = undefined; - } + epoch, + )); + session.assertCurrent(epoch, myCtx.signal); + analyzed = ExplainPlanAnalyzer.analyzeExecutionStats(explainResult, queryFilter); } // Extract extended stage info (as per design document) @@ -322,8 +301,7 @@ export const queryInsightsQueriesRouter = router({ // Cache the Stage 2 response for Stage 3's static analysis context if (!debugData) { - const session: ClusterSession = ClusterSession.getSession(sessionId); - session.setStage2Response(transformed, totalCollectionDocs); + session.setStage2Response(epoch, transformed, totalCollectionDocs, myCtx.signal); } // --- Stage 2 telemetry --- From 9de6a42cb983e21aa494aa368f15d4d779c04678 Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Mon, 23 Nov 2026 20:13:27 +0000 Subject: [PATCH 04/44] feat: add the shared unavailable connection banner (WI-6) Reuse the existing Fluent warning block and polite live region with one explicit recovery action. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../iterations/01-dev-plan.md | 7 +++ .../_integration/connectionUnavailable.ts | 18 ++++++ .../components/DisconnectedBanner.test.tsx | 45 +++++++++++++++ .../components/DisconnectedBanner.tsx | 57 +++++++++++++++++++ 4 files changed, 127 insertions(+) create mode 100644 src/webviews/_integration/connectionUnavailable.ts create mode 100644 src/webviews/components/DisconnectedBanner.test.tsx create mode 100644 src/webviews/components/DisconnectedBanner.tsx diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index b29f8f488..c1b6be364 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1526,6 +1526,13 @@ behave as today. Check the epoch, latch, and identity before applying results to session caches. Build and 193 focused tests passed. Procedure response shapes are unchanged for now; structured unavailable results and the remaining panels are subsequent WI-6 slices. +- **Webview design review:** A fresh Claude Opus 5.5 pass recommended one warning banner + using the existing MessageBlock and polite Announcer. Keep the editor and results in + place, do not move focus when the banner appears, and offer one explicit action. The + shared banner and its focused tests are in place, but not yet wired to panels. Keep + both planned stale-reply browser scenarios; adding the small harness support they need + is preferable to reducing coverage. Host action selection for a view with no credential + repair command is pending operator agreement. --- diff --git a/src/webviews/_integration/connectionUnavailable.ts b/src/webviews/_integration/connectionUnavailable.ts new file mode 100644 index 000000000..e5510c2fc --- /dev/null +++ b/src/webviews/_integration/connectionUnavailable.ts @@ -0,0 +1,18 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { type ConnectionUnavailableReason } from '../../documentdb/ConnectionUnavailableError'; + +export type ConnectionRecoveryAction = 'reconnect' | 'signInAgain' | 'updateCredentials' | 'close'; + +export interface ConnectionUnavailableDetails { + readonly reason: ConnectionUnavailableReason; + readonly text: string; + readonly action: ConnectionRecoveryAction; +} + +export interface ConnectionUnavailableResponse { + readonly unavailable: ConnectionUnavailableDetails; +} diff --git a/src/webviews/components/DisconnectedBanner.test.tsx b/src/webviews/components/DisconnectedBanner.test.tsx new file mode 100644 index 000000000..e3a73e765 --- /dev/null +++ b/src/webviews/components/DisconnectedBanner.test.tsx @@ -0,0 +1,45 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules +import { expect, it, vi } from 'vitest'; +import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; +import { DisconnectedBanner } from './DisconnectedBanner'; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +it('offers one explicit recovery action and cannot resubmit while recovery is running', async (): Promise => { + const unavailable: ConnectionUnavailableDetails = { + reason: 'signInRequired', + text: 'Your Microsoft session is unavailable.', + action: 'signInAgain', + }; + const onAction = vi.fn(); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + try { + await act(async () => root.render()); + expect(host.textContent).toContain(unavailable.text); + expect(host.querySelectorAll('button')).toHaveLength(1); + expect(host.querySelector('[role="status"]')?.getAttribute('aria-live')).toBe('polite'); + expect(host.querySelector('button')?.textContent).toBe('Retry sign-in'); + await act(async () => host.querySelector('button')?.click()); + expect(onAction).toHaveBeenCalledExactlyOnceWith('signInAgain'); + + await act(async () => + root.render(), + ); + expect(host.querySelector('button')?.disabled).toBe(true); + await act(async () => host.querySelector('button')?.click()); + expect(onAction).toHaveBeenCalledTimes(1); + } finally { + await act(async () => root.unmount()); + host.remove(); + } +}); diff --git a/src/webviews/components/DisconnectedBanner.tsx b/src/webviews/components/DisconnectedBanner.tsx new file mode 100644 index 000000000..dc79b9845 --- /dev/null +++ b/src/webviews/components/DisconnectedBanner.tsx @@ -0,0 +1,57 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { Button } from '@fluentui/react-components'; +import * as l10n from '@vscode/l10n'; +import { type JSX, type Ref } from 'react'; +import { + type ConnectionRecoveryAction, + type ConnectionUnavailableDetails, +} from '../_integration/connectionUnavailable'; +import { Announcer } from './accessibility'; +import { MessageBlock } from './MessageBlock'; + +interface DisconnectedBannerProps { + readonly unavailable: ConnectionUnavailableDetails; + readonly onAction: (action: ConnectionRecoveryAction) => void; + readonly recovering?: boolean; + readonly actionRef?: Ref; +} + +function actionLabel(action: ConnectionRecoveryAction): string { + switch (action) { + case 'reconnect': + return l10n.t('Reconnect'); + case 'signInAgain': + return l10n.t('Retry sign-in'); + case 'updateCredentials': + return l10n.t('Update credentials…'); + case 'close': + return l10n.t('Close tab'); + } +} + +export function DisconnectedBanner({ + unavailable: { reason, text, action }, + onAction, + recovering, + actionRef, +}: DisconnectedBannerProps): JSX.Element { + return ( + <> + onAction(action)}> + {actionLabel(action)} + + } + > + {text} + + + + ); +} From 798161ce985fcb4a9c535a57011f44f16edfe16a Mon Sep 17 00:00:00 2001 From: Tomasz Naumowicz Date: Tue, 24 Nov 2026 06:24:32 +0000 Subject: [PATCH 05/44] feat: keep disconnected views open under a recovery overlay (WI-6) Record decision 0016 and keep the view mounted and inert until an explicit recovery or close action. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../features/connection-lifecycle/README.md | 6 +- .../connection-lifecycle/decisions.md | 13 +++ .../iterations/01-dev-plan.md | 42 ++++----- .../iterations/01-implementation-plan.md | 15 ++-- .../components/DisconnectedBanner.test.tsx | 45 ---------- .../components/DisconnectedBanner.tsx | 57 ------------ .../components/DisconnectedOverlay.scss | 31 +++++++ .../components/DisconnectedOverlay.test.tsx | 69 +++++++++++++++ .../components/DisconnectedOverlay.tsx | 86 +++++++++++++++++++ 9 files changed, 232 insertions(+), 132 deletions(-) delete mode 100644 src/webviews/components/DisconnectedBanner.test.tsx delete mode 100644 src/webviews/components/DisconnectedBanner.tsx create mode 100644 src/webviews/components/DisconnectedOverlay.scss create mode 100644 src/webviews/components/DisconnectedOverlay.test.tsx create mode 100644 src/webviews/components/DisconnectedOverlay.tsx diff --git a/docs/ai-and-plans/features/connection-lifecycle/README.md b/docs/ai-and-plans/features/connection-lifecycle/README.md index 25a97a0d5..a63502715 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/README.md +++ b/docs/ai-and-plans/features/connection-lifecycle/README.md @@ -49,8 +49,9 @@ Evidence, telemetry and source pointers: [research-findings.md](./research-findi successful results and records a sanitized diagnostic if an account or tenant cannot be listed. - **Keep one client per cluster.** Surfaces resolve it per operation and check its identity fingerprint and generation. -- **Never change identity under an open surface.** It becomes disconnected, keeps its state, says why - and offers one action. +- **Never change identity under an open surface.** It stays open, keeps its state, and shows a + shaded, disabled overlay that explains the reason. Offer **Close** and, when supported, an + explicit recovery action. - After a database rejects a verified Entra identity, discard the client but keep its in-memory connection settings for explicit sign-in. Do not retain the rejected token or retry silently. When the tree offers **Retry sign-in**, it does not also offer **Retry**. @@ -86,6 +87,7 @@ See [decisions.md](./decisions.md): - 0013 corrections to 0012: latch before a credential save, epoch checks on replies, bindings carried through handoffs, an operation wrapper, folder deletion runs teardown. - 0014 retain in-memory settings for explicit sign-in recovery after verified Entra rejection. - 0015 use the existing latch to block startup after authentication rejection until explicit recovery. +- 0016 keep disconnected webviews open under a full-view overlay with explicit actions. ## Timeline diff --git a/docs/ai-and-plans/features/connection-lifecycle/decisions.md b/docs/ai-and-plans/features/connection-lifecycle/decisions.md index 9e5712c39..9b3aa3739 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/decisions.md +++ b/docs/ai-and-plans/features/connection-lifecycle/decisions.md @@ -27,6 +27,7 @@ created: 2026-11-19 | 0013 | Correct the minimal design where it lost edits, identity or recovery: latch before save, epoch checks | Accepted (modifies 0012) | Operator: "update the plan" after the omissions review | 2026-11-19 | — | | 0014 | Keep in-memory connection settings after a rejection for a verified Entra identity | Accepted | Operator selected A to make sign-in recovery smoother | 2026-11-23 | Yes; WI-5 previously said to delete the entry | | 0015 | Use the existing latch to block startup after authentication rejection | Accepted | Operator selected A; keep the approach simple and pragmatic | 2026-11-23 | Yes; expands the existing latch rather than adding a second hold | +| 0016 | Keep disconnected webviews open under a full-view overlay | Accepted | Operator chose a simple disabled state with explicit actions | 2026-11-24 | Yes; replaces the inline banner and single-action layout | > 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 @@ -424,3 +425,15 @@ the epoch still matches. It cannot clear a latch set by Disconnect, Remove or a The operator chose to reuse the existing latch rather than introduce a separate authentication hold, keeping one place to check for an unavailable connection. The rejection latch uses the existing epoch and does not add a subscription, new persistence, or a retry loop. + +## 0016. Keep disconnected webviews open under a full-view overlay + +The operator chose a simple disabled state instead of the planned warning banner. Keep the +webview and its contents mounted, but make the background unavailable for interaction. Shade +the whole view and show a calm, centered explanation with a row of actions. + +Always offer **Close**. If the connection has a supported recovery action, offer it alongside +Close. If there is no repair the tab can perform, show only **Close** and leave the tab open +until the user chooses it. Do not retry rejected credentials or navigate away automatically. +Keep this component local to the lifecycle webviews for now rather than adding a general +feature to the webview framework. diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md index c1b6be364..e9e0b70bc 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-dev-plan.md @@ -1373,7 +1373,7 @@ webview as a structured unavailable result, not a generic query error. - Collection View (all tabs), Document View and the Cluster Dashboard resolve their client per operation through a binding. -- They show an unavailable state (C-5) with a banner and one action. +- They show an unavailable state (C-5) with a full-view overlay, Close, and a repair action when supported. - They keep all user state. - They never apply stale results. - They never run under another identity. @@ -1448,17 +1448,18 @@ approved plan allows; the webview half then stacks on the host half without wait ### Webviews 1. **Shared UI.** - - A `DisconnectedBanner` component: a Fluent `MessageBar` with intent `warning`, the host-provided - reason text and **one** action button. It uses `role="status"` and `aria-live="polite"`. + - A feature-local `DisconnectedOverlay` shades the webview and shows the host-provided reason + text in the center. Show **Close** and at most one supported repair action (decision 0016). + Announce the reason politely and give keyboard focus to an overlay action, not the disabled content. - It shows when a procedure returns `unavailable`, or when the host's `disable(reason)` sends its one message to the panel over the existing webview channel. - Put it in the shared webview components folder, and run the detecting-accessibility-issues skill on it. 2. **Disabling.** - - While the banner shows, every action that talks to the server is disabled: run query, paging, + - While the overlay shows, every action that talks to the server is disabled: run query, paging, refresh, save, delete, insert, index actions, Query Insights stages and AI calls. - - Editors stay **editable**. The user can keep typing. - - A response that arrives while the banner shows is ignored. + - The underlying view is inert. Editors stay mounted and retain their contents and dirty state. + - A response that arrives while the overlay shows is ignored. - **A reply never overwrites a newer edit.** The Document View applies a save or load reply to the editor only if the editor content has not changed since the request was sent; otherwise it keeps the edit and stays dirty. Today's save handler (`documentView.tsx`) replaces the content and clears `isDirty` @@ -1470,14 +1471,15 @@ approved plan allows; the webview half then stacks on the host half without wait - **Dashboard:** the last data (WI-8 stops the polling). 4. **Actions.** - **Reconnect** (same fingerprint): clear the latch if one is set, and resolve again. On success, - remove the banner and re-enable the actions; the live region announces "Reconnected". The query is + remove the overlay and re-enable the actions; the live region announces "Reconnected". The query is not run automatically, and there is **no** "out of date" notice (decision 0010; see #1106). After a Disconnect the credentials are still cached (0011), so this is silent. - **Reconnect after an identity change:** an explicit rebind to the new fingerprint, then show "Now connected as {label}" (OT-3). - **Sign in again:** the WI-5 command. - **Update credentials:** the existing command. - - **Close:** dispose the panel. + - **Close:** dispose the panel only through an explicit action. When no supported repair is + available in the tab, Close is the only action. 5. **L2-dev scenarios** (`scenarios.ts` and `fixtures.ts`): - `collectionView/disconnected-signInRequired`: query text kept, Run disabled, no host calls when Run is clicked; @@ -1501,7 +1503,7 @@ behave as today. - `ClusterSession` no longer stores a client (a type-level or structural test); - a stale result is dropped before any host-side mutation, including a reply that started before a Disconnect and arrives after a Reconnect as the same user; -- the webview ignores a response that arrives while the banner shows; +- the webview ignores a response that arrives while the overlay shows; - one submission for a write whose reply is lost; - an import started from Collection View as identity A, with its file picker left open while the cluster moves to B, writes nothing until the user starts it again; @@ -1526,13 +1528,11 @@ behave as today. Check the epoch, latch, and identity before applying results to session caches. Build and 193 focused tests passed. Procedure response shapes are unchanged for now; structured unavailable results and the remaining panels are subsequent WI-6 slices. -- **Webview design review:** A fresh Claude Opus 5.5 pass recommended one warning banner - using the existing MessageBlock and polite Announcer. Keep the editor and results in - place, do not move focus when the banner appears, and offer one explicit action. The - shared banner and its focused tests are in place, but not yet wired to panels. Keep - both planned stale-reply browser scenarios; adding the small harness support they need - is preferable to reducing coverage. Host action selection for a view with no credential - repair command is pending operator agreement. +- **Webview design decision:** After the advisor's banner draft, the operator chose the + full-view disabled overlay in [decision 0016](../decisions.md#0016-keep-disconnected-webviews-open-under-a-full-view-overlay). + It keeps the content mounted and inert, uses a polite announcement, and shows only Close + when there is no supported repair. The shared component builds and passed its focused + test; panels are not yet wired. Keep both planned stale-reply browser scenarios. --- @@ -1709,7 +1709,7 @@ behave as today. ## WI-8: Cluster Dashboard health polling (PR 6) -**Outcome:** the poll stops when the cluster is unavailable, shows the banner, and resumes with exactly +**Outcome:** the poll stops when the cluster is unavailable, shows the overlay, and resumes with exactly one loop. **Steps:** @@ -1720,18 +1720,18 @@ one loop. of a failed command long enough to classify it. A terminal kind (auth, closed client) is rethrown so that `runWithClient` returns `unavailable`. An unsupported command, such as `serverStatus` on some servers, stays an ordinary partial sample with its entry in `errors`. -2. The webview poll effect depends on the banner state: it stops on `unavailable` or on a `disable` +2. The webview poll effect depends on the overlay state: it stops on `unavailable` or on a `disable` message, and starts again after Reconnect. React's effect cleanup keeps it to one loop; no extra loop token. -3. A ping that resolves while the banner shows is ignored (the WI-6 webview rule), so it cannot clear the - banner. +3. A ping that resolves while the overlay shows is ignored (the WI-6 webview rule), so it cannot clear the + overlay. 4. Visibility pause and backoff are the rest of #1091. Do them here only if they are trivial; otherwise leave them to #1091. **Tests** (fake timers): - no client lookups on ticks or on reveal after Disconnect; -- a late success does not clear the banner; +- a late success does not clear the overlay; - reconnecting starts exactly one loop; - `signInRequired` and `credentialsRejected` stop the loop after one tick, including when they happen **inside** the sampler's ping with the tree untouched; diff --git a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md index c83e4ecc2..965583acc 100644 --- a/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md +++ b/docs/ai-and-plans/features/connection-lifecycle/iterations/01-implementation-plan.md @@ -384,10 +384,11 @@ The largest item. Host side first, then each view. internally; test one application submission when the server accepts a write but its reply is lost. - **Webviews:** - - Push one connection-state channel per view over tRPC: connected, reconnecting, or disconnected - with a reason. Follow the webview-trpc-messaging and react-webview-architecture skills. - - Disconnected disables every action that talks to the server and shows a banner with the reason - and one action: Reconnect, Sign in again, Update credentials, or Close. + - Return unavailable results from operations and use the existing webview message channel for + teardown. Do not add a connection-state subscription (decision 0012). + - Disconnected dims the entire webview, disables the underlying content, and shows the reason + with **Close** and a supported repair (Reconnect, Retry sign-in, or Update credentials), if + available. The tab never closes automatically (decision 0016). - It **keeps** the editor contents, filter, sort, projection, page position and unsaved document edits. - Views: Collection View (query, documents, indexes and Query Insights tabs), Document View @@ -399,7 +400,7 @@ The largest item. Host side first, then each view. is not permission to restart a transfer under another identity. - **Tests:** - router tests for the three binding outcomes; - - a Collection View scenario: disconnected banner with the query text kept; + - a Collection View scenario: disconnected overlay with the query text kept; - a Document View scenario: dirty edit kept; - inject a disconnect after typing, then deliver a stale page or document read; neither applied results nor drafts may be overwritten, and disabled actions must issue no server calls; @@ -460,12 +461,12 @@ Coordinate with #1091. The minimum for this plan: - the poll uses the WI-6 binding; - after a `signInRequired`, `credentialsRejected` or disconnected outcome, polling **stops** and the - dashboard shows the WI-6 banner instead of starting a connection every 5 s. + dashboard shows the WI-6 overlay instead of starting a connection every 5 s. Visibility pause and backoff are the rest of #1091 and may ship separately. Existing visibility and in-flight guards do not distinguish a missing ping sample from terminal auth failure. With fake timers, verify no client lookups on ticks or reveal after Disconnect, -that a late successful ping cannot clear the banner, and that reconnect starts only one poll loop. +that a late successful ping cannot clear the overlay, and that reconnect starts only one poll loop. ## WI-9: Measure token renewal and recovery after release diff --git a/src/webviews/components/DisconnectedBanner.test.tsx b/src/webviews/components/DisconnectedBanner.test.tsx deleted file mode 100644 index e3a73e765..000000000 --- a/src/webviews/components/DisconnectedBanner.test.tsx +++ /dev/null @@ -1,45 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -// @vitest-environment jsdom - -import { act } from 'react'; -import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules -import { expect, it, vi } from 'vitest'; -import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; -import { DisconnectedBanner } from './DisconnectedBanner'; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -it('offers one explicit recovery action and cannot resubmit while recovery is running', async (): Promise => { - const unavailable: ConnectionUnavailableDetails = { - reason: 'signInRequired', - text: 'Your Microsoft session is unavailable.', - action: 'signInAgain', - }; - const onAction = vi.fn(); - const host = document.createElement('div'); - document.body.appendChild(host); - const root = createRoot(host); - try { - await act(async () => root.render()); - expect(host.textContent).toContain(unavailable.text); - expect(host.querySelectorAll('button')).toHaveLength(1); - expect(host.querySelector('[role="status"]')?.getAttribute('aria-live')).toBe('polite'); - expect(host.querySelector('button')?.textContent).toBe('Retry sign-in'); - await act(async () => host.querySelector('button')?.click()); - expect(onAction).toHaveBeenCalledExactlyOnceWith('signInAgain'); - - await act(async () => - root.render(), - ); - expect(host.querySelector('button')?.disabled).toBe(true); - await act(async () => host.querySelector('button')?.click()); - expect(onAction).toHaveBeenCalledTimes(1); - } finally { - await act(async () => root.unmount()); - host.remove(); - } -}); diff --git a/src/webviews/components/DisconnectedBanner.tsx b/src/webviews/components/DisconnectedBanner.tsx deleted file mode 100644 index dc79b9845..000000000 --- a/src/webviews/components/DisconnectedBanner.tsx +++ /dev/null @@ -1,57 +0,0 @@ -/*--------------------------------------------------------------------------------------------- - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for license information. - *--------------------------------------------------------------------------------------------*/ - -import { Button } from '@fluentui/react-components'; -import * as l10n from '@vscode/l10n'; -import { type JSX, type Ref } from 'react'; -import { - type ConnectionRecoveryAction, - type ConnectionUnavailableDetails, -} from '../_integration/connectionUnavailable'; -import { Announcer } from './accessibility'; -import { MessageBlock } from './MessageBlock'; - -interface DisconnectedBannerProps { - readonly unavailable: ConnectionUnavailableDetails; - readonly onAction: (action: ConnectionRecoveryAction) => void; - readonly recovering?: boolean; - readonly actionRef?: Ref; -} - -function actionLabel(action: ConnectionRecoveryAction): string { - switch (action) { - case 'reconnect': - return l10n.t('Reconnect'); - case 'signInAgain': - return l10n.t('Retry sign-in'); - case 'updateCredentials': - return l10n.t('Update credentials…'); - case 'close': - return l10n.t('Close tab'); - } -} - -export function DisconnectedBanner({ - unavailable: { reason, text, action }, - onAction, - recovering, - actionRef, -}: DisconnectedBannerProps): JSX.Element { - return ( - <> - onAction(action)}> - {actionLabel(action)} - - } - > - {text} - - - - ); -} diff --git a/src/webviews/components/DisconnectedOverlay.scss b/src/webviews/components/DisconnectedOverlay.scss new file mode 100644 index 000000000..1a61afd28 --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.scss @@ -0,0 +1,31 @@ +.disconnectedOverlayBackground { + display: contents; +} + +.disconnectedOverlay { + position: fixed; + inset: 0; + z-index: 1000; + display: grid; + place-content: safe center; + justify-items: center; + gap: 10px; + overflow: auto; + padding: 20px; + background: var(--vscode-editor-background); + background: color-mix(in srgb, var(--vscode-editor-background) 90%, transparent); + color: var(--vscode-editor-foreground); + text-align: center; + + p { + max-width: 40ch; + margin: 0; + } +} + +.disconnectedOverlayActions { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 10px; +} diff --git a/src/webviews/components/DisconnectedOverlay.test.tsx b/src/webviews/components/DisconnectedOverlay.test.tsx new file mode 100644 index 000000000..9353b7a72 --- /dev/null +++ b/src/webviews/components/DisconnectedOverlay.test.tsx @@ -0,0 +1,69 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// @vitest-environment jsdom + +import { act } from 'react'; +import { createRoot } from 'react-dom/client'; // eslint-disable-line import/no-internal-modules +import { expect, it, vi } from 'vitest'; +import { type ConnectionUnavailableDetails } from '../_integration/connectionUnavailable'; +import { DisconnectedOverlay } from './DisconnectedOverlay'; + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +it('keeps content mounted but inert, and only closes or retries on explicit clicks', async (): Promise => { + const unavailable: ConnectionUnavailableDetails = { + reason: 'signInRequired', + text: 'Your Microsoft session is unavailable.', + action: 'signInAgain', + }; + const onAction = vi.fn(); + const host = document.createElement('div'); + document.body.appendChild(host); + const root = createRoot(host); + try { + const render = async (failure?: ConnectionUnavailableDetails, recovering?: boolean): Promise => { + await act(async () => + root.render( + +