src/vs/platform/agentHost/node/claude/claudeFileEditObserver.ts

142 LOC · 138 covered · 4 uncovered · 23 ranges · 422 concepts · 13 introducers · 225 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 > /*--------------------------------------------------------------------------------------------- claudeFileEditObserver.ts ×4
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 { SDKMessage } from '@anthropic-ai/claude-agent-sdk';
7 > import { Disposable, IReference } from '../../../../base/common/lifecycle.js';
8 > import { IInstantiationService } from '../../../instantiation/common/instantiation.js';
9 > import { ILogService } from '../../../log/common/log.js';
10 > import { ISessionDatabase } from '../../common/sessionDataService.js';
11 > import { FileEditTracker } from '../shared/fileEditTracker.js';
12 > import type { ClaudeMapperState } from './claudeMapSessionEvents.js';
13 > import { getClaudeToolPath, isClaudeFileEditTool } from './claudeToolDisplay.js';
14 >
15 > /**
16 > * Phase 8 — file-edit observation off the SDK message stream.
17 > *
18 > * Owns the {@link FileEditTracker}, the in-flight `tool_use_id → path`
19 > * map, and the dbRef whose lifetime gates persistence writes. Snapshots
20 > * before-content when an assistant `tool_use` block arrives, snapshots
21 > * after-content when the matching synthetic `tool_result` arrives, and
22 > * stages a {@link ToolResultFileEditContent} on the session's
23 > * {@link ClaudeMapperState} so the synchronous mapper can attach it to
24 > * the `ChatToolCallComplete` action.
25 > *
26 > * Hooks (`Options.hooks.PreToolUse` / `Options.hooks.PostToolUse`) are
27 > * deliberately NOT used: they are user-bypassable via settings, whereas
28 > * the SDK message stream is the canonical, non-bypassable signal that
29 > * a tool will run. Mirrors the production extension's dispatch-time
30 > * observation (extensions/copilot/.../claudeMessageDispatch.ts:200) —
31 > * see the comment there about `bypassPermissions` and internal SDK
32 > * paths that skip `canUseTool`.
33 > *
34 > * Best-effort: the SDK proceeds to run the tool concurrently after
35 > * yielding the `tool_use` block, so {@link observeAssistant}'s before-
36 > * snapshot races against tool execution. Tool execution involves disk
37 > * I/O before the write, which gives enough microtask headroom in
38 > * practice; same guarantee the production extension relies on with
39 > * `stream.externalEdit`.
40 > */
41 > export class ClaudeFileEditObserver extends Disposable {
42 >
43 > private readonly _editTracker: FileEditTracker;
44 >
45 > /**
46 > * Maps SDK `tool_use_id` → file path + raw tool input + model
47 > * captured when the SDK yields the assistant `tool_use` block in
48 > * {@link observeAssistant}. Consumed (and removed) by
49 > * {@link observeUser} when the matching `tool_result` arrives.
50 > * The raw input is forwarded to
51 > * {@link FileEditTracker.takeCompletedEdit} so it can extract the
52 > * AI-written text chunks for the edit-survival reporter. The
53 > * model is read off the assistant message body and is naturally
54 > * per-subagent: when a subagent emits the `tool_use`, its model
55 > * (not the parent's) is what we record.
56 > */
57 > private readonly _editToolPaths = new Map<string, { readonly filePath: string; readonly toolName: string; readonly toolInput: unknown; readonly modelId: string | undefined }>();
58 >
59 > constructor(
60 > sessionUri: string, claudeFileEditObserver.ts ×1
61 > dbRef: IReference<ISessionDatabase>,
62 > @ILogService private readonly _logService: ILogService,
63 > @IInstantiationService instantiationService: IInstantiationService,
64 > ) {
65 > super();
66 > // Own the DB reference for this observer's lifetime so
67 > // {@link FileEditTracker.takeCompletedEdit}'s `storeFileEdit` write
68 > // has a live database. Disposed first — ahead of any owning
69 > // session's WarmQuery abort — so any in-flight write completes
70 > // against an open DB.
71 > this._register(dbRef);
72 > this._editTracker = instantiationService.createInstance(
73 > FileEditTracker,
74 > sessionUri,
75 > dbRef.object,
76 > );
77 > }
79 > /**
80 > * Snapshot before-content for any file-edit `tool_use` blocks
81 > * carried by an SDK assistant message. Caller must invoke this when
82 > * the SDK yields a canonical `'assistant'` message (full
83 > * `tool_use.input` available).
84 > */
85 > observeAssistant(message: Extract<SDKMessage, { type: 'assistant' }>): void {
86 > const content = message.message.content; claudeFileEditObserver.ts ×3
87 > if (!Array.isArray(content)) {
89 > }
90 > const modelId = typeof message.message.model === 'string' ? message.message.model : undefined; claudeFileEditObserver.ts ×3
91 > for (const block of content) {
92 > if (block.type !== 'tool_use' || !isClaudeFileEditTool(block.name)) { claudeFileEditObserver.ts ×1
94 > }
95 > const filePath = getClaudeToolPath(block.name, block.input); claudeFileEditObserver.ts ×1
96 > if (!filePath) {
98 > }
99 > this._editToolPaths.set(block.id, { filePath, toolName: block.name, toolInput: block.input, modelId }); claudeFileEditObserver.ts ×2
100 > void this._editTracker.trackEditStart(filePath).catch(err =>
101 > this._logService.warn(`[ClaudeFileEditObserver] trackEditStart failed for ${filePath}: ${err}`));
102 > }
105 > /**
106 > * Take after-content snapshots and stage
107 > * {@link ToolResultFileEditContent} entries on `mapperState` for any
108 > * `tool_result` blocks carried by an SDK user message. Caller MUST
109 > * await this BEFORE invoking the synchronous mapper, so the cached
110 > * file edit is already on `mapperState` when `mapUserMessage` calls
111 > * `state.takeFileEdit`.
112 > */
113 > async observeUser(
114 > message: Extract<SDKMessage, { type: 'user' }>, claudeFileEditObserver.ts ×2
115 > turnId: string,
116 > mapperState: ClaudeMapperState,
117 > ): Promise<void> {
118 > const content = message.message.content;
119 > if (!Array.isArray(content)) {
121 > }
122 > for (const block of content) { claudeFileEditObserver.ts ×4
123 > if (block.type !== 'tool_result') {
124 continue;
125 }
126 > const tracked = this._editToolPaths.get(block.tool_use_id); claudeFileEditObserver.ts ×4
127 > if (!tracked) {
129 > }
130 > this._editToolPaths.delete(block.tool_use_id); claudeFileEditObserver.ts ×2
131 > try {
132 > await this._editTracker.completeEdit(tracked.filePath);
133 > const fileEdit = await this._editTracker.takeCompletedEdit(turnId, block.tool_use_id, tracked.filePath, tracked.toolName, tracked.toolInput, tracked.modelId);
134 > if (fileEdit) {
135 > mapperState.cacheFileEdit(block.tool_use_id, fileEdit);
136 > }
137 > } catch (err) { claudeFileEditObserver.ts ×4
138 this._logService.warn(`[ClaudeFileEditObserver] file edit tracking failed for ${tracked.filePath}: ${err}`);
139 }