src/vs/platform/agentHost/node/shared/fileEditTracker.ts

239 LOC · 228 covered · 11 uncovered · 39 ranges · 2243 concepts · 13 introducers · 1043 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 > /*--------------------------------------------------------------------------------------------- fileEditTracker.ts ×9
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 { decodeHex, encodeHex, VSBuffer } from '../../../../base/common/buffer.js';
7 > import { basename } from '../../../../base/common/path.js';
8 > import { URI } from '../../../../base/common/uri.js';
9 > import { IFileService } from '../../../files/common/files.js';
10 > import { ILogService } from '../../../log/common/log.js';
11 > import { IDiffComputeService } from '../../common/diffComputeService.js';
12 > import { ISessionDatabase } from '../../common/sessionDataService.js';
13 > import { FileEditKind, ToolResultContentType, type ToolResultFileEditContent } from '../../common/state/sessionState.js';
14 > import { extractAiChunks } from './editChunkExtractor.js';
15 > import { IEditSurvivalReporterFactory } from './editSurvivalReporter.js';
16 >
17 > const SESSION_DB_SCHEME = 'session-db';
18 >
19 > /**
20 > * Builds a `session-db:` URI that references a file-edit content blob
21 > * stored in the session database. Parsed by {@link parseSessionDbUri}.
22 > */
23 > export function buildSessionDbUri(sessionUri: string, toolCallId: string, filePath: string, part: 'before' | 'after'): string {
24 > return URI.from({ fileEditTracker.ts ×1
25 > scheme: SESSION_DB_SCHEME,
26 > authority: encodeHex(VSBuffer.fromString(sessionUri)).toString(),
27 > path: `/${encodeURIComponent(toolCallId)}/${encodeHex(VSBuffer.fromString(filePath))}/${part}/${basename(filePath)}`,
28 > }).toString();
29 > }
31 > /** Parsed fields from a `session-db:` content URI. */
32 > export interface ISessionDbUriFields {
33 > sessionUri: string;
34 > toolCallId: string;
35 > filePath: string;
36 > part: 'before' | 'after';
37 > }
38 >
39 > /**
40 > * Parses a `session-db:` URI produced by {@link buildSessionDbUri}.
41 > * Returns `undefined` if the URI is not a valid `session-db:` URI.
42 > */
43 > export function parseSessionDbUri(raw: string): ISessionDbUriFields | undefined {
44 > const parsed = URI.parse(raw); fileEditTracker.ts ×3
45 > if (parsed.scheme !== SESSION_DB_SCHEME) {
46 > return undefined; fileEditTracker.ts ×1
47 > }
48 > const [, toolCallId, filePath, part] = parsed.path.split('/'); fileEditTracker.ts ×1
49 > if (!toolCallId || !filePath || (part !== 'before' && part !== 'after')) { fileEditTracker.ts ×3
50 > return undefined; fileEditTracker.ts ×1
51 > }
53 > return {
54 > sessionUri: decodeHex(parsed.authority).toString(),
55 > toolCallId: decodeURIComponent(toolCallId),
56 > filePath: decodeHex(filePath).toString(),
57 > part
58 > };
59 > } catch {
60 return undefined;
61 }
64 > /**
65 > * Tracks file edits made by tools in a session by snapshotting file content
66 > * before and after each edit tool invocation, persisting snapshots into the
67 > * session database.
68 > */
69 > export class FileEditTracker {
70 >
71 > /**
72 > * Pending edits keyed by file path. Populated by {@link trackEditStart}
73 > * before the edit tool runs; popped by {@link completeEdit} when it
74 > * finishes.
75 > */
76 > private readonly _pendingEdits = new Map<string, { beforeContent: VSBuffer; beforeExisted: boolean; snapshotDone: Promise<void> }>();
77 >
78 > /**
79 > * Completed edits keyed by file path. Populated by {@link completeEdit};
80 > * drained by {@link takeCompletedEdit}, which persists the entry to
81 > * the database.
82 > */
83 > private readonly _completedEdits = new Map<string, { beforeContent: VSBuffer; beforeExisted: boolean; afterContent: VSBuffer }>();
84 >
85 > constructor(
86 > private readonly _sessionUri: string, fileEditTracker.ts ×1
87 > private readonly _db: ISessionDatabase,
88 > @IFileService private readonly _fileService: IFileService,
89 > @ILogService private readonly _logService: ILogService,
90 > @IDiffComputeService private readonly _diffComputeService: IDiffComputeService,
91 > @IEditSurvivalReporterFactory private readonly _editSurvivalReporterFactory: IEditSurvivalReporterFactory,
92 > ) { }
94 > /**
95 > * Call before an edit tool runs. Reads the file's current content
96 > * into memory as the "before" state. Callers should await this so
97 > * the snapshot captures pre-edit content before the tool writes to
98 > * disk.
99 > *
100 > * @param filePath - Absolute path of the file being edited.
101 > */
102 > async trackEditStart(filePath: string): Promise<void> {
103 > const snapshotDone = this._readFileWithExistence(filePath); fileEditTracker.ts ×13
104 > const entry = {
105 > beforeContent: VSBuffer.fromString(''),
106 > beforeExisted: false,
107 > snapshotDone: snapshotDone.then(({ content, existed }) => {
108 > entry.beforeContent = content;
109 > entry.beforeExisted = existed;
110 > }),
111 > };
112 > this._pendingEdits.set(filePath, entry);
113 > await entry.snapshotDone;
114 > }
116 > /**
117 > * Call after an edit tool finishes. Reads the file content again as
118 > * the "after" state and stores the result for later retrieval via
119 > * {@link takeCompletedEdit}.
120 > *
121 > * @param filePath - Absolute path of the file that was edited.
122 > */
123 > async completeEdit(filePath: string): Promise<void> {
124 > const pending = this._pendingEdits.get(filePath); fileEditTracker.ts ×13
125 > if (!pending) {
126 return;
127 }
128 > this._pendingEdits.delete(filePath); fileEditTracker.ts ×13
129 > await pending.snapshotDone;
130 >
131 > const afterContent = await this._readFile(filePath);
132 >
133 > this._completedEdits.set(filePath, {
134 > beforeContent: pending.beforeContent,
135 > beforeExisted: pending.beforeExisted,
136 > afterContent,
137 > });
138 > }
140 > /**
141 > * Retrieves and removes a completed edit for the given file path,
142 > * persists it to the session database with computed diff counts,
143 > * and returns the result as an {@link ToolResultFileEditContent}
144 > * for inclusion in the tool result.
145 > *
146 > * `toolName` and `toolInput` are forwarded to {@link extractAiChunks}
147 > * for region-based survival scoring; unknown shapes fall back to
148 > * whole-file scoring.
149 > */
150 > async takeCompletedEdit(turnId: string, toolCallId: string, filePath: string, toolName: string, toolInput: unknown, modelId: string | undefined): Promise<ToolResultFileEditContent | undefined> {
151 > const edit = this._completedEdits.get(filePath); fileEditTracker.ts ×5
152 > if (!edit) {
153 > return undefined; fileEditTracker.ts ×1
154 > }
155 > this._completedEdits.delete(filePath); fileEditTracker.ts ×13
156 >
157 > if (!modelId) {
158 > this._logService.warn(`[FileEditTracker] No modelId for completed edit: ${filePath} (turn=${turnId}, toolCall=${toolCallId}, tool=${toolName || '<unknown>'}). Edit-survival telemetry will be emitted with an empty modelId.`);
159 > }
160 >
161 > const beforeBytes = edit.beforeContent.buffer;
162 > const afterBytes = edit.afterContent.buffer;
163 > const beforeText = edit.beforeContent.toString();
164 > const afterText = edit.afterContent.toString();
165 >
166 > const isCreate = !edit.beforeExisted && afterBytes.length > 0;
168 > let addedLines: number | undefined;
169 > let removedLines: number | undefined;
170 > try {
171 > const counts = await this._diffComputeService.computeDiffCounts(beforeText, afterText);
172 > addedLines = counts.added; fileEditTracker.ts ×13
173 > removedLines = isCreate ? 0 : counts.removed; fileEditTracker.ts ×5
174 > } catch (err) {
175 this._logService.warn(`[FileEditTracker] Failed to compute diff counts: ${filePath}`, err);
176 }
178 > try {
179 > await this._db.storeFileEdit({
180 > turnId,
181 > toolCallId,
182 > filePath,
183 > kind: isCreate ? FileEditKind.Create : FileEditKind.Edit, fileEditTracker.ts ×5
184 > beforeContent: beforeBytes,
185 > afterContent: afterBytes,
186 > addedLines,
187 > removedLines,
188 > });
189 > } catch (err) { fileEditTracker.ts ×13
190 this._logService.warn(`[FileEditTracker] Failed to persist file edit to database: ${filePath}`, err);
191 }
193 > this._editSurvivalReporterFactory.launch({
194 > sessionUri: this._sessionUri,
195 > turnId,
196 > toolCallId,
197 > filePath,
198 > beforeText,
199 > afterText,
200 > isCreate,
201 > modelId,
202 > toolName,
203 > aiChunks: extractAiChunks(toolName, toolInput, filePath),
204 > });
205 >
206 > return {
207 > type: ToolResultContentType.FileEdit,
208 > before: {
209 > uri: URI.file(filePath).toString(),
210 > content: { uri: buildSessionDbUri(this._sessionUri, toolCallId, filePath, 'before') },
211 > },
212 > after: {
213 > uri: URI.file(filePath).toString(),
214 > content: { uri: buildSessionDbUri(this._sessionUri, toolCallId, filePath, 'after') },
215 > },
216 > diff: addedLines !== undefined ? { added: addedLines, removed: removedLines } : undefined, fileEditTracker.ts ×5
217 > };
218 > }
220 > private async _readFile(filePath: string): Promise<VSBuffer> {
222 > const content = await this._fileService.readFile(URI.file(filePath));
223 > return content.value;
224 > } catch (err) {
225 this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${filePath}`, err);
226 return VSBuffer.fromString('');
227 }
230 > private async _readFileWithExistence(filePath: string): Promise<{ content: VSBuffer; existed: boolean }> {
232 > const content = await this._fileService.readFile(URI.file(filePath));
233 > return { content: content.value, existed: true }; fileEditTracker.ts ×1
234 > } catch (err) { fileEditTracker.ts ×13
235 > this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${filePath}`, err); fileEditTracker.ts ×1
236 > return { content: VSBuffer.fromString(''), existed: false };
237 > }