src/vs/platform/agentHost/test/common/sessionTestHelpers.ts

316 LOC · 264 covered · 52 uncovered · 63 ranges · 2241 concepts · 27 introducers · 1009 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 > /*--------------------------------------------------------------------------------------------- sessionTestHelpers.ts ×33
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 { Schemas } from '../../../../base/common/network.js';
8 > import { URI } from '../../../../base/common/uri.js';
9 > import { Event } from '../../../../base/common/event.js';
10 > import type { IDiffComputeService, IDiffCountResult } from '../../common/diffComputeService.js';
11 > import type { IFileEditContent, IFileEditRecord, ILocalTurnRecord, IReviewedFileRecord, ISessionDatabase, ISessionDataService } from '../../common/sessionDataService.js';
12 > import type { Message } from '../../common/state/sessionState.js';
13 >
14 > export class TestSessionDatabase implements ISessionDatabase {
15 > private readonly _edits: (IFileEditRecord & IFileEditContent)[] = []; sessionTestHelpers.ts ×1
16 > private readonly _metadata = new Map<string, string>();
17 > private readonly _drafts = new Map<string, Message>();
18 > private readonly _reviewedFiles: IReviewedFileRecord[] = [];
19 > private readonly _localTurns = new Map<string, ILocalTurnRecord>();
20 >
21 > getAllFileEditsCalls = 0;
22 > getFileEditsByTurnCalls = 0;
23 > deleteTurnsAfterCalls: string[] = [];
24 > deleteAllTurnsCalls = 0;
25 > setTurnEventIdCalls: Array<{ turnId: string; eventId: string }> = [];
27 > addEdit(edit: IFileEditRecord & IFileEditContent): void {
28 > this._edits.push(edit); sessionTestHelpers.ts ×2
29 > }
31 > async createTurn(): Promise<void> { }
32 >
33 > async deleteTurn(turnId: string): Promise<void> {
34 for (let i = this._edits.length - 1; i >= 0; i--) {
35 if (this._edits[i].turnId === turnId) {
36 this._edits.splice(i, 1);
37 }
38 }
39 }
41 > async storeFileEdit(edit: IFileEditRecord & IFileEditContent): Promise<void> {
42 > const existingIndex = this._edits.findIndex(e => e.toolCallId === edit.toolCallId && e.filePath === edit.filePath); claudeFileEditObserver.ts ×2
43 > if (existingIndex >= 0) {
44 this._edits[existingIndex] = edit;
46 > this._edits.push(edit);
47 > }
48 > }
50 > async getFileEdits(toolCallIds: string[]): Promise<IFileEditRecord[]> {
51 const toolCallIdsSet = new Set(toolCallIds);
52 return this._toEditRecords(this._edits.filter(e => toolCallIdsSet.has(e.toolCallId)));
53 }
55 > async getAllFileEdits(): Promise<IFileEditRecord[]> {
56 > this.getAllFileEditsCalls++; sessionTestHelpers.ts ×1
57 > return this._toEditRecords(this._edits);
58 > }
60 > async getFileEditsByTurn(turnId: string): Promise<IFileEditRecord[]> {
61 > this.getFileEditsByTurnCalls++; sessionDiffAggregator.ts ×1
62 > return this._toEditRecords(this._edits.filter(e => e.turnId === turnId));
63 > }
65 > async readFileEditContent(toolCallId: string, filePath: string): Promise<IFileEditContent | undefined> {
66 > return this._edits.find(e => e.toolCallId === toolCallId && e.filePath === filePath); sessionTestHelpers.ts ×1
67 > }
69 > async getMetadata(key: string): Promise<string | undefined> {
70 > return this._metadata.get(key); sessionTestHelpers.ts ×1
71 > }
73 > async getMetadataObject<T extends Record<string, unknown>>(obj: T): Promise<{ [K in keyof T]: string | undefined }> {
74 > return Object.fromEntries(Object.keys(obj).map(key => [key, this._metadata.get(key)])) as { [K in keyof T]: string | undefined }; sessionTestHelpers.ts ×1
75 > }
77 > async setMetadata(key: string, value: string): Promise<void> {
78 > this._metadata.set(key, value); sessionTestHelpers.ts ×1
79 > }
81 > async setChatDraft(chat: URI, draft: Message | undefined): Promise<void> {
82 > const key = chat.toString(); sessionTestHelpers.ts ×2
83 > if (draft) {
84 > this._drafts.set(key, draft);
85 > } else {
86 this._drafts.delete(key);
87 }
90 > async getChatDraft(chat: URI): Promise<Message | undefined> {
91 > return this._drafts.get(chat.toString()); sessionTestHelpers.ts ×1
92 > }
94 > async close(): Promise<void> { }
95 >
96 > async vacuumInto(_targetPath: string): Promise<void> { }
97 >
98 > dispose(): void { }
99 >
100 > async setTurnEventId(turnId: string, eventId: string): Promise<void> {
101 > this.setTurnEventIdCalls.push({ turnId, eventId }); copilotAgentSession.ts ×3
102 > }
104 > async getTurnEventId(_turnId: string): Promise<string | undefined> { return undefined; }
105 >
106 > async getNextTurnEventId(_turnId: string): Promise<string | undefined> { return undefined; }
107 >
108 > async getFirstTurnEventId(): Promise<string | undefined> { return undefined; }
109 >
110 > async truncateFromTurn(_turnId: string): Promise<void> { }
111 >
112 > async deleteTurnsAfter(turnId: string): Promise<void> {
113 > this.deleteTurnsAfterCalls.push(turnId); claudeAgentSession.ts ×1
114 > }
116 > async deleteAllTurns(): Promise<void> {
117 > this.deleteAllTurnsCalls++; claudeAgentSession.ts ×1
118 > this._edits.length = 0;
119 > }
121 > async insertLocalTurn(record: ILocalTurnRecord): Promise<void> {
122 > this._localTurns.set(record.turnId, record); sessionTestHelpers.ts ×1
123 > }
125 > async getLocalTurns(): Promise<ILocalTurnRecord[]> {
126 > return [...this._localTurns.values()].sort((a, b) => a.seq - b.seq); sessionTestHelpers.ts ×1
127 > }
129 > async deleteLocalTurns(turnIds: readonly string[]): Promise<void> {
130 > for (const id of turnIds) { agentHostLocalTurns.ts ×3
131 > this._localTurns.delete(id);
132 > }
133 > }
134 > async remapTurnIds(_mapping: ReadonlyMap<string, string>): Promise<void> { } sessionTestHelpers.ts ×33
135 >
136 > async markFileReviewed(uri: URI, nonce: string): Promise<void> {
137 if (!this._reviewedFiles.some(r => r.uri.toString() === uri.toString() && r.nonce === nonce)) {
138 this._reviewedFiles.push({ uri, nonce });
139 }
140 }
142 > async unmarkFileReviewed(uri: URI, nonce: string): Promise<void> {
143 const index = this._reviewedFiles.findIndex(r => r.uri.toString() === uri.toString() && r.nonce === nonce);
144 if (index >= 0) {
145 this._reviewedFiles.splice(index, 1);
146 }
147 }
149 > async getReviewedFiles(): Promise<IReviewedFileRecord[]> {
150 return [...this._reviewedFiles];
151 }
153 > async getReviewedFilesForUri(uri: URI): Promise<IReviewedFileRecord[]> {
154 return this._reviewedFiles.filter(r => r.uri.toString() === uri.toString());
155 }
157 > async isFileReviewed(uri: URI, nonce: string): Promise<boolean> {
158 return this._reviewedFiles.some(r => r.uri.toString() === uri.toString() && r.nonce === nonce);
159 }
161 > async setTurnCheckpointRef(_turnId: string, _ref: string): Promise<void> { }
162 >
163 > async getTurnCheckpointRef(_turnId: string): Promise<string | undefined> { return undefined; }
164 >
165 > async getPreviousCheckpointRef(_turnId: string): Promise<string | undefined> { return undefined; }
166 >
167 > async getAllCheckpointRefs(): Promise<string[]> { return []; }
168 >
169 > async whenIdle(): Promise<void> { }
170 >
171 > private _toEditRecords(edits: (IFileEditRecord & IFileEditContent)[]): IFileEditRecord[] {
172 > return edits.map(({ beforeContent: _, afterContent: _2, ...metadata }) => metadata); sessionTestHelpers.ts ×1
173 > }
175 >
176 > export class TestDiffComputeService implements IDiffComputeService {
177 > declare readonly _serviceBrand: undefined;
178 >
179 > callCount = 0;
180 >
181 > constructor(private readonly _result?: IDiffCountResult) { }
182 >
183 > async computeDiffCounts(original: string, modified: string): Promise<IDiffCountResult> {
184 > this.callCount++; sessionTestHelpers.ts ×2
185 > if (this._result) {
186 > return this._result; fileEditTracker.ts ×13
187 > }
189 > const originalLines = original ? original.split('\n') : []; sessionTestHelpers.ts ×2
190 > const modifiedLines = modified ? modified.split('\n') : [];
191 > return {
192 > added: Math.max(0, modifiedLines.length - originalLines.length),
193 > removed: Math.max(0, originalLines.length - modifiedLines.length),
194 > };
195 > }
197 >
198 > export function createZeroDiffComputeService(): IDiffComputeService {
199 > return new TestDiffComputeService({ added: 0, removed: 0 }); sessionTestHelpers.ts ×1
200 > }
202 > export function createSessionDataService(database: ISessionDatabase = new TestSessionDatabase()): ISessionDataService {
203 > return { sessionTestHelpers.ts ×1
204 > _serviceBrand: undefined,
205 > getSessionDataDir: session => URI.from({ scheme: Schemas.inMemory, path: `/session-data${session.path}` }),
206 > getSessionDataDirById: sessionId => URI.from({ scheme: Schemas.inMemory, path: `/session-data/${sessionId}` }),
207 > openDatabase: () => createReference(database),
208 > tryOpenDatabase: async () => createReference(database),
209 > deleteSessionData: async () => { },
210 > onWillDeleteSessionData: Event.None,
211 > cleanupOrphanedData: async () => { },
212 > whenIdle: async () => { },
213 > };
214 > }
216 > export function createNullSessionDataService(): ISessionDataService {
217 > return { sessionTestHelpers.ts ×1
218 > _serviceBrand: undefined,
219 > getSessionDataDir: session => URI.from({ scheme: Schemas.inMemory, path: `/session-data${session.path}` }),
220 > getSessionDataDirById: sessionId => URI.from({ scheme: Schemas.inMemory, path: `/session-data/${sessionId}` }),
221 > openDatabase: () => { throw new Error('not implemented'); },
222 > tryOpenDatabase: async () => undefined,
223 > deleteSessionData: async () => { },
224 > onWillDeleteSessionData: Event.None,
225 > cleanupOrphanedData: async () => { },
226 > whenIdle: async () => { },
227 > };
228 > }
230 > export function encodeString(text: string): Uint8Array {
231 > return new TextEncoder().encode(text); sessionTestHelpers.ts ×2
232 > }
234 > /**
235 > * Returns a no-op {@link IAgentHostGitService} suitable for tests that
236 > * exercise the {@link AgentService} but don't care about git state.
237 > * Tests that DO care about git state should pass their own implementation.
238 > */
239 > export function createNoopGitService(): import('../../common/agentHostGitService.js').IAgentHostGitService {
240 > return { sessionTestHelpers.ts ×1
241 > _serviceBrand: undefined,
242 > getCurrentBranch: async () => undefined,
243 > getDefaultBranch: async () => undefined,
244 > getBranch: async () => undefined,
245 > getRefs: async () => [],
246 > getBranches: async () => [],
247 > getRepositoryRoot: async () => undefined,
248 > getWorktreeRoots: async () => [],
249 > addWorktree: async () => { },
250 > copyWorktreeIncludeFiles: async () => { },
251 > addExistingWorktree: async () => { },
252 > removeWorktree: async () => { },
253 > branchExists: async () => false,
254 > hasUncommittedChanges: async () => false,
255 > commitAll: async () => { },
256 > restore: async () => { },
257 > hasUpstream: async () => false,
258 > pull: async () => { },
259 > push: async () => { },
260 > getSessionGitState: async () => undefined,
261 > computeSessionFileDiffs: async () => undefined,
262 > resolveBranchBaselineCommit: async () => undefined,
263 > showBlob: async () => undefined,
264 > captureWorkingTreeAsTree: async () => undefined,
265 > commitTree: async () => undefined,
266 > updateRef: async () => { },
267 > deleteRefs: async () => { },
268 > revParse: async () => undefined,
269 > overlayPathIntoTree: async () => undefined,
270 > diffTreePaths: async () => undefined,
271 > computeFileDiffsBetweenRefs: async () => undefined,
272 > getFetchRemoteUrls: async () => undefined,
273 > getUntrackedPaths: async () => [],
274 > getBranchDiffSafetyInfo: async () => undefined,
275 > getDiffPatchBetweenRefs: async () => undefined,
276 > };
277 > }
279 > /**
280 > * Returns a no-op {@link IAgentHostChangesetService} for tests that need to
281 > * inject the changeset service but don't exercise changeset computation.
282 > * Individual methods can be reassigned by callers that want to spy on them.
283 > */
284 > export function createNoopChangesetService(): import('../../common/agentHostChangesetService.js').IAgentHostChangesetService {
285 return {
286 _serviceBrand: undefined,
287 registerStaticChangesets: () => { },
288 restoreStaticChangeset: () => { },
289 parsePersistedStaticChangesets: () => ({}),
290 applyPersistedStaticChangesets: () => { },
291 restorePersistedStaticChangesets: () => ({}),
292 persistChangesSummary: () => { },
293 getListMetadataKeys: () => undefined,
294 computeListEntryChanges: () => undefined,
295 isStaticChangesetComputeActive: () => false,
296 refreshChangesetCatalog: () => { },
297 refreshBranchChangeset: () => { },
298 refreshSessionChangeset: () => { },
299 onWorkingDirectoryAvailable: () => { },
300 recomputeSubscribedChangesets: () => { },
301 onSessionDisposed: () => { },
302 computeTurnChangeset: async session => session,
303 computeCompareTurnsChangeset: async session => session,
304 computeUncommittedChangeset: async session => session,
305 onToolCallEditsApplied: () => { },
306 onTurnComplete: () => { },
307 onSessionTruncated: () => { },
308 };
309 }
311 > function createReference<T>(object: T): IReference<T> { sessionTestHelpers.ts ×1
312 > return {
313 > object,
314 > dispose: () => { },
315 > };
316 > }