Skip to content
Merged
2 changes: 2 additions & 0 deletions src/vs/platform/agentHost/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
123 changes: 112 additions & 11 deletions src/vs/platform/agentHost/browser/agentHostProtocolClient.ts

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions src/vs/platform/agentHost/common/agentService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1415,6 +1415,8 @@ export interface IAgentConnection {
*/
getSubscription<T extends StateComponents>(kind: T, resource: URI, owner: string): IReference<IAgentSubscription<ComponentToState[T]>>;
getSubscriptionUnmanaged<T extends StateComponents>(kind: T, resource: URI): IAgentSubscription<ComponentToState[T]> | undefined;
/** Loads the preceding page into the subscribed chat using its host-issued cursor. */
fetchTurns?(chat: URI, cursor: string): Promise<void>;

/**
* Returns the in-flight `createSession` Promise for `resource`, or `undefined` if no create is pending. Callers
Expand Down
35 changes: 29 additions & 6 deletions src/vs/platform/agentHost/common/state/agentSubscription.ts
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,7 @@ export class SessionStateSubscription extends BaseAgentSubscription<SessionState
interface IPendingChatAction {
readonly clientSeq: number;
readonly action: ChatAction;
readonly previousTurnId?: string;
}

/**
Expand Down Expand Up @@ -515,7 +516,8 @@ export class ChatStateSubscription extends BaseAgentSubscription<ChatState> {
*/
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);
Expand Down Expand Up @@ -543,7 +545,12 @@ export class ChatStateSubscription extends BaseAgentSubscription<ChatState> {
}

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;
Expand All @@ -552,8 +559,15 @@ export class ChatStateSubscription extends BaseAgentSubscription<ChatState> {
this._pendingActions.splice(i, 1);
}
}
super._onSnapshotApplied(fromSeq);
this._recomputeOptimistic();
}

getTurnRecoveryCursor(unsent: ReadonlySet<number>): string | undefined {
const state = this.verifiedValue;
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;
}
return undefined;
}

protected override _reconcile(envelope: ActionEnvelope, isOwnAction: boolean): void {
Expand All @@ -575,6 +589,9 @@ export class ChatStateSubscription extends BaseAgentSubscription<ChatState> {
this._promotePendingTurnStartIfTerminal(envelope.action);
this._confirmedApply(envelope.action);
}
if (envelope.action.type === ActionType.ChatTurnsLoaded && !envelope.rejectionReason) {
this._acknowledgeVisibleTurns();
}
this._recomputeOptimistic();
}

Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down
5 changes: 5 additions & 0 deletions src/vs/platform/agentHost/node/agentHostStateManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2797,6 +2797,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
Expand Down
120 changes: 120 additions & 0 deletions src/vs/platform/agentHost/node/chatHistoryView.ts
Original file line number Diff line number Diff line change
@@ -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<Turn> | 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 } : {}) };
}
}
Loading