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.
/*---------------------------------------------------------------------------------------------
fileEditTracker.ts ×9
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { decodeHex, encodeHex, VSBuffer } from '../../../../base/common/buffer.js';
import { basename } from '../../../../base/common/path.js';
import { URI } from '../../../../base/common/uri.js';
import { IFileService } from '../../../files/common/files.js';
import { ILogService } from '../../../log/common/log.js';
import { IDiffComputeService } from '../../common/diffComputeService.js';
import { ISessionDatabase } from '../../common/sessionDataService.js';
import { FileEditKind, ToolResultContentType, type ToolResultFileEditContent } from '../../common/state/sessionState.js';
import { extractAiChunks } from './editChunkExtractor.js';
import { IEditSurvivalReporterFactory } from './editSurvivalReporter.js';
const SESSION_DB_SCHEME = 'session-db';
/**
* Builds a `session-db:` URI that references a file-edit content blob
* stored in the session database. Parsed by {@link parseSessionDbUri}.
*/
export function buildSessionDbUri(sessionUri: string, toolCallId: string, filePath: string, part: 'before' | 'after'): string {
scheme: SESSION_DB_SCHEME,
authority: encodeHex(VSBuffer.fromString(sessionUri)).toString(),
path: `/${encodeURIComponent(toolCallId)}/${encodeHex(VSBuffer.fromString(filePath))}/${part}/${basename(filePath)}`,
}).toString();
}
/** Parsed fields from a `session-db:` content URI. */
export interface ISessionDbUriFields {
sessionUri: string;
toolCallId: string;
filePath: string;
part: 'before' | 'after';
}
/**
* Parses a `session-db:` URI produced by {@link buildSessionDbUri}.
* Returns `undefined` if the URI is not a valid `session-db:` URI.
*/
export function parseSessionDbUri(raw: string): ISessionDbUriFields | undefined {
if (parsed.scheme !== SESSION_DB_SCHEME) {
}
if (!toolCallId || !filePath || (part !== 'before' && part !== 'after')) {
fileEditTracker.ts ×3
}
return {
sessionUri: decodeHex(parsed.authority).toString(),
toolCallId: decodeURIComponent(toolCallId),
filePath: decodeHex(filePath).toString(),
part
};
} catch {
return undefined;
}
/**
* Tracks file edits made by tools in a session by snapshotting file content
* before and after each edit tool invocation, persisting snapshots into the
* session database.
*/
export class FileEditTracker {
/**
* Pending edits keyed by file path. Populated by {@link trackEditStart}
* before the edit tool runs; popped by {@link completeEdit} when it
* finishes.
*/
private readonly _pendingEdits = new Map<string, { beforeContent: VSBuffer; beforeExisted: boolean; snapshotDone: Promise<void> }>();
/**
* Completed edits keyed by file path. Populated by {@link completeEdit};
* drained by {@link takeCompletedEdit}, which persists the entry to
* the database.
*/
private readonly _completedEdits = new Map<string, { beforeContent: VSBuffer; beforeExisted: boolean; afterContent: VSBuffer }>();
constructor(
private readonly _db: ISessionDatabase,
@IFileService private readonly _fileService: IFileService,
@ILogService private readonly _logService: ILogService,
@IDiffComputeService private readonly _diffComputeService: IDiffComputeService,
@IEditSurvivalReporterFactory private readonly _editSurvivalReporterFactory: IEditSurvivalReporterFactory,
) { }
/**
* Call before an edit tool runs. Reads the file's current content
* into memory as the "before" state. Callers should await this so
* the snapshot captures pre-edit content before the tool writes to
* disk.
*
* @param filePath - Absolute path of the file being edited.
*/
async trackEditStart(filePath: string): Promise<void> {
const entry = {
beforeContent: VSBuffer.fromString(''),
beforeExisted: false,
snapshotDone: snapshotDone.then(({ content, existed }) => {
entry.beforeContent = content;
entry.beforeExisted = existed;
}),
};
this._pendingEdits.set(filePath, entry);
await entry.snapshotDone;
}
/**
* Call after an edit tool finishes. Reads the file content again as
* the "after" state and stores the result for later retrieval via
* {@link takeCompletedEdit}.
*
* @param filePath - Absolute path of the file that was edited.
*/
async completeEdit(filePath: string): Promise<void> {
if (!pending) {
return;
}
await pending.snapshotDone;
const afterContent = await this._readFile(filePath);
this._completedEdits.set(filePath, {
beforeContent: pending.beforeContent,
beforeExisted: pending.beforeExisted,
afterContent,
});
}
/**
* Retrieves and removes a completed edit for the given file path,
* persists it to the session database with computed diff counts,
* and returns the result as an {@link ToolResultFileEditContent}
* for inclusion in the tool result.
*
* `toolName` and `toolInput` are forwarded to {@link extractAiChunks}
* for region-based survival scoring; unknown shapes fall back to
* whole-file scoring.
*/
async takeCompletedEdit(turnId: string, toolCallId: string, filePath: string, toolName: string, toolInput: unknown, modelId: string | undefined): Promise<ToolResultFileEditContent | undefined> {
if (!edit) {
}
if (!modelId) {
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.`);
}
const beforeBytes = edit.beforeContent.buffer;
const afterBytes = edit.afterContent.buffer;
const beforeText = edit.beforeContent.toString();
const afterText = edit.afterContent.toString();
const isCreate = !edit.beforeExisted && afterBytes.length > 0;
let addedLines: number | undefined;
let removedLines: number | undefined;
try {
const counts = await this._diffComputeService.computeDiffCounts(beforeText, afterText);
} catch (err) {
this._logService.warn(`[FileEditTracker] Failed to compute diff counts: ${filePath}`, err);
}
try {
await this._db.storeFileEdit({
turnId,
toolCallId,
filePath,
beforeContent: beforeBytes,
afterContent: afterBytes,
addedLines,
removedLines,
});
this._logService.warn(`[FileEditTracker] Failed to persist file edit to database: ${filePath}`, err);
}
this._editSurvivalReporterFactory.launch({
sessionUri: this._sessionUri,
turnId,
toolCallId,
filePath,
beforeText,
afterText,
isCreate,
modelId,
toolName,
aiChunks: extractAiChunks(toolName, toolInput, filePath),
});
return {
type: ToolResultContentType.FileEdit,
before: {
uri: URI.file(filePath).toString(),
content: { uri: buildSessionDbUri(this._sessionUri, toolCallId, filePath, 'before') },
},
after: {
uri: URI.file(filePath).toString(),
content: { uri: buildSessionDbUri(this._sessionUri, toolCallId, filePath, 'after') },
},
diff: addedLines !== undefined ? { added: addedLines, removed: removedLines } : undefined,
fileEditTracker.ts ×5
};
}
private async _readFile(filePath: string): Promise<VSBuffer> {
const content = await this._fileService.readFile(URI.file(filePath));
return content.value;
} catch (err) {
this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${filePath}`, err);
return VSBuffer.fromString('');
}
private async _readFileWithExistence(filePath: string): Promise<{ content: VSBuffer; existed: boolean }> {
const content = await this._fileService.readFile(URI.file(filePath));
this._logService.trace(`[FileEditTracker] Could not read file for snapshot: ${filePath}`, err);
fileEditTracker.ts ×1
return { content: VSBuffer.fromString(''), existed: false };
}