From 30e99dade70d027788d87adb926d208ded6c4b71 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 09:19:44 -0800 Subject: [PATCH 1/9] agentHost: load recent chat turns first over the relay Page older turns on demand so opening a long chat does not exceed the relay message limit. Keep each subscriber's history window independent and preserve the transcript, checkpoints, and pending sends across reconnects. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- src/vs/platform/agentHost/AGENTS.md | 2 + .../browser/agentHostProtocolClient.ts | 123 ++++++- .../platform/agentHost/common/agentService.ts | 2 + .../common/state/agentSubscription.ts | 35 +- .../agentHost/node/agentHostStateManager.ts | 5 + .../agentHost/node/chatHistoryView.ts | 120 +++++++ .../agentHost/node/protocolServerHandler.ts | 332 +++++++++++++++--- .../agentHostProtocolClient.test.ts | 90 ++++- .../test/node/protocolServerHandler.test.ts | 187 ++++++++++ .../browser/actions/chatAccessibilityHelp.ts | 1 + .../agentHost/agentHostSessionHandler.ts | 158 +++++++-- .../agentHost/agentHostSnapshotController.ts | 20 +- .../cloudSandboxSessionHandler.ts | 4 + .../chat/browser/widget/chatListWidget.ts | 76 +++- .../contrib/chat/browser/widget/chatWidget.ts | 6 +- .../chatService/remoteChatSessionRestorer.ts | 59 +++- .../chat/common/chatSessionsService.ts | 4 + .../contrib/chat/common/model/chatModel.ts | 8 +- .../chat/common/model/chatViewModel.ts | 2 +- .../agentHostSnapshotController.test.ts | 32 +- .../agentHostChatContribution.test.ts | 165 ++++++++- .../browser/widget/chatListWidget.test.ts | 68 ++++ .../common/chatService/chatService.test.ts | 81 +++++ 23 files changed, 1451 insertions(+), 129 deletions(-) create mode 100644 src/vs/platform/agentHost/node/chatHistoryView.ts diff --git a/src/vs/platform/agentHost/AGENTS.md b/src/vs/platform/agentHost/AGENTS.md index 420a87aaeb0ea8..d64ba45273fac3 100644 --- a/src/vs/platform/agentHost/AGENTS.md +++ b/src/vs/platform/agentHost/AGENTS.md @@ -34,6 +34,8 @@ ### Guiding principles +- **Paged chat history is a subscription view, not provider state.** With `subscribe.view.turns`, `ProtocolServerHandler` returns a recent tail of completed turns, normally within 4 MiB of UTF-8 JSON. `fetchTurns` prepends one older page only on that subscription before acknowledging it. Without the hint, the snapshot contains all retained turns. A new baseline issues a fresh cursor; private pages are never part of shared action replay. +- On reconnect, a received page and its cursor survive ordinary action replay. A missed private page, a history reset, or a change of authorization requires a fresh baseline. Relay clients resume at most one chat in the handshake (preferring a pending prompt), then subscribe to the others individually. A client checking a lost prompt acknowledgement must not infer non-delivery from a short history page: check the echoed sequence, or the turn ID in retained history before resending. - **"Represent, don't orchestrate."** The agent harness creates and drives SDK chats; the orchestrator records what exists and routes protocol actions. No agent-specific logic leaks into `AgentService` or `AgentHostStateManager`. - **Composition over inheritance.** All harnesses share one membership path (`addChat`/`removeChat`), one authoritative persistence path (`AgentHostPeerChatStore` in `agent-host.db`, with a `PEER_CHATS_METADATA_KEY` compatibility mirror), and one restore path (`registerRestoredChatSummary` + `resolveChatState`). Per-harness features are expressed through `IAgentCapabilities` flags, not `if (provider === 'claude') ...` branches. - **Single catalog path.** Whether a chat is created by the user ("Add Chat") or spawned by the harness (subagent tool call), it enters the catalog through exactly one path (`AgentHostStateManager.addChat`). See invariant I4 below. diff --git a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts index fa5844ea74355f..d9c6ca16080cde 100644 --- a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts +++ b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts @@ -64,7 +64,7 @@ import type { IAgentHostFirstResponseDiagnostic } from '../common/otel/agentHost import type { IChatUserInteractionTiming } from '../../otel/common/chatUserInteraction.js'; import { AMBIENT_AGENT_HOST_AUTHORITY } from '../common/agentHostConnectionsService.js'; import { createRemoteWatchHandle, type IRemoteWatchHandle } from '../common/agentHostFileSystemProvider.js'; -import { AgentSubscriptionManager, type IActiveSubscriptionInfo, type IAgentSubscription } from '../common/state/agentSubscription.js'; +import { AgentSubscriptionManager, ChatStateSubscription, type IActiveSubscriptionInfo, type IAgentSubscription } from '../common/state/agentSubscription.js'; import { AGENT_HOST_SCHEME, agentHostAuthority, createAgentHostResourceUriMapper, fromAgentHostUri, type IAgentHostResourceUriMapper, toAgentHostUri } from '../common/agentHostUri.js'; import { AgentHostResourceIdentity, AgentHostResourcePermissionError, IAgentHostResourceService, LOCAL_AGENT_HOST_RESOURCE_IDENTITY } from '../common/agentHostResourceService.js'; import type { ClientNotificationMap, CommandMap, JsonRpcErrorResponse, JsonRpcRequest, JsonRpcResponse } from '../common/state/protocol/messages.js'; @@ -150,6 +150,8 @@ function toAgentExtensionStatus(value: unknown): AgentExtensionStatus | undefine */ const PING_INTERVAL_MS = 5_000; +const relayChatPageTurns = 10; + /** * Total inbound silence (ping interval + this) before a non-local connection * is declared dead and force-closed so the renderer's reconnect logic kicks @@ -387,7 +389,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect get clientConnectionKind(): AgentHostClientConnectionKind | undefined { return this._transport.clientConnectionKind; } private _relayRootRefresh: { readonly transport: IProtocolTransport; readonly promise: Promise } | undefined; private _initialAuthenticationResource: string | undefined; - private _expiredRelayAuthentication: { readonly transport: IProtocolTransport; readonly resource: string } | undefined; + private _expiredRelayAuthentication: { readonly transport: IProtocolTransport; readonly resource: string; readonly unsentTurns: Set; readonly pendingTurns: Set } | undefined; /** Disposable holding the listeners attached to the current transport. */ private readonly _transportListeners = this._register(new MutableDisposable()); /** The next reconnect sends `initialize` instead of `reconnect`, so the host decides its capabilities again. */ @@ -1227,7 +1229,18 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect reconnect.transportConnected = true; this._recordInboundTraffic(); - const subscriptions = this._subscriptionManager.currentSubscriptionUris().map(u => u.toString()); + const resources = this._subscriptionManager.currentSubscriptionUris(); + // An older host can return full snapshots. Never combine several relay chat histories in a handshake. + const chats = resources.filter(resource => this._usesPagedChatHistory(resource) && !this._subscriptionsAwaitingRestore.has(resource.toString()) + && this._subscriptionManager.getSubscriptionUnmanaged(resource)?.verifiedValue); + const resumeChat = chats.find(resource => this._subscriptionManager.getSubscriptionUnmanaged(resource)?.hasPendingActions) ?? chats[0]; + const subscriptions = resources.filter(resource => { + if (resource !== resumeChat && this._usesPagedChatHistory(resource)) { + this._subscriptionsAwaitingRestore.add(resource.toString()); + return false; + } + return true; + }).map(resource => resource.toString()); // Always include the always-live root state alongside getSubscription-managed entries. if (!subscriptions.includes(ROOT_STATE_URI)) { subscriptions.unshift(ROOT_STATE_URI); @@ -1247,6 +1260,9 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect this._gitHubEnvironment.set(getAgentHostGitHubEnvironmentStatus(result), undefined); } this._applyReconnectResult(result, freshInitialize, restoreAuthentication); + if (result.type === ReconnectResultType.Snapshot && resumeChat && !result.snapshots.some(s => s.resource === resumeChat.toString())) { + this._subscriptionsAwaitingRestore.add(resumeChat.toString()); + } this._updateManagedSettingsPermissions(true); // A replacement transport may need authentication even when the host remembers this client. if (restoreAuthentication) { @@ -1267,6 +1283,12 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect return; } } + if (resumeChat && result.type === ReconnectResultType.Snapshot && result.snapshots.some(s => s.resource === resumeChat.toString())) { + await this._verifyPendingPagedTurns(resumeChat); + if (!await this._continueReconnectAfterResume(reconnect, attempt, transport)) { + return; + } + } // Re-push renderer-owned config on reconnect too: a reconnected host may // be a freshly restarted process that never received these values (the @@ -1383,6 +1405,15 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect } return { result, freshInitialize: false, windowSnapshots }; } catch (error) { + if (error instanceof ProtocolError && error.code === JSON_RPC_INTERNAL_ERROR) { + const paged = subscriptions.filter(channel => this._usesPagedChatHistory(URI.parse(channel))); + if (paged.length) { + for (const channel of paged) { + this._subscriptionsAwaitingRestore.add(channel); + } + return this._reconnectOrInitialize(lastSeenServerSeq, subscriptions.filter(channel => !paged.includes(channel))); + } + } if (!(error instanceof ProtocolError) || error.code !== AhpErrorCodes.NotFound) { throw error; } @@ -1397,7 +1428,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect clientId: this._clientId, clientInfo: this._clientInfo, _meta: this._clientMeta(), - initialSubscriptions: subscriptions, + initialSubscriptions: subscriptions.filter(channel => !this._usesPagedChatHistory(URI.parse(channel))), }, { bypassReconnectGate: true }); this._windowedStateChannels.clear(); this._applyInitializeResult(initializeResult, false); @@ -1458,9 +1489,12 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect snapshot.resource, snapshot.state, snapshot.fromSeq, - !windowSnapshot, + this._usesPagedChatHistory(subscription.resource) ? 'turnStarts' : !windowSnapshot, ); this._serverSeq = Math.max(this._serverSeq, snapshot.fromSeq); + if (this._usesPagedChatHistory(subscription.resource)) { + await this._verifyPendingPagedTurns(subscription.resource); + } this._subscriptionsAwaitingRestore.delete(resource); } catch (error) { if (error instanceof ProtocolError && error.code === AHP_CLIENT_CONNECTION_CLOSED) { @@ -1468,6 +1502,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect this._subscriptionManager.cancelSnapshotRefresh(subscription.resource); throw error; } + this._logService.warn(`[AgentHostProtocolClient] Failed to restore subscription ${resource} after reconnect: ${error instanceof Error ? error.message : String(error)}`); this._subscriptionManager.cancelSnapshotRefresh(subscription.resource); this._subscriptionManager.markSubscriptionsMissing([subscription.resource]); @@ -1483,6 +1518,47 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect ]); } + /** A short snapshot may omit an accepted turn. Look back only to the last turn known when it was sent. */ + private async _verifyPendingPagedTurns(resource: URI): Promise { + if (!this._usesPagedChatHistory(resource)) { + return; + } + const sub = this._subscriptionManager.getSubscriptionUnmanaged(resource); + if (!(sub instanceof ChatStateSubscription) || !sub.hasPendingActions) { + return; + } + const channel = resource.toString(); + const queued = new Set(this._expiredRelayAuthentication?.unsentTurns); + if (this._state.kind === AgentHostClientState.Reconnecting) { + for (const message of this._state.reconnect.outbox) { + if (hasKey(message, { method: true }) && message.method === 'dispatchAction') { + queued.add(message.params.clientSeq); + } + } + } + const visited = new Set(); + try { + for (let cursor = sub.getTurnRecoveryCursor(queued); cursor; cursor = sub.getTurnRecoveryCursor(queued)) { + this._subscriptionsAwaitingRestore.add(channel); + if (visited.has(cursor) || visited.size >= 8) { + throw new Error('History recovery limit reached'); + } + visited.add(cursor); + await this._dispatchRequest('fetchTurns', { channel, cursor }, { bypassReconnectGate: true, timeoutMs: 30_000 }); + if (this._subscriptionManager.getSubscriptionUnmanaged(resource) !== sub) { + break; + } + } + } catch (error) { + if (error instanceof ProtocolError && error.code === AHP_CLIENT_CONNECTION_CLOSED) { + throw error; + } + sub.clearPending(); + sub.setError(new Error(localize('unverifiedPendingTurn', "Could not verify delivery of your message. It was not resent: {0}", getErrorMessage(error)))); + } + this._subscriptionsAwaitingRestore.delete(channel); + } + private async _restoreAuthentication(expectedState: AgentHostClientState.Connecting | AgentHostClientState.Reconnecting): Promise { const state = this._state; const transport = this._transport; @@ -1816,7 +1892,8 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect let maxSeq = this._serverSeq; for (const hostSnapshot of result.snapshots) { const snapshot = this._withOlderHostSnapshot(hostSnapshot); - this._subscriptionManager.applyReconnectSnapshot(snapshot.resource, snapshot.state, snapshot.fromSeq, preservePending); + this._subscriptionManager.applyReconnectSnapshot(snapshot.resource, snapshot.state, snapshot.fromSeq, + this._usesPagedChatHistory(URI.parse(snapshot.resource)) ? 'turnStarts' : preservePending); // This snapshot came from the current host, so it settles any // restore still owed for the channel. this._subscriptionsAwaitingRestore.delete(snapshot.resource); @@ -1877,6 +1954,10 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect this._sendMessage(msg); } for (const msg of outbox) { + if (hasKey(msg, { method: true }) && msg.method === 'dispatchAction' + && this._subscriptionManager.getSubscriptionUnmanaged(URI.parse(msg.params.channel))?.value instanceof Error) { + continue; + } this._sendMessage(msg); } } @@ -1895,6 +1976,10 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect return this._subscriptionManager.getSubscriptionUnmanaged(resource); } + async fetchTurns(chat: URI, cursor: string): Promise { + await this._sendRequest('fetchTurns', { channel: chat.toString(), cursor }); + } + getInflightSessionCreate(resource: URI): Promise | undefined { return this._subscriptionManager.getInflightSessionCreate(resource); } @@ -2080,7 +2165,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect return snapshot; } - private async _subscribeWindowedChannel(channel: string, receive: ChannelReceiveLimits | undefined, acceptWindow: (flowControl: ChannelFlowControl) => void, options: { readonly bypassReconnectGate?: boolean; readonly timeoutMs?: number } = {}): Promise { + private async _subscribeWindowedChannel(channel: string, receive: ChannelReceiveLimits | undefined, acceptWindow: (flowControl: ChannelFlowControl) => void, options: { readonly bypassReconnectGate?: boolean; readonly timeoutMs?: number; readonly view?: CommandMap['subscribe']['params']['view'] } = {}): Promise { const pending = this._pendingChannelSubscriptions.get(channel) ?? { generation: 0, requests: 0, windowed: false, messages: [], bufferedBytes: 0 }; this._pendingChannelSubscriptions.set(channel, pending); pending.requests++; @@ -2107,11 +2192,13 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect } }; try { + const { view, ...requestOptions } = options; return await this._dispatchRequest('subscribe', { channel, + ...(view && { view }), ...(receive ? { flowControl: { receive } } : {}), }, { - ...options, + ...requestOptions, acceptResult: value => { if (pending.generation !== generation) { throw new CancellationError(); @@ -2149,18 +2236,22 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect } } + private _usesPagedChatHistory(resource: URI): boolean { + return this._isWebPubSubRelay() && this._subscriptionManager.getSubscriptionKind(resource) === StateComponents.Chat; + } + private async _requestSnapshot(resource: URI, bypassReconnectGate = false): Promise { const channel = resource.toString(); const receive = !isAhpRootChannel(channel) && !this._isWebPubSubRelay() ? agentHostStateReceiveLimits : undefined; let pending: Promise | undefined; const result = await this._subscribeWindowedChannel(channel, receive, flowControl => { pending = this._acceptStateChannel(channel, flowControl); - }, { bypassReconnectGate }); + }, { bypassReconnectGate, view: this._usesPagedChatHistory(resource) ? { turns: relayChatPageTurns } : undefined }); const snapshot = pending ? await pending : result.snapshot; if (!snapshot) { throw new Error(`subscribe to ${channel} returned no snapshot`); } - if (pending) { + if (pending || this._usesPagedChatHistory(resource)) { this._serverSeq = Math.max(this._serverSeq, snapshot.fromSeq); } return this._withOlderHostSnapshot(snapshot); @@ -2228,6 +2319,10 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect * Dispatch a client action to the server. Returns the clientSeq used. */ private dispatchAction(channel: string, action: SessionAction | ChatAction | TerminalAction | ClientChangesetAction | ClientAnnotationsAction | ClientAutomationAction | ClientAutomationRunAction | IRootConfigChangedAction, _clientId: string, clientSeq: number): void { + if (action.type === ActionType.ChatTurnStarted && this._expiredRelayAuthentication && this._usesPagedChatHistory(URI.parse(channel))) { + this._expiredRelayAuthentication.unsentTurns.add(clientSeq); + return; + } this._grantImplicitReadsForOutgoingAction(action); if (action.type === ActionType.ChatTurnStarted) { this._onDidConnectionDiagnostic.fire({ @@ -2776,6 +2871,11 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect } if (this._expiredRelayAuthentication === expired && this._transport === transport && !operation.token.isCancellationRequested) { this._expiredRelayAuthentication = undefined; + for (const { channel, clientSeq, action } of this._subscriptionManager.getPendingActions()) { + if (action.type === ActionType.ChatTurnStarted && (expired.pendingTurns.has(clientSeq) || expired.unsentTurns.has(clientSeq))) { + this.dispatchAction(channel, action, this._clientId, clientSeq); + } + } this._onDidReconnect.fire(); } } @@ -3370,7 +3470,8 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect if (msg.method === 'auth/required' && this._isWebPubSubRelay() && isAhpRootChannel(msg.params.channel) && msg.params.reason === AuthRequiredReason.Expired && msg.params.resource.resource === this._initialAuthenticationResource && !this._expiredRelayAuthentication) { - this._expiredRelayAuthentication = { transport: this._transport, resource: msg.params.resource.resource }; + const pendingTurns = this._subscriptionManager.getPendingActions().filter(p => p.action.type === ActionType.ChatTurnStarted).map(p => p.clientSeq); + this._expiredRelayAuthentication = { transport: this._transport, resource: msg.params.resource.resource, pendingTurns: new Set(pendingTurns), unsentTurns: new Set() }; this._markSubscriptionsAwaitingRestore([]); } this._logService.trace(`[RemoteAgentHostProtocol] Notification: ${msg.method}`); diff --git a/src/vs/platform/agentHost/common/agentService.ts b/src/vs/platform/agentHost/common/agentService.ts index 55edabaec6179b..c0296c9854f494 100644 --- a/src/vs/platform/agentHost/common/agentService.ts +++ b/src/vs/platform/agentHost/common/agentService.ts @@ -1415,6 +1415,8 @@ export interface IAgentConnection { */ getSubscription(kind: T, resource: URI, owner: string): IReference>; getSubscriptionUnmanaged(kind: T, resource: URI): IAgentSubscription | undefined; + /** Loads the preceding page into the subscribed chat using its host-issued cursor. */ + fetchTurns?(chat: URI, cursor: string): Promise; /** * Returns the in-flight `createSession` Promise for `resource`, or `undefined` if no create is pending. Callers diff --git a/src/vs/platform/agentHost/common/state/agentSubscription.ts b/src/vs/platform/agentHost/common/state/agentSubscription.ts index 69e4f2a9ff9b31..f89e752c624ffb 100644 --- a/src/vs/platform/agentHost/common/state/agentSubscription.ts +++ b/src/vs/platform/agentHost/common/state/agentSubscription.ts @@ -478,6 +478,7 @@ export class SessionStateSubscription extends BaseAgentSubscription { */ applyOptimistic(action: ChatAction): number { const clientSeq = this._seqAllocator(); - this._pendingActions.push({ clientSeq, action }); + const previousTurnId = action.type === ActionType.ChatTurnStarted ? this.verifiedValue?.activeTurn?.id ?? this.verifiedValue?.turns.at(-1)?.id : undefined; + this._pendingActions.push({ clientSeq, action, previousTurnId }); const base = this._optimisticState ?? this.verifiedValue; if (base) { this._optimisticState = chatReducer(base, action as IProtocolChatAction, this._log); @@ -543,7 +545,12 @@ export class ChatStateSubscription extends BaseAgentSubscription { } protected override _onSnapshotApplied(fromSeq: number): void { - // A snapshot can confirm a turn before this subscription receives its start acknowledgement. + this._acknowledgeVisibleTurns(); + super._onSnapshotApplied(fromSeq); + this._recomputeOptimistic(); + } + + private _acknowledgeVisibleTurns(): void { const state = this._confirmedState; for (let i = this._pendingActions.length - 1; i >= 0; i--) { const action = this._pendingActions[i].action; @@ -552,8 +559,15 @@ export class ChatStateSubscription extends BaseAgentSubscription { this._pendingActions.splice(i, 1); } } - super._onSnapshotApplied(fromSeq); - this._recomputeOptimistic(); + } + + getTurnRecoveryCursor(unsent: ReadonlySet): string | undefined { + const state = this.verifiedValue; + if (state?.turnsNextCursor && this._pendingActions.some(p => p.action.type === ActionType.ChatTurnStarted && !unsent.has(p.clientSeq) + && (!p.previousTurnId || (p.previousTurnId !== state.activeTurn?.id && !state.turns.some(t => t.id === p.previousTurnId))))) { + return state.turnsNextCursor; + } + return undefined; } protected override _reconcile(envelope: ActionEnvelope, isOwnAction: boolean): void { @@ -575,6 +589,9 @@ export class ChatStateSubscription extends BaseAgentSubscription { this._promotePendingTurnStartIfTerminal(envelope.action); this._confirmedApply(envelope.action); } + if (envelope.action.type === ActionType.ChatTurnsLoaded && !envelope.rejectionReason) { + this._acknowledgeVisibleTurns(); + } this._recomputeOptimistic(); } @@ -1340,7 +1357,7 @@ export class AgentSubscriptionManager extends Disposable { * subscription when {@link ROOT_STATE_URI} matches, otherwise reseats the * matching entry in {@link _subscriptions}. Unknown resources are ignored. */ - applyReconnectSnapshot(resource: string, state: unknown, fromSeq: number, preservePending = false): void { + applyReconnectSnapshot(resource: string, state: unknown, fromSeq: number, preservePending: boolean | 'turnStarts' = false): void { if (isAhpRootChannel(resource)) { this._rootState.handleSnapshot(state as RootState, fromSeq); return; @@ -1355,7 +1372,13 @@ export class AgentSubscriptionManager extends Disposable { // Clear any pending optimistic actions before reseating confirmed // state \u2014 they were predicated on the pre-disconnect confirmed // state and won't reconcile correctly against a fresh snapshot. - if (!preservePending && (entry.sub instanceof SessionStateSubscription || entry.sub instanceof ChatStateSubscription || entry.sub instanceof AnnotationsStateSubscription)) { + if (preservePending === 'turnStarts' && entry.sub instanceof ChatStateSubscription) { + for (const { clientSeq, action } of entry.sub.getPendingActions()) { + if (action.type !== ActionType.ChatTurnStarted) { + entry.sub.dropPendingByClientSeq(clientSeq); + } + } + } else if (!preservePending && (entry.sub instanceof SessionStateSubscription || entry.sub instanceof ChatStateSubscription || entry.sub instanceof AnnotationsStateSubscription)) { entry.sub.clearPending(); } entry.sub.handleSnapshot(state as never, fromSeq); diff --git a/src/vs/platform/agentHost/node/agentHostStateManager.ts b/src/vs/platform/agentHost/node/agentHostStateManager.ts index 4df8f3ae4f138f..bdb04df4a00ca1 100644 --- a/src/vs/platform/agentHost/node/agentHostStateManager.ts +++ b/src/vs/platform/agentHost/node/agentHostStateManager.ts @@ -2784,6 +2784,11 @@ export class AgentHostStateManager extends Disposable { return { channel, action, serverSeq: ++this._serverSeq, origin: undefined }; } + /** Distinguishes two subscription baselines even if no shared state changed between them. */ + allocateSnapshotSequence(): number { + return ++this._serverSeq; + } + /** * Dispatch a server-originated action (from the agent backend). * The action is applied to state via the reducer and emitted as an diff --git a/src/vs/platform/agentHost/node/chatHistoryView.ts b/src/vs/platform/agentHost/node/chatHistoryView.ts new file mode 100644 index 00000000000000..b45b61e8d749e4 --- /dev/null +++ b/src/vs/platform/agentHost/node/chatHistoryView.ts @@ -0,0 +1,120 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { generateUuid } from '../../../base/common/uuid.js'; +import { ActionType } from '../common/state/sessionActions.js'; +import { JsonRpcErrorCodes, ProtocolError } from '../common/state/sessionProtocol.js'; +import type { Turn } from '../common/state/sessionState.js'; +import { DEFAULT_MAX_REASSEMBLY_BYTES } from '../common/webPubSub/chunking.js'; + +const pageBytes = 4 * 1024 * 1024; +// Includes room for the JSON-RPC envelope, sequence, and cursor. +const maximumBytes = DEFAULT_MAX_REASSEMBLY_BYTES - 1024; + +/** A connection's boundary between retained and displayed turns. Never stored in authoritative state. */ +export class ChatHistoryView { + private _hidden = 0; + private _boundary: Turn | undefined; + private _cursor: string | undefined; + private _length = 0; + private _lastTurn: WeakRef | undefined; + private _lastPrivateSeq = Infinity; + readonly count: number; + + constructor(count: number, private readonly _project: (turn: Turn) => Turn) { + if (!Number.isSafeInteger(count) || count < 0) { + throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'Invalid chat view turn count'); + } + this.count = Math.min(100, Math.max(1, count)); + } + + get hiddenCount(): number { return this._hidden; } + + recordPrivateDelivery(serverSeq: number): void { + this._lastPrivateSeq = serverSeq; + } + + resume(previous: ChatHistoryView, turns: readonly Turn[], lastSeen: number): boolean { + if (lastSeen < previous._lastPrivateSeq || turns.length < previous._length || turns[previous._hidden - 1] !== previous._boundary + || turns[previous._length - 1] !== previous._lastTurn?.deref()) { + return false; + } + this._lastPrivateSeq = previous._lastPrivateSeq; + this._cursor = previous._cursor; + this._hidden = previous._hidden; + this._boundary = previous._boundary; + this.observeTurns(turns); + return true; + } + + baseline(turns: readonly Turn[], snapshotBytes: number) { + return this._page(turns, turns.length, snapshotBytes, 'snapshot'); + } + + fetch(turns: readonly Turn[], cursor: string | undefined, envelopeBytes: number) { + if ((cursor !== undefined && cursor !== this._cursor) || turns[this._hidden - 1] !== this._boundary) { + throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'Unrecognized fetchTurns cursor; resubscribe to the chat'); + } + return this._page(turns, this._hidden, envelopeBytes); + } + + /** Prepending retained history must not push an unbounded load, or create a gap in the displayed suffix. */ + prepend(turns: readonly Turn[], envelopeBytes: number) { + return this._page(turns, this._hidden + turns.length - this._length, envelopeBytes, 'notification'); + } + + truncate(turns: readonly Turn[], target: string | undefined): boolean { + this.observeTurns(turns); + if (target === undefined) { + this._setBoundary(turns, 0); + } + return target !== undefined && turns.length <= this._hidden && turns.at(-1)?.id === target; + } + + rebaseline(turns: readonly Turn[], envelopeBytes: number) { + return this._page(turns, turns.length, envelopeBytes, 'notification'); + } + + observeTurns(turns: readonly Turn[]): void { + const last = turns.at(-1); + if (last !== this._lastTurn?.deref()) { + this._lastTurn = last && new WeakRef(last); + } + this._length = turns.length; + } + + private _setBoundary(turns: readonly Turn[], start: number): void { + this._hidden = start; + this._boundary = turns[start - 1]; + this._cursor = start > 0 ? generateUuid() : undefined; + this.observeTurns(turns); + } + + private _page(turns: readonly Turn[], end: number, bytes: number, kind: 'fetch' | 'snapshot' | 'notification' = 'fetch') { + if (bytes > maximumBytes) { + throw new ProtocolError(JsonRpcErrorCodes.InternalError, 'Chat snapshot exceeds the transport message size limit without history'); + } + const page: Turn[] = []; + let start = end; + while (start > 0 && page.length < this.count) { + const turn = this._project(turns[start - 1]); + const turnBytes = Buffer.byteLength(JSON.stringify(turn)) + 1; + if (page.length && bytes + turnBytes > pageBytes) { + break; + } + if (bytes + turnBytes > maximumBytes) { + if (kind === 'notification' || (kind === 'snapshot' && turnBytes <= maximumBytes)) { + break; + } + throw new ProtocolError(JsonRpcErrorCodes.InternalError, 'Chat turn exceeds the transport message size limit'); + } + page.push(turn); + bytes += turnBytes; + start--; + } + this._setBoundary(turns, start); + return { type: ActionType.ChatTurnsLoaded as const, turns: page.reverse(), ...(this._cursor ? { turnsNextCursor: this._cursor } : {}) }; + } +} diff --git a/src/vs/platform/agentHost/node/protocolServerHandler.ts b/src/vs/platform/agentHost/node/protocolServerHandler.ts index f13656a9f158a9..16ad0399db34c2 100644 --- a/src/vs/platform/agentHost/node/protocolServerHandler.ts +++ b/src/vs/platform/agentHost/node/protocolServerHandler.ts @@ -69,13 +69,15 @@ import { ChatMoveDestinationKind, ChatSourceKind } from '../common/state/protoco import { AgentChatMoveRefusedError, type AgentChatMoveDestination } from '../common/agentHostChatMove.js'; import type { CommandMap } from '../common/state/protocol/messages.js'; import type { ChatConfigChangedAction, SessionConfigChangedAction } from '../common/state/protocol/actions.js'; -import type { AutomationEntry, RootConfigState } from '../common/state/protocol/state.js'; +import { MessageAttachmentKind, type AutomationEntry, type ChatState, type RootConfigState } from '../common/state/protocol/state.js'; import { ActionEnvelope, ActionType, INotification, isAnnotationsAction, isAutomationAction, isAutomationRunAction, isChangesetAction, isChatAction, isSessionAction, isTerminalAction } from '../common/state/sessionActions.js'; import { compareProtocolVersions, isActionKnownToVersion, PROTOCOL_VERSION } from '../common/state/protocol/version/registry.js'; import { AgentHostTcpBudget } from '../common/agentHostTcpConnection.js'; import { agentHostStateReceiveLimits, negotiateChannelFlowControl } from '../common/agentHostChannel.js'; import { ChannelRecoveryKind, type ChannelFlowControl, type ResumedChannelSubscription } from '../common/state/protocol/common/state.js'; import { AgentHostConnectionChannels } from './agentHostConnectionChannels.js'; +import { ChatHistoryView } from './chatHistoryView.js'; +import { DEFAULT_MAX_REASSEMBLY_BYTES } from '../common/webPubSub/chunking.js'; import { getAgentHostSupportedProtocolVersions, negotiateAgentHostProtocolVersion } from '../common/agentHostProtocolCompatibility.js'; import { VSCODE_UPGRADE_METHOD, type UnsupportedProtocolVersionErrorDataEx } from '../common/state/protocolUpgrade.js'; import { getAgentHostManagementSocketPath, requestAgentHostUpgrade } from './agentHostUpgradeChannel.js'; @@ -431,7 +433,7 @@ const enum ChannelKind { * exposing pre-snapshot actions to the client. */ type ChannelSubscription = - | { readonly kind: ChannelKind.State; readonly uri: string; readonly active: boolean } + | { readonly kind: ChannelKind.State; readonly uri: string; readonly active: boolean; readonly history?: ChatHistoryView } | { readonly kind: ChannelKind.ResourceWatch; readonly uri: string; readonly active: boolean } | { readonly kind: ChannelKind.McpServerLogs; readonly uri: string; readonly session: string; readonly serverName: string; readonly level: OtlpLogLevelName; readonly disposable?: IDisposable } | { readonly kind: ChannelKind.OtlpLogs; readonly uri: string; readonly level: OtlpLogLevelName }; @@ -511,6 +513,7 @@ interface IConnectedClient { * the same logical channel collapse to one entry. */ readonly subscriptions: Map; + expiredChatViews?: Map; readonly channels: AgentHostConnectionChannels; readonly knownSessionSummaries: Set; readonly pendingAuthenticationSubscriptions: Set; @@ -552,6 +555,8 @@ interface IActiveClientRecord { } interface IGraceClientRecord { + readonly chatViews?: ReadonlyMap; + readonly chatViewPrincipal?: string; readonly legacySessionUris?: boolean; readonly legacyChatUris?: boolean; readonly state: 'grace'; @@ -746,6 +751,8 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien */ private readonly _baselineDebt = new Map>(); private readonly _replayBuffer: ActionEnvelope[] = []; + private _lastEvictedServerSeq = 0; + private readonly _chatSubscribeResults = new WeakMap>(); private readonly _extensionEnvelopes = new WeakSet(); private readonly _relayRootConfigEnvelopes = new WeakMap(); private readonly _telemetryReporter: AgentHostTelemetryReporter; @@ -865,6 +872,8 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien const record = client ? this._clients.get(client.clientId) : undefined; if (client && record?.state === 'active') { this._clearScopedModels(client); + const expired = this._chatViews(client); + client.expiredChatViews = new Map([...expired].map(([channel, view]) => [channel, this._createChatView(client!, channel, view.count)])); this._releaseClientSubscriptions(client, record, true); this._reconcileActiveClientSubscriptions(client); this._rejectPendingReverseRequestsForConnection(client, new ProtocolError(AHP_AUTH_REQUIRED, 'Relay identity authentication expired')); @@ -888,31 +897,31 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien // Handle initialize/reconnect as requests that set up the client if (!client && msg.method === 'initialize') { try { + const previousRecord = this._clients.get(msg.params.clientId); const result = this._handleInitialize(msg.params, transport, disposables); client = result.client; liveness.reset(); const sendInitializeResult = (response: IAgentHostExtensionInitializeResult) => { if (!disposables.isDisposed) { - transport.send(jsonRpcSuccess(msg.id, { ...response, snapshots: this._projectRelaySnapshots(result.client, response.snapshots) })); + transport.send(this._handshakeResponse(result.client, previousRecord, msg.id, + () => ({ ...response, snapshots: this._projectRelaySnapshots(result.client, response.snapshots) }))); this._onDidChangeQueuedCredentials.fire(); } }; if (result.response instanceof Promise) { - this._trackRequest(result.response).then( - sendInitializeResult, - err => { - if (client === result.client) { - client = undefined; - } - if (!disposables.isDisposed) { - transport.send(jsonRpcErrorFrom(msg.id, err)); - } - }, - ); + this._trackRequest(result.response).then(sendInitializeResult).catch(err => { + if (client === result.client) { + client = undefined; + } + if (!disposables.isDisposed) { + transport.send(jsonRpcErrorFrom(msg.id, err)); + } + }); } else { sendInitializeResult(result.response); } } catch (err) { + client = undefined; transport.send(jsonRpcErrorFrom(msg.id, err)); } return; @@ -921,27 +930,26 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien let responsePromise: Promise; let reconnectingClient: IConnectedClient; try { + const previousRecord = this._clients.get(msg.params.clientId); const result = this._handleReconnect(msg.params, transport, disposables); client = result.client; liveness.reset(); reconnectingClient = result.client; responsePromise = this._trackRequest(result.responsePromise); - responsePromise.then( - response => { - if (!disposables.isDisposed) { - channels.respond(jsonRpcSuccess(msg.id, this._projectRelayReconnectResult(reconnectingClient, response, msg.params.subscriptions)), response.windows?.items); - this._onDidChangeQueuedCredentials.fire(); - } - }, - err => { - if (client === reconnectingClient) { - client = undefined; - } - if (!disposables.isDisposed) { - transport.send(jsonRpcErrorFrom(msg.id, err)); - } - }, - ); + responsePromise.then(response => { + if (!disposables.isDisposed) { + channels.respond(this._handshakeResponse(reconnectingClient, previousRecord, msg.id, + () => this._projectRelayReconnectResult(reconnectingClient, response, msg.params.subscriptions)), response.windows?.items); + this._onDidChangeQueuedCredentials.fire(); + } + }).catch(err => { + if (client === reconnectingClient) { + client = undefined; + } + if (!disposables.isDisposed) { + transport.send(jsonRpcErrorFrom(msg.id, err)); + } + }); } catch (err) { transport.send(jsonRpcErrorFrom(msg.id, err)); } @@ -1015,6 +1023,7 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien const connectionIndex = record.connections.indexOf(client); if (connectionIndex !== -1) { const subscriptionCount = client.subscriptions.size; + const chatViews = this._chatViews(client); record.connections.splice(connectionIndex, 1); this._releaseClientSubscriptions(client, record); this._rejectPendingReverseRequestsForConnection(client); @@ -1022,6 +1031,8 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien this._logService.info(`[ProtocolServer] Client disconnected: ${client.clientId}, subscriptions=${subscriptionCount}`); this._clients.set(client.clientId, { state: 'grace', + chatViews, + chatViewPrincipal: this._chatViewPrincipal(client.transport), seenConnection: true, legacySessionUris: client.legacySessionUris, legacyChatUris: client.legacyChatUris, @@ -1397,6 +1408,7 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien if (offer === undefined || client.transport.relayClientId !== undefined || isAhpRootChannel(channel) || classifyChannel(channel)?.kind !== ChannelKind.State) { return undefined; } + try { return negotiateChannelFlowControl(channel, offer.receive, agentHostStateReceiveLimits); } catch { @@ -1404,6 +1416,38 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien } } + private _chatViewPrincipal(transport: IProtocolTransport): string | undefined { + const auth = transport.relayAuthentication; + return auth?.authenticated === false ? undefined : JSON.stringify([transport.relayClientId, auth?.resource, auth?.owner]); + } + + private _chatViews(client: IConnectedClient): Map { + const views = new Map(client.expiredChatViews); + for (const sub of client.subscriptions.values()) { + if (sub.kind === ChannelKind.State && sub.history) { + views.set(sub.uri, sub.history); + } + } + return views; + } + + private _createChatView(client: IConnectedClient, channel: string, count: number): ChatHistoryView { + const vscode = getAgentHostClientType(client.clientInfo) !== AgentHostClientType.Unknown; + return new ChatHistoryView(count, turn => this._usesCopilotModelConfig(channel) ? projectCopilotTurn(turn, vscode) : turn); + } + + private _pagedChatBaseline(client: IConnectedClient, channel: string, view: ChatHistoryView): IStateSnapshot { + const snapshot = this._agentService.getSnapshot(channel); + if (!snapshot || !hasKey(snapshot.state, { turns: true }) || !this._isChannelVisible(client, channel)) { + throw new ProtocolError(AHP_SESSION_NOT_FOUND, `Session not found: ${channel}`); + } + const base = this._projectRelayRootSnapshot(client, { ...snapshot, state: { ...snapshot.state, turns: [] } }); + const { turns, turnsNextCursor } = view.baseline(snapshot.state.turns, Buffer.byteLength(JSON.stringify(base))); + const fromSeq = this._stateManager.allocateSnapshotSequence(); + view.recordPrivateDelivery(fromSeq); + return { ...base, fromSeq, state: { ...base.state as ChatState, turns, ...(turnsNextCursor ? { turnsNextCursor } : {}) } }; + } + private _serveStateWindow(client: IConnectedClient, channel: string, snapshot: IStateSnapshot): void { let restored: IStateSnapshot | undefined = snapshot; client.channels.serveState(channel, () => { @@ -1490,6 +1534,11 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien const priorProtocolVersion = existingRecord.state === 'active' ? existingRecord.connections.at(-1)?.protocolVersion : existingRecord.protocolVersion; + const views = existingRecord.state === 'active' + ? this._chatViews(existingRecord.connections.at(-1)!) + : existingRecord.chatViews; + const sameViewPrincipal = existingRecord.state === 'grace' && existingRecord.chatViewPrincipal !== undefined + && existingRecord.chatViewPrincipal === this._chatViewPrincipal(transport); const isReconnect = this._clientConnections.hasSeenClient(params.clientId); const initializationDisposables = disposables.add(new DisposableStore()); const client: IConnectedClient = { @@ -1522,14 +1571,14 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien // for authority" until the client disconnected and re-initialized. this._registerClientFileSystemAuthority(params.clientId, initializationDisposables); - const oldestBuffered = this._replayBuffer.length > 0 ? this._replayBuffer[0].serverSeq : this._stateManager.serverSeq; // A global cursor only proves the client saw every ACTION; it says // nothing about whether a given channel ever received state from this // process to apply them to. Force snapshots while any requested // channel still owes a baseline. - const canReplay = params.lastSeenServerSeq >= oldestBuffered + const canReplay = params.lastSeenServerSeq >= this._lastEvictedServerSeq + && params.lastSeenServerSeq <= this._stateManager.serverSeq && !this._hasBaselineDebt(params.clientId, params.subscriptions); - const responsePromise = this._restoreReconnectSubscriptions(client, params, canReplay).then(result => { + const responsePromise = this._restoreReconnectSubscriptions(client, params, canReplay, views, sameViewPrincipal).then(result => { // Notifications are not replayed, so a reconnecting client also needs the current GitHub environment status. const githubEnvironmentMeta = this._getGitHubEnvironmentMeta(transport); return (transport.relayHandshakeMeta || Object.keys(githubEnvironmentMeta).length > 0) && typeof result === 'object' && result !== null @@ -1638,6 +1687,8 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien client: IConnectedClient, params: ReconnectParams, canReplay: boolean, + views?: ReadonlyMap, + sameViewPrincipal = false, ): Promise { const missing = [...new Set([ ...params.subscriptions, @@ -1645,7 +1696,7 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien ].filter(channel => channel.startsWith('ahp-tcp:')))]; const negotiatedWindows = new Map(); for (const item of params.windows?.items ?? []) { - if (!params.subscriptions.includes(item.channel) || negotiatedWindows.has(item.channel)) { + if (!params.subscriptions.includes(item.channel) || negotiatedWindows.has(item.channel) || views?.has(item.channel)) { continue; } try { @@ -1673,6 +1724,10 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien } restoredUris.add(classified.uri); if (client.transport.relayAuthentication?.authenticated === false && !isAhpRootChannel(key)) { + const previous = views?.get(key); + if (previous) { + (client.expiredChatViews ??= new Map()).set(key, this._createChatView(client, key, previous.count)); + } client.pendingAuthenticationSubscriptions.add(key); missing.push(sub); return undefined; @@ -1712,7 +1767,9 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien }; } const pendingSubscription: ChannelSubscription = { ...classified, active: false }; - pendingSubscriptions.push({ pending: pendingSubscription, active: classified }); + const previous = views?.get(key); + const active = previous === undefined ? classified : { ...classified, history: this._createChatView(client, key, previous.count), active: false }; + pendingSubscriptions.push({ pending: pendingSubscription, active }); client.subscriptions.set(classified.uri, pendingSubscription); try { const snapshot = await this._subscribeStateChannel( @@ -1746,9 +1803,17 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien // Activate the batch only after every restore settles so no channel can // receive an action both live and through the reconnect replay. + const paged = pendingSubscriptions.filter(({ pending, active }) => client.subscriptions.get(pending.uri) === pending && active.kind === ChannelKind.State && active.history); + canReplay &&= params.lastSeenServerSeq >= this._lastEvictedServerSeq && paged.every(({ active }) => { + const turns = this._stateManager.getChatState(active.uri)?.turns; + return sameViewPrincipal && active.kind === ChannelKind.State && !!turns + && active.history!.resume(views!.get(active.uri)!, turns, params.lastSeenServerSeq) + && !this._replayBuffer.some(e => e.serverSeq > params.lastSeenServerSeq && e.channel === active.uri + && (e.action.type === ActionType.ChatTruncated || e.action.type === ActionType.ChatTurnsLoaded)); + }); for (const { pending, active } of pendingSubscriptions) { if (client.subscriptions.get(pending.uri) === pending) { - client.subscriptions.set(active.uri, active); + client.subscriptions.set(active.uri, canReplay && active.kind === ChannelKind.State && active.history ? { ...active, active: true } : active); } } this._reconcileActiveClientSubscriptions(client); @@ -1762,18 +1827,27 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien if (canReplay) { const actions: ActionEnvelope[] = []; + const resumed = [...this._stateAndResourceWatchUris(client)]; for (const envelope of this._replayBuffer) { - if (envelope.serverSeq > params.lastSeenServerSeq && !client.channels.has(envelope.channel)) { + if (envelope.serverSeq > params.lastSeenServerSeq && !client.channels.has(envelope.channel) && isActionEnvelopeRelevantToSubscriptionUris(envelope, resumed)) { const projected = this._isRelevantToClient(client, envelope) ? this._projectActionForClient(client, envelope) : undefined; if (projected) { actions.push(projected); } } } - return { type: ReconnectResultType.Replay, actions, missing, ...windows }; + if (!paged.length || !this._isRelayClient(client) || !this._exceedsChatReplayBudget(actions)) { + return { type: ReconnectResultType.Replay, actions, missing, ...windows }; + } + } + // If several paged chats need fresh baselines, don't resume them together in one relay message. + if (paged.length > 1 && this._isRelayClient(client)) { + for (const { active } of paged) { + this._removeSubscription(client, active.uri); + } } const refreshedSnapshots = snapshots.map(snapshot => { - if (!snapshot || client.channels.has(snapshot.resource)) { + if (!snapshot || client.channels.has(snapshot.resource) || !client.subscriptions.has(snapshot.resource)) { return undefined; } const subscription = client.subscriptions.get(snapshot.resource.toString()); @@ -1791,6 +1865,11 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien return { type: ReconnectResultType.Snapshot, snapshots: refreshedSnapshots.filter((s): s is IStateSnapshot => s !== undefined), ...windows }; } + private _exceedsChatReplayBudget(actions: readonly ActionEnvelope[]): boolean { + let bytes = 0; + return actions.some(action => (bytes += Buffer.byteLength(JSON.stringify(action))) > 4 * 1024 * 1024); + } + /** Releases active-client and tool ownership not retained by another live connection's subscriptions. */ private _reconcileActiveClientSubscriptions(client: IConnectedClient): void { for (const session of this._stateManager.getSessionUris()) { @@ -2348,7 +2427,9 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien }, }; } - const flowControl = this._negotiateStateWindow(client, params.channel, params.flowControl); + const history = isAhpChatChannel(params.channel) && params.view?.turns !== undefined + ? this._createChatView(client, params.channel, params.view.turns) : undefined; + const flowControl = history ? undefined : this._negotiateStateWindow(client, params.channel, params.flowControl); const existingSubscription = client.subscriptions.get(classified.uri); const pendingSubscription = existingSubscription?.kind === ChannelKind.State && existingSubscription.active ? existingSubscription @@ -2363,7 +2444,9 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien if (client.subscriptions.get(classified.uri) !== pendingSubscription) { throw new Error(`Subscription cancelled: ${params.channel}`); } - client.subscriptions.set(classified.uri, classified); + const subscription = history ? { ...classified, history, active: false } : classified; + client.subscriptions.set(classified.uri, subscription); + client.expiredChatViews?.delete(classified.uri); client.pendingAuthenticationSubscriptions.delete(classified.uri); this._clearClientToolCallDisconnectTimeout(client.clientId, classified.uri); this._clearBaselineDebt(client.clientId, classified.uri); @@ -2371,10 +2454,11 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien this._serveStateWindow(client, classified.uri, snapshot); return { flowControl }; } - // `IStateSnapshot` is widened with `ChatState` (see sessionProtocol.ts); - // the generated wire `Snapshot` union does not list it yet. The value - // is JSON over the wire, so narrowing at this boundary is safe. - return { snapshot: snapshot as SubscribeResult['snapshot'] }; + const result: SubscribeResult = { snapshot }; + if (isAhpChatChannel(classified.uri)) { + this._chatSubscribeResults.set(result, subscription); + } + return result; } catch (err) { // Losing request ownership cancels the subscription, not the resource. if (client.subscriptions.get(classified.uri) !== pendingSubscription) { @@ -2520,6 +2604,10 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien if (params.provider !== undefined) { options = { ...options, provider: params.provider }; } + if (source) { + this._loadReferencedTurn(_client, source.chat, source.turnId); + } + this._loadChatAttachmentTurns(_client, params.initialMessage); const create = () => this._agentService.createChat( URI.parse(params.channel), URI.parse(params.chat), @@ -2647,18 +2735,19 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien completions: async (_client, params) => { return this._agentService.completions(params); }, - fetchTurns: async (_client, params) => { - const state = this._stateManager.getChatState(params.channel); - if (!state) { + fetchTurns: async (client, params) => { + const sub = client.subscriptions.get(params.channel); + const snapshot = this._stateManager.getSnapshot(params.channel); + if (sub?.kind !== ChannelKind.State || !sub.active || !snapshot || !hasKey(snapshot.state, { turns: true }) + || !this._isChannelVisible(client, params.channel) || this._getActiveClient(client.clientId) !== client) { throw new ProtocolError(AHP_SESSION_NOT_FOUND, `Session not found: ${params.channel}`); } - if (params.cursor && params.cursor !== state.turnsNextCursor) { - throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, `Unrecognized fetchTurns cursor`); + if (!sub.history && params.cursor !== undefined) { + throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, 'Unrecognized fetchTurns cursor'); } - this._stateManager.dispatchServerAction(params.channel, { - type: ActionType.ChatTurnsLoaded, - turns: [], - }); + const page = sub.history?.fetch(snapshot.state.turns, params.cursor, Buffer.byteLength(JSON.stringify(params.channel))) + ?? { type: ActionType.ChatTurnsLoaded as const, turns: [] }; + this._sendAction(client, this._stateManager.createServerActionEnvelope(params.channel, page)); return {}; }, resourceList: async (_client, params) => { @@ -2753,8 +2842,26 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien if (!result.snapshot) { return result; } + const sub = this._chatSubscribeResults.get(result); + if (sub && client.subscriptions.get(sub.uri) !== sub) { + throw new SubscriptionCancelledError(sub.uri); + } + if (sub?.history) { + try { + const snapshot = this._pagedChatBaseline(client, sub.uri, sub.history); + client.subscriptions.set(sub.uri, { ...sub, active: true }); + return { snapshot }; + } catch (error) { + this._removeSubscription(client, sub.uri); + throw error; + } + } // Refresh before the ordinary response discards the window's queued actions. const snapshot = client.channels.getStateSnapshot(result.snapshot.resource) ?? this._projectRelayRootSnapshot(client, result.snapshot); + if (sub && client.transport.relayClientId !== undefined && Buffer.byteLength(JSON.stringify(snapshot)) > DEFAULT_MAX_REASSEMBLY_BYTES - 1024) { + this._removeSubscription(client, sub.uri); + throw new ProtocolError(JsonRpcErrorCodes.InternalError, 'Chat snapshot exceeds the transport message size limit; subscribe with view.turns'); + } return { ...result, snapshot: snapshot as SubscribeResult['snapshot'] }; }, }; @@ -3063,6 +3170,21 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien // Rejections are broadcast and replayed; Assisted permissions feedback must not be. this._stateManager.rejectClientAction(params.channel, action.type === ActionType.ChatToolCallConfirmed ? withoutAgentPermissionFeedback(action) : action, origin, rejection); } else if (isHandledClientAction(action)) { + try { + if (action.type === ActionType.ChatTurnResume) { + this._loadReferencedTurn(client, params.channel, action.turnId); + } + if (action.type === ActionType.ChatTurnStarted || action.type === ActionType.ChatPendingMessageSet) { + this._loadChatAttachmentTurns(client, action.message); + } + } catch (error) { + if (!(error instanceof ProtocolError)) { + throw error; + } + checkAuthorization(); + this._stateManager.rejectClientAction(params.channel, action, origin, error.message); + return; + } return this._agentService.dispatchAction(params.channel, action, client.clientId, params.clientSeq, client.telemetryContext, this._config.scopedRelayCredentials ? this._getScopedAuthentication(client) : undefined); } @@ -3341,7 +3463,29 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien private _projectRelaySnapshots(client: IConnectedClient, snapshots: readonly IStateSnapshot[]): IStateSnapshot[] { return snapshots .filter(snapshot => client.transport.relayAuthentication?.authenticated !== false || isAhpRootChannel(snapshot.resource)) - .map(snapshot => this._projectRelayRootSnapshot(client, snapshot)); + .filter(snapshot => !isAhpChatChannel(snapshot.resource) || (client.subscriptions.has(snapshot.resource) && this._isChannelVisible(client, snapshot.resource))) + .map(snapshot => { + const sub = client.subscriptions.get(snapshot.resource); + if (sub?.kind === ChannelKind.State && sub.history) { + const baseline = this._pagedChatBaseline(client, sub.uri, sub.history); + client.subscriptions.set(sub.uri, { ...sub, active: true }); + return baseline; + } + return this._projectRelayRootSnapshot(client, snapshot); + }); + } + + private _handshakeResponse(client: IConnectedClient, previousRecord: IClientRecord | undefined, id: number, project: () => IAgentHostExtensionInitializeResult | ReconnectResult): JsonRpcResponse { + try { + const response = jsonRpcSuccess(id, project()); + if (client.transport.relayClientId !== undefined && Buffer.byteLength(JSON.stringify(response)) > DEFAULT_MAX_REASSEMBLY_BYTES) { + throw new ProtocolError(JsonRpcErrorCodes.InternalError, 'Handshake exceeds the transport message size limit; subscribe to chats separately with view.turns'); + } + return response; + } catch (error) { + this._rollbackFailedInitialization(client, previousRecord); + throw error; + } } private _projectRelayReconnectResult(client: IConnectedClient, result: ReconnectResult, requestedSubscriptions: readonly string[]): ReconnectResult { @@ -4563,7 +4707,7 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien } this._replayBuffer.push(envelope); if (this._replayBuffer.length > REPLAY_BUFFER_CAPACITY) { - this._replayBuffer.shift(); + this._lastEvictedServerSeq = this._replayBuffer.shift()!.serverSeq; } this._broadcastAction(envelope); } @@ -4573,15 +4717,86 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien for (const record of this._clients.values()) { const client = this._getActiveClientFromRecord(record); if (client && this._isRelevantToClient(client, envelope)) { + const sub = client.subscriptions.get(envelope.channel); + if (sub?.kind === ChannelKind.State && sub.history && !envelope.rejectionReason && this._sendChatViewAction(client, sub.history, envelope)) { + continue; + } const projected = this._projectActionForClient(client, envelope); if (projected) { - const msg: AhpServerNotification<'action'> = { jsonrpc: '2.0', method: 'action', params: this._projectRelayRootAction(client, projected) }; - client.channels.send(msg); + this._sendAction(client, this._projectRelayRootAction(client, projected)); } } } } + private _sendAction(client: IConnectedClient, envelope: ActionEnvelope): void { + if (envelope.action.type === ActionType.ChatTurnsLoaded) { + const sub = client.subscriptions.get(envelope.channel); + if (sub?.kind === ChannelKind.State) { + sub.history?.recordPrivateDelivery(envelope.serverSeq); + } + } + const msg: AhpServerNotification<'action'> = { jsonrpc: '2.0', method: 'action', params: envelope }; + client.channels.send(msg); + } + + private _loadChatAttachmentTurns(client: IConnectedClient, message: Message | undefined): void { + for (const attachment of message?.attachments ?? []) { + if (attachment.type === MessageAttachmentKind.Chat && attachment.endTurn !== undefined) { + this._loadReferencedTurn(client, attachment.resource, attachment.endTurn); + } + } + } + + private _loadReferencedTurn(client: IConnectedClient, channel: string, turnId: string): void { + const sub = client.subscriptions.get(channel); + if (sub?.kind !== ChannelKind.State || !sub.active || !sub.history?.hiddenCount) { + return; + } + const checkAuthorization = this._captureRelayAuthorization(client); + const snapshot = this._stateManager.getSnapshot(channel); + if (!snapshot || !hasKey(snapshot.state, { turns: true }) || !this._isChannelVisible(client, channel)) { + return; + } + const turns = snapshot.state.turns; + const target = turns.findIndex(turn => turn.id === turnId); + while (target >= 0 && target < sub.history.hiddenCount) { + checkAuthorization(); + if (client.subscriptions.get(channel) !== sub || this._getActiveClient(client.clientId) !== client) { + throw new SubscriptionCancelledError(channel); + } + const page = sub.history.fetch(turns, undefined, Buffer.byteLength(JSON.stringify(channel))); + this._sendAction(client, this._stateManager.createServerActionEnvelope(channel, page)); + } + } + + private _sendChatViewAction(client: IConnectedClient, view: ChatHistoryView, envelope: ActionEnvelope): boolean { + const { channel, action } = envelope; + const snapshot = this._stateManager.getSnapshot(channel); + if (!snapshot || !hasKey(snapshot.state, { turns: true })) { + return true; + } + const turns = snapshot.state.turns; + if (action.type === ActionType.ChatTurnsLoaded) { + const page = view.prepend(turns, Buffer.byteLength(JSON.stringify(channel))); + this._sendAction(client, { ...envelope, action: page }); + return true; + } + if (action.type === ActionType.ChatTruncated && view.truncate(turns, action.turnId)) { + // Reset to the retained prefix instead of sending history the truncation discards. + this._sendAction(client, { ...envelope, action: { type: ActionType.ChatTruncated } }); + const sub = client.subscriptions.get(channel); + if (sub?.kind !== ChannelKind.State || sub.history !== view || !this._isRelevantToClient(client, envelope)) { + return true; + } + const page = view.rebaseline(turns, Buffer.byteLength(JSON.stringify(channel))); + this._sendAction(client, this._stateManager.createServerActionEnvelope(channel, page)); + return true; + } + view.observeTurns(turns); + return false; + } + private _broadcastNotification(notification: INotification): void { if (this._config.relayRoots) { return; @@ -4852,6 +5067,7 @@ export class ProtocolServerHandler extends Disposable implements IAgentHostClien * and tears down the agent-service refcount for state channels. */ private _removeSubscription(client: IConnectedClient, channel: string): void { + client.expiredChatViews?.delete(channel); client.channels.remove(channel); const classified = classifyChannel(channel); if (!classified) { diff --git a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts index 453850564359ff..3f339969dc9088 100644 --- a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts +++ b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts @@ -42,7 +42,7 @@ import { buildAnnotationsUri } from '../../common/annotationsUri.js'; import { CODEX_SESSION_MODEL_META_KEY, withCodexSessionModel } from '../../common/meta/codexSessionModel.js'; import { toAgentPermissionResponseMeta } from '../../common/meta/agentPermissionResponseMeta.js'; import { ConfigurationTarget, type IConfigurationValue } from '../../../configuration/common/configuration.js'; -import { CompletionItemKind, ContentEncoding, ReconnectResultType } from '../../common/state/protocol/commands.js'; +import { CompletionItemKind, ContentEncoding, ReconnectResultType, type InitializeParams, type ReconnectParams } from '../../common/state/protocol/commands.js'; import { ChatSourceKind } from '../../common/state/protocol/channels-chat/commands.js'; import { ChatInteractivity, ResourceChangeType, ResponsePartKind, SessionLifecycle } from '../../common/state/protocol/state.js'; import { AhpErrorCodes, JsonRpcErrorCodes } from '../../common/state/protocol/errors.js'; @@ -5766,6 +5766,8 @@ suite('AgentHostProtocolClient', () => { transport.fireMessage({ jsonrpc: '2.0', id: watchSubscription.id, result: {} }); await flushMicrotasks(); + const start = chatTurnStarted('delivery', 'Continue', '2026-10-02T00:01:00Z'); + client.dispatch(chatUri.toString(), start); transport.fireMessage({ jsonrpc: '2.0', method: 'auth/required', params: { channel: ROOT_STATE_URI, resource: { resource: 'https://api.github.com' }, reason: AuthRequiredReason.Expired }, @@ -5777,7 +5779,7 @@ suite('AgentHostProtocolClient', () => { transport.fireMessage({ jsonrpc: '2.0', id: rootSubscription.id, result: root }); for (const [index, snapshot] of snapshots.entries()) { const subscribe = await waitForRequestAtWithin(transport, 'subscribe', index + 5); - assert.deepStrictEqual(subscribe.params, { channel: snapshot.resource }); + assert.deepStrictEqual(subscribe.params, { channel: snapshot.resource, ...(index === 1 ? { view: { turns: 10 } } : {}) }); if (index === 0) { transport.fireMessage({ jsonrpc: '2.0', method: 'auth/required', @@ -5786,10 +5788,11 @@ suite('AgentHostProtocolClient', () => { } transport.fireMessage({ jsonrpc: '2.0', id: subscribe.id, - result: { snapshot: { ...snapshot, state: { ...snapshot.state, title: 'After expiry' }, fromSeq: 3 } }, + result: { snapshot: { ...snapshot, state: { ...snapshot.state, title: 'After expiry', ...(index === 1 && connectionKind === AgentHostClientConnectionKind.WebPubSub ? { activeTurn: chatReducer(chatState, start).activeTurn } : {}) }, fromSeq: 3 } }, }); } await renewed; + assert.strictEqual(transport.sentMessages.filter(m => hasKey(m, { method: true }) && m.method === 'dispatchAction').length, connectionKind === AgentHostClientConnectionKind.WebPubSub ? 1 : 2); const restoredWatch = await waitForRequestAtWithin(transport, 'createResourceWatch', 1); transport.fireMessage({ jsonrpc: '2.0', id: restoredWatch.id, result: { channel: 'ahp-resource-watch:/restored' } }); const restoredWatchSubscription = await waitForRequestAtWithin(transport, 'subscribe', 7); @@ -5846,7 +5849,7 @@ suite('AgentHostProtocolClient', () => { transport.fireMessage({ jsonrpc: '2.0', id: restored.id, result: { snapshot: { resource, state, fromSeq: 2 } } }); await renewed; assert.deepStrictEqual({ request: restored.params, state: subscription.object.value }, { - request: { channel: resource }, state, + request: { channel: resource, ...(kind === StateComponents.Chat ? { view: { turns: 10 } } : {}) }, state, }); }); } @@ -6179,6 +6182,85 @@ suite('AgentHostProtocolClient', () => { await connectPromise; } + for (const recovery of ['fresh', 'oversize', 'replayLostRequest', 'replayLostEcho', 'snapshotHiddenEcho', 'snapshotLostRequest'] as const) { + test(`pages an opaque chat and reconciles its pending prompt on ${recovery}`, async () => { + const fresh = recovery === 'fresh'; + const kind = fresh ? AgentHostClientConnectionKind.MissionControl : AgentHostClientConnectionKind.WebPubSub; + const { client, transports } = createFactoryClient(undefined, undefined, undefined, { autoRestore: true, initialDelayMs: 1, maxDelayMs: 1, maxAttempts: 1 }, undefined, undefined, undefined, undefined, kind); + const connecting = client.connect(); + await completeHandshake(transports[0], connecting); + const chat = URI.parse('store://other-host/conversations/not-a-local-id'); + const channel = chat.toString(); + const state = createChatState({ resource: channel, title: 'Recent messages', status: SessionStatus.Idle, modifiedAt: new Date(0).toISOString() }); + const snapshot = { resource: channel, fromSeq: 5, state }; + const ref = disposables.add(client.getSubscription(StateComponents.Chat, chat, 'test')); + const first = await waitForRequestAtWithin(transports[0], 'subscribe', 0); + transports[0].fireWireMessage({ jsonrpc: '2.0', id: first.id, result: { snapshot: { ...snapshot, state: { ...state, turnsNextCursor: 'opaque previous page' } } } }); + await flushMicrotasks(); + const tail = ref.object.value; + assert.ok(tail && !(tail instanceof Error) && tail.turnsNextCursor); + const fetching = client.fetchTurns(chat, tail.turnsNextCursor); + const page = await waitForRequestAtWithin(transports[0], 'fetchTurns', 0); + const start = chatTurnStarted('pending', 'Continue', '2026-01-02T00:00:00.000Z'); + const prior = chatReducer(chatReducer(state, { ...start, turnId: 'earlier' }), chatTurnComplete('earlier', 1)).turns; + transports[0].fireWireMessage({ jsonrpc: '2.0', method: 'action', params: { channel, serverSeq: 6, action: { type: ActionType.ChatTurnsLoaded, turns: prior, turnsNextCursor: 'older' } } }); + transports[0].fireWireMessage({ jsonrpc: '2.0', id: page.id, result: {} }); + await fetching; + client.dispatch(channel, start); + const original = findDispatchAction(transports[0], ActionType.ChatTurnStarted)!; + const origin = { clientId: client.clientId, clientSeq: (original.params as { clientSeq: number }).clientSeq }; + + const recovered = Event.toPromise(client.onDidReconnect); + transports[0].fireClose(); + const transport = await waitForTransport(transports, 1); + transport.connectDeferred.complete(); + const reconnect = await waitForRequestAtWithin(transport, 'reconnect', 0); + if (fresh) { + transport.fireWireMessage({ jsonrpc: '2.0', id: reconnect.id, error: { code: AhpErrorCodes.NotFound, message: 'Client not found' } }); + const initialize = await waitForRequestAtWithin(transport, 'initialize', 0); + assert.deepStrictEqual((initialize.params as InitializeParams).initialSubscriptions, [ROOT_STATE_URI]); + transport.fireWireMessage({ jsonrpc: '2.0', id: initialize.id, result: { protocolVersion: PROTOCOL_VERSION, serverSeq: 6, snapshots: [] } }); + const root = await waitForRequestAtWithin(transport, 'subscribe', 0); + assert.deepStrictEqual(root.params, { channel: ROOT_STATE_URI }); + transport.fireWireMessage({ jsonrpc: '2.0', id: root.id, result: { snapshot: { resource: ROOT_STATE_URI, fromSeq: 6, state: { agents: [] } } } }); + const restore = await waitForRequestAtWithin(transport, 'subscribe', 1); + assert.deepStrictEqual(restore.params, { channel, view: { turns: 10 } }); + // A host that ignores the advisory view is also valid. + transport.fireWireMessage({ jsonrpc: '2.0', id: restore.id, result: { snapshot } }); + } else if (recovery === 'oversize') { + transport.fireWireMessage({ jsonrpc: '2.0', id: reconnect.id, error: { code: -32603, message: 'Handshake does not fit' } }); + const reduced = await waitForRequestAtWithin(transport, 'reconnect', 1); + assert.deepStrictEqual((reduced.params as ReconnectParams).subscriptions, [ROOT_STATE_URI]); + transport.fireWireMessage({ jsonrpc: '2.0', id: reduced.id, result: { type: ReconnectResultType.Replay, actions: [], missing: [] } }); + const restore = await waitForRequestAtWithin(transport, 'subscribe', 0); + assert.deepStrictEqual(restore.params, { channel, view: { turns: 10 } }); + transport.fireWireMessage({ jsonrpc: '2.0', id: restore.id, result: { snapshot: { ...snapshot, state: { ...state, turns: prior, turnsNextCursor: 'older' } } } }); + } else if (recovery === 'snapshotHiddenEcho' || recovery === 'snapshotLostRequest') { + transport.fireWireMessage({ jsonrpc: '2.0', id: reconnect.id, result: { type: ReconnectResultType.Snapshot, snapshots: [{ ...snapshot, fromSeq: 8, state: { ...state, turnsNextCursor: 'check' } }] } }); + const check = await waitForRequestAtWithin(transport, 'fetchTurns', 0); + assert.deepStrictEqual(check.params, { channel, cursor: 'check' }); + const turns = recovery === 'snapshotLostRequest' ? prior : chatReducer(chatReducer(state, start), chatTurnComplete(start.turnId, 1)).turns; + transport.fireWireMessage({ jsonrpc: '2.0', method: 'action', params: { channel, serverSeq: 9, action: { type: ActionType.ChatTurnsLoaded, turns, turnsNextCursor: 'older' } } }); + transport.fireWireMessage({ jsonrpc: '2.0', id: check.id, result: {} }); + } else { + const actions = recovery === 'replayLostEcho' ? [{ channel, serverSeq: 7, origin, action: start }] : []; + transport.fireWireMessage({ jsonrpc: '2.0', id: reconnect.id, result: { type: ReconnectResultType.Replay, actions, missing: [] } }); + } + await recovered; + const restored = ref.object.value; + assert.ok(restored && !(restored instanceof Error)); + assert.deepStrictEqual({ + first: first.params, previous: page.params, handshake: (reconnect.params as ReconnectParams).subscriptions, + retries: transport.sentMessages.filter(m => hasKey(m, { method: true }) && m.method === 'dispatchAction'), + resource: restored.resource, cursor: restored.turnsNextCursor, turns: restored.turns.map(t => t.id), + }, { + first: { channel, view: { turns: 10 } }, previous: { channel, cursor: 'opaque previous page' }, handshake: [ROOT_STATE_URI, channel], + retries: fresh || recovery === 'oversize' || recovery === 'replayLostRequest' || recovery === 'snapshotLostRequest' ? [original] : [], + resource: channel, cursor: fresh ? undefined : 'older', turns: fresh ? [] : recovery === 'snapshotHiddenEcho' ? ['pending'] : ['earlier'], + }); + }); + } + /** * Connects a client whose host's `multipleChatProviders` gate is off at the handshake (no capability), then turns * the gate on through a root config action, as this client's own mirror does. Returns the requests each transport sent. diff --git a/src/vs/platform/agentHost/test/node/protocolServerHandler.test.ts b/src/vs/platform/agentHost/test/node/protocolServerHandler.test.ts index fdcb5f260ed2d3..990f14a68533a9 100644 --- a/src/vs/platform/agentHost/test/node/protocolServerHandler.test.ts +++ b/src/vs/platform/agentHost/test/node/protocolServerHandler.test.ts @@ -3988,6 +3988,193 @@ suite('ProtocolServerHandler', () => { assert.strictEqual(result.snapshot.resource.toString(), sessionUri.toString()); }); + suite('paged chat history', () => { + const channel = defaultChatUri; + let id = 100; + function seed(texts: string[]): Turn[] { + const turns = texts.map((text, i): Turn => ({ id: `turn-${i}`, message: { text, origin: { kind: MessageKind.User } }, responseParts: [], state: TurnState.Complete, usage: undefined })); + stateManager.createSession(makeSessionSummary()); + stateManager.seedDefaultChatTurns(sessionUri, turns); + return turns; + } + + async function call(transport: MockProtocolTransport, method: string, params: object): Promise { + const response = waitForResponse(transport, ++id); + transport.simulateMessage(request(id, method, params)); + return await response as JsonRpcResponse; + } + + async function subscribe(transport: MockProtocolTransport, count?: number): Promise { + const response = await call(transport, 'subscribe', { channel, view: { turns: count } }); + assert.ok(hasKey(response, { result: true })); + return (response.result as SubscribeResult).snapshot!.state as ChatState; + } + + function actions(transport: MockProtocolTransport) { + return findNotifications(transport.sent, 'action').map(message => message.params as ActionEnvelope).filter(e => e.channel === channel); + } + + test('pages the requesting subscription before acknowledging, without changing another view or shared history', async () => { + const turns = seed(['a', 'b', 'c', 'd', 'e']); + const full = connectClient('full'); + const one = connectClient('one'); + const two = connectClient('two'); + const [all, tail, pair] = await Promise.all([subscribe(full), subscribe(one, 1), subscribe(two, 2)]); + const state = stateManager.getChatState(channel); + assert.deepStrictEqual([all.turns, tail.turns, pair.turns], [turns, turns.slice(-1), turns.slice(-2)]); + assert.ok(tail.turnsNextCursor && pair.turnsNextCursor && tail.turnsNextCursor !== pair.turnsNextCursor); + const wrong = await call(two, 'fetchTurns', { channel, cursor: tail.turnsNextCursor }); + assert.ok(hasKey(wrong, { error: true }) && wrong.error.code === JsonRpcErrorCodes.InvalidParams); + two.sent.length = 0; + await call(two, 'fetchTurns', { channel, cursor: pair.turnsNextCursor }); + const page = actions(two)[0].action; + assert.ok(page.type === ActionType.ChatTurnsLoaded && page.turnsNextCursor); + assert.deepStrictEqual([two.sent.length, isJsonRpcResponse(two.sent[1]), page.turns], [2, true, turns.slice(1, 3)]); + const stale = await call(two, 'fetchTurns', { channel, cursor: pair.turnsNextCursor }); + assert.ok(hasKey(stale, { error: true }) && stale.error.code === JsonRpcErrorCodes.InvalidParams); + await call(two, 'fetchTurns', { channel }); + assert.deepStrictEqual(actions(two)[1].action, { type: ActionType.ChatTurnsLoaded, turns: turns.slice(0, 1) }); + assert.deepStrictEqual([actions(full), actions(one)], [[], []]); + assert.strictEqual(stateManager.getChatState(channel), state); + }); + + test('rebases an undisplayed truncation and bounds a host history refresh', async () => { + const turns = seed(['a', 'b', 'c', 'd', 'e']); + const paged = connectClient('paged-truncate'); + const full = connectClient('full-truncate'); + const old = await subscribe(paged, 1); + await subscribe(full); + stateManager.dispatchServerAction(channel, { type: ActionType.ChatTruncated, turnId: turns[2].id }); + const [reset, load] = actions(paged); + assert.deepStrictEqual(reset.action, { type: ActionType.ChatTruncated }); + assert.ok(load.action.type === ActionType.ChatTurnsLoaded && load.action.turnsNextCursor && load.serverSeq > reset.serverSeq); + assert.deepStrictEqual(load.action.turns, [turns[2]]); + assert.deepStrictEqual(actions(full).map(e => e.action), [{ type: ActionType.ChatTruncated, turnId: turns[2].id }]); + assert.ok(hasKey(await call(paged, 'fetchTurns', { channel, cursor: old.turnsNextCursor }), { error: true })); + await call(paged, 'fetchTurns', { channel, cursor: load.action.turnsNextCursor }); + const older = actions(paged).at(-1)!.action; + assert.ok(older.type === ActionType.ChatTurnsLoaded); + assert.deepStrictEqual(older.turns, [turns[1]]); + stateManager.refreshChatHistory(channel, stateManager.getChatState(channel)!.turns, turns); + const refreshed = actions(paged).at(-1)!.action; + assert.ok(refreshed.type === ActionType.ChatTurnsLoaded && refreshed.turnsNextCursor); + assert.deepStrictEqual(refreshed.turns, turns.slice(-1)); + }); + + test('loads an undisplayed fork source for its observer before creation', async () => { + const turns = seed(['a', 'b', 'c', 'd']); + const client = connectClient('fork-pager'); + const other = connectClient('other-pager'); + await subscribe(client, 1); + await subscribe(other, 1); + let beforeCreate: string[][] = []; + agentService.createChat = async () => { + beforeCreate = actions(client).map(e => e.action.type === ActionType.ChatTurnsLoaded ? e.action.turns.map(t => t.id) : []); + }; + const result = await call(client, 'createChat', { + channel: sessionUri, chat: buildChatUri(sessionUri, 'fork'), + source: { kind: 'fork', chat: channel, turnId: turns[1].id }, + }); + assert.deepStrictEqual([hasKey(result, { result: true }), beforeCreate, actions(other)], [true, [[turns[2].id], [turns[1].id]], []]); + }); + + test('requires a new subscription after relay authorization expires', async () => { + seed(['a', 'b']); + const expired = disposables.add(new Emitter()); + const client = new MockProtocolTransport(AgentHostTransportKind.WebSocket, 'relay-pager'); + client.relayAuthenticated = true; + client.onDidRelayAuthenticationExpire = expired.event; + server.simulateConnection(client); + await call(client, 'initialize', { channel: ROOT_STATE_URI, clientId: 'relay-pager', protocolVersions: [PROTOCOL_VERSION] }); + const { turnsNextCursor: cursor } = await subscribe(client, 1); + client.relayAuthenticated = false; + expired.fire(); + const denied = await call(client, 'fetchTurns', { channel, cursor }); + client.relayAuthenticated = true; + const unsubscribed = await call(client, 'fetchTurns', { channel, cursor }); + const fresh = await subscribe(client, 1); + const stale = await call(client, 'fetchTurns', { channel, cursor }); + assert.deepStrictEqual([denied, unsubscribed, stale].map(reply => hasKey(reply, { error: true }) && reply.error.code), [ + AHP_AUTH_REQUIRED, AHP_SESSION_NOT_FOUND, JsonRpcErrorCodes.InvalidParams, + ]); + assert.ok(fresh.turnsNextCursor && fresh.turnsNextCursor !== cursor); + assert.deepStrictEqual(actions(client), []); + }); + + test('shapes the fresh response when replacing a previously windowed subscription', async () => { + const turns = seed(['a', 'b', 'c']); + const client = connectClient('switch-to-pages'); + await call(client, 'subscribe', { channel, flowControl: { receive: agentHostStateReceiveLimits } }); + const stale = stateManager.getSnapshot(channel)!; + agentService.subscribe = async () => stale; + stateManager.dispatchServerAction(channel, chatTurnStarted('active', 'in progress', '2026-01-01T00:00:00Z')); + const state = await subscribe(client, 1); + assert.deepStrictEqual([state.activeTurn?.id, state.turns], ['active', turns.slice(-1)]); + assert.ok(state.turnsNextCursor); + }); + + test('uses UTF-8 bytes, retains one large turn, and fails oversized fetch and active baseline without disconnect', async () => { + const large = '界'.repeat(800_000); + const huge = 'x'.repeat(32 * 1024 * 1024); + const turns = seed([huge, large + large, large, large]); + const client = connectClient('byte-budget'); + const tail = await subscribe(client, 10); + assert.deepStrictEqual(tail.turns.map(t => t.id), [turns[3].id]); + await call(client, 'fetchTurns', { channel }); + await call(client, 'fetchTurns', { channel }); + const pages = actions(client).map(e => e.action.type === ActionType.ChatTurnsLoaded ? e.action.turns.map(t => t.id) : []); + assert.deepStrictEqual(pages, [[turns[2].id], [turns[1].id]]); + const failed = await call(client, 'fetchTurns', { channel }); + assert.ok(hasKey(failed, { error: true }) && /size limit/.test(failed.error.message)); + client.simulateMessage(notification('unsubscribe', { channel })); + stateManager.dispatchServerAction(channel, chatTurnStarted('active', huge, '2026-01-01T00:00:00Z')); + const oversized = await call(client, 'subscribe', { channel, view: { turns: 1 } }); + assert.ok(hasKey(oversized, { error: true }) && /without history/.test(oversized.error.message)); + assert.deepStrictEqual([client.isDisposed, hasKey(await call(client, 'ping', {}), { result: true })], [false, true]); + }); + + test('reconnect replays a lost turn echo without discarding received pages or changing their cursor', async () => { + const turns = seed(['a', 'b', 'c', 'd']); + const previous = connectClient('resume-pager'); + await subscribe(previous, 1); + await call(previous, 'fetchTurns', { channel }); + const [{ action, serverSeq: lastSeenServerSeq }] = actions(previous); + assert.ok(action.type === ActionType.ChatTurnsLoaded && action.turnsNextCursor); + const start = chatTurnStarted('accepted', 'Continue', '2026-01-01T00:00:00Z'); + const origin = { clientId: 'resume-pager', clientSeq: 12 }; + stateManager.dispatchClientAction(channel, start, origin); + previous.simulateClose(); + const transport = new MockProtocolTransport(); + server.simulateConnection(transport); + const response = await call(transport, 'reconnect', { channel: ROOT_STATE_URI, clientId: origin.clientId, subscriptions: [channel], lastSeenServerSeq }); + assert.ok(hasKey(response, { result: true })); + const result = response.result as ReconnectResult; + assert.ok(result.type === 'replay'); + await call(transport, 'fetchTurns', { channel, cursor: action.turnsNextCursor }); + const [older] = actions(transport); + assert.deepStrictEqual([result.actions.map(e => [e.action, e.origin]), older.action.type === ActionType.ChatTurnsLoaded && older.action.turns], [[[start, origin]], [turns[1]]]); + }); + + test('reconnect baselines a requested paged chat without replaying private pages', async () => { + const turns = seed(['a', 'b', 'c']); + const previous = connectClient('reconnecting-pager'); + const old = await subscribe(previous, 1); + const lastSeenServerSeq = stateManager.serverSeq; + await call(previous, 'fetchTurns', { channel }); + previous.simulateClose(); + const transport = new MockProtocolTransport(); + server.simulateConnection(transport); + const response = await call(transport, 'reconnect', { channel: ROOT_STATE_URI, clientId: 'reconnecting-pager', subscriptions: [channel], lastSeenServerSeq }); + assert.ok(hasKey(response, { result: true })); + const result = response.result as ReconnectResult; + assert.ok(result.type === 'snapshot'); + const chat = result.snapshots[0].state as ChatState; + assert.deepStrictEqual(chat.turns, turns.slice(-1)); + assert.ok(chat.turnsNextCursor && chat.turnsNextCursor !== old.turnsNextCursor); + assert.ok(hasKey(await call(transport, 'fetchTurns', { channel, cursor: old.turnsNextCursor }), { error: true })); + }); + }); + suite('windowed state delivery', () => { function receive(transport: MockProtocolTransport, method: string, params: object): void { transport.simulateMessage(parseProtocolMessage(JSON.stringify(notification(method, params)))); diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts index 52578e05e8715e..0639c5480d2a66 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts @@ -139,6 +139,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui if (type !== 'inlineChat' && type !== 'quickChat') { content.push(localize('chat.generateCustomizations', "Use the Chat: Generate commands in the Command Palette to create agents, skills, instructions, prompts, and hooks. Local chats use built-in creation skills; other harnesses receive a plain-text request and a Documentation reference. Use Tab to reach the reference and Enter or Space to open the documentation. You can edit the request and describe what you want to create before sending. Generate Agent Instructions sends its request immediately to analyze the codebase.")); content.push(getChatViewModeAccessibilityHelp()); + content.push(localize('chat.olderHistory', "In an Agent Host conversation, focus the message list and use Up Arrow or Page Up near the top to load earlier messages. Focus stays on the current message.")); content.push(localize('chat.agentRequiredModels', "When the selected agent requires specific models, the model picker only offers those models. Its footer explains that the agent defines the models. Use Tab to reach the agent link, then Enter or Space to open its definition.")); content.push(localize('chat.permissionLevelPolicy', "When Assisted permissions or Allow all is unavailable for a session, the option remains in the permissions picker as a disabled option with its reason, such as Disabled by your organization. Its hover also explains the restriction. Disabled options cannot be selected.")); content.push(localize('chat.manageToolApprovals', "Run Chat: Manage Tool Approval from the Command Palette to manage approval rules. Expand the terminal tool to change or delete user command rules, or choose Add Command Rule. Expand the fetch tool and choose Add URL Pattern to allow requests without approving responses. Enter accepts a new rule and Escape cancels. These settings also apply to local Agent Host sessions, not remote hosts.")); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts index 1e92a9fc13464a..a45f6c208d4204 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts @@ -771,6 +771,8 @@ function snapshotInvocationToAdopt(opts: IObserveTurnOptions, toolCallId: string const emptyCanvasReferences: readonly CanvasReference[] = []; +type HistoryWindowChange = 'page' | 'window' | 'metadata'; + class AgentHostChatSession extends Disposable implements IChatSession { readonly progressObs = observableValue('agentHostProgress', []); readonly isCompleteObs = observableValue('agentHostComplete', true); @@ -820,9 +822,53 @@ class AgentHostChatSession extends Disposable implements IChatSession { readonly onDidChangeHistory = this._onDidChangeHistory.event; get history(): readonly IChatSessionHistoryItem[] { return this._history; } - updateHistory(history: readonly IChatSessionHistoryItem[]): void { + private _loadingOlderHistory: Promise | undefined; + async loadOlderHistory(): Promise { + const chat = this._chatState.get().get(); + if (!this._fetchTurns || !chat || chat.turnsNextCursor === undefined || this._store.isDisposed) { + return; + } + this._loadingOlderHistory ??= this._fetchTurns(URI.parse(chat.resource), chat.turnsNextCursor) + .finally(() => this._loadingOlderHistory = undefined); + await this._loadingOlderHistory; + } + + readonly ownsHistoryRequestIds = true; + + reconcileHistory(chat: ChatState, project: (turns: readonly Turn[]) => IChatSessionHistoryItem[], reason: HistoryWindowChange): readonly Turn[] { + const previous = this._historyTurns; + const window = chat.turns; + if (previous === window && reason !== 'metadata') { + return []; + } + // Only the first turn of a partial window can vouch for a cached prefix before it. + const anchor = chat.turnsNextCursor !== undefined && window.length ? previous.findIndex(turn => turn.id === window[0].id) : -1; + const prefix = previous.slice(0, Math.max(0, anchor)); + const windowIds = new Set(window.map(turn => turn.id)); + const turns = prefix.length && !prefix.some(turn => windowIds.has(turn.id)) ? [...prefix, ...window] : window; + const added = turns.length - previous.length; + const activeId = chat.activeTurn?.id; + const activeIndex = activeId !== undefined ? this._history.findLastIndex(item => item.type === 'request' && item.id === activeId) : -1; + const active = activeIndex < 0 ? [] : this._history.slice(activeIndex, activeIndex + 2); + let history: readonly IChatSessionHistoryItem[]; + const previousIds = reason === 'page' ? new Set(previous.map(turn => turn.id)) : undefined; + const older = previousIds ? window.filter(turn => !previousIds.has(turn.id)) : []; + // turnsToHistory emits a request/response pair per completed turn, followed separately by the restored active pair. + const completed = this._history.slice(0, previous.length * 2); + if (reason === 'page' && added > 0 && older.length === added && previous.every((turn, i) => equals(turn, turns[i + added]))) { + history = [...project(older), ...completed, ...active]; + } else if (reason !== 'metadata' && added >= 0 && previous.every((turn, i) => equals(turn, turns[i]))) { + history = [...completed, ...project(turns.slice(previous.length)), ...active]; + } else { + history = [...project(turns), ...active]; + } + this._historyTurns = turns; + if (history.length === this._history.length && history.every((item, index) => item === this._history[index])) { + return older; + } this._history = history; this._onDidChangeHistory.fire(history); + return older; } readonly interruptActiveResponseCallback: IChatSession['interruptActiveResponseCallback']; @@ -841,6 +887,7 @@ class AgentHostChatSession extends Disposable implements IChatSession { constructor( readonly sessionResource: URI, private _history: readonly IChatSessionHistoryItem[], + private _historyTurns: readonly Turn[], readonly historyLoadError: IChatSession['historyLoadError'], readonly title: string | undefined, backendSession: URI, @@ -850,6 +897,7 @@ class AgentHostChatSession extends Disposable implements IChatSession { canvases: { readonly provider: AgentHostCanvasCollection; readonly available: IObservable } | undefined, private readonly _promptCacheNotification: AgentHostPromptCacheNotification | undefined, refreshChat: (() => Promise) | undefined, + private readonly _fetchTurns: IAgentConnection['fetchTurns'], private readonly _forkSession: NonNullable, private readonly _renameSession: ((title: string, token: CancellationToken) => Promise), transferredState: IChatSession['transferredState'], @@ -1848,6 +1896,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC } this._logService.trace(`[AgentHost] provideChatSessionContent start: ${resolvedSession.toString()} (isNewSession=${isNewSession})`); const history: IChatSessionHistoryItem[] = []; + let historyTurns: readonly Turn[] = []; let historyLoadError: IChatSession['historyLoadError']; let initialProgress: IChatProgress[] | undefined; let initialResponsePartCount = 0; @@ -1901,6 +1950,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC this._logService.trace(`[AgentHost] provideChatSessionContent: chat state hydrated for ${chatURI}`); const sessionState = this._getSessionState(resolvedSession.toString(), chatURI); if (sessionState) { + historyTurns = sessionState.turns; chatTitle = this._getHostChatTitle(sessionResource, sessionState, chatURI); const draft = sessionState.draft ?? emptyDraftFromLastTurn(sessionState); draftInputState = this._draftToInputState(sessionResource, draft); @@ -2046,6 +2096,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC AgentHostChatSession, sessionResource, history, + historyTurns, historyLoadError, chatTitle, resolvedSession, @@ -2060,6 +2111,7 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC return chat !== undefined ? this._config.connection.refreshSubscription!(URI.parse(chat)) : Promise.resolve(); } : undefined, + this._config.connection.fetchTurns ? (chat, cursor) => this._config.connection.fetchTurns!(chat, cursor) : undefined, (request: IChatSessionRequestHistoryItem | undefined, token: CancellationToken, options?: IChatSessionForkOptions) => { if (!this._getSessionState(resolvedSession.toString())) { throw new Error('Cannot fork session before the initial request'); @@ -3001,8 +3053,12 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC } }; updateSubagentPresentation(currentState); + let applyingPage = false; disposables.add(chatSub.onWillApplyAction(envelope => { const action = envelope.action; + const before = chatSub.verifiedValue; + applyingPage = !envelope.rejectionReason && action.type === ActionType.ChatTurnsLoaded && !!before + && (before.turnsNextCursor !== undefined || before.turns.length > 0); if (!envelope.rejectionReason && action.type === ActionType.ChatTurnStarted && action.queuedMessageId) { // Claim the submission before queue reconciliation treats its disappearance as cancellation. this._chatService.consumePendingRequest(sessionResource, action.queuedMessageId, action.turnId); @@ -3024,20 +3080,28 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC disposables.add(sessionSub.onDidChange(updateSessionCost)); updateSessionCost(); }).catch(error => this._logService.error('[AgentHost] Failed to observe chat billing', error)); - let historyRefreshPending = false; - const refreshHistory = () => { + let lastWindow: readonly Turn[] | undefined; + const reconcileHistory = (reason: HistoryWindowChange) => { + const chat = chatSub.verifiedValue; + if (!chat || (chat.turns === lastWindow && reason !== 'metadata')) { + return; + } const state = this._getSessionState(sessionStr, chatURI); const chatSession = this._activeSessions.get(sessionResource); - if (!historyRefreshPending || !state || state.activeTurn || !chatSession) { + if (!state || !chatSession) { return; } - historyRefreshPending = false; - const lookup = this._createTurnModelLookup(sessionResource, lastTurnModelSelection(state)?.id); + lastWindow = chat.turns; const allowTurnResume = !this._isChatReadOnly(sessionStr, chatURI); - chatSession.updateHistory(turnsToHistory(backendSession, state.turns, this._config.agentId, this._config.connectionAuthority, - lookup, this._chatErrorContext(sessionResource), this._config.connection.initializeResult.get()?.terminalCommandPrefix, - this._config.connection.resourceUris, turn => this._getTurnErrorDetails(sessionResource, turn, allowTurnResume), - readAgentContextUsage(state, state.turns.at(-1)?.usage), this._managedPluginRetryTarget(backendSession, chatURI))); + const older = chatSession.reconcileHistory(chat, turns => turnsToHistory(backendSession, turns, this._config.agentId, this._config.connectionAuthority, + this._createTurnModelLookup(sessionResource, lastTurnModelSelection(state)?.id), this._chatErrorContext(sessionResource), + this._config.connection.initializeResult.get()?.terminalCommandPrefix, this._config.connection.resourceUris, + turn => this._getTurnErrorDetails(sessionResource, turn, allowTurnResume), + turns.at(-1) === chat.turns.at(-1) ? readAgentContextUsage(state, chat.turns.at(-1)?.usage) : undefined, + this._managedPluginRetryTarget(backendSession, chatURI)), reason); + if (older.length) { + this._prependHistoryCheckpoints(sessionResource, older); + } }; let previousContextUsage = currentState ? readAgentContextUsage(currentState, currentState.turns.at(-1)?.usage) : undefined; disposables.add(sessionSub.onDidChange(() => { @@ -3048,17 +3112,13 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC const contextUsage = readAgentContextUsage(state, state.turns.at(-1)?.usage); if (!equals(previousContextUsage, contextUsage)) { previousContextUsage = contextUsage; - historyRefreshPending = true; - refreshHistory(); - } - })); - disposables.add(chatSub.onDidChange(refreshHistory)); - disposables.add(chatSub.onDidApplyAction(envelope => { - if (envelope.action.type === ActionType.ChatTurnsLoaded) { - historyRefreshPending = true; - refreshHistory(); + reconcileHistory('metadata'); } })); + // A snapshot can introduce both completed turns and an active turn. Publish history before the start below. + disposables.add(chatSub.onDidChange(() => reconcileHistory(applyingPage ? 'page' : 'window'))); + disposables.add(chatSub.onDidApplyAction(() => applyingPage = false)); + reconcileHistory('window'); // Conversation contents live on the chat, while its catalog title and // other session-scoped fields live on the session. Re-evaluate on either. const onChange = () => { @@ -3885,9 +3945,35 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC // Failed, unsent requests have no host turn and must not hide a truncation that still needs committing. const seenAtIndex = protocolState.turns.findLastIndex(turn => previousRequestIds.has(turn.id)); if (seenAtIndex < protocolState.turns.length - 1) { + let keepTurnId = protocolState.turns[seenAtIndex]?.id; + if (seenAtIndex < 0) { + const controller = chatModel.editingSession; + const firstDisabled = controller instanceof AgentHostSnapshotController ? controller.requestDisablement.get()[0]?.requestId : undefined; + const boundary = protocolState.turns.findIndex(turn => turn.id === firstDisabled); + if (boundary > 0) { + keepTurnId = protocolState.turns[boundary - 1].id; + } else if (protocolState.turnsNextCursor !== undefined) { + // No predecessor in a partial view does not mean "erase the whole chat". + if (boundary !== 0 || !this._config.connection.fetchTurns) { + throw new Error(localize('agentHost.checkpointHistoryUnavailable', "The checkpoint boundary is not loaded. Load earlier messages before retrying.")); + } + await this._config.connection.fetchTurns(URI.parse(chatURI), protocolState.turnsNextCursor); + if (this._isInvocationAbandoned(cancellationToken)) { + return; + } + const refreshed = chatSubscription.verifiedValue; + const index = refreshed?.turns.findIndex(turn => turn.id === firstDisabled) ?? -1; + if (!refreshed || index <= 0 || refreshed.turns.length !== index + protocolState.turns.length || + !protocolState.turns.every((turn, i) => refreshed.turns[index + i].id === turn.id) || + controller?.requestDisablement.get()[0]?.requestId !== firstDisabled) { + throw new Error(localize('agentHost.checkpointHistoryChanged', "The chat history changed before the checkpoint could be restored. Reopen the chat and try again.")); + } + keepTurnId = refreshed.turns[index - 1].id; + } + } const truncateAction: ChatTruncatedAction = { type: ActionType.ChatTruncated, - ...(seenAtIndex >= 0 ? { turnId: protocolState.turns[seenAtIndex].id } : {}), + ...(keepTurnId !== undefined ? { turnId: keepTurnId } : {}), }; this._steeringMessageHandoffs.get(turnChannel)?.clear(); const store = new DisposableStore(); @@ -6882,6 +6968,25 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC } } + private _prependHistoryCheckpoints(sessionResource: URI, turns: readonly Turn[]): void { + const pending = this._pendingHistoryTurns.get(sessionResource); + const history = pending ? [...turns, ...pending] : turns; + const controller = this._chatService.getSession(sessionResource)?.editingSession; + if (!(controller instanceof AgentHostSnapshotController)) { + this._pendingHistoryTurns.set(sessionResource, history); + return; + } + this._pendingHistoryTurns.delete(sessionResource); + controller.prependRequestCheckpoints(history.map(turn => turn.id)); + for (const turn of history) { + for (const part of turn.responseParts) { + if (part.kind === ResponsePartKind.ToolCall) { + controller.addToolCallEdits(turn.id, part.toolCall); + } + } + } + } + /** * Ensures the chat model has a snapshot controller bound (creating one * via our registered editing-session provider if needed) and returns it. @@ -6910,17 +7015,8 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC // edits) so "Restore Checkpoint" on any historical request can // find a boundary and mark subsequent requests as disabled via // requestDisablement. - const pendingTurns = this._pendingHistoryTurns.get(sessionResource); - if (pendingTurns) { - this._pendingHistoryTurns.delete(sessionResource); - for (const turn of pendingTurns) { - editingSession.ensureRequestCheckpoint(turn.id); - for (const rp of turn.responseParts) { - if (rp.kind === ResponsePartKind.ToolCall) { - editingSession.addToolCallEdits(turn.id, rp.toolCall); - } - } - } + if (this._pendingHistoryTurns.has(sessionResource)) { + this._prependHistoryCheckpoints(sessionResource, []); } return editingSession; diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts index eb5095dbf798a4..d707e691cf173e 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts @@ -178,6 +178,16 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit }); } + /** Adds already-completed requests before the loaded window without changing the undo/redo boundary. */ + prependRequestCheckpoints(ids: readonly string[]): void { + const existing = new Set(this._checkpoints.map(checkpoint => checkpoint.requestId)); + const older = [...new Set(ids)].filter(id => !existing.has(id)).map(requestId => ({ requestId, edits: [], turnEditsResolved: false, seenToolCallIds: new Set() })); + if (older.length) { + this._checkpoints.unshift(...older); + this._currentCheckpointIndex.set(this._currentCheckpointIndex.get() + older.length, undefined); + } + } + /** * Folds a completed tool call's file edits into the checkpoint for the * given request. Idempotent on `toolCallId`. @@ -290,13 +300,16 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit */ private async _navigateToCheckpointIndex(targetIdx: number): Promise { const currentIdx = this._currentCheckpointIndex.get(); + // Older pages can arrive while the file operations are pending. + const boundary = this._checkpoints[Math.max(0, targetIdx)]; const crossed = this._checkpoints.slice(Math.min(currentIdx, targetIdx) + 1, Math.max(currentIdx, targetIdx) + 1); + const undo = targetIdx < currentIdx; + const reviewCheckpoints = undo ? this._checkpoints.slice(targetIdx + 1) : crossed; // A failed fetch must leave every file and the checkpoint cursor at the original boundary. await Promise.all(crossed.map(checkpoint => this._resolveCheckpointEdits(checkpoint))); - const undo = targetIdx < currentIdx; const affectedResources = crossed.flatMap(checkpoint => checkpoint.edits.flatMap(edit => edit.originalResource ? [edit.resource, edit.originalResource] : [edit.resource])); const updateReview = await this.checkpointReview.prepareRestore( - undo ? this._checkpoints.slice(targetIdx + 1) : crossed, + reviewCheckpoints, undo, affectedResources, ); @@ -322,7 +335,8 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit } transaction(tx => { - this._currentCheckpointIndex.set(targetIdx, tx); + const boundaryIndex = this._checkpoints.indexOf(boundary); + this._currentCheckpointIndex.set(targetIdx < 0 ? Math.max(-1, boundaryIndex - 1) : boundaryIndex, tx); if (!undo || failures.length === 0) { updateReview(tx); } diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts index f5e24281e590f6..dcab79062f9f55 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts @@ -59,6 +59,8 @@ class PromotableCloudSandboxChatSession extends Disposable implements IChatSessi } get history() { return this._source.history; } + get ownsHistoryRequestIds() { return this._source.ownsHistoryRequestIds; } + readonly loadOlderHistory = async () => { await this._source.loadOlderHistory?.(); }; get title() { return this._source.title; } get options() { return this._source.options; } get transferredState() { return this._source.transferredState; } @@ -185,6 +187,8 @@ class CloudSandboxChatSessionReference extends Disposable implements IChatSessio get sessionResource() { return this._session.sessionResource; } get history() { return this._session.history; } + get ownsHistoryRequestIds() { return this._session.ownsHistoryRequestIds; } + get loadOlderHistory() { return this._session.loadOlderHistory; } get preserveHistoryItemIdentity() { return this._session.preserveHistoryItemIdentity; } get title() { return this._session.title; } get options() { return this._session.options; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts index b7d748d961c055..1a88eef6a350e4 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatListWidget.ts @@ -6,6 +6,8 @@ import * as dom from '../../../../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; import { IMouseWheelEvent } from '../../../../../base/browser/mouseEvent.js'; +import { EventType as TouchEventType, GestureEvent } from '../../../../../base/browser/touch.js'; +import { status } from '../../../../../base/browser/ui/aria/aria.js'; import { Button } from '../../../../../base/browser/ui/button/button.js'; import { ITreeContextMenuEvent, ITreeElement, ITreeFilter } from '../../../../../base/browser/ui/tree/tree.js'; import { RenderIndentGuides } from '../../../../../base/browser/ui/tree/abstractTree.js'; @@ -405,6 +407,8 @@ export class ChatListWidget extends Disposable { private readonly _renderer: ChatListItemRenderer; private _viewModel: IChatViewModel | undefined; + private readonly _historyNavigationFrame = this._register(new MutableDisposable()); + private _loadingHistoryFor: IChatViewModel | undefined; private _visible = true; private _lastItem: ChatTreeItem | undefined; /** What the last full {@link refresh} rendered, so response-only updates can skip diffing the whole transcript. */ @@ -800,10 +804,33 @@ export class ChatListWidget extends Disposable { this.trackUserToggleResize(element, e.target); } })); - this._register(dom.addDisposableListener(this._container, dom.EventType.WHEEL, () => this.cancelUserToggleScrollRestoration())); - this._register(dom.addDisposableListener(this._container, dom.EventType.POINTER_DOWN, () => this.cancelUserToggleScrollRestoration())); + this._register(dom.addDisposableListener(this._tree.getHTMLElement(), dom.EventType.WHEEL, e => { + this.cancelUserToggleScrollRestoration(); + if (e.deltaY < 0 && !e.ctrlKey && !e.shiftKey) { + this.scheduleOlderHistory(); + } + }, { capture: true, passive: true })); + this._register(dom.addDisposableListener(this._tree.getHTMLElement(), TouchEventType.Change, e => { + if ((e as GestureEvent).translationY > 0) { + this.scheduleOlderHistory(); + } + }, true)); + this._register(dom.addDisposableListener(this._container, dom.EventType.POINTER_DOWN, e => { + this.cancelUserToggleScrollRestoration(); + if (dom.isHTMLElement(e.target) && e.target.closest('.scrollbar.vertical')) { + this.scheduleOlderHistory(this.scrollTop); + } + }, true)); + this._register(dom.addDisposableListener(this._container, dom.EventType.POINTER_MOVE, e => { + if (e.buttons === 1 && e.movementY < 0 && dom.isHTMLElement(e.target) && e.target.closest('.scrollbar.vertical')) { + this.scheduleOlderHistory(); + } + }, true)); this._register(dom.addDisposableListener(this._container, dom.EventType.KEY_DOWN, e => { const keyCode = new StandardKeyboardEvent(e).keyCode; + if (e.target === this._tree.getHTMLElement() && (keyCode === KeyCode.UpArrow || keyCode === KeyCode.PageUp || keyCode === KeyCode.Home)) { + this.scheduleOlderHistory(); + } if (keyCode === KeyCode.UpArrow || keyCode === KeyCode.DownArrow || keyCode === KeyCode.PageUp @@ -1042,6 +1069,8 @@ export class ChatListWidget extends Disposable { setViewModel(viewModel: IChatViewModel | undefined): void { if (this._viewModel !== viewModel) { this.clearScrollHeightReservation(); + this._historyNavigationFrame.clear(); + this._loadingHistoryFor = undefined; } this._viewModel = viewModel; this._renderedState = undefined; @@ -1080,8 +1109,10 @@ export class ChatListWidget extends Disposable { const editing = this._viewModel.editing; const diffIds = new Map(); + const previousFirst = this._renderedState?.items[0]; + const anchor = previousFirst && items[0] !== previousFirst && items.includes(previousFirst) ? this.getScrollAnchor() : undefined; - this._withPersistedAutoScroll(() => { + const updateTree = () => { this._tree.setChildren(null, treeItems, { diffDepth: 1, diffIdentityProvider: { @@ -1095,7 +1126,13 @@ export class ChatListWidget extends Disposable { }, } }); - }); + }; + if (anchor) { + updateTree(); + this.revealScrollAnchor(anchor); + } else { + this._withPersistedAutoScroll(updateTree); + } this._renderedState = { viewModel: this._viewModel, @@ -1291,6 +1328,37 @@ export class ChatListWidget extends Disposable { delegateScrollFromMouseWheelEvent(event: IMouseWheelEvent): void { this.cancelUserToggleScrollRestoration(); this._tree.delegateScrollFromMouseWheelEvent(event); + if (event.deltaY < 0 && !event.ctrlKey && !event.shiftKey) { + this.scheduleOlderHistory(); + } + } + + private scheduleOlderHistory(beforeScrollbarClick?: number): void { + const viewModel = this._viewModel; + if (!viewModel?.model.loadOlderHistory || !this._visible || this._historyNavigationFrame.value || this._loadingHistoryFor === viewModel) { + return; + } + // Check after native list navigation, including gestures at the edge that emit no scroll event. + this._historyNavigationFrame.value = dom.scheduleAtNextAnimationFrame(dom.getWindow(this._container), async () => { + this._historyNavigationFrame.clear(); + if (!this._visible || this._viewModel !== viewModel || this.scrollTop > this.renderHeight / 2 + || (beforeScrollbarClick !== undefined && this.scrollTop >= beforeScrollbarClick)) { + return; + } + this._loadingHistoryFor = viewModel; + try { + await viewModel.model.loadOlderHistory?.(); + } catch (error) { + if (this._viewModel === viewModel && !this._store.isDisposed) { + this.logService.warn('Failed to load older chat history', error); + status(localize('chat.olderHistoryFailed', "Could not load earlier messages. Navigate up to retry.")); + } + } finally { + if (this._loadingHistoryFor === viewModel) { + this._loadingHistoryFor = undefined; + } + } + }); } /** diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts index f01b8ba43c029f..e39f5adbde8b1b 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts @@ -3451,9 +3451,11 @@ export class ChatWidget extends Disposable implements IChatWidget { this._updateAgentCapabilitiesContextKeys(e.agent); } if (e.kind === 'addRequest') { - this.inputPart?.clearTodoListWidget(this.viewModel?.sessionResource, false); this._sessionIsEmptyContextKey.set(false); - this.chatSuggestNextWidget.hide(); + if (e.index === undefined) { + this.inputPart?.clearTodoListWidget(this.viewModel?.sessionResource, false); + this.chatSuggestNextWidget.hide(); + } } // Hide widget on request removal if (e.kind === 'removeRequest') { diff --git a/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts b/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts index ca2012599dfc7e..35b11dee500efa 100644 --- a/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts +++ b/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts @@ -143,6 +143,7 @@ export class RemoteChatSessionRestorer extends Disposable { private readonly _localRequestIds = new Set(); /** The latest history that is not applied yet. */ private _pendingHistory: readonly IChatSessionHistoryItem[] | undefined; + private readonly _supersededRequestIds = new Set(); private _activeRefresh: Promise | undefined; /** The request that history responses are applied to. */ @@ -165,6 +166,15 @@ export class RemoteChatSessionRestorer extends Disposable { this._model = _options.model; this._session = _options.session; this._restoredHistory = this._session.history; + if (this._session.loadOlderHistory) { + this._model.loadOlderHistory = async () => { + if (this._state === RestoreState.Published) { + await this._session.loadOlderHistory?.(); + await this.historyRefresh; + } + }; + this._register(toDisposable(() => this._model.loadOlderHistory = undefined)); + } this._hasProgressStreaming = !!(this._session.progressObs && this._session.interruptActiveResponseCallback); // Cancel pending cooperative waits when the restorer is disposed, not only when the service token is. const budgetCancellation = new CancellationTokenSource(_options.token); @@ -173,6 +183,13 @@ export class RemoteChatSessionRestorer extends Disposable { if (this._session.onDidChangeHistory) { this._register(this._session.onDidChangeHistory(history => { + if (this._session.ownsHistoryRequestIds && this._pendingHistory) { + for (const item of this._pendingHistory) { + if (item.type === 'request' && item.id !== undefined) { + this._supersededRequestIds.add(item.id); + } + } + } this._pendingHistory = history; if (this._state === RestoreState.Published) { this.scheduleHistoryRefresh(); @@ -376,10 +393,17 @@ export class RemoteChatSessionRestorer extends Disposable { private async _applyPendingHistory(force: boolean): Promise { try { - while (this._pendingHistory && (force || !this._model.hasActiveRequest.get())) { + while (this._pendingHistory) { const history = this._pendingHistory; + const prefixLength = history.length - this._restoredHistory.length; + // Only a strict prepend can be applied without touching the live response. + const prepended = this._state === RestoreState.Published && this._session.loadOlderHistory && !this._supersededRequestIds.size && this._restoredHistory.length > 0 + && prefixLength > 0 && this._restoredHistory.every((item, index) => item === history[index + prefixLength]); + if (!prepended && !force && this._model.hasActiveRequest.get()) { + break; + } this._pendingHistory = undefined; - const refresh = this._budget.run(this._refreshSteps(history)); + const refresh = this._budget.run(prepended ? this._prependSteps(history, prefixLength) : this._refreshSteps(history)); if (refresh) { await refresh; } @@ -390,11 +414,33 @@ export class RemoteChatSessionRestorer extends Disposable { } } + private *_prependSteps(history: readonly IChatSessionHistoryItem[], prefixLength: number): Generator { + this._budget.startSlice(); + const turns = groupHistoryTurns(history.slice(0, prefixLength)); + const existing = new Set(this._model.getRequests().map(request => request.id)); + this._lastRequest = undefined; + // Inserting backwards keeps the boundary valid even if the user removes a request between slices. + for (let i = turns.length - 1; i >= 0; i--) { + const turn = turns[i]; + if (turn.id !== undefined && existing.has(turn.id)) { + this._localRequestIds.add(turn.id); + continue; + } + const [request] = yield* this._applyHistorySteps(turn.items, () => ({ index: 0 })); + turn.id = request.id; + } + this._completeLastResponse(); + this._restoredTurns = [...turns, ...this._restoredTurns]; + this._restoredHistory = history; + } + private *_refreshSteps(history: readonly IChatSessionHistoryItem[]): Generator { const requests = this._model.getRequests(); const turns = groupHistoryTurns(history); const restoredTurns = this._restoredTurns; - if (turns.length === restoredTurns.length && turns.every((turn, index) => equals(turn.items, restoredTurns[index].items))) { + const superseded = new Set(this._supersededRequestIds); + this._supersededRequestIds.clear(); + if (!superseded.size && turns.length === restoredTurns.length && turns.every((turn, index) => equals(turn.items, restoredTurns[index].items))) { return; } const previousAnonymous = restoredTurns.filter(turn => turn.request.id === undefined); @@ -420,9 +466,11 @@ export class RemoteChatSessionRestorer extends Disposable { this._budget.startSlice(); } for (const request of [...requests]) { - if (previousTurns.has(request.id) && !incomingIds.has(request.id) && !this._localRequestIds.has(request.id)) { + const providerOwned = this._session.ownsHistoryRequestIds && (previousTurns.has(request.id) || superseded.has(request.id)); + if (!incomingIds.has(request.id) && (providerOwned || (previousTurns.has(request.id) && !this._localRequestIds.has(request.id)))) { yield; this._model.removeRequest(request.id); + this._localRequestIds.delete(request.id); } } this._lastRequest = undefined; @@ -434,6 +482,9 @@ export class RemoteChatSessionRestorer extends Disposable { const isInModel = (request: ChatRequestModel) => this._model.getRequests().includes(request); for (const [turnIndex, turn] of turns.entries()) { if (turn.id !== undefined && this._localRequestIds.has(turn.id)) { + if (this._session.ownsHistoryRequestIds) { + this._localRequestIds.delete(turn.id); + } continue; } const existing = turn.id === undefined ? undefined : requestsById.get(turn.id); diff --git a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts index 9dc9b40e02f198..070d3fb8c42daf 100644 --- a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts +++ b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts @@ -576,6 +576,8 @@ export interface IChatSession extends IDisposable { readonly title?: string; readonly history: readonly IChatSessionHistoryItem[]; + /** Requests one older page, if available. The resulting history is published through onDidChangeHistory. */ + readonly loadOlderHistory?: () => Promise; /** Initial history loading failed; any rendered error or partial history is not an authoritative snapshot. */ readonly historyLoadError?: { readonly message: string; @@ -589,6 +591,8 @@ export interface IChatSession extends IDisposable { readonly onDidChangeHistory?: Event; /** Updates model and usage decoration in place for otherwise unchanged turns with stable request IDs. */ readonly preserveHistoryItemIdentity?: boolean; + /** Once this provider reports a request ID in history, a later omission removes it, even for requests started locally. */ + readonly ownsHistoryRequestIds?: boolean; readonly options?: ReadonlyChatSessionOptionsMap; diff --git a/src/vs/workbench/contrib/chat/common/model/chatModel.ts b/src/vs/workbench/contrib/chat/common/model/chatModel.ts index c38cfc03910bc3..03108ec290c411 100644 --- a/src/vs/workbench/contrib/chat/common/model/chatModel.ts +++ b/src/vs/workbench/contrib/chat/common/model/chatModel.ts @@ -2144,6 +2144,7 @@ export interface IChatModel extends IDisposable { readonly isReadOnly: IObservable; readonly isInputBlocked: IObservable; readonly historyStatus?: IObservable; + readonly loadOlderHistory?: () => Promise; readonly modelConfigurationState?: IObservable; /** Provider-reported active shells across all turns; undefined allows transcript-based detection. */ readonly backgroundShellCount?: IObservable; @@ -3044,6 +3045,7 @@ export class ChatModel extends Disposable implements IChatModel { readonly isReadOnly: IObservable; readonly isInputBlocked: IObservable; readonly historyStatus: IObservable; + loadOlderHistory?: () => Promise; readonly modelConfigurationState: IObservable | undefined; readonly backgroundShellCount: IObservable | undefined; readonly canvasContext: IObservable | undefined; @@ -3662,8 +3664,10 @@ export class ChatModel extends Disposable implements IChatModel { throw new BugIndicatingError('Invalid chat request insertion index'); } const replacedRequest = insertion?.replace ? this._requests[index] : undefined; - const editedFileEvents = [...this.currentEditedFileEvents.values()]; - this.currentEditedFileEvents.clear(); + const editedFileEvents = insertion ? [] : [...this.currentEditedFileEvents.values()]; + if (!insertion) { + this.currentEditedFileEvents.clear(); + } const requestTimestamp = timestamp === undefined ? Date.now() : typeof timestamp === 'number' && Number.isFinite(timestamp) && timestamp > 0 diff --git a/src/vs/workbench/contrib/chat/common/model/chatViewModel.ts b/src/vs/workbench/contrib/chat/common/model/chatViewModel.ts index 80bde59731f195..6ff7f6297c7452 100644 --- a/src/vs/workbench/contrib/chat/common/model/chatViewModel.ts +++ b/src/vs/workbench/contrib/chat/common/model/chatViewModel.ts @@ -420,7 +420,7 @@ export class ChatViewModel extends Disposable implements IChatViewModel { } const modelEventToVmEvent: IChatViewModelChangeEvent = - e.kind === 'addRequest' ? { kind: 'addRequest' } + e.kind === 'addRequest' && e.index === undefined ? { kind: 'addRequest' } : e.kind === 'initialize' ? { kind: 'initialize' } : e.kind === 'setHidden' ? { kind: 'setHidden' } : null; diff --git a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts index f112637e0212b5..1e5cc8e6e6cb8f 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { timeout } from '../../../../../../base/common/async.js'; +import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; import { VSBuffer } from '../../../../../../base/common/buffer.js'; import { DisposableStore } from '../../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../../base/common/network.js'; @@ -132,6 +132,36 @@ suite('AgentHostSnapshotController', () => { assert.deepStrictEqual(controller.entries.get(), []); }); + test('paging in checkpoints preserves an undo branch and allows restoring a fetched request', async () => { + const controller = createController(store, new Map()); + controller.ensureRequestCheckpoint('middle'); + controller.ensureRequestCheckpoint('latest'); + await controller.restoreSnapshot('latest', undefined); + controller.prependRequestCheckpoints(['oldest', 'earlier']); + controller.prependRequestCheckpoints(['oldest', 'earlier']); + const afterPaging = controller.requestDisablement.get().map(request => request.requestId); + await controller.restoreSnapshot('earlier', undefined); + assert.deepStrictEqual([afterPaging, controller.requestDisablement.get().map(request => request.requestId)], [ + ['latest'], ['earlier', 'middle', 'latest'], + ]); + }); + + test('a page arriving during restore keeps the checkpoint on the same request', async () => { + const resolving = new DeferredPromise(); + const edits = new DeferredPromise(); + const controller = createController(store, new Map(), { + getChanges: () => undefined, + resolve: () => { resolving.complete(); return edits.p; }, + }); + controller.ensureRequestCheckpoint('first-visible'); + const restore = controller.restoreSnapshot('first-visible', undefined); + await resolving.p; + controller.prependRequestCheckpoints(['hidden']); + await edits.complete([]); + await restore; + assert.deepStrictEqual(controller.requestDisablement.get(), [{ requestId: 'first-visible' }]); + }); + test('addToolCallEdits records snapshot data, enables undo', () => { const contentMap = new Map(); const controller = createController(store, contentMap); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts index 11ef983cd915b2..18276e7cf5ba7a 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts @@ -532,6 +532,14 @@ class MockAgentHostService extends mock() { entry.onDidError.fire(error); } + applyChatSnapshot(state: ChatState): void { + const entry = this._liveSubscriptions.get(state.resource); + assert.ok(entry); + this.chatStates.set(state.resource, state); + entry.state = state; + entry.emitter.fire(state); + } + async subscribe(resource: URI): Promise { const resourceStr = resource.toString(); const existingState = this.sessionStates.get(resourceStr); @@ -2113,12 +2121,12 @@ suite('AgentHostChatContribution', () => { } suite('checkpoint truncation', () => { - async function openRestoredSession(keepFirstTurn: boolean) { + async function openRestoredSession(keepFirstTurn: boolean, turnsNextCursor?: string) { const turns = ['turn-1', 'turn-2', 'turn-3'].map(id => ({ id, message: { text: id, origin: { kind: MessageKind.User } }, responseParts: [], usage: undefined, state: TurnState.Complete, })); - const context = await openWireSession({ chat: { turns } }); + const context = await openWireSession({ chat: { turns, turnsNextCursor } }); const controller = disposables.add(new AgentHostSnapshotController(context.sessionResource, context.client, 'local', undefined, new NullLogService(), disposables.add(new TestFileService()), new MockWorkingCopyService())); for (const turn of turns) { controller.ensureRequestCheckpoint(turn.id); @@ -2153,6 +2161,58 @@ suite('AgentHostChatContribution', () => { }; } + test('restoring the first displayed checkpoint retains turns from earlier pages', async () => { + const context = await openRestoredSession(false, 'previous-page'); + const fetching = context.peer.nextRequest('fetchTurns'); + const truncating = context.peer.nextDispatch(ActionType.ChatTruncated); + const starting = context.peer.nextDispatch(ActionType.ChatTurnStarted); + const invoking = context.invoke(); + const page = await fetching; + context.fire({ + type: ActionType.ChatTurnsLoaded, + turns: [{ id: 'previous-turn', message: { text: 'Previous', origin: { kind: MessageKind.User } }, responseParts: [], usage: undefined, state: TurnState.Complete }], + turnsNextCursor: 'even-earlier', + }); + context.peer.deliver({ jsonrpc: '2.0', id: page.id, result: {} }); + const truncate = await truncating; + assert.deepStrictEqual(truncate.action, { type: ActionType.ChatTruncated, turnId: 'previous-turn' }); + context.echo(truncate); + context.echo(await starting); + context.fire(chatTurnComplete('replacement', 1)); + await invoking; + assert.deepStrictEqual(context.turnIds(), ['previous-turn', 'replacement']); + }); + + test('an unconfirmed page boundary never sends a truncate-all action', async () => { + const context = await openRestoredSession(false, 'previous-page'); + const fetching = context.peer.nextRequest('fetchTurns'); + const invoking = assert.rejects(context.invoke(), /chat history changed/i); + context.peer.deliver({ jsonrpc: '2.0', id: (await fetching).id, result: {} }); + await invoking; + assert.deepStrictEqual(context.dispatched, []); + }); + + for (const modelAlreadyOpen of [false, true]) { + test(`fetched turns become restorable checkpoints (model already open: ${modelAlreadyOpen})`, async () => { + const turn = (id: string) => ({ id, message: { text: id, origin: { kind: MessageKind.User } }, responseParts: [], usage: undefined, state: TurnState.Complete }); + const context = await openWireSession({ chat: { turns: [turn('recent')], turnsNextCursor: 'before-recent' } }); + const controller = disposables.add(new AgentHostSnapshotController(context.sessionResource, context.client, 'local', undefined, new NullLogService(), disposables.add(new TestFileService()), new MockWorkingCopyService())); + const attachModel = () => context.chatService.setSession(context.sessionResource, upcastPartial({ + sessionResource: context.sessionResource, editingSession: controller, + getRequests: () => [], getPendingRequests: () => [], onDidChangePendingRequests: Event.None, + })); + if (modelAlreadyOpen) { + attachModel(); + } + context.fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('older')] }); + if (!modelAlreadyOpen) { + attachModel(); + } + await controller.restoreSnapshot('older', undefined); + assert.deepStrictEqual(controller.requestDisablement.get().map(request => request.requestId), ['older', 'recent']); + }); + } + for (const keepFirstTurn of [false, true]) { for (const synchronous of [false, true]) { test(`waits for authoritative history truncation before sending the replacement (keep first: ${keepFirstTurn}, synchronous: ${synchronous})`, async () => { @@ -21865,6 +21925,107 @@ suite('AgentHostChatContribution', () => { assert.deepStrictEqual(updates.map(history => history.filter(item => item.type === 'request').map(item => item.prompt)), [['Later message']]); }); + test('loads older history only on demand from the advertised chat and cursor', async () => { + const { sessionHandler, agentHostService } = createContribution(disposables); + const backend = AgentSession.uri('copilot', 'paged'); + const resource = URI.from({ scheme: 'agent-host-copilot', path: '/paged' }); + const chat = 'ahp-chat:/opaque/transcript-42'; + const summary: SessionSummary = { + resource: backend.toString(), provider: 'copilot', title: 'Paged', status: SessionStatus.Idle, + createdAt: new Date(0).toISOString(), modifiedAt: new Date(0).toISOString(), + }; + const turn = (id: string): Turn => ({ id, message: { text: id, origin: { kind: MessageKind.User } }, responseParts: [], state: TurnState.Complete, usage: undefined }); + const chatSummary = createDefaultChatSummary(summary, chat); + agentHostService.sessionStates.set(backend.toString(), { ...createSessionState(summary), lifecycle: SessionLifecycle.Ready, defaultChat: chat, chats: [chatSummary] }); + agentHostService.chatStates.set(chat, { ...createChatState(chatSummary), turns: [turn('newest')], turnsNextCursor: 'first cursor' }); + const calls: [string, string][] = []; + let page = new DeferredPromise(); + agentHostService.fetchTurns = (uri, cursor) => { + calls.push([uri.toString(), cursor]); + return page.p; + }; + const session = disposables.add(await sessionHandler.provideChatSessionContent(resource, CancellationToken.None)); + const newest = session.history[0]; + const initial = { prompt: newest.type === 'request' && newest.prompt, fetches: calls.length }; + const first = Promise.all([session.loadOlderHistory!(), session.loadOlderHistory!()]); + await page.error(new Error('offline')); + await assert.rejects(first, /offline/); + page = new DeferredPromise(); + const retry = session.loadOlderHistory!(); + agentHostService.fireAction({ + channel: chat, action: { type: ActionType.ChatTurnsLoaded, turns: [turn('older'), turn('newest')], turnsNextCursor: 'second cursor' }, + serverSeq: 1, origin: undefined, + }); + await page.complete(); + await retry; + const afterRetry = calls.length; + await session.loadOlderHistory!(); + agentHostService.fireAction({ + channel: chat, action: { type: ActionType.ChatTurnsLoaded, turns: [turn('oldest')] }, serverSeq: 2, origin: undefined, + }); + await session.loadOlderHistory!(); + assert.deepStrictEqual({ + initial, calls, afterRetry, requests: session.history.flatMap(item => item.type === 'request' ? [item.prompt] : []), + retained: session.history.includes(newest), + }, { + initial: { prompt: 'newest', fetches: 0 }, calls: [[chat, 'first cursor'], [chat, 'first cursor'], [chat, 'second cursor']], + afterRetry: 2, requests: ['oldest', 'older', 'newest'], retained: true, + }); + }); + + test('reconciles reconnect windows before the next turn and never prepends a replacement transcript', async () => { + const { sessionHandler, agentHostService } = createContribution(disposables); + const backend = AgentSession.uri('copilot', 'reconnect-window'); + const resource = URI.from({ scheme: 'agent-host-copilot', path: '/reconnect-window' }); + const chat = 'ahp-chat:/opaque/reconnect'; + const summary: SessionSummary = { + resource: backend.toString(), provider: 'copilot', title: 'Reconnect', status: SessionStatus.Idle, + createdAt: new Date(0).toISOString(), modifiedAt: new Date(0).toISOString(), + }; + const chatSummary = createDefaultChatSummary(summary, chat); + const base = createChatState(chatSummary); + const turn = (id: string): Turn => ({ id, message: { text: id, origin: { kind: MessageKind.User } }, responseParts: [], state: TurnState.Complete, usage: undefined }); + agentHostService.sessionStates.set(backend.toString(), { ...createSessionState(summary), lifecycle: SessionLifecycle.Ready, defaultChat: chat, chats: [chatSummary] }); + agentHostService.chatStates.set(chat, { ...base, turns: [turn('b'), turn('c')], turnsNextCursor: 'prev' }); + let fetches = 0; + agentHostService.fetchTurns = async () => { fetches++; }; + const session = disposables.add(await sessionHandler.provideChatSessionContent(resource, CancellationToken.None)); + const ids = () => session.history.flatMap(item => item.type === 'request' ? [item.id] : []); + const atTurnStart: (string | undefined)[][] = []; + disposables.add(session.onDidStartServerRequest!(() => atTurnStart.push(ids()))); + const checkpoints = sessionHandler as unknown as { _prependHistoryCheckpoints(resource: URI, turns: readonly Turn[]): void }; + const prepends = sinon.spy(checkpoints, '_prependHistoryCheckpoints'); + disposables.add(toDisposable(() => prepends.restore())); + let serverSeq = 0; + const fire = (action: ChatAction) => agentHostService.fireAction({ channel: chat, action, serverSeq: ++serverSeq, origin: undefined }); + fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('a')] }); + const beforeReconnect = ids(); + agentHostService.applyChatSnapshot({ + ...base, turns: [turn('c'), turn('offline')], turnsNextCursor: 'new cursor', + activeTurn: createActiveTurn('live', turn('live').message, new Date(0).toISOString()), + }); + fire(chatTurnComplete('live', 1)); + fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('b')], turnsNextCursor: 'final cursor' }); + const overlap = ids(); + fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('older'), turn('a')] }); + const expanded = ids(); + agentHostService.applyChatSnapshot({ ...base, turns: [turn('unrelated')], turnsNextCursor: 'unanchored' }); + const noAnchor = ids(); + fire({ type: ActionType.ChatTruncated }); + const cleared = ids(); + fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('replacement'), turn('also-replaced')] }); + const replaced = ids(); + fire({ type: ActionType.ChatTruncated, turnId: 'replacement' }); + fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('earliest'), turn('earlier'), turn('replacement')] }); + const prependedPages = prepends.args.map(([, turns]) => turns.map(turn => turn.id)); + assert.deepStrictEqual({ beforeReconnect, atTurnStart, overlap, expanded, noAnchor, cleared, replaced, final: ids(), prependedPages, fetches }, { + beforeReconnect: ['a', 'b', 'c'], atTurnStart: [['a', 'b', 'c', 'offline']], + overlap: ['a', 'b', 'c', 'offline', 'live'], expanded: ['older', 'a', 'b', 'c', 'offline', 'live'], + noAnchor: ['unrelated'], cleared: [], replaced: ['replacement', 'also-replaced'], final: ['earliest', 'earlier', 'replacement'], + prependedPages: [['a'], ['older'], ['earliest', 'earlier']], fetches: 0, + }); + }); + test('preserves independent default chat titles and renames without cloud customization', async () => { const { sessionHandler, agentHostService, chatService } = createContribution(disposables); const backendSession = AgentSession.uri('copilot', 'independent-default-title'); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts index d2a7258e193fc0..5997253e0709e7 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatListWidget.test.ts @@ -1578,6 +1578,74 @@ suite('ChatListWidget', () => { }); }); + test('loads older history from the focused short list, coalescing gestures and discarding stale navigation', async () => { + const { model, viewModel, container, widget } = createWidget(); + const page = new DeferredPromise(); + let loads = 0; + model.loadOlderHistory = () => { loads++; return page.p; }; + model.addRequest({ text: 'Recent', parts: [] }, { variables: [] }, 0).response!.complete(); + widget.layout(300, 500); + widget.refresh(); + widget.focusItem(viewModel.getItems()[0]); + const tree = container.querySelector('.monaco-list')!; + const wheel = (deltaY: number) => tree.dispatchEvent(new WheelEvent('wheel', { deltaY, bubbles: true })); + wheel(10); + await nextFrame(); + const before = { loads, scrollable: widget.scrollHeight > widget.renderHeight }; + const event = new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true }); + Object.defineProperty(event, 'keyCode', { get: () => 38 }); + tree.dispatchEvent(event); + await nextFrame(); + const keyboardLoads = loads; + wheel(-10); + await nextFrame(); + const whileLoading = loads; + await page.complete(); + await nextFrame(); + wheel(-10); + widget.setViewModel(undefined); + await nextFrame(); + assert.deepStrictEqual({ before, keyboardLoads, whileLoading, final: loads }, { + before: { loads: 0, scrollable: false }, keyboardLoads: 1, whileLoading: 1, final: 1, + }); + }); + + test('loads older history by wheel without losing the reading row or tree focus', async () => { + const { model, viewModel, widget, container } = createWidget(); + const question = model.addRequest({ text: 'Recent', parts: [] }, { variables: [] }, 0); + model.acceptResponseProgress(question, { kind: 'markdownContent', content: new MarkdownString('Recent paragraph\n\n'.repeat(30)) }); + question.response!.complete(); + widget.layout(300, 500); + widget.refresh(); + const focused = viewModel.getItems()[1]; + widget.focusItem(focused); + const page = new DeferredPromise(); + let loads = 0; + model.loadOlderHistory = () => { loads++; return page.p; }; + const tree = container.querySelector('.monaco-list')!; + widget.scrollToEnd(); + tree.dispatchEvent(new WheelEvent('wheel', { deltaY: -1, bubbles: true })); + await nextFrame(); + const awayFromTop = loads; + widget.scrollTop = widget.getElementTop(focused)! + 12; + tree.dispatchEvent(new WheelEvent('wheel', { deltaY: -1, bubbles: true })); + await nextFrame(); + // The user continues reading while the request is in flight. + widget.scrollTop = widget.getElementTop(focused)! + 32; + const anchor = widget.getScrollAnchor(); + const insertion: Parameters = [{ text: 'Older', parts: [] }, { variables: [] }, 0]; + insertion[24] = { index: 0 }; + const older = model.addRequest(...insertion); + model.acceptResponseProgress(older, { kind: 'markdownContent', content: new MarkdownString('Older paragraph\n\n'.repeat(30)) }); + older.response!.complete(); + widget.refresh(); + await page.complete(); + await waitForStableLayout(widget); + assert.deepStrictEqual({ + awayFromTop, loads, anchor: widget.getScrollAnchor(), focused: widget.getFocus()[0] === focused && widget.isDOMFocused(), + }, { awayFromTop: 0, loads: 1, anchor, focused: true }); + }); + test('restores the row at the top of the viewport after switching to another chat and back', async () => { const { disposables, instantiationService, model, viewModel, widget } = createWidget(); const other = disposables.add(instantiationService.createInstance(ChatModel, undefined, { initialLocation: ChatAgentLocation.Chat, canUseTools: true })); diff --git a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts index c5544d5a2c541b..faab491ce826d9 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts @@ -4586,6 +4586,8 @@ suite('ChatService', () => { readonly interruptActiveResponseCallback?: () => Promise; readonly onDidStartServerRequest?: Event; readonly onDidChangeHistory?: Event; + readonly loadOlderHistory?: IChatSession['loadOlderHistory']; + readonly ownsHistoryRequestIds?: boolean; readonly history?: readonly IChatSessionHistoryItem[]; readonly preserveHistoryItemIdentity?: boolean; readonly transferredState?: IChatSession['transferredState']; @@ -4616,6 +4618,8 @@ suite('ChatService', () => { canvasContext: opts.canvasContext, interruptActiveResponseCallback: opts.interruptActiveResponseCallback, onDidStartServerRequest: opts.onDidStartServerRequest, + loadOlderHistory: opts.loadOlderHistory, + ownsHistoryRequestIds: opts.ownsHistoryRequestIds, // Like the agent host provider, update the history before announcing the change. onDidChangeHistory: onDidChangeHistory && Event.map(onDidChangeHistory, next => history = next, testDisposables), preserveHistoryItemIdentity: opts.preserveHistoryItemIdentity, @@ -6012,6 +6016,83 @@ suite('ChatService', () => { }); } + test('loads older history in front of a running request without replaying it as a new send', async () => { + const changes = testDisposables.add(new Emitter()); + const history: IChatSessionHistoryItem[] = [{ id: 'recent', type: 'request', prompt: 'Recent', participant: remoteScheme }]; + const { resource } = setupRemoteProvider({ + history, onDidChangeHistory: changes.event, + loadOlderHistory: async () => changes.fire([ + { id: 'first', type: 'request', prompt: 'First', participant: remoteScheme }, + { id: 'second', type: 'request', prompt: 'Second', participant: remoteScheme }, + ...history, + ]), + }); + const service = createChatServiceWithFrozenHistoryClock(); + const ref = await service.acquireOrLoadSession(resource, ChatAgentLocation.Chat, CancellationToken.None); + assert.ok(ref); + testDisposables.add(ref); + const model = ref.object as ChatModel; + const view = testDisposables.add(instantiationService.createInstance(ChatViewModel, model, undefined)); + const recent = model.lastRequest; + const live = model.addRequest({ text: 'Live', parts: [] }, { variables: [] }, 0); + let sends = 0; + testDisposables.add(view.onDidChange(change => { if (change?.kind === 'addRequest') { sends++; } })); + await model.loadOlderHistory!(); + assert.deepStrictEqual({ + order: view.getItems().filter(isRequestVM).map(item => item.messageText), sends, + preserved: model.getRequests()[2] === recent && model.lastRequest === live, + active: model.hasActiveRequest.get(), complete: model.getRequests().map(r => r.response?.isIncomplete.get()), + }, { order: ['First', 'Second', 'Recent', 'Live'], sends: 0, preserved: true, active: true, complete: [false, false, false, true] }); + model.cancelRequest(live); + }); + + test('authoritative history removes confirmed local turns even if snapshots coalesce while streaming', async () => { + const changes = testDisposables.add(new Emitter()); + const first = { id: 'one', type: 'request', prompt: 'First', participant: remoteScheme } as const; + const { resource } = setupRemoteProvider({ history: [first], onDidChangeHistory: changes.event, ownsHistoryRequestIds: true }); + const service = createChatServiceWithFrozenHistoryClock(); + const ref = await service.acquireOrLoadSession(resource, ChatAgentLocation.Chat, CancellationToken.None); + assert.ok(ref); + const model = testDisposables.add(ref).object as ChatModel; + const local = model.addRequest({ parts: [], text: 'Local' }, { variables: [] }, 0); + const observed = { ...first, prompt: 'Local', id: local.id }; + changes.fire([first, observed]); + changes.fire([first]); + local.response!.complete(); + await timeout(0); + const afterCoalescing = model.getRequests().map(request => request.id); + const settled = model.addRequest({ parts: [], text: 'Settled' }, { variables: [] }, 0); + settled.response!.complete(); + changes.fire([first, { ...first, prompt: 'Settled', id: settled.id }]); + const sameLocal = model.lastRequest === settled; + changes.fire([]); + changes.fire([{ ...first, id: 'replacement' }]); + assert.deepStrictEqual({ afterCoalescing, sameLocal, final: model.getRequests().map(request => request.id) }, { + afterCoalescing: ['one'], sameLocal: true, final: ['replacement'], + }); + }); + + test('send-time history truncation preserves the optimistic request before host confirmation', async () => { + const changes = testDisposables.add(new Emitter()); + const first = { id: 'keep', type: 'request', prompt: 'First', participant: remoteScheme } as const; + const { resource } = setupRemoteProvider({ + history: [first, { ...first, id: 'discard' }], onDidChangeHistory: changes.event, ownsHistoryRequestIds: true, + }); + const service = createChatServiceWithFrozenHistoryClock(); + const ref = await service.acquireOrLoadSession(resource, ChatAgentLocation.Chat, CancellationToken.None); + assert.ok(ref); + const model = testDisposables.add(ref).object as ChatModel; + const sending = model.addRequest({ parts: [], text: 'New branch' }, { variables: [] }, 0); + const response = sending.response!; + changes.fire([first]); + const inFlight = model.lastRequest === sending && model.hasActiveRequest.get(); + response.complete(); + await timeout(0); + assert.deepStrictEqual({ inFlight, sameResponse: model.lastRequest?.response === response, ids: model.getRequests().map(r => r.id) }, { + inFlight: true, sameResponse: true, ids: ['keep', sending.id], + }); + }); + for (const [previousCount, nextCount] of [[2, 1], [1, 2]]) { test(`passive history does not reuse ambiguous ID-less identities: ${previousCount} to ${nextCount}`, async () => { const changes = testDisposables.add(new Emitter()); From 983af80f35dbcf41a0faff7183579e92473c5646 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 17:54:39 -0800 Subject: [PATCH 2/9] chat: page older prompts from the gutter Share the existing chat history page request between the transcript and its navigation controls. Keep the current row in place, and distinguish missing history from an exhausted cursor when a remote host goes offline. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../browser/actions/chatAccessibilityHelp.ts | 2 + .../agentHost/agentHostSessionHandler.ts | 19 ++- .../promptTimeline/media/promptTimeline.css | 24 +++ .../promptTimelineGutterRail.ts | 148 ++++++++++++++---- .../promptTimeline/promptTimelineModel.ts | 6 + .../promptTimelineStickyHeader.ts | 8 +- .../promptTimelineWidgetContrib.ts | 8 +- .../cloudSandboxReadOnlySessionHandler.ts | 3 +- .../cloudSandboxSessionHandler.ts | 11 +- .../chatService/remoteChatSessionRestorer.ts | 24 ++- .../chat/common/chatSessionsService.ts | 4 + .../contrib/chat/common/model/chatModel.ts | 4 + .../agentHostChatContribution.test.ts | 6 +- .../promptTimelineGutterRail.test.ts | 63 ++++++++ .../cloudSandboxSessionHandler.test.ts | 22 +++ .../common/chatService/chatService.test.ts | 27 ++-- 16 files changed, 316 insertions(+), 63 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts index 0639c5480d2a66..0fc3f6811368a2 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts @@ -140,6 +140,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.generateCustomizations', "Use the Chat: Generate commands in the Command Palette to create agents, skills, instructions, prompts, and hooks. Local chats use built-in creation skills; other harnesses receive a plain-text request and a Documentation reference. Use Tab to reach the reference and Enter or Space to open the documentation. You can edit the request and describe what you want to create before sending. Generate Agent Instructions sends its request immediately to analyze the codebase.")); content.push(getChatViewModeAccessibilityHelp()); content.push(localize('chat.olderHistory', "In an Agent Host conversation, focus the message list and use Up Arrow or Page Up near the top to load earlier messages. Focus stays on the current message.")); + content.push(localize('chat.findOlderHistory', "Find searches loaded messages first. If there are no matches, or you move past the known matches, it checks earlier pages. Escape closes Find and stops the search.")); content.push(localize('chat.agentRequiredModels', "When the selected agent requires specific models, the model picker only offers those models. Its footer explains that the agent defines the models. Use Tab to reach the agent link, then Enter or Space to open its definition.")); content.push(localize('chat.permissionLevelPolicy', "When Assisted permissions or Allow all is unavailable for a session, the option remains in the permissions picker as a disabled option with its reason, such as Disabled by your organization. Its hover also explains the restriction. Disabled options cannot be selected.")); content.push(localize('chat.manageToolApprovals', "Run Chat: Manage Tool Approval from the Command Palette to manage approval rules. Expand the terminal tool to change or delete user command rules, or choose Add Command Rule. Expand the fetch tool and choose Add URL Pattern to allow requests without approving responses. Enter accepts a new rule and Escape cancels. These settings also apply to local Agent Host sessions, not remote hosts.")); @@ -152,6 +153,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.codexContinuation', "A ChatGPT limit suggestion may offer Continue with Copilot. If the eligible Codex session is not active, the guide highlights its row in the Sessions list. Activate Open Session in the guide or open the row using the list's usual keyboard shortcut: by default, Command+Down Arrow on macOS or Enter on Windows and Linux. The next step opens its model picker with a matching Copilot model in the search. Activate Use Copilot in the guide or use Up and Down Arrow and Enter in the picker to select the Copilot model. Use Tab or Shift+Tab to reach the guide's buttons and Enter or Space to activate them. An already-active eligible session goes directly to the picker. End Tour or Escape cancels the remaining guidance; it does not undo a model selection.")); } if (isSessionsWindow) { + content.push(localize('chat.gutterOlderHistory', "In the prompt gutter, use Up Arrow at the first prompt to load the previous page. Focus stays on that prompt; press Up Arrow again to move to its predecessor.")); content.push(localize('chat.missionControl.help', "Connect to Mission Control Environment opens a list of existing user-local hosts. Cached hosts are shown while the list refreshes in the background without clearing your search. Use Up and Down Arrow to choose a host and Enter to connect, or Escape to cancel. The owning application must be running; connecting does not create replacement compute. Passive connections are read-only, and local sessions continue using the local host.")); content.push(localize('chat.sessionPreparation', "While a session is being prepared, a progress message appears in the transcript. Use Tab or Shift+Tab to reach Show Log, when available, and press Enter or Space to open the output log. Use Stop to cancel preparation. The chat input and attachment controls are disabled until preparation finishes.")); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts index a45f6c208d4204..6aca1c90e7fcd7 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts @@ -823,6 +823,11 @@ class AgentHostChatSession extends Disposable implements IChatSession { get history(): readonly IChatSessionHistoryItem[] { return this._history; } private _loadingOlderHistory: Promise | undefined; + readonly olderHistoryCursor = derived(this, reader => + this._fetchTurns && !this._disposed.read(reader) ? this._chatState.read(reader).read(reader)?.turnsNextCursor : undefined); + readonly olderHistoryUnavailable = derived(this, reader => + !this._fetchTurns && this._chatState.read(reader).read(reader)?.turnsNextCursor !== undefined); + async loadOlderHistory(): Promise { const chat = this._chatState.get().get(); if (!this._fetchTurns || !chat || chat.turnsNextCursor === undefined || this._store.isDisposed) { @@ -2208,16 +2213,10 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC this._configureActiveClientReconciliation(sessionResource, resolvedSession, sessionSubscription); session.prepareForClientTools = token => this._ensureActiveClient(sessionResource, resolvedSession, token); - if (!isNewSession) { - // Only wire up pending-message/draft sync once the chat URI has been - // resolved. When hydration failed (see the catch above), `chatURI` - // stays undefined; subscribing anyway would later invoke - // `_syncPendingMessages`, whose `_getChatURI` lookup throws because no - // mapping was ever stored for this session resource. - if (chatURI !== undefined) { - this._ensurePendingMessageSubscription(sessionResource, resolvedSession); - this._ensureDraftSyncSubscription(sessionResource, resolvedSession, chatURI); - } + // Subscribing again after a failed chat read would overwrite its visible error with an empty history. + if (!isNewSession && chatURI !== undefined && chatSubscription?.verifiedValue) { + this._ensurePendingMessageSubscription(sessionResource, resolvedSession); + this._ensureDraftSyncSubscription(sessionResource, resolvedSession, chatURI); // Eagerly create the snapshot controller once the ChatModel for // this session is available so that "Restore Checkpoint" works diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css index 7cbfea63193200..5e131034a6918c 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css @@ -567,6 +567,13 @@ outline-offset: 1px; } +.prompt-timeline-gutter-rest.has-older-prompts:empty::before { + content: var(--vscode-icon-chevron-up-content); + font-family: var(--vscode-icon-chevron-up-font-family); + font-size: var(--vscode-codiconFontSize); + color: var(--vscode-descriptionForeground); +} + .prompt-timeline-gutter-dot { width: var(--prompt-timeline-gutter-dot-size); height: var(--prompt-timeline-gutter-dot-size); @@ -707,6 +714,23 @@ box-shadow: none; } +.prompt-timeline-gutter-panel.has-older-prompts { + background-image: linear-gradient(to bottom, var(--vscode-scrollbar-shadow), transparent); + background-repeat: no-repeat; + background-size: 100% var(--vscode-spacing-size80); + overscroll-behavior-y: contain; +} + +.monaco-workbench:is(.hc-black, .hc-light) .prompt-timeline-gutter-panel.has-older-prompts { + background-image: none; + border-top-style: dashed; +} + +.prompt-timeline-gutter-error { + color: var(--vscode-errorForeground); + font-size: var(--vscode-fontSize-body2); +} + /* Each prompt is a full-width row split into two targets: the label on the left reveals the prompt, * the diff badge on the right opens that turn's changes. The fill always lives on the halves, never * on this container, so at any point exactly one layer paints a background and highlights never diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts index 8d821da0a84e0f..1bdd3bda408ec4 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts @@ -130,6 +130,9 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel private _focusRow = 0; /** Which of that row's two buttons holds it. */ private _focusColumn: RowColumn = 'jump'; + private _loadOlder: (() => Promise) | undefined; + private _loadingOlder: (() => Promise) | undefined; + private _historyError: HTMLElement | undefined; private readonly _onDidSelect = this._register(new Emitter()); readonly onDidSelect: Event = this._onDidSelect.event; @@ -165,6 +168,21 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._list = append(this._domNode, $('.prompt-timeline-gutter-panel')); this._list.id = panelId; + this._register(addDisposableListener(this._list, 'wheel', e => { + if (e.deltaY < 0 && !e.ctrlKey && !e.shiftKey && this._list.scrollTop <= 1) { + void this._requestOlder(); + } + })); + let touchY: number | undefined; + this._register(addDisposableListener(this._list, 'touchstart', (e: TouchEvent) => { + touchY = e.touches.length === 1 ? e.touches[0].clientY : undefined; + }, { passive: true })); + this._register(addDisposableListener(this._list, 'touchmove', (e: TouchEvent) => { + if (touchY !== undefined && e.touches.length === 1 && e.touches[0].clientY > touchY && this._list.scrollTop <= 1) { + touchY = undefined; + void this._requestOlder(); + } + }, { passive: true })); // Mouse: reveal while the pointer is over the rail subtree. The rail element is // pointer-transparent (its children opt back in), so `mouseenter` never fires on it — bubble @@ -202,6 +220,10 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel event.preventDefault(); event.stopPropagation(); this._toggleOpen(); + } else if (event.keyCode === KeyCode.UpArrow && this._open && this._rows.length === 0) { + event.preventDefault(); + event.stopPropagation(); + void this._requestOlder(); } })); @@ -234,6 +256,42 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._open = true; this._updateRevealed(); this._focusActiveRow(); + if (!this._rows.length) { + void this._requestOlder(); + } + } + } + + setOlderHistoryLoader(loadOlder: (() => Promise) | undefined): void { + if (this._loadOlder !== loadOlder) { + this._loadOlder = loadOlder; + this._historyError?.remove(); + this._historyError = undefined; + this._list.classList.toggle('has-older-prompts', !!loadOlder); + this._rest.classList.toggle('has-older-prompts', !!loadOlder); + } + } + + private async _requestOlder(): Promise { + const load = this._loadOlder; + if (!load || this._loadingOlder === load || (!this._open && !this._hovering)) { + return; + } + this._loadingOlder = load; + this._historyError?.remove(); + this._historyError = undefined; + try { + await load(); + } catch { + if (load === this._loadOlder && !this._store.isDisposed && (this._open || this._hovering)) { + this._historyError = $('span.prompt-timeline-gutter-error', { role: 'status' }); + this._list.prepend(this._historyError); + this._historyError.textContent = localize('promptTimeline.gutter.historyError', "Could not load earlier prompts. Navigate up to retry."); + } + } finally { + if (this._loadingOlder === load) { + this._loadingOlder = undefined; + } } } @@ -401,6 +459,28 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel if (this._railHeight <= 0) { this._railHeight = this._domNode.clientHeight; } + const start = this._rows.length && ticks.length > this._rows.length ? ticks.findIndex(t => t.requestId === this._rows[0].tick.requestId) : -1; + if (start >= 0 && this._rows.every((r, i) => r.tick.requestId === ticks[start + i]?.requestId)) { + const first = this._rows[0].container; + const preserveScroll = start > 0 && (this._open || this._hovering); + const relativeTop = preserveScroll ? first.offsetTop - this._list.scrollTop : 0; + this._setPreview(-1); + const prefix = ticks.slice(0, start).map(t => this._createRow(t)); + if (prefix.length) { + first.before(...prefix.map(r => r.container)); + this._rows.unshift(...prefix); + this._focusRow += start; + } + for (let i = this._rows.length; i < ticks.length; i++) { + const row = this._createRow(ticks[i]); + this._list.appendChild(row.container); + this._rows.push(row); + } + this._renderDots(ticks.length); + if (preserveScroll) { + this._list.scrollTop = first.offsetTop - relativeTop; + } + } const sameStructure = ticks.length === this._rows.length && ticks.every((t, i) => this._rows[i]?.tick.requestId === t.requestId); if (sameStructure) { @@ -435,37 +515,8 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._renderDots(ticks.length); for (const tick of ticks) { - // The row is a plain container, not a button: it holds two independent targets, and a - // button may not nest inside a button. - const container = append(this._list, $('.prompt-timeline-gutter-row')); - const jump = append(container, $('button.prompt-timeline-gutter-row-jump')); - jump.tabIndex = -1; - const label = append(jump, $('span.prompt-timeline-gutter-row-label')); - const diff = append(container, $('button.prompt-timeline-gutter-row-diff')); - diff.tabIndex = -1; - const stat = append(diff, $('span.prompt-timeline-gutter-row-stat')); - const entry: IRowEntry = { tick, container, jump, diff, label, stat }; - this._renderRow(entry, tick); - const requestId = tick.requestId; - // Both targets collapse the disclosure so it does not linger over the transcript (a pointer - // still resting on the rail keeps it revealed, as hover always has). Jumping returns focus - // to the handle; reviewing leaves it alone, for the diff editor to take. - this._rowDisposables.add(addDisposableListener(jump, EventType.CLICK, () => { - this._onDidSelect.fire(requestId); - this._close(); - })); - this._rowDisposables.add(addDisposableListener(diff, EventType.CLICK, () => { - this._onDidReview.fire(entry.tick); - this._close(/*restoreFocus*/ false); - })); - for (const [button, column] of [[jump, 'jump'], [diff, 'diff']] as const) { - this._rowDisposables.add(addDisposableListener(button, EventType.FOCUS, () => { - // Keyboard-focusing a row (e.g. Tab in from the handle) counts as opening the disclosure. - this._open = true; - this._updateRevealed(); - this._updateTabStops(this._rows.indexOf(entry), column); - })); - } + const entry = this._createRow(tick); + this._list.appendChild(entry.container); this._rows.push(entry); } @@ -474,6 +525,34 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._updateActiveClasses(); } + private _createRow(tick: PromptTick): IRowEntry { + const container = $('.prompt-timeline-gutter-row'); + const jump = append(container, $('button.prompt-timeline-gutter-row-jump')); + jump.tabIndex = -1; + const label = append(jump, $('span.prompt-timeline-gutter-row-label')); + const diff = append(container, $('button.prompt-timeline-gutter-row-diff')); + diff.tabIndex = -1; + const stat = append(diff, $('span.prompt-timeline-gutter-row-stat')); + const entry: IRowEntry = { tick, container, jump, diff, label, stat }; + this._renderRow(entry, tick); + this._rowDisposables.add(addDisposableListener(jump, EventType.CLICK, () => { + this._onDidSelect.fire(entry.tick.requestId); + this._close(); + })); + this._rowDisposables.add(addDisposableListener(diff, EventType.CLICK, () => { + this._onDidReview.fire(entry.tick); + this._close(/*restoreFocus*/ false); + })); + for (const [button, column] of [[jump, 'jump'], [diff, 'diff']] as const) { + this._rowDisposables.add(addDisposableListener(button, EventType.FOCUS, () => { + this._open = true; + this._updateRevealed(); + this._updateTabStops(this._rows.indexOf(entry), column); + })); + } + return entry; + } + private _renderRow(entry: IRowEntry, tick: PromptTick): void { entry.tick = tick; entry.jump.setAttribute('aria-label', tick.ariaLabel); @@ -568,7 +647,12 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel let nextColumn = currentColumn; switch (event.keyCode) { case KeyCode.DownArrow: nextIndex = Math.min(this._rows.length - 1, currentIndex + 1); break; - case KeyCode.UpArrow: nextIndex = Math.max(0, currentIndex - 1); break; + case KeyCode.UpArrow: + if (currentIndex === 0) { + void this._requestOlder(); + } + nextIndex = Math.max(0, currentIndex - 1); + break; case KeyCode.Home: nextIndex = 0; break; case KeyCode.End: nextIndex = this._rows.length - 1; break; case KeyCode.RightArrow: nextColumn = 'diff'; break; diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts index 0c29c5bfea3bdc..93cce0e94490bf 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts @@ -149,6 +149,7 @@ export class PromptTimelineModel extends Disposable { /** The chat session resource, tracked reactively so the editing session can be resolved. */ private readonly _sessionResource: IObservable; + readonly olderHistoryLoader: IObservable<(() => Promise) | undefined>; /** The chat editing session for this chat, if one exists (local or agent-host). */ private readonly _editingSession = derived(this, reader => { @@ -259,6 +260,11 @@ export class PromptTimelineModel extends Disposable { // Assigned here (not as a field initializer) because it reads `this.widget`, // which parameter properties only assign once the constructor body runs. this._sessionResource = observableFromEvent(this, this.widget.onDidChangeViewModel, () => this.widget.viewModel?.sessionResource); + const activeModel = observableFromEvent(this, this.widget.onDidChangeViewModel, () => this.widget.viewModel?.model); + this.olderHistoryLoader = derived(this, reader => { + const model = activeModel.read(reader); + return model?.olderHistoryCursor?.read(reader) !== undefined ? model.loadOlderHistory : undefined; + }); this._register(this.widget.onDidChangeViewModel(() => this._bindViewModel())); this._register(this.widget.onDidScroll(() => { this._updateActive(); this._triggerScrollLayout(); })); this._register(this.widget.onDidChangeContentHeight(() => this._triggerScrollLayout())); diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineStickyHeader.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineStickyHeader.ts index b0f4b37cc88a7a..ba3ed08bf44097 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineStickyHeader.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineStickyHeader.ts @@ -60,11 +60,13 @@ export class PromptTimelineStickyHeader extends Disposable { } /** Names the pinned prompt (1-based index within all prompts). */ - update(text: string, index: number, total: number): void { + update(text: string, index: number, total: number | undefined): void { const label = text || localize('promptTimeline.emptyPrompt', "(empty prompt)"); - this._count.textContent = localize('promptTimeline.stickyCount', "{0}/{1}", index, total); + this._count.textContent = total === undefined ? '' : localize('promptTimeline.stickyCount', "{0}/{1}", index, total); this._labelButton.title = label; - this._labelButton.setAttribute('aria-label', localize('promptTimeline.stickyLabel', "Go to prompt {0} of {1}: {2}", index, total, label)); + this._labelButton.setAttribute('aria-label', total === undefined + ? localize('promptTimeline.stickyPartialLabel', "Go to prompt: {0}", label) + : localize('promptTimeline.stickyLabel', "Go to prompt {0} of {1}: {2}", index, total, label)); if (label !== this._currentLabel || index !== this._lastIndex) { // Step direction from the previous prompt drives which way the label rolls. diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts index e8bcb3d16a736c..e5cdeaf068d4b2 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts @@ -165,9 +165,13 @@ export class PromptTimelineWidgetContrib extends Disposable implements IChatWidg this._enablement.add(autorun(reader => { const ticks = ticksObs.read(reader); + const loadOlder = rail instanceof PromptTimelineGutterRail ? model.olderHistoryLoader.read(reader) : undefined; + if (rail instanceof PromptTimelineGutterRail) { + rail.setOlderHistoryLoader(loadOlder); + } // Toggle visibility before rendering so the rail's fit measurement in // setTicks runs against the displayed (non-zero height) element. - rail.domNode.classList.toggle('hidden', ticks.length < MIN_RAIL_PROMPTS); + rail.domNode.classList.toggle('hidden', ticks.length < MIN_RAIL_PROMPTS && !loadOlder); rail.setTicks(ticks); })); @@ -198,7 +202,7 @@ export class PromptTimelineWidgetContrib extends Disposable implements IChatWidg const active = model.activePrompt.read(reader); const pinned = model.activePinned.read(reader); if (active && pinned) { - sticky.update(active.text, active.index, active.total); + sticky.update(active.text, active.index, model.olderHistoryLoader.read(reader) ? undefined : active.total); } sticky.setVisible(!!active && pinned); })); diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxReadOnlySessionHandler.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxReadOnlySessionHandler.ts index f44d04fca5d47a..4a7eb86a60563b 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxReadOnlySessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxReadOnlySessionHandler.ts @@ -53,6 +53,7 @@ export class ReadOnlyChatSession extends Disposable implements IChatSession { readonly title: string | undefined, readonly isReadOnly: IObservable, onDispose?: () => void, + readonly olderHistoryUnavailable?: IObservable, ) { super(); if (onDispose) { @@ -196,7 +197,7 @@ export class CloudSandboxReadOnlySessionHandler extends Disposable implements IC if (this._chatContexts.get(sessionResource) === context) { this._chatContexts.delete(sessionResource); } - }); + }, constObservable(!!replayed?.truncated || chat?.turnsNextCursor !== undefined)); } resolveChatResponseUri(resource: URI, href: string, kind: 'link' | 'image'): string { diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts index dcab79062f9f55..bd5dd489ee6f00 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts @@ -47,6 +47,8 @@ class PromotableCloudSandboxChatSession extends Disposable implements IChatSessi readonly isReadOnly = observableValue(this, true); readonly isInputBlocked = observableValue(this, false); readonly historyStatus = observableValue(this, undefined); + readonly olderHistoryCursor = observableValue(this, undefined); + readonly olderHistoryUnavailable = observableValue(this, false); readonly backgroundShellCount = observableValue(this, undefined); readonly canvasContext = observableValue(this, undefined); readonly sessionResource: URI; @@ -93,7 +95,8 @@ class PromotableCloudSandboxChatSession extends Disposable implements IChatSessi } suspendLive(): void { - this._bindSource(new ReadOnlyChatSession(this.sessionResource, [...this.history], this.title, constObservable(true)), false, false); + const partial = this.olderHistoryUnavailable.get() || this.olderHistoryCursor.get() !== undefined; + this._bindSource(new ReadOnlyChatSession(this.sessionResource, [...this.history], this.title, constObservable(true), undefined, constObservable(partial)), false, false); } private _bindSource(source: IChatSession, promote: boolean, live: boolean): void { @@ -142,6 +145,8 @@ class PromotableCloudSandboxChatSession extends Disposable implements IChatSessi const readOnly = source.isReadOnly?.read(reader) ?? false; const blocked = !live || (source.isInputBlocked?.read(reader) ?? false); const backgroundShellCount = source.backgroundShellCount?.read(reader); + const olderHistoryCursor = source.loadOlderHistory && source.olderHistoryCursor?.read(reader); + const unavailable = source.olderHistoryUnavailable?.read(reader) ?? false; const canvasContext = source.canvasContext?.read(reader); if (live && (previousProgress !== progress || previousComplete !== complete)) { this._invalidateHistory(); @@ -154,6 +159,8 @@ class PromotableCloudSandboxChatSession extends Disposable implements IChatSessi this.isReadOnly.set(readOnly, tx); this.isInputBlocked.set(blocked, tx); this.backgroundShellCount.set(backgroundShellCount, tx); + this.olderHistoryCursor.set(olderHistoryCursor, tx); + this.olderHistoryUnavailable.set(unavailable, tx); this.canvasContext.set(canvasContext, tx); }); })); @@ -189,6 +196,8 @@ class CloudSandboxChatSessionReference extends Disposable implements IChatSessio get history() { return this._session.history; } get ownsHistoryRequestIds() { return this._session.ownsHistoryRequestIds; } get loadOlderHistory() { return this._session.loadOlderHistory; } + get olderHistoryCursor() { return this._session.olderHistoryCursor; } + get olderHistoryUnavailable() { return this._session.olderHistoryUnavailable; } get preserveHistoryItemIdentity() { return this._session.preserveHistoryItemIdentity; } get title() { return this._session.title; } get options() { return this._session.options; } diff --git a/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts b/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts index 35b11dee500efa..ac02f08003b7bb 100644 --- a/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts +++ b/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts @@ -10,7 +10,7 @@ import { Event } from '../../../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; import { equals } from '../../../../../base/common/objects.js'; import { setTimeout0 } from '../../../../../base/common/platform.js'; -import { autorun } from '../../../../../base/common/observable.js'; +import { autorun, transaction } from '../../../../../base/common/observable.js'; import { clearMarks, mark } from '../../../../../base/common/performance.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { getChatSessionHistoryContent, IChatSession, IChatSessionHistoryItem, IChatSessionRequestHistoryItem, IChatSessionServerRequest } from '../chatSessionsService.js'; @@ -167,13 +167,17 @@ export class RemoteChatSessionRestorer extends Disposable { this._session = _options.session; this._restoredHistory = this._session.history; if (this._session.loadOlderHistory) { - this._model.loadOlderHistory = async () => { + let page: Promise | undefined; + const readPage = async () => { if (this._state === RestoreState.Published) { await this._session.loadOlderHistory?.(); await this.historyRefresh; } }; - this._register(toDisposable(() => this._model.loadOlderHistory = undefined)); + this._model.loadOlderHistory = () => page ??= readPage().finally(() => { page = undefined; }); + this._register(toDisposable(() => { + this._model.loadOlderHistory = undefined; + })); } this._hasProgressStreaming = !!(this._session.progressObs && this._session.interruptActiveResponseCallback); // Cancel pending cooperative waits when the restorer is disposed, not only when the service token is. @@ -238,6 +242,20 @@ export class RemoteChatSessionRestorer extends Disposable { } this._state = RestoreState.Published; + if (this._session.olderHistoryCursor || this._session.olderHistoryUnavailable) { + this._register(autorun(reader => { + const cursor = this._session.olderHistoryCursor?.read(reader); + const unavailable = !!this._session.olderHistoryUnavailable?.read(reader) || (cursor !== undefined && !this._session.loadOlderHistory); + transaction(tx => { + this._model.olderHistoryCursor.set(this._session.loadOlderHistory ? cursor : undefined, tx); + this._model.olderHistoryUnavailable.set(unavailable, tx); + }); + })); + this._register(toDisposable(() => transaction(tx => { + this._model.olderHistoryCursor.set(undefined, tx); + this._model.olderHistoryUnavailable.set(false, tx); + }))); + } this._register(Event.once(this._model.onDidDispose)(() => this.dispose())); try { this._lastRequest = this._model.getRequests().at(-1); diff --git a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts index 070d3fb8c42daf..074ebaab84ba4b 100644 --- a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts +++ b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts @@ -578,6 +578,10 @@ export interface IChatSession extends IDisposable { readonly history: readonly IChatSessionHistoryItem[]; /** Requests one older page, if available. The resulting history is published through onDidChangeHistory. */ readonly loadOlderHistory?: () => Promise; + /** The opaque cursor for the next older page, or undefined when no page is available. */ + readonly olderHistoryCursor?: IObservable; + /** The displayed history is known to be incomplete but the missing messages cannot currently be read. */ + readonly olderHistoryUnavailable?: IObservable; /** Initial history loading failed; any rendered error or partial history is not an authoritative snapshot. */ readonly historyLoadError?: { readonly message: string; diff --git a/src/vs/workbench/contrib/chat/common/model/chatModel.ts b/src/vs/workbench/contrib/chat/common/model/chatModel.ts index 03108ec290c411..6f54cca71a8b15 100644 --- a/src/vs/workbench/contrib/chat/common/model/chatModel.ts +++ b/src/vs/workbench/contrib/chat/common/model/chatModel.ts @@ -2145,6 +2145,8 @@ export interface IChatModel extends IDisposable { readonly isInputBlocked: IObservable; readonly historyStatus?: IObservable; readonly loadOlderHistory?: () => Promise; + readonly olderHistoryCursor?: IObservable; + readonly olderHistoryUnavailable?: IObservable; readonly modelConfigurationState?: IObservable; /** Provider-reported active shells across all turns; undefined allows transcript-based detection. */ readonly backgroundShellCount?: IObservable; @@ -3046,6 +3048,8 @@ export class ChatModel extends Disposable implements IChatModel { readonly isInputBlocked: IObservable; readonly historyStatus: IObservable; loadOlderHistory?: () => Promise; + readonly olderHistoryCursor = observableValue(this, undefined); + readonly olderHistoryUnavailable = observableValue(this, false); readonly modelConfigurationState: IObservable | undefined; readonly backgroundShellCount: IObservable | undefined; readonly canvasContext: IObservable | undefined; diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts index 18276e7cf5ba7a..04af0cf78f8077 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts @@ -21946,6 +21946,7 @@ suite('AgentHostChatContribution', () => { }; const session = disposables.add(await sessionHandler.provideChatSessionContent(resource, CancellationToken.None)); const newest = session.history[0]; + const cursors = [session.olderHistoryCursor?.get()]; const initial = { prompt: newest.type === 'request' && newest.prompt, fetches: calls.length }; const first = Promise.all([session.loadOlderHistory!(), session.loadOlderHistory!()]); await page.error(new Error('offline')); @@ -21958,6 +21959,7 @@ suite('AgentHostChatContribution', () => { }); await page.complete(); await retry; + cursors.push(session.olderHistoryCursor?.get()); const afterRetry = calls.length; await session.loadOlderHistory!(); agentHostService.fireAction({ @@ -21965,11 +21967,11 @@ suite('AgentHostChatContribution', () => { }); await session.loadOlderHistory!(); assert.deepStrictEqual({ - initial, calls, afterRetry, requests: session.history.flatMap(item => item.type === 'request' ? [item.prompt] : []), + initial, calls, cursors: [...cursors, session.olderHistoryCursor?.get()], afterRetry, requests: session.history.flatMap(item => item.type === 'request' ? [item.prompt] : []), retained: session.history.includes(newest), }, { initial: { prompt: 'newest', fetches: 0 }, calls: [[chat, 'first cursor'], [chat, 'first cursor'], [chat, 'second cursor']], - afterRetry: 2, requests: ['oldest', 'older', 'newest'], retained: true, + cursors: ['first cursor', 'second cursor', undefined], afterRetry: 2, requests: ['oldest', 'older', 'newest'], retained: true, }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts index 851441ba8a1a37..9f7be5ff14da5d 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts @@ -5,6 +5,7 @@ import assert from 'assert'; import { getWindow } from '../../../../../../base/browser/dom.js'; +import { DeferredPromise } from '../../../../../../base/common/async.js'; import { toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { PromptTimelineGutterRail, restDotCount } from '../../../browser/promptTimeline/promptTimelineGutterRail.js'; @@ -39,6 +40,68 @@ suite('PromptTimelineGutterRail', () => { target.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true, cancelable: true })); } + test('loads one older page at the gutter boundary and preserves the focused row and column', async () => { + const stat = { added: 1, removed: 0, fileCount: 1 }; + const recent = [tick(90, stat), tick(91)]; + const rail = createRail(recent); + const page = new DeferredPromise(); + let loads = 0; + rail.setOlderHistoryLoader(async () => { loads++; await page.p; }); + const panel = rail.domNode.querySelector('.prompt-timeline-gutter-panel')!; + const selected: string[] = []; + store.add(rail.onDidSelect(id => selected.push(id))); + const first = rowParts(rail)[0].diff; + rail.domNode.querySelector('.prompt-timeline-gutter-rest')!.click(); + keydown(rowParts(rail)[0].jump, 'ArrowRight', 39); + const loadsBeforeGesture = loads; + keydown(first, 'ArrowUp', 38); + assert.strictEqual(loads, 1, 'Up at the first focused row must request a page'); + panel.dispatchEvent(new WheelEvent('wheel', { deltaY: -10, bubbles: true })); + keydown(first, 'ArrowUp', 38); + rail.setTicks([tick(88), tick(89, stat), ...recent]); + rail.setOlderHistoryLoader(undefined); + await page.complete(); + const preserved = document.activeElement === first; + keydown(first, 'ArrowUp', 38); + const predecessor = rowParts(rail)[1]; + const focusedPrevious = document.activeElement === predecessor.diff; + predecessor.jump.click(); + assert.deepStrictEqual({ loadsBeforeGesture, loads, preserved, focusedPrevious, selected, more: panel.classList.contains('has-older-prompts') }, + { loadsBeforeGesture: 0, loads: 1, preserved: true, focusedPrevious: true, selected: ['89'], more: false }); + }); + + test('a page without user prompts still offers paging without inventing a prompt row', () => { + const rail = createRail([]); + let loads = 0; + rail.setOlderHistoryLoader(async () => { loads++; }); + const handle = rail.domNode.querySelector('.prompt-timeline-gutter-rest')!; + const idleLoads = loads; + handle.click(); + assert.deepStrictEqual({ affordance: handle.matches('.has-older-prompts:empty'), rows: rowParts(rail).length, idleLoads, loads }, + { affordance: true, rows: 0, idleLoads: 0, loads: 1 }); + }); + + test('a failed wheel request can be retried without leaving the gutter', async () => { + const rail = createRail([tick(90), tick(91)]); + const panel = rail.domNode.querySelector('.prompt-timeline-gutter-panel')!; + let attempts = 0; + rail.setOlderHistoryLoader(async () => { + if (++attempts === 1) { + throw new Error('offline'); + } + rail.setTicks([tick(89), tick(90), tick(91)]); + }); + panel.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + const wheel = () => panel.dispatchEvent(new WheelEvent('wheel', { deltaY: -1, bubbles: true })); + wheel(); + await Promise.resolve(); + const notified = !!panel.querySelector('[role=status]'); + wheel(); + await Promise.resolve(); + assert.deepStrictEqual({ notified, error: !!panel.querySelector('[role=status]'), attempts, rows: rowParts(rail).map(r => r.jump.textContent) }, + { notified: true, error: false, attempts: 2, rows: ['89', '90', '91'] }); + }); + test('highlights a row previewed from a dot, but leaves a row under the pointer to its own halves', () => { const rail = createRail(Array.from({ length: 3 }, (_, index) => tick(index))); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts index 31d579f56efc2e..9640a3af75dbe1 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts @@ -257,6 +257,7 @@ suite('CloudSandboxSessionHandler', () => { const handler = createHandler(undefined, undefined, undefined, undefined, undefined, undefined, (resource, title) => { titles.push({ resource: resource.toString(), title }); }); + const session = await handler.provideChatSessionContent(resource, CancellationToken.None); const initialTitle = session.title; const live = store.add(new LiveSession(undefined, 'Authoritative live title')); @@ -268,6 +269,27 @@ suite('CloudSandboxSessionHandler', () => { }); }); + test('older history follows the live source and is unavailable while suspended', async () => { + const handler = createHandler(async () => recordedHistory()); + const session = store.add(await handler.provideChatSessionContent(resource, CancellationToken.None)); + const cursor = observableValue('cursor', 'older'); + let loads = 0; + const live = Object.assign(store.add(new LiveSession()), { + olderHistoryCursor: cursor, + loadOlderHistory: async () => { loads++; cursor.set('oldest', undefined); }, + }); + const cursors = [session.olderHistoryCursor?.get()]; + handler.setLiveProvider({ provideChatSessionContent: async () => live }); + await waitForState(session.isInputBlocked!, blocked => !blocked); + cursors.push(session.olderHistoryCursor?.get()); + await session.loadOlderHistory!(); + cursors.push(session.olderHistoryCursor?.get()); + handler.clearLiveProvider(); + await session.loadOlderHistory!(); + assert.deepStrictEqual({ cursors: [...cursors, session.olderHistoryCursor?.get()], unavailable: session.olderHistoryUnavailable?.get(), loads }, + { cursors: [undefined, 'older', 'oldest', undefined], unavailable: true, loads: 1 }); + }); + test('publishes a refreshed recorded title without replacing the open conversation', async () => { const fresh = new DeferredPromise(); const titles: string[] = []; diff --git a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts index faab491ce826d9..0383d4c4e7abbe 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts @@ -4587,6 +4587,7 @@ suite('ChatService', () => { readonly onDidStartServerRequest?: Event; readonly onDidChangeHistory?: Event; readonly loadOlderHistory?: IChatSession['loadOlderHistory']; + readonly olderHistoryCursor?: IChatSession['olderHistoryCursor']; readonly ownsHistoryRequestIds?: boolean; readonly history?: readonly IChatSessionHistoryItem[]; readonly preserveHistoryItemIdentity?: boolean; @@ -4619,6 +4620,7 @@ suite('ChatService', () => { interruptActiveResponseCallback: opts.interruptActiveResponseCallback, onDidStartServerRequest: opts.onDidStartServerRequest, loadOlderHistory: opts.loadOlderHistory, + olderHistoryCursor: opts.olderHistoryCursor, ownsHistoryRequestIds: opts.ownsHistoryRequestIds, // Like the agent host provider, update the history before announcing the change. onDidChangeHistory: onDidChangeHistory && Event.map(onDidChangeHistory, next => history = next, testDisposables), @@ -6019,13 +6021,19 @@ suite('ChatService', () => { test('loads older history in front of a running request without replaying it as a new send', async () => { const changes = testDisposables.add(new Emitter()); const history: IChatSessionHistoryItem[] = [{ id: 'recent', type: 'request', prompt: 'Recent', participant: remoteScheme }]; + const cursor = observableValue('cursor', 'older'); + let loads = 0; const { resource } = setupRemoteProvider({ - history, onDidChangeHistory: changes.event, - loadOlderHistory: async () => changes.fire([ - { id: 'first', type: 'request', prompt: 'First', participant: remoteScheme }, - { id: 'second', type: 'request', prompt: 'Second', participant: remoteScheme }, - ...history, - ]), + history, onDidChangeHistory: changes.event, olderHistoryCursor: cursor, + loadOlderHistory: async () => { + loads++; + changes.fire([ + { id: 'first', type: 'request', prompt: 'First', participant: remoteScheme }, + { id: 'second', type: 'request', prompt: 'Second', participant: remoteScheme }, + ...history, + ]); + cursor.set(undefined, undefined); + }, }); const service = createChatServiceWithFrozenHistoryClock(); const ref = await service.acquireOrLoadSession(resource, ChatAgentLocation.Chat, CancellationToken.None); @@ -6037,12 +6045,13 @@ suite('ChatService', () => { const live = model.addRequest({ text: 'Live', parts: [] }, { variables: [] }, 0); let sends = 0; testDisposables.add(view.onDidChange(change => { if (change?.kind === 'addRequest') { sends++; } })); - await model.loadOlderHistory!(); + const before = model.olderHistoryCursor.get(); + await Promise.all([model.loadOlderHistory!(), model.loadOlderHistory!()]); assert.deepStrictEqual({ - order: view.getItems().filter(isRequestVM).map(item => item.messageText), sends, + order: view.getItems().filter(isRequestVM).map(item => item.messageText), sends, loads, cursors: [before, model.olderHistoryCursor.get()], preserved: model.getRequests()[2] === recent && model.lastRequest === live, active: model.hasActiveRequest.get(), complete: model.getRequests().map(r => r.response?.isIncomplete.get()), - }, { order: ['First', 'Second', 'Recent', 'Live'], sends: 0, preserved: true, active: true, complete: [false, false, false, true] }); + }, { order: ['First', 'Second', 'Recent', 'Live'], sends: 0, loads: 1, cursors: ['older', undefined], preserved: true, active: true, complete: [false, false, false, true] }); model.cancelRequest(live); }); From d6c7547a9cad9dad10109477309779290e49d429 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 17:56:31 -0800 Subject: [PATCH 3/9] chat: keep partial prompt counts honest while offline Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../browser/promptTimeline/promptTimelineModel.ts | 12 ++++++++---- .../promptTimeline/promptTimelineWidgetContrib.ts | 2 +- .../remoteAgentHost/cloudSandboxSessionHandler.ts | 6 +++--- .../promptTimeline/promptTimelineModel.test.ts | 12 ++++++++++++ .../cloudSandboxSessionHandler.test.ts | 10 ++++++++-- 5 files changed, 32 insertions(+), 10 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts index 93cce0e94490bf..47c3130502e79e 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts @@ -21,6 +21,7 @@ import { getChatRequestText } from '../chatRequestText.js'; import { ChatTreeItem } from '../chat.js'; import { IChatResponseFileChangesService } from '../chatResponseFileChangesService.js'; import { IChatEditingService, IEditSessionEntryDiff } from '../../common/editing/chatEditingService.js'; +import { IChatModel } from '../../common/model/chatModel.js'; import { IChatRequestViewModel, isRequestVM, isResponseVM } from '../../common/model/chatViewModel.js'; import { budgetBucketPrompts, MAX_TICKS, PromptItem } from './promptBucketing.js'; @@ -48,7 +49,7 @@ export interface IPromptScrollLayout { /** Each prompt's top offset in the rail's estimated content space. */ readonly marks: readonly { readonly requestId: string; readonly top: number }[]; /** Total content height in the estimated space, matching `marks`. */ - readonly total: number; + readonly total: number | undefined; /** Current scroll offset (px, the transcript's real scroll space) — drives the rail's own scrollbar thumb. */ readonly scrollTop: number; /** Full scrollable content height (px, the transcript's real scroll space). */ @@ -149,6 +150,7 @@ export class PromptTimelineModel extends Disposable { /** The chat session resource, tracked reactively so the editing session can be resolved. */ private readonly _sessionResource: IObservable; + private readonly _activeModel: IObservable; readonly olderHistoryLoader: IObservable<(() => Promise) | undefined>; /** The chat editing session for this chat, if one exists (local or agent-host). */ @@ -232,7 +234,9 @@ export class PromptTimelineModel extends Disposable { } const prompts = this._prompts.read(reader); const index = prompts.findIndex(p => p.requestId === id); - return index < 0 ? undefined : { text: prompts[index].text, index: index + 1, total: prompts.length }; + const model = this._activeModel.read(reader); + const partial = model?.olderHistoryCursor?.read(reader) !== undefined || model?.olderHistoryUnavailable?.read(reader); + return index < 0 ? undefined : { text: prompts[index].text, index: index + 1, total: partial ? undefined : prompts.length }; }); get activePrompt(): IObservable { return this._activePrompt; } @@ -260,9 +264,9 @@ export class PromptTimelineModel extends Disposable { // Assigned here (not as a field initializer) because it reads `this.widget`, // which parameter properties only assign once the constructor body runs. this._sessionResource = observableFromEvent(this, this.widget.onDidChangeViewModel, () => this.widget.viewModel?.sessionResource); - const activeModel = observableFromEvent(this, this.widget.onDidChangeViewModel, () => this.widget.viewModel?.model); + this._activeModel = observableFromEvent(this, this.widget.onDidChangeViewModel, () => this.widget.viewModel?.model); this.olderHistoryLoader = derived(this, reader => { - const model = activeModel.read(reader); + const model = this._activeModel.read(reader); return model?.olderHistoryCursor?.read(reader) !== undefined ? model.loadOlderHistory : undefined; }); this._register(this.widget.onDidChangeViewModel(() => this._bindViewModel())); diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts index e5cdeaf068d4b2..242b304cd507f3 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineWidgetContrib.ts @@ -202,7 +202,7 @@ export class PromptTimelineWidgetContrib extends Disposable implements IChatWidg const active = model.activePrompt.read(reader); const pinned = model.activePinned.read(reader); if (active && pinned) { - sticky.update(active.text, active.index, model.olderHistoryLoader.read(reader) ? undefined : active.total); + sticky.update(active.text, active.index, active.total); } sticky.setVisible(!!active && pinned); })); diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts index bd5dd489ee6f00..e589f6dffa47d6 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionHandler.ts @@ -145,8 +145,8 @@ class PromotableCloudSandboxChatSession extends Disposable implements IChatSessi const readOnly = source.isReadOnly?.read(reader) ?? false; const blocked = !live || (source.isInputBlocked?.read(reader) ?? false); const backgroundShellCount = source.backgroundShellCount?.read(reader); - const olderHistoryCursor = source.loadOlderHistory && source.olderHistoryCursor?.read(reader); - const unavailable = source.olderHistoryUnavailable?.read(reader) ?? false; + const cursor = source.olderHistoryCursor?.read(reader); + const unavailable = !!source.olderHistoryUnavailable?.read(reader) || (cursor !== undefined && !source.loadOlderHistory); const canvasContext = source.canvasContext?.read(reader); if (live && (previousProgress !== progress || previousComplete !== complete)) { this._invalidateHistory(); @@ -159,7 +159,7 @@ class PromotableCloudSandboxChatSession extends Disposable implements IChatSessi this.isReadOnly.set(readOnly, tx); this.isInputBlocked.set(blocked, tx); this.backgroundShellCount.set(backgroundShellCount, tx); - this.olderHistoryCursor.set(olderHistoryCursor, tx); + this.olderHistoryCursor.set(source.loadOlderHistory ? cursor : undefined, tx); this.olderHistoryUnavailable.set(unavailable, tx); this.canvasContext.set(canvasContext, tx); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineModel.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineModel.test.ts index 2e075c3b0b27cb..8eae4b4443e4a5 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineModel.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineModel.test.ts @@ -15,6 +15,7 @@ import { IChatResponseFileChangesService } from '../../../browser/chatResponseFi import { PromptTimelineModel } from '../../../browser/promptTimeline/promptTimelineModel.js'; import { ChatWidget } from '../../../browser/widget/chatWidget.js'; import { IChatEditingService, IEditSessionEntryDiff } from '../../../common/editing/chatEditingService.js'; +import { IChatModel } from '../../../common/model/chatModel.js'; import { ChatViewModel, IChatRequestViewModel, IChatViewModelChangeEvent } from '../../../common/model/chatViewModel.js'; suite('PromptTimelineModel', () => { @@ -38,7 +39,9 @@ suite('PromptTimelineModel', () => { const onDidChange = store.add(new Emitter()); const onDidChangeViewModel = store.add(new Emitter()); let scrollTop = 0; + const olderHistoryUnavailable = observableValue('olderHistoryUnavailable', false); let viewModel = upcastPartial({ + model: upcastPartial({ olderHistoryUnavailable }), sessionResource: URI.parse('test:/first'), onDidChange: onDidChange.event, getItems: () => items, @@ -63,6 +66,7 @@ suite('PromptTimelineModel', () => { return { model, + olderHistoryUnavailable, setRequests(requests: readonly IChatRequestViewModel[]): void { items.splice(0, items.length, ...requests); onDidChange.fire(null); @@ -90,6 +94,14 @@ suite('PromptTimelineModel', () => { }; } + test('does not present a cached tail as the entire prompt list while the host is unavailable', () => { + const { model, olderHistoryUnavailable } = createModel([{ item: request('last', 'Last', 1), top: 0 }]); + olderHistoryUnavailable.set(true, undefined); + const offline = model.activePrompt.get(); + olderHistoryUnavailable.set(false, undefined); + assert.deepStrictEqual([offline?.text, offline?.total, model.activePrompt.get()?.total], ['Last', undefined, 1]); + }); + for (const ticksProperty of ['promptTicks', 'ticks'] as const) { test(`${ticksProperty} only recomputes the changed prompt and suppresses equal diff stats`, () => { const now = Date.now(); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts index 9640a3af75dbe1..1ee8abd83f7545 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxSessionHandler.test.ts @@ -286,8 +286,12 @@ suite('CloudSandboxSessionHandler', () => { cursors.push(session.olderHistoryCursor?.get()); handler.clearLiveProvider(); await session.loadOlderHistory!(); - assert.deepStrictEqual({ cursors: [...cursors, session.olderHistoryCursor?.get()], unavailable: session.olderHistoryUnavailable?.get(), loads }, - { cursors: [undefined, 'older', 'oldest', undefined], unavailable: true, loads: 1 }); + cursors.push(session.olderHistoryCursor?.get()); + const suspended = session.olderHistoryUnavailable?.get(); + handler.setLiveProvider({ provideChatSessionContent: async () => store.add(new LiveSession()) }); + await waitForState(session.isInputBlocked!, blocked => !blocked); + assert.deepStrictEqual({ cursors, suspended, reconnected: session.olderHistoryUnavailable?.get(), loads }, + { cursors: [undefined, 'older', 'oldest', undefined], suspended: true, reconnected: false, loads: 1 }); }); test('publishes a refreshed recorded title without replacing the open conversation', async () => { @@ -557,10 +561,12 @@ suite('CloudSandboxSessionHandler', () => { assert.deepStrictEqual({ prompts: session.history.filter(item => item.type === 'request').map(item => item.prompt), warnings: session.history.flatMap(item => item.type === 'response' ? item.parts.filter(part => part.kind === 'warning').map(part => part.content.value) : []), + incomplete: session.olderHistoryUnavailable?.get(), readOnly: session.isReadOnly?.get(), status: session.historyStatus?.get(), }, { prompts: ['custom-chat:/opaque-main'], warnings: ['This conversation is incomplete. Its recorded history ends mid-response, so the last exchange may be missing.'], + incomplete: true, readOnly: true, status: undefined, }); }); From 10b5b4f3f59e84039b37d99d1e29db8bf8f33a9a Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 18:03:42 -0800 Subject: [PATCH 4/9] chat: find earlier matches without loading history on open Search loaded turns first, then share the backward pager with the gutter when navigation needs older messages. Keep partial results usable when a read fails, release stale searches, and wait for restored matches to enter the transcript before revealing them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../promptTimelineGutterRail.ts | 10 +- .../promptTimeline/promptTimelineModel.ts | 4 +- .../browser/widget/chatFind/chatFindModel.ts | 59 +++- .../browser/widget/chatFind/chatFindWidget.ts | 291 +++++++++++++--- .../contrib/chat/browser/widget/chatWidget.ts | 5 +- .../promptTimelineGutterRail.test.ts | 18 +- .../test/browser/widget/chatFindModel.test.ts | 57 +++- .../browser/widget/chatFindWidget.test.ts | 313 +++++++++++++++++- .../browser/find/simpleFindWidget.ts | 64 +++- 9 files changed, 742 insertions(+), 79 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts index 1bdd3bda408ec4..56758e8fbfd991 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts @@ -24,6 +24,7 @@ import './media/promptTimeline.css'; const MAX_REST_DOTS = 50; /** Never sample below this: two dots are the fewest that can still span the session's start and end. */ const MIN_REST_DOTS = 2; +const WHEEL_GESTURE_GAP_MS = 120; /** * Resting-dot geometry, mirrored from the `--prompt-timeline-gutter-*` variables in * `promptTimeline.css` so {@link restDotCount} can size the column without measuring it (which would @@ -168,8 +169,15 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._list = append(this._domNode, $('.prompt-timeline-gutter-panel')); this._list.id = panelId; + let lastWheelTime = -Infinity; + let pagedInGesture = false; this._register(addDisposableListener(this._list, 'wheel', e => { - if (e.deltaY < 0 && !e.ctrlKey && !e.shiftKey && this._list.scrollTop <= 1) { + if (e.timeStamp - lastWheelTime > WHEEL_GESTURE_GAP_MS || e.deltaY > 0) { + pagedInGesture = false; + } + lastWheelTime = e.timeStamp; + if (!pagedInGesture && this._loadOlder && e.deltaY < 0 && !e.ctrlKey && !e.shiftKey && this._list.scrollTop <= 1) { + pagedInGesture = true; void this._requestOlder(); } })); diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts index 47c3130502e79e..cad5fbf518bd8d 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineModel.ts @@ -49,7 +49,7 @@ export interface IPromptScrollLayout { /** Each prompt's top offset in the rail's estimated content space. */ readonly marks: readonly { readonly requestId: string; readonly top: number }[]; /** Total content height in the estimated space, matching `marks`. */ - readonly total: number | undefined; + readonly total: number; /** Current scroll offset (px, the transcript's real scroll space) — drives the rail's own scrollbar thumb. */ readonly scrollTop: number; /** Full scrollable content height (px, the transcript's real scroll space). */ @@ -136,7 +136,7 @@ function promptsEqual(a: readonly PromptItem[], b: readonly PromptItem[]): boole export interface IActivePrompt { readonly text: string; readonly index: number; - readonly total: number; + readonly total: number | undefined; } /** diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindModel.ts b/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindModel.ts index af9dad57b1ca25..dfec1386037220 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindModel.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindModel.ts @@ -57,6 +57,10 @@ interface IChatFindAnchor { readonly occurrenceIndex: number; } +function isSameOccurrence(match: IChatFindMatch, anchor: IChatFindAnchor): boolean { + return match.itemId === anchor.itemId && match.partIndex === anchor.partIndex && match.occurrenceIndex === anchor.occurrenceIndex; +} + function buildSegments(items: readonly ChatTreeItem[]): IChatFindSegment[] { const segments: IChatFindSegment[] = []; for (const item of items) { @@ -164,6 +168,7 @@ export class ChatFindModel extends Disposable { private _query = ''; private _options: IChatFindOptions = { isRegex: false, matchCase: false, wholeWord: false }; private _matches: IChatFindMatch[] = []; + private _completedRows = new WeakMap(); private _activeIndex = -1; private _activeAnchor: IChatFindAnchor | undefined; private _invalidRegex = false; @@ -208,6 +213,7 @@ export class ChatFindModel extends Disposable { this._query = query; this._options = options; if (changed) { + this._completedRows = new WeakMap(); this._activeAnchor = undefined; this._activeIndex = -1; } @@ -245,20 +251,15 @@ export class ChatFindModel extends Disposable { } const items = this.getItems(); - const segments = buildSegments(items); const matches: IChatFindMatch[] = []; - // Newest first: `buildSegments` produces transcript order, so both walks are reversed. - for (let index = segments.length - 1; index >= 0 && matches.length < MAX_FIND_MATCHES; index--) { - const segmentMatches = findMatchesInSegment(segments[index], regex, MAX_FIND_MATCHES - matches.length); - for (let occurrence = segmentMatches.length - 1; occurrence >= 0; occurrence--) { - matches.push(segmentMatches[occurrence]); - } + for (let index = items.length - 1; index >= 0 && matches.length < MAX_FIND_MATCHES; index--) { + matches.push(...this._matchesInRow(items[index], regex, MAX_FIND_MATCHES - matches.length)); } this._matches = matches; if (previousAnchor) { - this._activeIndex = matches.findIndex(m => m.itemId === previousAnchor.itemId && m.partIndex === previousAnchor.partIndex && m.occurrenceIndex === previousAnchor.occurrenceIndex); + this._activeIndex = matches.findIndex(m => isSameOccurrence(m, previousAnchor)); } if (this._activeIndex < 0) { this._activeIndex = this._seedActiveIndex(matches, items); @@ -268,6 +269,35 @@ export class ChatFindModel extends Disposable { this._onDidChangeMatches.fire(); } + private _matchesInRow(item: ChatTreeItem, regex: RegExp, limit: number): readonly IChatFindMatch[] { + if (!isRequestVM(item) && !isResponseVM(item)) { + return []; + } + const cached = this._completedRows.get(item); + if (item.isComplete && cached && cached.dataId === item.dataId && (cached.matches.length < cached.limit || limit <= cached.limit)) { + return cached.matches.length > limit ? cached.matches.slice(0, limit) : cached.matches; + } + const matches: IChatFindMatch[] = []; + const segments = buildSegments([item]); + for (let index = segments.length - 1; index >= 0 && matches.length < limit; index--) { + matches.push(...findMatchesInSegment(segments[index], regex, limit - matches.length).reverse()); + } + if (item.isComplete) { + this._completedRows.set(item, { dataId: item.dataId, limit, matches }); + } else { + this._completedRows.delete(item); + } + return matches; + } + + invalidateRenderedRow(item: ChatTreeItem): boolean { + return this._completedRows.delete(item); + } + + isActiveOccurrence(match: IChatFindMatch): boolean { + return !!this._activeAnchor && isSameOccurrence(match, this._activeAnchor); + } + /** Moves to the next match in navigation order, which is the next one *back* in the transcript. */ next(): IChatFindMatch | undefined { if (this._matches.length === 0) { @@ -290,7 +320,20 @@ export class ChatFindModel extends Disposable { return this.activeMatch; } + /** When a page adds matches, enter it at the end appropriate to the navigation direction. */ + selectOlderThan(boundary: IChatFindMatch, wrapToOldest: boolean): boolean { + const index = this._matches.findIndex(match => isSameOccurrence(match, boundary)); + if (index < 0 || index + 1 >= this._matches.length) { + return false; + } + this._activeIndex = wrapToOldest ? this._matches.length - 1 : index + 1; + this._updateAnchor(); + this._onDidChangeMatches.fire(); + return true; + } + clear(): void { + this._completedRows = new WeakMap(); this._query = ''; this._matches = []; this._activeIndex = -1; diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts index d18be03359329b..d19117b602da3f 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatFind/chatFindWidget.ts @@ -5,12 +5,14 @@ import './chatFindWidget.css'; import * as dom from '../../../../../../base/browser/dom.js'; -import { DeferredPromise, Delayer } from '../../../../../../base/common/async.js'; +import { DeferredPromise, Delayer, raceCancellation } from '../../../../../../base/common/async.js'; +import { cancelOnDispose } from '../../../../../../base/common/cancellation.js'; import { createRegExp } from '../../../../../../base/common/strings.js'; import { isDefined } from '../../../../../../base/common/types.js'; import { Event } from '../../../../../../base/common/event.js'; import { URI } from '../../../../../../base/common/uri.js'; -import { MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { DisposableStore, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { IObservable, runOnChange } from '../../../../../../base/common/observable.js'; import { Range as EditorRange } from '../../../../../../editor/common/core/range.js'; import { EditorOption } from '../../../../../../editor/common/config/editorOptions.js'; import { IEditorDecorationsCollection } from '../../../../../../editor/common/editorCommon.js'; @@ -20,8 +22,10 @@ import { IContextKey, IContextKeyService } from '../../../../../../platform/cont import { IContextViewService } from '../../../../../../platform/contextview/browser/contextView.js'; import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; -import { SimpleFindWidget } from '../../../../codeEditor/browser/find/simpleFindWidget.js'; +import { localize } from '../../../../../../nls.js'; +import { ISimpleFindResultCount, SimpleFindWidget } from '../../../../codeEditor/browser/find/simpleFindWidget.js'; import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; +import { IChatModel } from '../../../common/model/chatModel.js'; import { ChatTreeItem, IChatCodeBlockInfo, IChatFindController } from '../../chat.js'; import { IChatListItemTemplate } from '../chatListRenderer.js'; import { CodeBlockPart } from '../chatContentParts/codeBlockPart.js'; @@ -31,8 +35,11 @@ import { ChatFindModel, IChatFindMatch, MAX_FIND_MATCHES } from './chatFindModel export interface IChatFindHost { readonly transcriptDomNode: HTMLElement; + readonly activeModel?: IObservable; + readonly transcriptVisible?: IObservable; getItems(): readonly ChatTreeItem[]; readonly onDidChangeContent: Event; + hasElement?(item: ChatTreeItem): boolean; reveal(item: ChatTreeItem, relativeTop?: number): void; getTemplateDataForRequestId(requestId: string | undefined): IChatListItemTemplate | undefined; readonly onDidRerenderRow: Event; @@ -258,6 +265,10 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl private readonly _recomputeDelayer = this._register(new Delayer(200)); private readonly _searchDelayer = this._register(new Delayer(SEARCH_DEBOUNCE_DELAY)); private readonly _codeDecorations = new Map(); + private readonly _historyInterest = this._register(new MutableDisposable()); + private readonly _historyListeners = this._register(new DisposableStore()); + private _historyReadFailed = false; + private _pendingTreeReveal: IChatFindMatch | undefined; private _lastFocusedElement: HTMLElement | undefined; private _lastNavigationWasPrevious = false; @@ -309,16 +320,34 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl this._model = this._register(new ChatFindModel(() => this.host.getItems(), () => this.host.getViewportAnchorItemId())); this._register(this._model.onDidChangeMatches(() => this._onMatchesChanged())); + if (host.activeModel) { + this._register(runOnChange(host.activeModel, () => { + if (this.visible) { + this._close(false); + } + this._model.clear(); + })); + } + if (host.transcriptVisible) { + this._register(runOnChange(host.transcriptVisible, visible => { + if (!visible) { + this._cancelSearchInterest(); + this._searchDelayer.cancel(); + this._pendingSearch = undefined; + } else if (this._isModelStale()) { + this._scheduleSearch(); + } else { + this._scheduleRecompute(); + } + })); + } this._register(this.host.onDidChangeContent(() => { - if (this.isVisible()) { - this._recomputeDelayer.trigger(() => { - this._model.recompute(); - // The row usually rerenders before this debounced pass, against the old matches. - this._scheduleRepaint(); - }).catch(() => { }); - } + this._scheduleRecompute(); })); - this._register(this.host.onDidRerenderRow(() => { + this._register(this.host.onDidRerenderRow(template => { + if (template.currentElement && this._model.invalidateRenderedRow(template.currentElement)) { + this._scheduleRecompute(); + } if (this.isVisible()) { this._scheduleRepaint(); } @@ -332,8 +361,26 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl } override show(seedText?: string, focus: boolean = true): void { + if (this.host.transcriptVisible?.get() === false || (this.host.activeModel && !this.host.activeModel.get())) { + return; + } if (shouldCaptureFocusBeforeShow(this.isVisible())) { this._lastFocusedElement = this._targetWindow.document.activeElement as HTMLElement | undefined; + const model = this.host.activeModel?.get(); + if (model?.olderHistoryCursor) { + this._historyListeners.add(runOnChange(model.olderHistoryCursor, () => { + this._historyReadFailed = false; + this._scheduleRecompute(); + })); + } + if (model?.olderHistoryUnavailable) { + this._historyListeners.add(runOnChange(model.olderHistoryUnavailable, unavailable => { + if (unavailable) { + this._historyInterest.clear(); + } + this._scheduleRecompute(); + })); + } } this._findWidgetVisibleKey.set(true); // Opening reads the count before the seed text reaches the model, reporting "No results". @@ -343,32 +390,51 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl } else { super.show(seedText); } - this._model.setQuery(this.inputValue, this._currentFindOptions()); - this._navigateToActive(); + this.findFirst(); } override hide(): void { + this._close(true); + } + + private _close(restoreFocus: boolean): void { super.hide(); this._findWidgetVisibleKey.reset(); - this._recomputeDelayer.cancel(); + this._historyListeners.clear(); + this._cancelSearchInterest(); this._searchDelayer.cancel(); this._pendingSearch = undefined; - this._completeSettle(); - this._revealScheduler.clear(); - this._repaintScheduler.clear(); this._clearHighlights(); - this._restoreFocus(); + if (restoreFocus) { + this._restoreFocus(); + } else { + this._lastFocusedElement = undefined; + } } find(previous: boolean): void { + if (!this.visible || this.host.transcriptVisible?.get() === false) { + return; + } this._lastNavigationWasPrevious = previous; this._unlocatableSkips = 0; if (this._flushPendingSearch()) { // The query was not searched yet, so Enter lands on its first match, not its second. - this._navigateToActive(); - void this.updateResultCount(); return; } + if (this._recomputeDelayer.isTriggered()) { + // A page from another reader can arrive before the debounced content refresh. + this._recomputeDelayer.cancel(); + if (this._refreshLoadedMatches()) { + return; + } + } + const { matches, activeIndex } = this._model; + const atBoundary = !matches.length || (previous ? activeIndex === 0 : activeIndex === matches.length - 1); + if (atBoundary && matches.length < MAX_FIND_MATCHES && this._seekOlder(matches.at(-1), previous)) { + return; + } + this._historyInterest.clear(); this._advanceActiveMatch(previous); } @@ -382,7 +448,7 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl } this._searchDelayer.cancel(); this._pendingSearch = undefined; - this._model.setQuery(this.inputValue, this._currentFindOptions()); + this._search(); return true; } @@ -412,12 +478,14 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl } findFirst(): void { + if (!this.visible) { + return; + } this._unlocatableSkips = 0; // Toggling an option supersedes a keystroke still waiting out the debounce. this._searchDelayer.cancel(); this._pendingSearch = undefined; - this._model.setQuery(this.inputValue, this._currentFindOptions()); - this._navigateToActive(); + this._search(); } next(): void { @@ -474,13 +542,11 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl */ private _scheduleSearch(): void { // An option toggle also reaches here via `findFirst`; a duplicate would swallow Enter. - if (!this._isModelStale()) { + if (!this.visible || this.host.transcriptVisible?.get() === false || (!this._isModelStale() && !this._pendingSearch)) { return; } - const search = this._searchDelayer.trigger(() => { - this._model.setQuery(this.inputValue, this._currentFindOptions()); - this._navigateToActive(); - }); + this._cancelSearchInterest(); + const search = this._searchDelayer.trigger(() => this._search()); this._pendingSearch = search; search.catch(() => { }).finally(() => { if (this._pendingSearch === search) { @@ -489,6 +555,117 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl }); } + private _cancelSearchInterest(): void { + this._pendingTreeReveal = undefined; + this._historyInterest.clear(); + this._historyReadFailed = false; + this._recomputeDelayer.cancel(); + this._revealScheduler.clear(); + this._repaintScheduler.clear(); + this._completeSettle(); + } + + private _search(): void { + this._cancelSearchInterest(); + this._model.setQuery(this.inputValue, this._currentFindOptions()); + this._navigateToActive(); + if (!this._model.activeMatch) { + this._seekOlder(); + } + } + + private _scheduleRecompute(): void { + if (!this.visible || this.host.transcriptVisible?.get() === false || this._isModelStale()) { + return; + } + this._recomputeDelayer.trigger(() => { + if (!this._refreshLoadedMatches()) { + this._scheduleRepaint(); + } + if (!this._model.activeMatch && !this._historyReadFailed) { + this._seekOlder(); + } + }).catch(() => { }); + } + + /** Returns whether newly available text already satisfied the search for its first hit. */ + private _refreshLoadedMatches(): boolean { + const hadMatch = !!this._model.activeMatch; + this._model.recompute(); + if (!hadMatch && this._model.activeMatch) { + this._historyInterest.clear(); + this._navigateToActive(); + void this.updateResultCount(); + return true; + } + if (this._pendingTreeReveal && this._model.isActiveOccurrence(this._pendingTreeReveal)) { + this._navigateToActive(); + } else { + this._pendingTreeReveal = undefined; + } + return false; + } + + /** A pending provider read is shared with the transcript; only this widget's interest is cancelled. */ + private _seekOlder(boundary?: IChatFindMatch, previous = false): boolean { + if (this._historyInterest.value) { + return true; + } + const model = this.host.activeModel?.get(); + const cursor = model?.olderHistoryCursor?.get(); + if (!this.visible || this.host.transcriptVisible?.get() === false || !this._model.query || this._model.isInvalidRegex || !model?.loadOlderHistory || cursor === undefined || model.olderHistoryUnavailable?.get()) { + return false; + } + this._recomputeDelayer.cancel(); + this._revealScheduler.clear(); + this._completeSettle(); + void this._readUntilMatch(model, cursor, boundary, previous); + return true; + } + + private async _readUntilMatch(model: IChatModel, cursor: string, boundary: IChatFindMatch | undefined, previous: boolean): Promise { + const token = cancelOnDispose(this._historyInterest.value = new DisposableStore()); + this._historyReadFailed = false; + void this.updateResultCount(); + const visited = new Set(); + try { + while (!token.isCancellationRequested && model.loadOlderHistory) { + visited.add(cursor); + try { + await raceCancellation(model.loadOlderHistory(), token); + } catch { + if (token.isCancellationRequested) { + return; + } + this._historyReadFailed = true; + } + if (token.isCancellationRequested || this._isModelStale()) { + return; + } + this._recomputeDelayer.cancel(); + this._model.recompute(); + const next = model.olderHistoryCursor?.get(); + this._historyReadFailed ||= !model.olderHistoryCursor || !model.loadOlderHistory || (next !== undefined && visited.has(next)); + if (boundary ? this._model.selectOlderThan(boundary, previous) : this._model.activeMatch) { + this._navigateToActive(); + return; + } + if (this._historyReadFailed || next === undefined || this._model.matches.length >= MAX_FIND_MATCHES) { + if (boundary) { + this._advanceActiveMatch(previous); + } + return; + } + cursor = next; + } + } finally { + if (!token.isCancellationRequested) { + this._historyInterest.clear(); + void this.updateResultCount(); + } + } + } + /** Marks the start of locating an active match, if one is not already in progress. */ private _beginSettle(): void { this._settleBarrier ??= new DeferredPromise(); @@ -519,12 +696,30 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl } } - protected async _getResultCount(): Promise<{ resultIndex: number; resultCount: number } | undefined> { + protected async _getResultCount(): Promise { await this._whenSettled(); if (this._model.isInvalidRegex) { return undefined; } - return { resultIndex: this._model.activeIndex, resultCount: this._model.matches.length }; + const model = this.host.activeModel?.get(); + const cursor = model?.olderHistoryCursor; + const hasOlder = cursor?.get() !== undefined; + const unavailable = model?.olderHistoryUnavailable?.get(); + const searching = !!this._historyInterest.value; + const incomplete = !!this._model.query && (searching || this._historyReadFailed || !!unavailable || hasOlder || (!!model?.loadOlderHistory && !cursor)); + const resultCount = this._model.matches.length; + let status: string | undefined; + if (searching) { + status = localize('chat.find.searchingHistory', "Searching…"); + } else if (this._historyReadFailed && resultCount) { + status = localize('chat.find.partialAfterFailure', "{0} of {1}+ (search incomplete)", this._model.activeIndex + 1, resultCount); + } else if (!resultCount && incomplete) { + status = localize('chat.find.searchIncomplete', "Search incomplete"); + } + return { + resultIndex: this._model.activeIndex, resultCount, incomplete, status, + canRetry: !searching && !unavailable && hasOlder && !!model?.loadOlderHistory, + }; } protected _onFocusTrackerFocus(): void { @@ -548,10 +743,14 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl } private _onMatchesChanged(): void { - void this.updateResultCount(); + if (!this._historyInterest.value) { + void this.updateResultCount(); + } } private _navigateToActive(): void { + this._pendingTreeReveal = undefined; + this._revealScheduler.clear(); const match = this._model.activeMatch; this._clearHighlights(); this._beginSettle(); @@ -561,23 +760,37 @@ export class ChatFindWidget extends SimpleFindWidget implements IChatFindControl return; } - const item = this._findItemForMatch(match); - if (item) { - this.host.reveal(item); + const item = this._getRevealableItem(match); + if (!item) { + return; } - + this.host.reveal(item); this._revealScheduler.value = dom.scheduleAtNextAnimationFrame(this._targetWindow, () => this._revealActiveMatch(match)); } + private _getRevealableItem(match: IChatFindMatch): ChatTreeItem | undefined { + if (this._model.isActiveOccurrence(match)) { + const item = this._findItemForMatch(match); + if (item && this.host.hasElement?.(item) !== false) { + return item; + } + // The view model can contain a prepended page before the list refreshes. + this._pendingTreeReveal = item ? match : undefined; + } + this._completeSettle(); + return undefined; + } + private _revealActiveMatch(match: IChatFindMatch, attempt: number = 0): void { + const item = this._getRevealableItem(match); + if (!item) { + return; + } const locatedMatch = this._locateMatch(match); if (!locatedMatch) { // A long jump outruns the list, which mounts and re-measures rows over later frames. if (attempt < ChatFindWidget.MAX_LOCATE_ATTEMPTS) { - const item = this._findItemForMatch(match); - if (item) { - this.host.reveal(item); - } + this.host.reveal(item); this._revealScheduler.value = dom.scheduleAtNextAnimationFrame(this._targetWindow, () => this._revealActiveMatch(match, attempt + 1)); return; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts index e39f5adbde8b1b..ec63c65c03f184 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts @@ -1299,8 +1299,11 @@ export class ChatWidget extends Disposable implements IChatWidget { if (this.viewOptions.enableFind) { const host: IChatFindHost = { transcriptDomNode: this.listWidget.domNode, + activeModel: this._viewModelObs.map(viewModel => viewModel?.model), + transcriptVisible: this._visible, getItems: () => this.viewModel?.getItems() ?? [], onDidChangeContent: this._onDidChangeFindableContent.event, + hasElement: item => this.listWidget.hasElement(item), reveal: (item, relativeTop) => this.reveal(item, relativeTop), getTemplateDataForRequestId: (requestId) => this.getTemplateDataForRequestId(requestId), onDidRerenderRow: this.onDidRerenderRow, @@ -1592,6 +1595,7 @@ export class ChatWidget extends Disposable implements IChatWidget { // Update list widget state and refresh this.listWidget.setVisibleChangeCount(this.visibleChangeCount); this.listWidget.refresh(changes); + this._onDidChangeFindableContent.fire(); if (this._pendingFirstRenderSessionResource && this.viewModel && isEqual(this.viewModel.sessionResource, this._pendingFirstRenderSessionResource)) { this._pendingFirstRenderSessionResource = undefined; @@ -3413,7 +3417,6 @@ export class ChatWidget extends Disposable implements IChatWidget { if (events?.some(e => e?.kind === 'addRequest') && this.visible && !this.listWidget.isAutoScrollHeld) { this.listWidget.scrollToEnd(); } - this._onDidChangeFindableContent.fire(); }))); this.viewModelDisposables.add(this.viewModel.onDidDisposeModel(() => { // Ensure that view state is saved here, because we will load it again when a new model is assigned diff --git a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts index 9f7be5ff14da5d..e211203aab7e7e 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts @@ -81,7 +81,7 @@ suite('PromptTimelineGutterRail', () => { { affordance: true, rows: 0, idleLoads: 0, loads: 1 }); }); - test('a failed wheel request can be retried without leaving the gutter', async () => { + test('a failed wheel request waits for a new gesture to retry, without leaving the gutter', async () => { const rail = createRail([tick(90), tick(91)]); const panel = rail.domNode.querySelector('.prompt-timeline-gutter-panel')!; let attempts = 0; @@ -92,14 +92,20 @@ suite('PromptTimelineGutterRail', () => { rail.setTicks([tick(89), tick(90), tick(91)]); }); panel.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); - const wheel = () => panel.dispatchEvent(new WheelEvent('wheel', { deltaY: -1, bubbles: true })); - wheel(); + const wheel = (timeStamp: number) => { + const event = new WheelEvent('wheel', { deltaY: -1, bubbles: true }); + Object.defineProperty(event, 'timeStamp', { value: timeStamp }); + panel.dispatchEvent(event); + }; + wheel(1000); await Promise.resolve(); const notified = !!panel.querySelector('[role=status]'); - wheel(); + wheel(1010); + const afterMomentum = attempts; + wheel(2000); await Promise.resolve(); - assert.deepStrictEqual({ notified, error: !!panel.querySelector('[role=status]'), attempts, rows: rowParts(rail).map(r => r.jump.textContent) }, - { notified: true, error: false, attempts: 2, rows: ['89', '90', '91'] }); + assert.deepStrictEqual({ notified, afterMomentum, error: !!panel.querySelector('[role=status]'), attempts, rows: rowParts(rail).map(r => r.jump.textContent) }, + { notified: true, afterMomentum: 1, error: false, attempts: 2, rows: ['89', '90', '91'] }); }); test('highlights a row previewed from a dot, but leaves a row under the pointer to its own halves', () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatFindModel.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatFindModel.test.ts index 4f235b55f32cf0..f5ba33a442af24 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatFindModel.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatFindModel.test.ts @@ -6,9 +6,11 @@ import assert from 'assert'; import { MarkdownString } from '../../../../../../base/common/htmlContent.js'; import { URI } from '../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { ChatFindModel } from '../../../browser/widget/chatFind/chatFindModel.js'; import { ChatTreeItem } from '../../../browser/chat.js'; +import { IChatRequestViewModel } from '../../../common/model/chatViewModel.js'; /** Builds a minimal fake request item satisfying `isRequestVM` (`'message' in item`). */ function fakeRequest(id: string, messageText: string): ChatTreeItem { @@ -47,7 +49,60 @@ function toolInvocation(invocationMessage: string, pastTenseMessage?: string, is } suite('ChatFindModel', () => { - ensureNoDisposablesAreLeakedInTestSuite(); + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('a strict prepend reads each completed row only once for the same query and options', () => { + const reads: string[] = []; + function row(id: string) { + return upcastPartial({ + id, dataId: id, isComplete: true, message: { text: '', parts: [] }, + get messageText() { reads.push(id); return 'needle'; }, + }); + } + const items = [row('3')]; + const model = store.add(new ChatFindModel(() => items)); + const options = { isRegex: false, matchCase: false, wholeWord: false }; + model.setQuery('needle', options); + items.unshift(row('2')); + model.recompute(); + items.unshift(row('1')); + model.recompute(); + assert.deepStrictEqual({ reads, matches: model.matches.map(m => m.itemId) }, { reads: ['3', '2', '1'], matches: ['3', '2', '1'] }); + }); + + test('rescans live, versioned, replaced and renderer-invalidated rows and changed options', () => { + let version = 0; + let complete = false; + let text = 'Needle'; + const row = () => upcastPartial({ + id: 'row', message: { text: '', parts: [] }, + get dataId() { return String(version); }, + get isComplete() { return complete; }, + get messageText() { return text; }, + }); + let item = row(); + const model = store.add(new ChatFindModel(() => [item])); + const options = { isRegex: false, matchCase: true, wholeWord: false }; + model.setQuery('needle', options); + const counts = [model.matches.length]; + const refresh = () => { model.recompute(); counts.push(model.matches.length); }; + text = 'needle'; + refresh(); + complete = true; + refresh(); + text = 'Needle'; + version++; + refresh(); + text = 'needle needle'; + item = row(); + refresh(); + text = 'Needle Needle'; + model.invalidateRenderedRow(item); + refresh(); + model.setQuery('needle', { ...options, matchCase: false }); + counts.push(model.matches.length); + assert.deepStrictEqual(counts, [0, 1, 1, 0, 2, 0, 2]); + }); test('finds matches across a user request and response markdown', () => { const items = [ diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts index e85ae69a805ff8..653d58aabe06e7 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatFindWidget.test.ts @@ -4,20 +4,25 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; -import { Event as BaseEvent } from '../../../../../../base/common/event.js'; -import { DisposableStore } from '../../../../../../base/common/lifecycle.js'; +import { DeferredPromise, retry, timeout } from '../../../../../../base/common/async.js'; +import { Emitter, Event as BaseEvent } from '../../../../../../base/common/event.js'; +import { DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { observableValue } from '../../../../../../base/common/observable.js'; import { createRegExp } from '../../../../../../base/common/strings.js'; +import { upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; import { ChatTreeItem } from '../../../browser/chat.js'; +import { IChatListItemTemplate } from '../../../browser/widget/chatListRenderer.js'; import { ChatFindModel } from '../../../browser/widget/chatFind/chatFindModel.js'; import { ChatFindWidget, computeRevealScrollTop, findMatchRangesInDom, IChatFindHost, openAncestorDisclosures, rangesEqual, shouldCaptureFocusBeforeShow } from '../../../browser/widget/chatFind/chatFindWidget.js'; +import { IChatModel } from '../../../common/model/chatModel.js'; +import { IChatRequestViewModel } from '../../../common/model/chatViewModel.js'; suite('ChatFindWidget', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - function createWidget(items: readonly ChatTreeItem[] = []) { + function createWidget(items: readonly ChatTreeItem[] = [], overrides?: Partial) { const disposables = store.add(new DisposableStore()); const instantiationService = workbenchInstantiationService(undefined, disposables); const container = document.createElement('div'); @@ -35,14 +40,16 @@ suite('ChatFindWidget', () => { setScrollTop: () => { }, getRenderHeight: () => 0, getViewportAnchorItemId: () => undefined, + ...overrides, }; const widget = disposables.add(instantiationService.createInstance(ChatFindWidget, host)); const model = Reflect.get(widget, '_model') as ChatFindModel; - return { disposables, model, widget }; + return { disposables, model, widget, container }; } test('does not search intermediate IME composition text', async () => { const { model, widget } = createWidget(); + widget.show(undefined, false); const input = widget.getDomNode().querySelector('input'); assert.ok(input); @@ -110,6 +117,302 @@ suite('ChatFindWidget', () => { next.disposables.dispose(); previous.disposables.dispose(); }); + + suite('older history', () => { + function createPagedWidget(recent = '') { + const items: ChatTreeItem[] = []; + const templates = new Map(); + function prepend(id: string, text: string) { + const value = document.createElement('div'); + value.textContent = text; + templates.set(id, upcastPartial({ value })); + items.unshift(upcastPartial({ id, message: { text, parts: [] }, messageText: text })); + } + prepend('recent', recent); + const cursor = observableValue('cursor', 'p1'); + const unavailable = observableValue('unavailable', false); + const transcriptVisible = observableValue('transcriptVisible', true); + const notInTree = new Set(); + const content = store.add(new Emitter()); + const reads: string[] = []; + const reveals: string[] = []; + let pending: DeferredPromise | undefined; + function loadOlderHistory() { + if (!pending) { + reads.push(cursor.get()!); + pending = new DeferredPromise(); + } + return pending.p; + } + const activeModel = observableValue('active model', upcastPartial({ olderHistoryCursor: cursor, olderHistoryUnavailable: unavailable, loadOlderHistory })); + const fixture = createWidget(items, { + activeModel, + transcriptVisible, + getTemplateDataForRequestId: id => id ? templates.get(id) : undefined, + onDidChangeContent: content.event, + hasElement: item => !notInTree.has(item.id), + reveal: item => { + assert.ok(!notInTree.has(item.id), 'cannot reveal an element before the list refresh'); + reveals.push(item.id); + }, + }); + const count = fixture.widget.getDomNode().querySelector('.matchesCount')!; + async function finish(next: string | undefined, text?: string, error?: Error) { + assert.ok(pending); + if (text) { + prepend(cursor.get()!, text); + } + cursor.set(next, undefined); + content.fire(); + const page = pending; + pending = undefined; + if (error) { + await page.error(error); + } else { + await page.complete(); + } + await timeout(0); + } + const label = (expected: string) => retry(async () => assert.strictEqual(count.textContent, expected), 10, 100); + return { ...fixture, activeModel, transcriptVisible, cursor, unavailable, notInTree, content, reads, reveals, prepend, loadOlderHistory, finish, label }; + } + + test('searches pages in order with the current options and stops at the first matching page', async () => { + const { widget, reads, reveals, finish, label } = createPagedWidget('Marker12'); + widget.show(undefined, false); + widget.toggleRegex(); + widget.toggleWholeWord(); + widget.toggleCaseSensitive(); + widget.show('marker\\d+'); + await label('Searching…'); + await finish('p2', 'prefixmarker12'); + await finish('p3', 'found marker42 here'); + await label('1 of 1+'); + assert.deepStrictEqual({ reads, reveals }, { reads: ['p1', 'p2'], reveals: ['p2'] }); + }); + + test('navigates past the known boundary to the nearest unseen occurrence before wrapping', async () => { + const { widget, model, container, reads, reveals, finish, label } = createPagedWidget('needle needle'); + document.body.appendChild(container); + store.add(toDisposable(() => container.remove())); + widget.show('needle'); + await label('1 of 2+'); + widget.find(false); + await label('2 of 2+'); + assert.deepStrictEqual(reads, []); + widget.find(false); + widget.find(false); + await label('Searching…'); + await finish('p2', 'no match'); + assert.deepStrictEqual([model.activeMatch?.itemId, model.activeMatch?.occurrenceIndex], ['recent', 0]); + await finish('p3', 'needle needle'); + await label('3 of 4+'); + assert.deepStrictEqual([model.activeMatch?.itemId, model.activeMatch?.occurrenceIndex], ['p2', 1]); + widget.find(false); + await label('4 of 4+'); + widget.find(false); + await finish(undefined); + await label('1 of 4'); + assert.deepStrictEqual({ reads, reveals, focused: document.activeElement === widget.getDomNode().querySelector('input') }, { + reads: ['p1', 'p2', 'p3'], reveals: ['recent', 'recent', 'p2', 'p2', 'recent'], focused: true, + }); + }); + + test('a new query can reuse a shared pending page without continuing the released search', async () => { + const { widget, loadOlderHistory, reads, reveals, finish, label } = createPagedWidget(); + const externalRead = loadOlderHistory(); + widget.show('not here'); + await label('Searching…'); + const input = widget.getDomNode().querySelector('input')!; + input.value = 'needle'; + input.dispatchEvent(new Event('input')); + widget.find(false); + await finish('p2', 'needle'); + await externalRead; + await label('1 of 1+'); + assert.deepStrictEqual({ reads, reveals }, { reads: ['p1'], reveals: ['p1'] }); + }); + + test('a newly loaded hit releases a still-pending read without losing the selected occurrence', async () => { + const { widget, content, prepend, reads, reveals, finish, label, model } = createPagedWidget(); + widget.show('needle'); + await label('Searching…'); + prepend('streamed', 'needle needle'); + content.fire(); + await label('1 of 2+'); + await finish('p2', 'needle'); + await label('1 of 3+'); + assert.deepStrictEqual({ reads, reveals, occurrence: model.activeMatch?.occurrenceIndex }, { reads: ['p1'], reveals: ['streamed'], occurrence: 1 }); + }); + + test('changing options releases a pending read when a loaded occurrence now matches', async () => { + const { widget, reads, reveals, finish, label } = createPagedWidget('NEEDLE'); + widget.show(undefined, false); + widget.toggleCaseSensitive(); + widget.show('needle'); + await label('Searching…'); + widget.toggleCaseSensitive(); + await label('1 of 1+'); + await finish('p2', 'needle'); + await label('1 of 2+'); + assert.deepStrictEqual({ reads, reveals }, { reads: ['p1'], reveals: ['recent'] }); + }); + + test('empty and invalid queries do not read and hiding Find releases an outstanding read', async () => { + const { widget, content, reads, reveals, finish, label } = createPagedWidget(); + content.fire(); + widget.show(undefined, false); + widget.toggleRegex(); + widget.show('['); + widget.find(false); + assert.deepStrictEqual(reads, []); + widget.show('needle'); + await label('Searching…'); + widget.hide(); + await finish('p2', 'needle'); + content.fire(); + widget.find(false); + await timeout(220); + assert.deepStrictEqual({ reads, reveals, visible: widget.visible }, { reads: ['p1'], reveals: [], visible: false }); + }); + + for (const end of ['switch', 'dispose'] as const) { + test(`a pending page cannot navigate or start another read after ${end}`, async () => { + const { widget, activeModel, reads, reveals, finish, label } = createPagedWidget(); + widget.show('needle'); + await label('Searching…'); + if (end === 'switch') { + activeModel.set(upcastPartial({}), undefined); + } else { + widget.dispose(); + } + await finish('p2', 'needle'); + assert.deepStrictEqual({ reads, reveals, visible: widget.visible }, { reads: ['p1'], reveals: [], visible: false }); + }); + } + + test('unchanged cursors and failed reads stay incomplete until deliberate navigation retries', async () => { + const { widget, reads, finish, label } = createPagedWidget(); + widget.show('needle'); + await finish('p1'); + await label('Search incomplete'); + const next = widget.getDomNode().querySelector('.codicon-find-next-match')!; + assert.strictEqual(next.classList.contains('disabled'), false); + next.click(); + await finish('p1', undefined, new Error('offline')); + await label('Search incomplete'); + widget.find(true); + await finish(undefined); + await label('No results'); + assert.deepStrictEqual(reads, ['p1', 'p1', 'p1']); + }); + + test('history without a usable cursor or loader is not counted as a complete search', async () => { + const { widget, activeModel, loadOlderHistory, cursor, reads, label } = createPagedWidget(); + for (const model of [{ loadOlderHistory }, { olderHistoryCursor: cursor }]) { + activeModel.set(upcastPartial(model), undefined); + widget.show('needle'); + widget.find(false); + await label('Search incomplete'); + } + assert.deepStrictEqual(reads, []); + }); + + test('counts a page before the tree refresh and reveals only the still-active occurrence afterward', async () => { + const { widget, notInTree, content, reveals, finish, label } = createPagedWidget(); + notInTree.add('p1'); + widget.show('needle'); + await finish('p2', 'needle'); + await label('1 of 1+'); + assert.deepStrictEqual(reveals, []); + notInTree.clear(); + content.fire(); + await retry(async () => assert.deepStrictEqual(reveals, ['p1']), 10, 100); + notInTree.add('p2'); + widget.find(false); + await finish(undefined, 'needle'); + await label('2 of 2'); + widget.show('different'); + notInTree.clear(); + content.fire(); + await label('No results'); + await timeout(220); + assert.deepStrictEqual(reveals, ['p1']); + }); + + test('Previous visits every occurrence on a newly loaded page before it requests another', async () => { + for (const next of [undefined, 'p2']) { + const { widget, model, reads, finish, label } = createPagedWidget('needle needle'); + widget.show('needle'); + await label('1 of 2+'); + widget.find(true); + await finish(next, 'needle needle'); + await label(next ? '4 of 4+' : '4 of 4'); + const oldest = model.activeMatch?.occurrenceIndex; + widget.find(true); + await label(next ? '3 of 4+' : '3 of 4'); + assert.deepStrictEqual([oldest, model.activeMatch?.itemId, model.activeMatch?.occurrenceIndex, reads], [0, 'p1', 1, ['p1']]); + } + }); + + test('a failed boundary read still wraps through loaded hits and can be retried', async () => { + const { widget, reads, finish, label } = createPagedWidget('needle needle'); + widget.show('needle'); + await label('1 of 2+'); + widget.find(true); + await finish('p1', undefined, new Error('offline')); + await label('2 of 2+ (search incomplete)'); + widget.find(false); + await finish(undefined); + await label('1 of 2'); + assert.deepStrictEqual(reads, ['p1', 'p1']); + }); + + test('hiding the transcript pauses paging but retains the search in the same chat', async () => { + const { widget, transcriptVisible, reads, reveals, finish, label } = createPagedWidget(); + widget.show('needle'); + await label('Searching…'); + transcriptVisible.set(false, undefined); + await finish('p2'); + widget.find(false); + assert.deepStrictEqual({ visible: widget.visible, reads, reveals }, { visible: true, reads: ['p1'], reveals: [] }); + transcriptVisible.set(true, undefined); + await label('Searching…'); + await retry(async () => assert.strictEqual(reads.length, 2), 10, 100); + await finish(undefined, 'needle'); + await label('1 of 1'); + }); + + test('another reader advancing or exhausting the failed cursor clears the failure', async () => { + const { widget, reads, cursor, finish, label } = createPagedWidget(); + widget.show('absent'); + await finish('p1', undefined, new Error('offline')); + await label('Search incomplete'); + cursor.set('p2', undefined); + await label('Searching…'); + await finish('p2'); + await label('Search incomplete'); + cursor.set(undefined, undefined); + await label('No results'); + assert.deepStrictEqual(reads, ['p1', 'p2']); + }); + + test('suspending history releases the read and keeps counts partial without requesting another page', async () => { + const { widget, cursor, unavailable, reads, finish, label } = createPagedWidget(); + widget.show('needle'); + await label('Searching…'); + unavailable.set(true, undefined); + await finish('p2'); + await label('Search incomplete'); + widget.find(false); + cursor.set(undefined, undefined); + widget.find(true); + await label('Search incomplete'); + unavailable.set(false, undefined); + await label('No results'); + assert.deepStrictEqual(reads, ['p1']); + }); + }); }); suite('ChatFindWidget DOM highlighting', () => { diff --git a/src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts b/src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts index e5c48220407969..d03faa4df9b0f5 100644 --- a/src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts +++ b/src/vs/workbench/contrib/codeEditor/browser/find/simpleFindWidget.ts @@ -8,7 +8,7 @@ import * as nls from '../../../../../nls.js'; import * as dom from '../../../../../base/browser/dom.js'; import { FindInput } from '../../../../../base/browser/ui/findinput/findInput.js'; import { Widget } from '../../../../../base/browser/ui/widget.js'; -import { Delayer, disposableTimeout } from '../../../../../base/common/async.js'; +import { Delayer, disposableTimeout, TimeoutTimer } from '../../../../../base/common/async.js'; import { KeyCode } from '../../../../../base/common/keyCodes.js'; import { IDisposable } from '../../../../../base/common/lifecycle.js'; import { FindReplaceState, INewFindReplaceState } from '../../../../../editor/contrib/find/browser/findState.js'; @@ -56,6 +56,14 @@ interface IFindOptions { const SIMPLE_FIND_WIDGET_INITIAL_WIDTH = 310; const MATCHES_COUNT_WIDTH = 73; +export interface ISimpleFindResultCount { + readonly resultIndex: number; + readonly resultCount: number; + readonly incomplete?: boolean; + readonly status?: string; + readonly canRetry?: boolean; +} + export abstract class SimpleFindWidget extends Widget implements IVerticalSashLayoutProvider { private readonly _findInput: FindInput; private readonly _domNode: HTMLElement; @@ -67,6 +75,8 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa private readonly nextBtn: SimpleButton; private readonly _matchesLimit: number; private _matchesCount: HTMLElement | undefined; + private _countRequest = 0; + private readonly _visibilityTimer = this._register(new TimeoutTimer()); private _isVisible: boolean = false; private _foundMatch: boolean = false; @@ -126,14 +136,18 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa this._register(this._findInput.onInput(async (e) => { if (!options.checkImeCompletionState || !this._findInput.isImeSessionInProgress) { this._foundMatch = this._onInputChanged(); - if (options.showResultCount) { - await this.updateResultCount(); + if (!this._isVisible) { + return; } - this.updateButtons(this._foundMatch); if (!options.checkImeCompletionState || !e.fromCompositionEnd) { this.focusFindBox(); } this._delayedUpdateHistory(); + if (options.showResultCount) { + await this.updateResultCount(); + } else { + this.updateButtons(this._foundMatch); + } } })); @@ -227,9 +241,12 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa })); this._register(this._findInput.onDidOptionChange(async () => { this._foundMatch = this._onInputChanged(); - await this.updateResultCount(); + if (!this._isVisible) { + return; + } this.focusFindBox(); this._delayedUpdateHistory(); + await this.updateResultCount(); })); } @@ -279,7 +296,7 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa protected abstract _onFocusTrackerBlur(): void; protected abstract _onFindInputFocusTrackerFocus(): void; protected abstract _onFindInputFocusTrackerBlur(): void; - protected abstract _getResultCount(): Promise<{ resultIndex: number; resultCount: number } | undefined>; + protected abstract _getResultCount(): Promise; protected get inputValue() { return this._findInput.getValue(); @@ -294,6 +311,7 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa } override dispose() { + this._isVisible = false; super.dispose(); this._domNode?.remove(); @@ -326,14 +344,14 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa this.updateResultCount(); this.layout(); - setTimeout(() => { + this._visibilityTimer.cancelAndSet(() => { this._innerDomNode.classList.toggle('suppress-transition', !animated); this._innerDomNode.classList.add('visible', 'visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'false'); this._findInput.select(); if (!animated) { - setTimeout(() => { + this._visibilityTimer.cancelAndSet(() => { this._innerDomNode.classList.remove('suppress-transition'); }, 0); } @@ -348,7 +366,8 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa this._isVisible = true; this.layout(); - setTimeout(() => { + this._visibilityTimer.cancelAndSet(() => { + this._innerDomNode.classList.remove('suppress-transition'); this._innerDomNode.classList.add('visible', 'visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'false'); @@ -357,14 +376,15 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa public hide(animated = true): void { if (this._isVisible) { + this._isVisible = false; + this._countRequest++; // Reset the accessibility help hint flag so it can be announced again on next reveal this._accessibilityHelpHintAnnounced = false; this._innerDomNode.classList.toggle('suppress-transition', !animated); this._innerDomNode.classList.remove('visible-transition'); this._innerDomNode.setAttribute('aria-hidden', 'true'); // Need to delay toggling visibility until after Transition, then visibility hidden - removes from tabIndex list - setTimeout(() => { - this._isVisible = false; + this._visibilityTimer.cancelAndSet(() => { this.updateButtons(this._foundMatch); this._innerDomNode.classList.remove('visible', 'suppress-transition'); }, animated ? 200 : 0); @@ -424,19 +444,28 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa } async updateResultCount(): Promise { + if (!this._isVisible) { + return; + } if (!this._matchesCount) { this.updateButtons(this._foundMatch); return; } + const request = ++this._countRequest; const count = await this._getResultCount(); + if (request !== this._countRequest || !this._isVisible) { + return; + } this._matchesCount.textContent = ''; - const showRedOutline = (this.inputValue.length > 0 && count?.resultCount === 0); + const showRedOutline = (this.inputValue.length > 0 && count?.resultCount === 0 && !count.incomplete); this._matchesCount.classList.toggle('no-results', showRedOutline); let label = ''; - if (count?.resultCount) { + if (count?.status) { + label = count.status; + } else if (count?.resultCount) { let matchesCount: string = String(count.resultCount); - if (count.resultCount >= this._matchesLimit) { + if (count.incomplete || count.resultCount >= this._matchesLimit) { matchesCount += '+'; } let matchesPosition: string = String(count.resultIndex + 1); @@ -447,9 +476,12 @@ export abstract class SimpleFindWidget extends Widget implements IVerticalSashLa } else { label = NLS_NO_RESULTS; } - status(this._announceSearchResults(label, this.inputValue)); + const partialCount = count?.incomplete && count.resultCount > 0 + ? nls.localize('ariaPartialSearchCount', "Match {0} of at least {1} for '{2}'", count.resultIndex + 1, count.resultCount, this.inputValue) + : undefined; + status(count?.status ?? partialCount ?? this._announceSearchResults(label, this.inputValue)); this._matchesCount.appendChild(document.createTextNode(label)); - this._foundMatch = !!count && count.resultCount > 0; + this._foundMatch = !!count && (count.resultCount > 0 || !!count.canRetry); this.updateButtons(this._foundMatch); } From a1cae5e52c4635983cf53237be86f0856c02de6a Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 19:40:44 -0800 Subject: [PATCH 5/9] chat: show a chevron when earlier prompts can be loaded Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../promptTimeline/media/promptTimeline.css | 17 +++++++---- .../promptTimelineGutterRail.ts | 26 +++++++++++++--- .../promptTimelineGutterRail.test.ts | 30 ++++++++++++++++++- 3 files changed, 62 insertions(+), 11 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css index 5e131034a6918c..163cc0290da166 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css @@ -715,15 +715,20 @@ } .prompt-timeline-gutter-panel.has-older-prompts { - background-image: linear-gradient(to bottom, var(--vscode-scrollbar-shadow), transparent); - background-repeat: no-repeat; - background-size: 100% var(--vscode-spacing-size80); + padding-top: var(--vscode-spacing-size160); overscroll-behavior-y: contain; } -.monaco-workbench:is(.hc-black, .hc-light) .prompt-timeline-gutter-panel.has-older-prompts { - background-image: none; - border-top-style: dashed; +.prompt-timeline-rail-gutter.revealed .prompt-timeline-gutter-panel.show-older-prompts-chevron::before { + content: var(--vscode-icon-chevron-up-compact-content) / ''; + font-family: var(--vscode-icon-chevron-up-compact-font-family); + font-size: var(--vscode-codiconFontSize-compact); + line-height: 1; + position: absolute; + top: var(--vscode-spacing-size20); + inset-inline: 0; + text-align: center; + pointer-events: none; } .prompt-timeline-gutter-error { diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts index 56758e8fbfd991..43b9ea526ce1ab 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts @@ -169,6 +169,11 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._list = append(this._domNode, $('.prompt-timeline-gutter-panel')); this._list.id = panelId; + this._register(addDisposableListener(this._list, EventType.SCROLL, () => { + if (this._loadOlder) { + this._updateOlderHistoryChevron(); + } + })); let lastWheelTime = -Infinity; let pagedInGesture = false; this._register(addDisposableListener(this._list, 'wheel', e => { @@ -176,7 +181,7 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel pagedInGesture = false; } lastWheelTime = e.timeStamp; - if (!pagedInGesture && this._loadOlder && e.deltaY < 0 && !e.ctrlKey && !e.shiftKey && this._list.scrollTop <= 1) { + if (!pagedInGesture && this._loadOlder && e.deltaY < 0 && !e.ctrlKey && !e.shiftKey && this._atHistoryStart()) { pagedInGesture = true; void this._requestOlder(); } @@ -186,7 +191,7 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel touchY = e.touches.length === 1 ? e.touches[0].clientY : undefined; }, { passive: true })); this._register(addDisposableListener(this._list, 'touchmove', (e: TouchEvent) => { - if (touchY !== undefined && e.touches.length === 1 && e.touches[0].clientY > touchY && this._list.scrollTop <= 1) { + if (touchY !== undefined && e.touches.length === 1 && e.touches[0].clientY > touchY && this._atHistoryStart()) { touchY = undefined; void this._requestOlder(); } @@ -277,9 +282,19 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._historyError = undefined; this._list.classList.toggle('has-older-prompts', !!loadOlder); this._rest.classList.toggle('has-older-prompts', !!loadOlder); + this._rest.ariaDescription = loadOlder ? localize('promptTimeline.gutter.olderPromptsHint', "Press Up Arrow on the first prompt to load earlier prompts.") : null; + this._updateOlderHistoryChevron(); } } + private _atHistoryStart(): boolean { + return this._list.scrollTop <= 1; + } + + private _updateOlderHistoryChevron(): void { + this._list.classList.toggle('show-older-prompts-chevron', !!this._loadOlder && this._atHistoryStart()); + } + private async _requestOlder(): Promise { const load = this._loadOlder; if (!load || this._loadingOlder === load || (!this._open && !this._hovering)) { @@ -449,8 +464,8 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel if (!container) { return; } - const top = container.offsetTop; - const bottom = top + container.offsetHeight; + const top = index === 0 && this._loadOlder ? 0 : container.offsetTop; + const bottom = container.offsetTop + container.offsetHeight; const viewTop = this._list.scrollTop; const viewBottom = viewTop + this._list.clientHeight; if (top < viewTop) { @@ -630,6 +645,9 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel private _focusCell(rowIndex: number, column: RowColumn): void { this._updateTabStops(rowIndex, column); this._cell(this._focusRow, this._focusColumn)?.focus(); + if (this._loadOlder && this._focusRow === 0) { + this._list.scrollTop = 0; + } } /** diff --git a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts index e211203aab7e7e..deffd8f010b2b3 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts @@ -4,10 +4,11 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { getWindow } from '../../../../../../base/browser/dom.js'; +import { $, append, getWindow } from '../../../../../../base/browser/dom.js'; import { DeferredPromise } from '../../../../../../base/common/async.js'; import { toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; +import { getIconsStyleSheet } from '../../../../../../platform/theme/browser/iconsStyleSheet.js'; import { PromptTimelineGutterRail, restDotCount } from '../../../browser/promptTimeline/promptTimelineGutterRail.js'; import { PromptTick } from '../../../browser/promptTimeline/promptTimelineModel.js'; @@ -40,6 +41,33 @@ suite('PromptTimelineGutterRail', () => { target.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true, cancelable: true })); } + test('shows the chevron only at the open, loadable top edge without loading on hover', () => { + const rail = createRail(Array.from({ length: 10 }, (_, i) => tick(151 + i))); + const panel = rail.domNode.querySelector('.prompt-timeline-gutter-panel')!; + const handle = rail.domNode.querySelector('.prompt-timeline-gutter-rest')!; + append(rail.domNode, $('style')).textContent = store.add(getIconsStyleSheet(undefined)).getCSS().toString(); + panel.style.maxHeight = '100px'; + const visible = () => getWindow(panel).getComputedStyle(panel, '::before').content !== 'none'; + const hover = () => panel.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + hover(); + const complete = visible(); + panel.dispatchEvent(new MouseEvent('mouseout', { bubbles: true })); + let loads = 0; + rail.setOlderHistoryLoader(async () => { loads++; }); + const closed = visible(); + hover(); + const atTop = visible(); + panel.scrollTop = panel.scrollHeight; + panel.dispatchEvent(new Event('scroll')); + const scrolled = visible(); + keydown(rowParts(rail).at(-1)!.jump, 'Home', 36); + panel.dispatchEvent(new Event('scroll')); + const afterHome = visible(); + rail.setOlderHistoryLoader(undefined); + assert.deepStrictEqual({ complete, closed, atTop, scrolled, afterHome, exhausted: visible(), hint: handle.ariaDescription, loads }, + { complete: false, closed: false, atTop: true, scrolled: false, afterHome: true, exhausted: false, hint: null, loads: 0 }); + }); + test('loads one older page at the gutter boundary and preserves the focused row and column', async () => { const stat = { added: 1, removed: 0, fileCount: 1 }; const recent = [tick(90, stat), tick(91)]; From f55ac2611c8a02c5d8470c86ff9e6423e9c2880f Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 19:49:40 -0800 Subject: [PATCH 6/9] chat: make the gutter chevron load earlier prompts Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../browser/actions/chatAccessibilityHelp.ts | 2 +- .../promptTimeline/media/promptTimeline.css | 36 +++++++--- .../promptTimelineGutterRail.ts | 68 +++++++++++++++--- .../promptTimelineGutterRail.test.ts | 70 ++++++++++++++++++- 4 files changed, 156 insertions(+), 20 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts index 0fc3f6811368a2..2dbdddc3d90f76 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts @@ -153,7 +153,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.codexContinuation', "A ChatGPT limit suggestion may offer Continue with Copilot. If the eligible Codex session is not active, the guide highlights its row in the Sessions list. Activate Open Session in the guide or open the row using the list's usual keyboard shortcut: by default, Command+Down Arrow on macOS or Enter on Windows and Linux. The next step opens its model picker with a matching Copilot model in the search. Activate Use Copilot in the guide or use Up and Down Arrow and Enter in the picker to select the Copilot model. Use Tab or Shift+Tab to reach the guide's buttons and Enter or Space to activate them. An already-active eligible session goes directly to the picker. End Tour or Escape cancels the remaining guidance; it does not undo a model selection.")); } if (isSessionsWindow) { - content.push(localize('chat.gutterOlderHistory', "In the prompt gutter, use Up Arrow at the first prompt to load the previous page. Focus stays on that prompt; press Up Arrow again to move to its predecessor.")); + content.push(localize('chat.gutterOlderHistory', "At the top of the prompt gutter, activate Load Earlier Prompts to show the previous page. Or press Up Arrow on the first prompt to load earlier prompts without losing your place.")); content.push(localize('chat.missionControl.help', "Connect to Mission Control Environment opens a list of existing user-local hosts. Cached hosts are shown while the list refreshes in the background without clearing your search. Use Up and Down Arrow to choose a host and Enter to connect, or Escape to cancel. The owning application must be running; connecting does not create replacement compute. Passive connections are read-only, and local sessions continue using the local host.")); content.push(localize('chat.sessionPreparation', "While a session is being prepared, a progress message appears in the transcript. Use Tab or Shift+Tab to reach Show Log, when available, and press Enter or Space to open the output log. Use Stop to cancel preparation. The chat input and attachment controls are disabled until preparation finishes.")); } diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css index 163cc0290da166..79e6f77364528f 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css @@ -715,20 +715,34 @@ } .prompt-timeline-gutter-panel.has-older-prompts { - padding-top: var(--vscode-spacing-size160); + padding-top: var(--vscode-spacing-size320); overscroll-behavior-y: contain; } -.prompt-timeline-rail-gutter.revealed .prompt-timeline-gutter-panel.show-older-prompts-chevron::before { - content: var(--vscode-icon-chevron-up-compact-content) / ''; - font-family: var(--vscode-icon-chevron-up-compact-font-family); - font-size: var(--vscode-codiconFontSize-compact); - line-height: 1; +.prompt-timeline-gutter-panel .prompt-timeline-gutter-older { + display: none; position: absolute; - top: var(--vscode-spacing-size20); - inset-inline: 0; - text-align: center; - pointer-events: none; + top: var(--vscode-spacing-size40); + inset-inline: var(--vscode-spacing-size40); + height: var(--vscode-spacing-size240); + align-items: center; + justify-content: center; + color: inherit; + background: var(--vscode-toolbar-hoverBackground); + border-radius: var(--vscode-cornerRadius-small); + cursor: pointer; +} + +.prompt-timeline-rail-gutter.revealed .show-older-prompts-chevron .prompt-timeline-gutter-older { + display: flex; +} + +.prompt-timeline-gutter-older .codicon-chevron-up-compact { + font-size: var(--vscode-codiconFontSize-compact); +} + +.prompt-timeline-gutter-older:not(.disabled):hover { + background: var(--vscode-list-hoverBackground); } .prompt-timeline-gutter-error { @@ -821,12 +835,14 @@ border-radius: 0 var(--vscode-cornerRadius-small) var(--vscode-cornerRadius-small) 0; } +.prompt-timeline-gutter-older:is(:focus-visible, .focus-visible), .prompt-timeline-gutter-row-jump:is(:focus-visible, .focus-visible), .prompt-timeline-gutter-row-diff:is(:focus-visible, .focus-visible) { outline: var(--vscode-strokeThickness, 1px) solid var(--vscode-focusBorder); outline-offset: calc(-1 * var(--vscode-strokeThickness, 1px)); } +.monaco-workbench:is(.hc-black, .hc-light) .prompt-timeline-gutter-older:hover:not(.disabled, :focus-visible, .focus-visible), .monaco-workbench:is(.hc-black, .hc-light) .prompt-timeline-gutter-row-jump:is(:hover, .hovered):not(:focus-visible, .focus-visible), .monaco-workbench:is(.hc-black, .hc-light) .prompt-timeline-gutter-row-diff:is(:hover, .hovered):not(:focus-visible, .focus-visible) { outline: var(--vscode-strokeThickness, 1px) dashed var(--vscode-contrastActiveBorder); diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts index 43b9ea526ce1ab..34641603bd602a 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts @@ -6,6 +6,9 @@ import { $, addDisposableListener, append, clearNode, EventType, getWindow } from '../../../../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../../../../base/browser/keyboardEvent.js'; import { Gesture, EventType as TouchEventType } from '../../../../../base/browser/touch.js'; +import { Button } from '../../../../../base/browser/ui/button/button.js'; +import { renderIcon } from '../../../../../base/browser/ui/iconLabel/iconLabels.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { KeyCode } from '../../../../../base/common/keyCodes.js'; import { Disposable, DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; @@ -133,6 +136,8 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel private _focusColumn: RowColumn = 'jump'; private _loadOlder: (() => Promise) | undefined; private _loadingOlder: (() => Promise) | undefined; + private _olderButton: Button | undefined; + private _loadingFromButton = false; private _historyError: HTMLElement | undefined; private readonly _onDidSelect = this._register(new Emitter()); @@ -170,7 +175,7 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._list = append(this._domNode, $('.prompt-timeline-gutter-panel')); this._list.id = panelId; this._register(addDisposableListener(this._list, EventType.SCROLL, () => { - if (this._loadOlder) { + if (this._loadOlder || this._loadingFromButton) { this._updateOlderHistoryChevron(); } })); @@ -278,29 +283,66 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel setOlderHistoryLoader(loadOlder: (() => Promise) | undefined): void { if (this._loadOlder !== loadOlder) { this._loadOlder = loadOlder; + if (loadOlder && !this._olderButton) { + this._olderButton = this._createOlderButton(); + } + if (loadOlder && this._olderButton && this._loadingOlder !== loadOlder) { + this._loadingFromButton = false; + this._olderButton.enabled = true; + } this._historyError?.remove(); this._historyError = undefined; - this._list.classList.toggle('has-older-prompts', !!loadOlder); this._rest.classList.toggle('has-older-prompts', !!loadOlder); this._rest.ariaDescription = loadOlder ? localize('promptTimeline.gutter.olderPromptsHint', "Press Up Arrow on the first prompt to load earlier prompts.") : null; this._updateOlderHistoryChevron(); } } + private _createOlderButton(): Button { + const label = localize('promptTimeline.gutter.loadEarlier', "Load Earlier Prompts"); + const button = this._register(new Button(this._list, { ariaLabel: label, title: label })); + button.element.classList.add('prompt-timeline-gutter-older'); + const icon = button.element.appendChild(renderIcon(Codicon.chevronUpCompact)); + icon.ariaHidden = 'true'; + this._list.prepend(button.element); + this._register(addDisposableListener(button.element, EventType.FOCUS, () => { + this._open = true; + this._updateRevealed(); + })); + this._register(button.onDidClick(() => { + button.focus(); + void this._requestOlder(true); + })); + this._register(button.onDidEscape(() => this._close())); + return button; + } + private _atHistoryStart(): boolean { return this._list.scrollTop <= 1; } private _updateOlderHistoryChevron(): void { - this._list.classList.toggle('show-older-prompts-chevron', !!this._loadOlder && this._atHistoryStart()); + // The final cursor can disappear before all the prompts from that page have been inserted. + const hasOlder = !!this._loadOlder || (this._loadingFromButton && !!this._olderButton?.hasFocus()); + const show = hasOlder && this._atHistoryStart(); + if (!show && this._olderButton?.hasFocus()) { + const target = hasOlder ? this._cell(this._focusRow, this._focusColumn) : this._rows[0]?.jump; + (target ?? this._rest).focus({ preventScroll: true }); + } + this._list.classList.toggle('has-older-prompts', hasOlder); + this._list.classList.toggle('show-older-prompts-chevron', show); } - private async _requestOlder(): Promise { + private async _requestOlder(fromButton = false): Promise { const load = this._loadOlder; if (!load || this._loadingOlder === load || (!this._open && !this._hovering)) { return; } this._loadingOlder = load; + this._loadingFromButton = fromButton; + if (this._olderButton) { + this._olderButton.enabled = false; + } this._historyError?.remove(); this._historyError = undefined; try { @@ -309,11 +351,16 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel if (load === this._loadOlder && !this._store.isDisposed && (this._open || this._hovering)) { this._historyError = $('span.prompt-timeline-gutter-error', { role: 'status' }); this._list.prepend(this._historyError); - this._historyError.textContent = localize('promptTimeline.gutter.historyError', "Could not load earlier prompts. Navigate up to retry."); + this._historyError.textContent = localize('promptTimeline.gutter.historyError', "Could not load earlier prompts. Try again."); } } finally { if (this._loadingOlder === load) { this._loadingOlder = undefined; + this._loadingFromButton = false; + if (this._olderButton && !this._store.isDisposed) { + this._olderButton.enabled = true; + this._updateOlderHistoryChevron(); + } } } } @@ -485,7 +532,8 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel const start = this._rows.length && ticks.length > this._rows.length ? ticks.findIndex(t => t.requestId === this._rows[0].tick.requestId) : -1; if (start >= 0 && this._rows.every((r, i) => r.tick.requestId === ticks[start + i]?.requestId)) { const first = this._rows[0].container; - const preserveScroll = start > 0 && (this._open || this._hovering); + const showButtonPage = start > 0 && this._loadingFromButton && this._olderButton?.hasFocus() && this._atHistoryStart(); + const preserveScroll = start > 0 && !showButtonPage && (this._open || this._hovering); const relativeTop = preserveScroll ? first.offsetTop - this._list.scrollTop : 0; this._setPreview(-1); const prefix = ticks.slice(0, start).map(t => this._createRow(t)); @@ -500,7 +548,9 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel this._rows.push(row); } this._renderDots(ticks.length); - if (preserveScroll) { + if (showButtonPage) { + this._list.scrollTop = 0; + } else if (preserveScroll) { this._list.scrollTop = first.offsetTop - relativeTop; } } @@ -530,10 +580,12 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel } this._rowDisposables.clear(); + for (const row of this._rows) { + row.container.remove(); + } this._rows.length = 0; this._previewIndex = -1; this._previewBand = -1; - clearNode(this._list); // The resting dots preview how many prompts the flyout holds and where the transcript is. this._renderDots(ticks.length); diff --git a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts index deffd8f010b2b3..d120b4cf7bce01 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts @@ -47,7 +47,11 @@ suite('PromptTimelineGutterRail', () => { const handle = rail.domNode.querySelector('.prompt-timeline-gutter-rest')!; append(rail.domNode, $('style')).textContent = store.add(getIconsStyleSheet(undefined)).getCSS().toString(); panel.style.maxHeight = '100px'; - const visible = () => getWindow(panel).getComputedStyle(panel, '::before').content !== 'none'; + const visible = () => { + const button = panel.querySelector('[role=button]'); + const chevron = button?.querySelector('.codicon'); + return !!chevron && chevron.getClientRects().length > 0 && getWindow(chevron).getComputedStyle(chevron, '::before').content !== 'none'; + }; const hover = () => panel.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); hover(); const complete = visible(); @@ -68,6 +72,51 @@ suite('PromptTimelineGutterRail', () => { { complete: false, closed: false, atTop: true, scrolled: false, afterHome: true, exhausted: false, hint: null, loads: 0 }); }); + test('clicking the full chevron strip shows an earlier page; keyboard activation reaches the start', async () => { + const recent = Array.from({ length: 10 }, (_, i) => tick(21 + i)); + const earlier = Array.from({ length: 10 }, (_, i) => tick(11 + i)); + const firstPage = new DeferredPromise(); + const rail = createRail(recent); + const selected: string[] = []; + store.add(rail.onDidSelect(id => selected.push(id))); + const panel = rail.domNode.querySelector('.prompt-timeline-gutter-panel')!; + panel.style.maxHeight = '100px'; + panel.style.transition = 'none'; + for (const size of [4, 24, 32]) { + panel.style.setProperty(`--vscode-spacing-size${size * 10}`, `${size}px`); + } + let loads = 0; + rail.setOlderHistoryLoader(async () => { + if (++loads === 1) { + await firstPage.p; + for (let i = earlier.length - 1; i >= 0; i--) { + rail.setTicks([...earlier.slice(i), ...recent]); + } + } else { + rail.setOlderHistoryLoader(undefined); + rail.setTicks([tick(2), ...earlier, ...recent]); + rail.setTicks([tick(1), tick(2), ...earlier, ...recent]); + } + }); + panel.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + const button = panel.querySelector('[role=button][aria-label="Load Earlier Prompts"]')!; + const area = button.getBoundingClientRect(); + const edge = panel.getBoundingClientRect(); + const hit = (x: number) => document.elementFromPoint(x, area.top + area.height / 2); + assert.ok(area.height >= 24 && area.width >= panel.clientWidth - 10 && hit(edge.left + 8) === button && hit(edge.left + panel.clientWidth - 8) === button, + `button ${JSON.stringify(area)}, panel ${JSON.stringify(edge)}, hit ${hit(edge.left + 8)?.className} / ${hit(edge.left + panel.clientWidth - 8)?.className}`); + hit(edge.left + 8)!.dispatchEvent(new MouseEvent('click', { bubbles: true })); + button.click(); + const pending = { loads, disabled: button.ariaDisabled }; + await firstPage.complete(); + await Promise.resolve(); + const first = { top: panel.scrollTop, prompt: rowParts(rail)[0].jump.textContent, focused: document.activeElement === button }; + keydown(button, 'Enter', 13); + await Promise.resolve(); + assert.deepStrictEqual({ pending, first, loads, selected, hidden: !button.getClientRects().length, focused: document.activeElement?.textContent }, + { pending: { loads: 1, disabled: 'true' }, first: { top: 0, prompt: '11', focused: true }, loads: 2, selected: [], hidden: true, focused: '1' }); + }); + test('loads one older page at the gutter boundary and preserves the focused row and column', async () => { const stat = { added: 1, removed: 0, fileCount: 1 }; const recent = [tick(90, stat), tick(91)]; @@ -98,6 +147,25 @@ suite('PromptTimelineGutterRail', () => { { loadsBeforeGesture: 0, loads: 1, preserved: true, focusedPrevious: true, selected: ['89'], more: false }); }); + test('a page arriving after the reader moves on does not take their place in the gutter', async () => { + const recent = Array.from({ length: 10 }, (_, i) => tick(21 + i)); + const rail = createRail(recent); + const panel = rail.domNode.querySelector('.prompt-timeline-gutter-panel')!; + panel.style.maxHeight = '100px'; + const page = new DeferredPromise(); + rail.setOlderHistoryLoader(() => page.p); + panel.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + const button = panel.querySelector('[role=button]')!; + button.click(); + keydown(button, 'End', 35); + const last = rowParts(rail).at(-1)!.jump; + const before = last.offsetTop - panel.scrollTop; + rail.setTicks([tick(20), ...recent]); + await page.complete(); + assert.deepStrictEqual({ focused: document.activeElement === last, top: last.offsetTop - panel.scrollTop }, + { focused: true, top: before }); + }); + test('a page without user prompts still offers paging without inventing a prompt row', () => { const rail = createRail([]); let loads = 0; From fd0e1392a82896477c668f4840dc61e88a3a12e8 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 19:57:07 -0800 Subject: [PATCH 7/9] chat: show loading dots while paging the prompt gutter Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../promptTimeline/media/promptTimeline.css | 9 +++++ .../promptTimelineGutterRail.ts | 25 ++++++++----- .../promptTimelineGutterRail.test.ts | 35 +++++++++++++++++-- 3 files changed, 58 insertions(+), 11 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css index 79e6f77364528f..42feaea3f04bf6 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/media/promptTimeline.css @@ -741,6 +741,15 @@ font-size: var(--vscode-codiconFontSize-compact); } +.monaco-enable-motion .prompt-timeline-gutter-older .codicon-ellipsis { + animation: prompt-timeline-loading-dots 1.2s steps(3, jump-start) infinite; +} + +@keyframes prompt-timeline-loading-dots { + from { clip-path: inset(0 100% 0 0); } + to { clip-path: inset(0); } +} + .prompt-timeline-gutter-older:not(.disabled):hover { background: var(--vscode-list-hoverBackground); } diff --git a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts index 34641603bd602a..683c3a8893819c 100644 --- a/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts +++ b/src/vs/workbench/contrib/chat/browser/promptTimeline/promptTimelineGutterRail.ts @@ -286,9 +286,9 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel if (loadOlder && !this._olderButton) { this._olderButton = this._createOlderButton(); } - if (loadOlder && this._olderButton && this._loadingOlder !== loadOlder) { + if (loadOlder && this._loadingOlder !== loadOlder) { this._loadingFromButton = false; - this._olderButton.enabled = true; + this._setOlderButtonLoading(false); } this._historyError?.remove(); this._historyError = undefined; @@ -302,8 +302,6 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel const label = localize('promptTimeline.gutter.loadEarlier', "Load Earlier Prompts"); const button = this._register(new Button(this._list, { ariaLabel: label, title: label })); button.element.classList.add('prompt-timeline-gutter-older'); - const icon = button.element.appendChild(renderIcon(Codicon.chevronUpCompact)); - icon.ariaHidden = 'true'; this._list.prepend(button.element); this._register(addDisposableListener(button.element, EventType.FOCUS, () => { this._open = true; @@ -317,6 +315,17 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel return button; } + private _setOlderButtonLoading(loading: boolean): void { + const button = this._olderButton; + if (button) { + const icon = renderIcon(loading ? Codicon.ellipsis : Codicon.chevronUpCompact); + icon.ariaHidden = 'true'; + button.element.replaceChildren(icon); + button.element.ariaBusy = String(loading); + button.enabled = !loading; + } + } + private _atHistoryStart(): boolean { return this._list.scrollTop <= 1; } @@ -340,9 +349,7 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel } this._loadingOlder = load; this._loadingFromButton = fromButton; - if (this._olderButton) { - this._olderButton.enabled = false; - } + this._setOlderButtonLoading(true); this._historyError?.remove(); this._historyError = undefined; try { @@ -357,8 +364,8 @@ export class PromptTimelineGutterRail extends Disposable implements IPromptTimel if (this._loadingOlder === load) { this._loadingOlder = undefined; this._loadingFromButton = false; - if (this._olderButton && !this._store.isDisposed) { - this._olderButton.enabled = true; + if (!this._store.isDisposed) { + this._setOlderButtonLoading(false); this._updateOlderHistoryChevron(); } } diff --git a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts index d120b4cf7bce01..d02196313b388b 100644 --- a/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/promptTimeline/promptTimelineGutterRail.test.ts @@ -110,11 +110,42 @@ suite('PromptTimelineGutterRail', () => { const pending = { loads, disabled: button.ariaDisabled }; await firstPage.complete(); await Promise.resolve(); - const first = { top: panel.scrollTop, prompt: rowParts(rail)[0].jump.textContent, focused: document.activeElement === button }; + const first = { top: panel.scrollTop, prompt: rowParts(rail)[0].jump.textContent, focused: document.activeElement === button, chevron: !!button.querySelector('.codicon-chevron-up-compact') }; keydown(button, 'Enter', 13); await Promise.resolve(); assert.deepStrictEqual({ pending, first, loads, selected, hidden: !button.getClientRects().length, focused: document.activeElement?.textContent }, - { pending: { loads: 1, disabled: 'true' }, first: { top: 0, prompt: '11', focused: true }, loads: 2, selected: [], hidden: true, focused: '1' }); + { pending: { loads: 1, disabled: 'true' }, first: { top: 0, prompt: '11', focused: true, chevron: true }, loads: 2, selected: [], hidden: true, focused: '1' }); + }); + + test('cycles one, two, three loading dots, keeps all three for reduced motion and restores the chevron on failure', async () => { + const rail = createRail([tick(1), tick(2)]); + rail.domNode.classList.add('monaco-enable-motion'); + append(rail.domNode, $('style')).textContent = store.add(getIconsStyleSheet(undefined)).getCSS().toString(); + const page = new DeferredPromise(); + rail.setOlderHistoryLoader(() => page.p); + const panel = rail.domNode.querySelector('.prompt-timeline-gutter-panel')!; + panel.style.transition = 'none'; + panel.style.setProperty('--vscode-spacing-size240', '24px'); + panel.dispatchEvent(new MouseEvent('mouseover', { bubbles: true })); + const button = panel.querySelector('[role=button]')!; + button.click(); + const busy = button.ariaBusy; + const dots = button.querySelector('.codicon-ellipsis')!; + const visibleDots = () => { + const { left, top, width, height } = dots.getBoundingClientRect(); + return [0.25, 0.5, 0.75].filter(x => document.elementFromPoint(left + width * x, top + height / 2) === dots).length; + }; + const [animation] = dots.getAnimations(); + animation.pause(); + const cycle = [0.1, 0.4, 0.8, 1.1].map(fraction => { + animation.currentTime = Number(animation.effect!.getTiming().duration) * fraction; + return visibleDots(); + }); + rail.domNode.classList.replace('monaco-enable-motion', 'monaco-reduce-motion'); + const reduced = { dots: visibleDots(), animations: dots.getAnimations().length }; + await page.error(new Error('offline')); + assert.deepStrictEqual({ busy, cycle, reduced, retry: button.ariaDisabled, idle: button.ariaBusy, chevron: !!button.querySelector('.codicon-chevron-up-compact') }, + { busy: 'true', cycle: [1, 2, 3, 1], reduced: { dots: 3, animations: 0 }, retry: 'false', idle: 'false', chevron: true }); }); test('loads one older page at the gutter boundary and preserves the focused row and column', async () => { From 236352eb7231893bd6343d372d204d2fcd0c5647 Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 20:11:16 -0800 Subject: [PATCH 8/9] chat: preserve prompts, checkpoints, and Find results across paging Verify accepted turns even when the host returns an empty cursor. Reconcile completed checkpoints without moving local requests past their steering turns, and let Find finish a page only once its messages are searchable. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../browser/agentHostProtocolClient.ts | 2 +- .../common/state/agentSubscription.ts | 2 +- .../agentHostProtocolClient.test.ts | 5 +- .../agentHost/agentHostSessionHandler.ts | 33 ++++---- .../agentHost/agentHostSnapshotController.ts | 78 ++++++++++++++++--- .../chatService/remoteChatSessionRestorer.ts | 34 +++++--- .../agentHostSnapshotController.test.ts | 31 ++++++-- .../agentHostChatContribution.test.ts | 20 +++-- .../common/chatService/chatService.test.ts | 49 ++++++++++++ 9 files changed, 202 insertions(+), 52 deletions(-) diff --git a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts index d9c6ca16080cde..6ac7f9f4953cb5 100644 --- a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts +++ b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts @@ -1538,7 +1538,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect } const visited = new Set(); try { - for (let cursor = sub.getTurnRecoveryCursor(queued); cursor; cursor = sub.getTurnRecoveryCursor(queued)) { + for (let cursor = sub.getTurnRecoveryCursor(queued); cursor !== undefined; cursor = sub.getTurnRecoveryCursor(queued)) { this._subscriptionsAwaitingRestore.add(channel); if (visited.has(cursor) || visited.size >= 8) { throw new Error('History recovery limit reached'); diff --git a/src/vs/platform/agentHost/common/state/agentSubscription.ts b/src/vs/platform/agentHost/common/state/agentSubscription.ts index f89e752c624ffb..bf55f42dc52f96 100644 --- a/src/vs/platform/agentHost/common/state/agentSubscription.ts +++ b/src/vs/platform/agentHost/common/state/agentSubscription.ts @@ -563,7 +563,7 @@ export class ChatStateSubscription extends BaseAgentSubscription { getTurnRecoveryCursor(unsent: ReadonlySet): string | undefined { const state = this.verifiedValue; - if (state?.turnsNextCursor && this._pendingActions.some(p => p.action.type === ActionType.ChatTurnStarted && !unsent.has(p.clientSeq) + if (state?.turnsNextCursor !== undefined && this._pendingActions.some(p => p.action.type === ActionType.ChatTurnStarted && !unsent.has(p.clientSeq) && (!p.previousTurnId || (p.previousTurnId !== state.activeTurn?.id && !state.turns.some(t => t.id === p.previousTurnId))))) { return state.turnsNextCursor; } diff --git a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts index 3f339969dc9088..a207b10a4c8462 100644 --- a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts +++ b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts @@ -6236,9 +6236,10 @@ suite('AgentHostProtocolClient', () => { assert.deepStrictEqual(restore.params, { channel, view: { turns: 10 } }); transport.fireWireMessage({ jsonrpc: '2.0', id: restore.id, result: { snapshot: { ...snapshot, state: { ...state, turns: prior, turnsNextCursor: 'older' } } } }); } else if (recovery === 'snapshotHiddenEcho' || recovery === 'snapshotLostRequest') { - transport.fireWireMessage({ jsonrpc: '2.0', id: reconnect.id, result: { type: ReconnectResultType.Snapshot, snapshots: [{ ...snapshot, fromSeq: 8, state: { ...state, turnsNextCursor: 'check' } }] } }); + const cursor = recovery === 'snapshotHiddenEcho' ? '' : 'check'; + transport.fireWireMessage({ jsonrpc: '2.0', id: reconnect.id, result: { type: ReconnectResultType.Snapshot, snapshots: [{ ...snapshot, fromSeq: 8, state: { ...state, turnsNextCursor: cursor } }] } }); const check = await waitForRequestAtWithin(transport, 'fetchTurns', 0); - assert.deepStrictEqual(check.params, { channel, cursor: 'check' }); + assert.deepStrictEqual(check.params, { channel, cursor }); const turns = recovery === 'snapshotLostRequest' ? prior : chatReducer(chatReducer(state, start), chatTurnComplete(start.turnId, 1)).turns; transport.fireWireMessage({ jsonrpc: '2.0', method: 'action', params: { channel, serverSeq: 9, action: { type: ActionType.ChatTurnsLoaded, turns, turnsNextCursor: 'older' } } }); transport.fireWireMessage({ jsonrpc: '2.0', id: check.id, result: {} }); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts index 6aca1c90e7fcd7..3339f33545adc1 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts @@ -840,11 +840,11 @@ class AgentHostChatSession extends Disposable implements IChatSession { readonly ownsHistoryRequestIds = true; - reconcileHistory(chat: ChatState, project: (turns: readonly Turn[]) => IChatSessionHistoryItem[], reason: HistoryWindowChange): readonly Turn[] { + reconcileHistory(chat: ChatState, project: (turns: readonly Turn[]) => IChatSessionHistoryItem[], reason: HistoryWindowChange): readonly Turn[] | undefined { const previous = this._historyTurns; const window = chat.turns; if (previous === window && reason !== 'metadata') { - return []; + return undefined; } // Only the first turn of a partial window can vouch for a cached prefix before it. const anchor = chat.turnsNextCursor !== undefined && window.length ? previous.findIndex(turn => turn.id === window[0].id) : -1; @@ -868,12 +868,11 @@ class AgentHostChatSession extends Disposable implements IChatSession { history = [...project(turns), ...active]; } this._historyTurns = turns; - if (history.length === this._history.length && history.every((item, index) => item === this._history[index])) { - return older; + if (history.length !== this._history.length || history.some((item, index) => item !== this._history[index])) { + this._history = history; + this._onDidChangeHistory.fire(history); } - this._history = history; - this._onDidChangeHistory.fire(history); - return older; + return turns.length !== previous.length || turns.some((turn, i) => turn.id !== previous[i].id) ? turns : undefined; } readonly interruptActiveResponseCallback: IChatSession['interruptActiveResponseCallback']; @@ -3092,14 +3091,14 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC } lastWindow = chat.turns; const allowTurnResume = !this._isChatReadOnly(sessionStr, chatURI); - const older = chatSession.reconcileHistory(chat, turns => turnsToHistory(backendSession, turns, this._config.agentId, this._config.connectionAuthority, + const historyTurns = chatSession.reconcileHistory(chat, turns => turnsToHistory(backendSession, turns, this._config.agentId, this._config.connectionAuthority, this._createTurnModelLookup(sessionResource, lastTurnModelSelection(state)?.id), this._chatErrorContext(sessionResource), this._config.connection.initializeResult.get()?.terminalCommandPrefix, this._config.connection.resourceUris, turn => this._getTurnErrorDetails(sessionResource, turn, allowTurnResume), turns.at(-1) === chat.turns.at(-1) ? readAgentContextUsage(state, chat.turns.at(-1)?.usage) : undefined, this._managedPluginRetryTarget(backendSession, chatURI)), reason); - if (older.length) { - this._prependHistoryCheckpoints(sessionResource, older); + if (historyTurns) { + this._syncHistoryCheckpoints(sessionResource, historyTurns); } }; let previousContextUsage = currentState ? readAgentContextUsage(currentState, currentState.turns.at(-1)?.usage) : undefined; @@ -6967,17 +6966,18 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC } } - private _prependHistoryCheckpoints(sessionResource: URI, turns: readonly Turn[]): void { - const pending = this._pendingHistoryTurns.get(sessionResource); - const history = pending ? [...turns, ...pending] : turns; + private _syncHistoryCheckpoints(sessionResource: URI, history: readonly Turn[]): void { const controller = this._chatService.getSession(sessionResource)?.editingSession; if (!(controller instanceof AgentHostSnapshotController)) { this._pendingHistoryTurns.set(sessionResource, history); return; } this._pendingHistoryTurns.delete(sessionResource); - controller.prependRequestCheckpoints(history.map(turn => turn.id)); + const toHydrate = controller.reconcileHistoryCheckpoints(history.map(turn => turn.id)); for (const turn of history) { + if (!toHydrate.has(turn.id)) { + continue; + } for (const part of turn.responseParts) { if (part.kind === ResponsePartKind.ToolCall) { controller.addToolCallEdits(turn.id, part.toolCall); @@ -7014,8 +7014,9 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC // edits) so "Restore Checkpoint" on any historical request can // find a boundary and mark subsequent requests as disabled via // requestDisablement. - if (this._pendingHistoryTurns.has(sessionResource)) { - this._prependHistoryCheckpoints(sessionResource, []); + const history = this._pendingHistoryTurns.get(sessionResource); + if (history) { + this._syncHistoryCheckpoints(sessionResource, history); } return editingSession; diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts index d707e691cf173e..29d15f312f0c05 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSnapshotController.ts @@ -8,7 +8,7 @@ import { VSBuffer } from '../../../../../../base/common/buffer.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { Disposable, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../../base/common/network.js'; -import { autorun, constObservable, derived, derivedOpts, disposableObservableValue, IObservable, IReader, observableValue, transaction } from '../../../../../../base/common/observable.js'; +import { autorun, constObservable, derived, derivedOpts, disposableObservableValue, IObservable, IReader, observableSignal, observableValue, transaction } from '../../../../../../base/common/observable.js'; import { basename } from '../../../../../../base/common/resources.js'; import { URI } from '../../../../../../base/common/uri.js'; import { localize } from '../../../../../../nls.js'; @@ -89,6 +89,7 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit readonly requestDisablement: IObservable = derivedOpts( { equalsFn: (a, b) => a.length === b.length && a.every((v, i) => v.requestId === b[i].requestId) }, reader => { + this._checkpointOrderChanged.read(reader); const currentIdx = this._currentCheckpointIndex.read(reader); const disabled: IChatRequestDisablement[] = []; for (let i = currentIdx + 1; i < this._checkpoints.length; i++) { @@ -99,12 +100,17 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit ); readonly canUndo: IObservable = derived(this, r => this._currentCheckpointIndex.read(r) >= 0); - readonly canRedo: IObservable = derived(this, r => this._currentCheckpointIndex.read(r) < this._checkpoints.length - 1); + readonly canRedo: IObservable = derived(this, r => { + this._checkpointOrderChanged.read(r); + return this._currentCheckpointIndex.read(r) < this._checkpoints.length - 1; + }); private readonly _onDidDispose = this._register(new Emitter()); readonly onDidDispose: Event = this._onDidDispose.event; - private readonly _checkpoints: IAgentHostCheckpoint[] = []; + private _checkpoints: IAgentHostCheckpoint[] = []; + private _historyIds = new Set(); + private readonly _checkpointOrderChanged = observableSignal(this); private readonly _currentCheckpointIndex = observableValue(this, -1); private readonly _undoRedoSequencer = new Sequencer(); @@ -178,14 +184,50 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit }); } - /** Adds already-completed requests before the loaded window without changing the undo/redo boundary. */ - prependRequestCheckpoints(ids: readonly string[]): void { - const existing = new Set(this._checkpoints.map(checkpoint => checkpoint.requestId)); - const older = [...new Set(ids)].filter(id => !existing.has(id)).map(requestId => ({ requestId, edits: [], turnEditsResolved: false, seenToolCallIds: new Set() })); - if (older.length) { - this._checkpoints.unshift(...older); - this._currentCheckpointIndex.set(this._currentCheckpointIndex.get() + older.length, undefined); + /** Reconciles completed turns in transcript order, retaining local checkpoints and the reader's restore boundary. */ + reconcileHistoryCheckpoints(ids: readonly string[]): ReadonlySet { + const previous = this._checkpoints; + const existing = new Map(previous.map(cp => [cp.requestId, cp])); + const history = new Set(ids); + const localsBefore = new Map(); + let localTail: IAgentHostCheckpoint[] = []; + for (const cp of previous) { + // A steering turn can reach history before the local request it followed. + if (history.has(cp.requestId)) { + if (localTail.length) { + localsBefore.set(cp.requestId, localTail); + localTail = []; + } + } else if (!this._historyIds.has(cp.requestId)) { + localTail.push(cp); + } + } + const toHydrate = new Set(); + const ordered: IAgentHostCheckpoint[] = []; + for (const requestId of history) { + const cp = existing.get(requestId); + if (!cp || !this._historyIds.has(requestId)) { + toHydrate.add(requestId); + } + ordered.push(...(localsBefore.get(requestId) ?? [])); + ordered.push(cp ?? { requestId, edits: [], turnEditsResolved: false, seenToolCallIds: new Set() }); + } + ordered.push(...localTail); + this._historyIds = history; + const index = this._currentCheckpointIndex.get(); + let nextIndex = ordered.length - 1; + if (index < previous.length - 1) { + const retained = new Set(ordered); + const firstDisabled = previous.slice(index + 1).find(cp => retained.has(cp)); + const lastEnabled = previous.slice(0, index + 1).findLast(cp => retained.has(cp)); + nextIndex = firstDisabled ? ordered.indexOf(firstDisabled) - 1 : lastEnabled ? ordered.indexOf(lastEnabled) : nextIndex; } + this._checkpoints = ordered; + transaction(tx => { + this._currentCheckpointIndex.set(nextIndex, tx); + this._checkpointOrderChanged.trigger(tx); + }); + return toHydrate; } /** @@ -305,6 +347,20 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit const crossed = this._checkpoints.slice(Math.min(currentIdx, targetIdx) + 1, Math.max(currentIdx, targetIdx) + 1); const undo = targetIdx < currentIdx; const reviewCheckpoints = undo ? this._checkpoints.slice(targetIdx + 1) : crossed; + let order = this._checkpoints; + const verifyRestoreRange = () => { + if (order === this._checkpoints) { + return; + } + const boundaryIndex = this._checkpoints.indexOf(boundary); + const target = targetIdx < 0 ? boundaryIndex - 1 : boundaryIndex; + const current = this._currentCheckpointIndex.get(); + const start = Math.min(current, target) + 1; + if (boundaryIndex < 0 || current - target !== currentIdx - targetIdx || !crossed.every((cp, i) => this._checkpoints[start + i] === cp)) { + throw new Error(localize('agentHostSnapshot.historyChanged', "The chat history changed while restoring the checkpoint.")); + } + order = this._checkpoints; + }; // A failed fetch must leave every file and the checkpoint cursor at the original boundary. await Promise.all(crossed.map(checkpoint => this._resolveCheckpointEdits(checkpoint))); const affectedResources = crossed.flatMap(checkpoint => checkpoint.edits.flatMap(edit => edit.originalResource ? [edit.resource, edit.originalResource] : [edit.resource])); @@ -323,6 +379,7 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit } const failures: Error[] = []; for (const checkpoint of undo ? [...crossed].reverse() : crossed) { + verifyRestoreRange(); try { await this._writeCheckpointContent(checkpoint, undo ? 'before' : 'after'); } catch (error) { @@ -334,6 +391,7 @@ export class AgentHostSnapshotController extends Disposable implements IChatEdit failures.push(afterRestoreError); } + verifyRestoreRange(); transaction(tx => { const boundaryIndex = this._checkpoints.indexOf(boundary); this._currentCheckpointIndex.set(targetIdx < 0 ? Math.max(-1, boundaryIndex - 1) : boundaryIndex, tx); diff --git a/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts b/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts index ac02f08003b7bb..06cd13782cebf1 100644 --- a/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts +++ b/src/vs/workbench/contrib/chat/common/chatService/remoteChatSessionRestorer.ts @@ -10,7 +10,7 @@ import { Event } from '../../../../../base/common/event.js'; import { Disposable, DisposableStore, IDisposable, toDisposable } from '../../../../../base/common/lifecycle.js'; import { equals } from '../../../../../base/common/objects.js'; import { setTimeout0 } from '../../../../../base/common/platform.js'; -import { autorun, transaction } from '../../../../../base/common/observable.js'; +import { autorun, observableValue, transaction } from '../../../../../base/common/observable.js'; import { clearMarks, mark } from '../../../../../base/common/performance.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { getChatSessionHistoryContent, IChatSession, IChatSessionHistoryItem, IChatSessionRequestHistoryItem, IChatSessionServerRequest } from '../chatSessionsService.js'; @@ -145,6 +145,8 @@ export class RemoteChatSessionRestorer extends Disposable { private _pendingHistory: readonly IChatSessionHistoryItem[] | undefined; private readonly _supersededRequestIds = new Set(); private _activeRefresh: Promise | undefined; + private _nextRefresh: DeferredPromise | undefined; + private readonly _readingPage = observableValue(this, false); /** The request that history responses are applied to. */ private _lastRequest: ChatRequestModel | undefined; @@ -166,12 +168,26 @@ export class RemoteChatSessionRestorer extends Disposable { this._model = _options.model; this._session = _options.session; this._restoredHistory = this._session.history; + // Cancel pending cooperative waits when the restorer is disposed, not only when the service token is. + const budgetCancellation = new CancellationTokenSource(_options.token); + this._register(toDisposable(() => budgetCancellation.dispose(true))); + this._budget = new CooperativeMutationBudget(scheduler, budgetCancellation.token, () => this._state === RestoreState.Disposed); if (this._session.loadOlderHistory) { let page: Promise | undefined; const readPage = async () => { if (this._state === RestoreState.Published) { - await this._session.loadOlderHistory?.(); - await this.historyRefresh; + this._readingPage.set(true, undefined); + try { + await this._session.loadOlderHistory?.(); + while (this._activeRefresh || this._pendingHistory) { + // A replacement window can wait behind a streaming response until a later refresh. + this._budget.throwIfCancelled(); + const refresh = this._activeRefresh ?? (this._nextRefresh ??= new DeferredPromise()).p; + await raceCancellationError(refresh, budgetCancellation.token); + } + } finally { + this._readingPage.set(false, undefined); + } } }; this._model.loadOlderHistory = () => page ??= readPage().finally(() => { page = undefined; }); @@ -180,10 +196,6 @@ export class RemoteChatSessionRestorer extends Disposable { })); } this._hasProgressStreaming = !!(this._session.progressObs && this._session.interruptActiveResponseCallback); - // Cancel pending cooperative waits when the restorer is disposed, not only when the service token is. - const budgetCancellation = new CancellationTokenSource(_options.token); - this._register(toDisposable(() => budgetCancellation.dispose(true))); - this._budget = new CooperativeMutationBudget(scheduler, budgetCancellation.token, () => this._state === RestoreState.Disposed); if (this._session.onDidChangeHistory) { this._register(this._session.onDidChangeHistory(history => { @@ -246,8 +258,11 @@ export class RemoteChatSessionRestorer extends Disposable { this._register(autorun(reader => { const cursor = this._session.olderHistoryCursor?.read(reader); const unavailable = !!this._session.olderHistoryUnavailable?.read(reader) || (cursor !== undefined && !this._session.loadOlderHistory); + const readingPage = this._readingPage.read(reader); transaction(tx => { - this._model.olderHistoryCursor.set(this._session.loadOlderHistory ? cursor : undefined, tx); + if (!readingPage) { + this._model.olderHistoryCursor.set(this._session.loadOlderHistory ? cursor : undefined, tx); + } this._model.olderHistoryUnavailable.set(unavailable, tx); }); })); @@ -403,7 +418,8 @@ export class RemoteChatSessionRestorer extends Disposable { if (this._activeRefresh) { return this._activeRefresh; } - const completion = new DeferredPromise(); + const completion = this._nextRefresh ?? new DeferredPromise(); + this._nextRefresh = undefined; this._activeRefresh = completion.p; void this._applyPendingHistory(force).then(() => completion.complete(), error => completion.error(error)); return completion.p; diff --git a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts index 1e5cc8e6e6cb8f..656166241813eb 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSnapshotController.test.ts @@ -134,15 +134,14 @@ suite('AgentHostSnapshotController', () => { test('paging in checkpoints preserves an undo branch and allows restoring a fetched request', async () => { const controller = createController(store, new Map()); - controller.ensureRequestCheckpoint('middle'); - controller.ensureRequestCheckpoint('latest'); + controller.reconcileHistoryCheckpoints(['middle', 'latest']); await controller.restoreSnapshot('latest', undefined); - controller.prependRequestCheckpoints(['oldest', 'earlier']); - controller.prependRequestCheckpoints(['oldest', 'earlier']); + controller.reconcileHistoryCheckpoints(['oldest', 'earlier', 'middle', 'latest', 'offline']); + controller.reconcileHistoryCheckpoints(['oldest', 'earlier', 'middle', 'latest', 'offline']); const afterPaging = controller.requestDisablement.get().map(request => request.requestId); await controller.restoreSnapshot('earlier', undefined); assert.deepStrictEqual([afterPaging, controller.requestDisablement.get().map(request => request.requestId)], [ - ['latest'], ['earlier', 'middle', 'latest'], + ['latest', 'offline'], ['earlier', 'middle', 'latest', 'offline'], ]); }); @@ -156,12 +155,32 @@ suite('AgentHostSnapshotController', () => { controller.ensureRequestCheckpoint('first-visible'); const restore = controller.restoreSnapshot('first-visible', undefined); await resolving.p; - controller.prependRequestCheckpoints(['hidden']); + controller.reconcileHistoryCheckpoints(['hidden', 'first-visible']); await edits.complete([]); await restore; assert.deepStrictEqual(controller.requestDisablement.get(), [{ requestId: 'first-visible' }]); }); + test('a replacement window while fetching a checkpoint does not write the removed turn', async () => { + const file = URI.file('/file.txt').toString(); + const before = URI.file('/snap/before').toString(); + const after = URI.file('/snap/after').toString(); + const contents = new Map([[file, 'current'], [before, 'old'], [after, 'current']]); + const resolving = new DeferredPromise(); + const edits = new DeferredPromise(); + const controller = createController(store, contents, { + getChanges: () => undefined, + resolve: () => { resolving.complete(); return edits.p; }, + }); + controller.reconcileHistoryCheckpoints(['removed']); + const restore = controller.restoreSnapshot('removed', undefined); + await resolving.p; + controller.reconcileHistoryCheckpoints(['replacement']); + await edits.complete([{ before: { uri: file, content: { uri: before } }, after: { uri: file, content: { uri: after } } }]); + await assert.rejects(restore, /history changed/); + assert.deepStrictEqual({ file: contents.get(file), disabled: controller.requestDisablement.get() }, { file: 'current', disabled: [] }); + }); + test('addToolCallEdits records snapshot data, enables undo', () => { const contentMap = new Map(); const controller = createController(store, contentMap); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts index 04af0cf78f8077..36d111e937a4f1 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts @@ -21976,7 +21976,7 @@ suite('AgentHostChatContribution', () => { }); test('reconciles reconnect windows before the next turn and never prepends a replacement transcript', async () => { - const { sessionHandler, agentHostService } = createContribution(disposables); + const { sessionHandler, agentHostService, chatService } = createContribution(disposables); const backend = AgentSession.uri('copilot', 'reconnect-window'); const resource = URI.from({ scheme: 'agent-host-copilot', path: '/reconnect-window' }); const chat = 'ahp-chat:/opaque/reconnect'; @@ -21995,9 +21995,13 @@ suite('AgentHostChatContribution', () => { const ids = () => session.history.flatMap(item => item.type === 'request' ? [item.id] : []); const atTurnStart: (string | undefined)[][] = []; disposables.add(session.onDidStartServerRequest!(() => atTurnStart.push(ids()))); - const checkpoints = sessionHandler as unknown as { _prependHistoryCheckpoints(resource: URI, turns: readonly Turn[]): void }; - const prepends = sinon.spy(checkpoints, '_prependHistoryCheckpoints'); - disposables.add(toDisposable(() => prepends.restore())); + const controller = disposables.add(new AgentHostSnapshotController(resource, agentHostService, 'test', undefined, + new NullLogService(), disposables.add(new TestFileService()), new MockWorkingCopyService())); + chatService.setSession(resource, upcastPartial({ + sessionResource: resource, editingSession: controller, + getRequests: () => [], getPendingRequests: () => [], onDidChangePendingRequests: Event.None, + })); + const disabled = () => controller.requestDisablement.get().map(r => r.requestId); let serverSeq = 0; const fire = (action: ChatAction) => agentHostService.fireAction({ channel: chat, action, serverSeq: ++serverSeq, origin: undefined }); fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('a')] }); @@ -22007,6 +22011,8 @@ suite('AgentHostChatContribution', () => { activeTurn: createActiveTurn('live', turn('live').message, new Date(0).toISOString()), }); fire(chatTurnComplete('live', 1)); + await controller.restoreSnapshot('offline', undefined); + const offlineCheckpoint = disabled(); fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('b')], turnsNextCursor: 'final cursor' }); const overlap = ids(); fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('older'), turn('a')] }); @@ -22019,12 +22025,12 @@ suite('AgentHostChatContribution', () => { const replaced = ids(); fire({ type: ActionType.ChatTruncated, turnId: 'replacement' }); fire({ type: ActionType.ChatTurnsLoaded, turns: [turn('earliest'), turn('earlier'), turn('replacement')] }); - const prependedPages = prepends.args.map(([, turns]) => turns.map(turn => turn.id)); - assert.deepStrictEqual({ beforeReconnect, atTurnStart, overlap, expanded, noAnchor, cleared, replaced, final: ids(), prependedPages, fetches }, { + await controller.restoreSnapshot('earliest', undefined); + assert.deepStrictEqual({ beforeReconnect, atTurnStart, overlap, expanded, noAnchor, cleared, replaced, final: ids(), offlineCheckpoint, finalCheckpoints: disabled(), fetches }, { beforeReconnect: ['a', 'b', 'c'], atTurnStart: [['a', 'b', 'c', 'offline']], overlap: ['a', 'b', 'c', 'offline', 'live'], expanded: ['older', 'a', 'b', 'c', 'offline', 'live'], noAnchor: ['unrelated'], cleared: [], replaced: ['replacement', 'also-replaced'], final: ['earliest', 'earlier', 'replacement'], - prependedPages: [['a'], ['older'], ['earliest', 'earlier']], fetches: 0, + offlineCheckpoint: ['offline', 'live'], finalCheckpoints: ['earliest', 'earlier', 'replacement'], fetches: 0, }); }); diff --git a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts index 0383d4c4e7abbe..4e8ba4eb73f83e 100644 --- a/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/chatService/chatService.test.ts @@ -6055,6 +6055,55 @@ suite('ChatService', () => { model.cancelRequest(live); }); + test('keeps a fetched page searchable as pending until its replacement history is applied', async () => { + const changes = testDisposables.add(new Emitter()); + const recent = { id: 'recent', type: 'request', prompt: 'Recent', participant: remoteScheme } as const; + const cursor = observableValue('cursor', 'last page'); + let loads = 0; + const { resource } = setupRemoteProvider({ + history: [recent], onDidChangeHistory: changes.event, olderHistoryCursor: cursor, ownsHistoryRequestIds: true, + loadOlderHistory: async () => { + loads++; + changes.fire([{ ...recent, id: 'older', prompt: 'Unique early match' }, { ...recent }]); + cursor.set(undefined, undefined); + }, + }); + const service = createChatServiceWithFrozenHistoryClock(); + const ref = await service.acquireOrLoadSession(resource, ChatAgentLocation.Chat, CancellationToken.None); + assert.ok(ref); + const model = testDisposables.add(ref).object as ChatModel; + const live = model.addRequest({ parts: [], text: 'Live' }, { variables: [] }, 0); + let finished = false; + const page = model.loadOlderHistory!().then(() => { finished = true; }); + await timeout(0); + const before = { finished, cursor: model.olderHistoryCursor.get(), rows: model.getRequests().map(r => r.id) }; + const samePage = model.loadOlderHistory!(); + live.response!.complete(); + await Promise.all([page, samePage]); + assert.deepStrictEqual({ before, loads, cursor: model.olderHistoryCursor.get(), prompts: model.getRequests().map(r => r.message.text) }, { + before: { finished: false, cursor: 'last page', rows: ['recent', live.id] }, loads: 1, cursor: undefined, + prompts: ['Unique early match', 'Recent', 'Live'], + }); + }); + + test('disposing the model cancels a page waiting for its replacement history', async () => { + const changes = testDisposables.add(new Emitter()); + const recent = { id: 'recent', type: 'request', prompt: 'Recent', participant: remoteScheme } as const; + const { resource } = setupRemoteProvider({ + history: [recent], onDidChangeHistory: changes.event, + loadOlderHistory: async () => changes.fire([{ ...recent, id: 'older' }, { ...recent }]), + }); + const service = createChatServiceWithFrozenHistoryClock(); + const ref = await service.acquireOrLoadSession(resource, ChatAgentLocation.Chat, CancellationToken.None); + assert.ok(ref); + const model = testDisposables.add(ref).object as ChatModel; + model.addRequest({ parts: [], text: 'Live' }, { variables: [] }, 0); + const page = model.loadOlderHistory!(); + await timeout(0); + model.dispose(); + await assert.rejects(page, isCancellationError); + }); + test('authoritative history removes confirmed local turns even if snapshots coalesce while streaming', async () => { const changes = testDisposables.add(new Emitter()); const first = { id: 'one', type: 'request', prompt: 'First', participant: remoteScheme } as const; From 621233c88a09801a3f683af4c69746bd1c73ec3e Mon Sep 17 00:00:00 2001 From: Osvaldo Ortega Date: Thu, 19 Nov 2026 20:45:02 -0800 Subject: [PATCH 9/9] chat: initialize the Find event in the first-render trace test Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../contrib/chat/test/browser/widget/chatWidget.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts index 0870f94508fa38..304a3fb08d15fb 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidget.test.ts @@ -167,6 +167,7 @@ suite('ChatWidget', () => { _viewModel: upcastPartial({ model, sessionResource: resource, getItems: () => [] }), _pendingFirstRenderSessionResource: resource, _onWillMaybeChangeHeight: store.add(new Emitter()), + _onDidChangeFindableContent: store.add(new Emitter()), logService, chatOpenDiagnosticsService: store.add(new ChatOpenDiagnosticsService(new NullLogService())), listWidget: { setVisibleChangeCount: () => { }, refresh: () => { } },