src/vs/platform/agentHost/node/agentHostLocalTurns.ts

161 LOC · 147 covered · 14 uncovered · 37 ranges · 1064 concepts · 15 introducers · 508 tests

File neighbourhood

The centred file is linked to every concept that introduces one of its ranges, every test that runs code from the file, and the gray connector concepts standing between those tests and the file's own introducer concepts. Undirected links join concepts to every file where they introduce source and concepts to the tests they introduce; arrows show specialization between the displayed concepts and bridge only concepts omitted from this view. Concept colors match the source ranges below; connector concepts have no source color and are shown in gray.

Focused file, its introducer and connector concepts, their introduced files, and tests that run code from the file

In the embedded map, ordinary wheel input scrolls the page; use the visible controls to zoom and drag to pan. Open the full-screen map for canvas navigation: wheel pans, Ctrl/Command plus wheel zooms, and arrow keys pan when this region is focused. On touch screens, open the full-screen map to pan or pinch. If JavaScript or WebGL is unavailable, use the related-file, concept, and source links on this page.

Graph controls are ready.

Interactive rendering requires JavaScript and WebGL. Use the related-file, concept, and source links on this page while the interactive map is unavailable.

1 > /*--------------------------------------------------------------------------------------------- agentHostLocalTurns.ts ×12
2 > * Copyright (c) Microsoft Corporation. All rights reserved.
3 > * Licensed under the MIT License. See License.txt in the project root for license information.
4 > *--------------------------------------------------------------------------------------------*/
5 >
6 > import type { IReference } from '../../../base/common/lifecycle.js';
7 > import { URI } from '../../../base/common/uri.js';
8 > import { ILogService } from '../../log/common/log.js';
9 > import type { ILocalTurnRecord, ISessionDatabase, ISessionDataService } from '../common/sessionDataService.js';
10 > import type { Turn } from '../common/state/sessionState.js';
11 >
12 > /**
13 > * Tracks host-injected ("local") turns — completed protocol turns the agent SDK
14 > * never saw, such as the `/rename` acknowledgement or a `!command` terminal run.
15 > *
16 > * These turns exist only in the agent host: they are never forwarded to the
17 > * agent SDK, so they are absent from the SDK transcript that
18 > * {@link AgentService} replays on restore. This registry persists them (so they
19 > * survive reload) and remembers, for each, the id of the preceding concrete
20 > * (SDK-backed) turn — the *anchor* — so that fork/truncate operations targeting
21 > * a local turn can be redirected to the concrete SDK message before it.
22 > *
23 > * Everything is scoped to a **chat** (its channel URI): a session's default
24 > * chat and each of its peer chats are handled identically. Persistence lives in
25 > * the owning session's database (one per session, shared across its chats),
26 > * discriminated by {@link ILocalTurnRecord.chatUri}.
27 > */
28 > export class AgentHostLocalTurns {
29 >
30 > /** chat URI → (localTurnId → { anchorTurnId, seq }). */
31 > private readonly _byChat = new Map<string, Map<string, { readonly anchorTurnId: string | undefined; readonly seq: number }>>();
32 > /** session URI → highest `seq` assigned so far (seq is session-global for stable ordering). */
33 > private readonly _seqBySession = new Map<string, number>();
34 >
35 > constructor(
36 > private readonly _sessionDataService: ISessionDataService, agentHostLocalTurns.ts ×1
37 > private readonly _logService: ILogService,
38 > ) { }
40 > /** Whether `turnId` is a known host-injected local turn in `chat`. */
41 > isLocal(chat: string, turnId: string): boolean {
42 > return this._byChat.get(chat)?.has(turnId) ?? false; agentHostLocalTurns.ts ×1
43 > }
45 > /** All known local turn ids for `chat`. */
46 > getLocalTurnIds(chat: string): string[] {
47 > const map = this._byChat.get(chat); agentHostLocalTurns.ts ×3
48 > return map ? [...map.keys()] : [];
49 > }
51 > /**
52 > * Resolves `turnId` to the concrete (SDK-backed) turn a fork/truncate should
53 > * operate on within `chat`. For a local turn this is its anchor (the
54 > * preceding real turn, or `undefined` when it precedes any real turn); for a
55 > * concrete turn it is the turn itself.
56 > */
57 > resolveConcreteTurnId(chat: string, turnId: string): string | undefined {
58 > const entry = this._byChat.get(chat)?.get(turnId); agentHostLocalTurns.ts ×1
59 > return entry ? entry.anchorTurnId : turnId;
60 > }
62 > /**
63 > * Persist a local turn and remember it in memory. `anchorTurnId` is the id
64 > * of the preceding concrete turn in `chat` (or `undefined` when there is
65 > * none). `session` identifies the database to persist into.
66 > */
67 > record(session: string, chat: string, turn: Turn, anchorTurnId: string | undefined): void {
68 > const seq = (this._seqBySession.get(session) ?? 0) + 1; agentHostLocalTurns.ts ×2
69 > this._noteInMemory(session, chat, turn.id, anchorTurnId, seq);
70 > const record: ILocalTurnRecord = { turnId: turn.id, chatUri: chat, anchorTurnId, seq, payload: JSON.stringify(turn) };
71 > let ref: IReference<ISessionDatabase>;
72 > try {
73 > ref = this._sessionDataService.openDatabase(URI.parse(session));
74 > } catch (err) {
75 > this._logService.warn(`[AgentHostLocalTurns] Failed to open database to persist local turn ${turn.id}`, err); agentHostLocalTurns.ts ×1
76 > return;
77 > }
78 > ref.object.insertLocalTurn(record).catch(err => { agentHostLocalTurns.ts ×2
79 this._logService.warn(`[AgentHostLocalTurns] Failed to persist local turn ${turn.id}`, err);
80 > }).finally(() => ref.dispose()); agentHostLocalTurns.ts ×2
83 > /**
84 > * Loads persisted local turns for `session`, populating the in-memory index
85 > * (keyed by each record's chat), and returns the records for `chat` in
86 > * `seq` order so the caller can interleave them into that chat's SDK-derived
87 > * turns during restore.
88 > */
89 > async loadForChat(session: string, chat: string): Promise<ILocalTurnRecord[]> {
90 > const records = await this._load(session); agentHostLocalTurns.ts ×5
91 > return records.filter(r => r.chatUri === chat);
92 > }
94 > /** Note a local turn in memory only (used by fork seeding). */
95 > noteInMemory(session: string, chat: string, turnId: string, anchorTurnId: string | undefined, seq: number): void {
96 this._noteInMemory(session, chat, turnId, anchorTurnId, seq);
97 }
99 > /** Delete the given local turns from memory and the session database. */
100 > deleteLocals(session: string, turnIds: readonly string[]): void {
101 > if (turnIds.length === 0) { agentHostLocalTurns.ts ×3
103 > }
104 > const idSet = new Set(turnIds); agentHostLocalTurns.ts ×3
105 > for (const map of this._byChat.values()) {
106 > for (const id of idSet) {
107 > map.delete(id);
108 > }
109 > }
110 > let ref: IReference<ISessionDatabase>;
111 > try {
112 > ref = this._sessionDataService.openDatabase(URI.parse(session));
113 > } catch (err) {
114 this._logService.warn(`[AgentHostLocalTurns] Failed to open database to delete local turns for ${session}`, err);
115 return;
116 }
117 > ref.object.deleteLocalTurns(turnIds).catch(err => { agentHostLocalTurns.ts ×3
118 this._logService.warn(`[AgentHostLocalTurns] Failed to delete local turns for ${session}`, err);
119 > }).finally(() => ref.dispose()); agentHostLocalTurns.ts ×3
122 > /** Drop all in-memory state for a chat. */
123 > forgetChat(chat: string): void {
124 this._byChat.delete(chat);
125 }
127 > private async _load(session: string): Promise<ILocalTurnRecord[]> {
128 > const ref = this._sessionDataService.tryOpenDatabase?.(URI.parse(session)); agentHostLocalTurns.ts ×5
129 > if (!ref) {
130 return [];
131 }
133 > const db = await ref;
134 > if (!db) {
135 > return []; agentService.ts ×3
136 > }
138 > const records = await db.object.getLocalTurns();
139 > for (const r of records) {
140 > this._noteInMemory(session, r.chatUri, r.turnId, r.anchorTurnId, r.seq); agentHostLocalTurns.ts ×1
141 > }
142 > return records; agentHostLocalTurns.ts ×2
143 > } finally {
144 > db.dispose();
145 > }
146 > } catch (err) { agentHostLocalTurns.ts ×5
147 this._logService.warn(`[AgentHostLocalTurns] Failed to load local turns for ${session}`, err);
148 return [];
149 }
152 > private _noteInMemory(session: string, chat: string, turnId: string, anchorTurnId: string | undefined, seq: number): void {
153 > let map = this._byChat.get(chat); agentHostLocalTurns.ts ×1
154 > if (!map) {
155 > map = new Map();
156 > this._byChat.set(chat, map);
157 > }
158 > map.set(turnId, { anchorTurnId, seq });
159 > this._seqBySession.set(session, Math.max(this._seqBySession.get(session) ?? 0, seq));
160 > }