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

216 LOC · 162 covered · 54 uncovered · 40 ranges · 934 concepts · 9 introducers · 490 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 > /*--------------------------------------------------------------------------------------------- agentHostCommitOperationHandler.ts ×10
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 { basename } from '../../../base/common/resources.js';
7 > import { CancellationToken } from '../../../base/common/cancellation.js';
8 > import { URI } from '../../../base/common/uri.js';
9 > import { localize } from '../../../nls.js';
10 > import { IAgentService } from '../common/agentService.js';
11 > import { IAgentHostGitHubEndpointService } from './agentHostGitHubEndpointService.js';
12 > import { parseChangesetUri } from '../common/changesetUri.js';
13 > import { type IChangesetOperationHandler } from '../common/agentHostChangesetOperationService.js';
14 > import type { InvokeChangesetOperationParams, InvokeChangesetOperationResult } from '../common/state/protocol/channels-changeset/commands.js';
15 > import { AHP_AUTH_REQUIRED, AHP_SESSION_NOT_FOUND, JsonRpcErrorCodes, ProtocolError } from '../common/state/sessionProtocol.js';
16 > import { readSessionGitState, type ISessionFileDiff, type SessionState } from '../common/state/sessionState.js';
17 > import { ILogService } from '../../log/common/log.js';
18 > import { IAgentHostGitService } from '../common/agentHostGitService.js';
19 > import { CopilotApiError, ICopilotApiService } from './shared/copilotApiService.js';
20 >
21 > const MAX_CHANGE_SUMMARY_PROMPT_CHARS = 20_000;
22 >
23 > export class AgentHostCommitOperationHandler implements IChangesetOperationHandler {
24 >
25 > public static readonly OPERATION_COMMIT = 'commit';
26 >
27 > constructor(
28 > private readonly _getSessionState: (sessionKey: string) => SessionState | undefined, agentHostCommitOperationHandler.ts ×1
29 > private readonly _onCommitted: (sessionKey: string) => Promise<void>,
30 > @IAgentService private readonly _agentService: IAgentService,
31 > @IAgentHostGitHubEndpointService private readonly _gitHubEndpointService: IAgentHostGitHubEndpointService,
32 > @IAgentHostGitService private readonly _gitService: IAgentHostGitService,
33 > @ICopilotApiService private readonly _copilotApiService: ICopilotApiService,
34 > @ILogService private readonly _logService: ILogService,
35 > ) { }
37 > async invoke(params: InvokeChangesetOperationParams, token: CancellationToken): Promise<InvokeChangesetOperationResult> {
38 > const abortController = new AbortController(); agentHostCommitOperationHandler.ts ×9
39 > if (token.isCancellationRequested) {
40 > abortController.abort(); agentHostCommitOperationHandler.ts ×2
41 > }
42 > const cancellationListener = token.onCancellationRequested(() => abortController.abort()); agentHostCommitOperationHandler.ts ×9
43 > try {
44 > return await this._invoke(params, token, abortController.signal);
45 > } finally {
46 > cancellationListener.dispose();
47 > }
48 > }
50 > private async _invoke(params: InvokeChangesetOperationParams, token: CancellationToken, signal: AbortSignal): Promise<InvokeChangesetOperationResult> {
51 > const parsed = parseChangesetUri(params.channel); agentHostCommitOperationHandler.ts ×9
52 > if (!parsed) {
53 throw new ProtocolError(JsonRpcErrorCodes.InvalidParams, `Not an uncommitted changeset URI: ${params.channel}`);
54 }
55 > this._throwIfCancelled(token); agentHostCommitOperationHandler.ts ×9
56 >
57 > const sessionUri = parsed.sessionUri;
58 > const sessionState = this._getSessionState(sessionUri);
59 > if (!sessionState) {
60 throw new ProtocolError(AHP_SESSION_NOT_FOUND, `Session not found: ${sessionUri}`);
61 }
63 > const workingDirectoryStr = sessionState.workingDirectories?.[0];
64 > if (!workingDirectoryStr) { agentHostCommitOperationHandler.ts ×9
65 throw new ProtocolError(JsonRpcErrorCodes.InternalError, `Session has no working directory: ${sessionUri}`);
66 }
67 > const workingDirectory = URI.parse(workingDirectoryStr); agentHostCommitOperationHandler.ts ×3
68 >
69 > const gitState = readSessionGitState(sessionState._meta);
70 > if (!gitState) {
71 throw new ProtocolError(JsonRpcErrorCodes.InternalError, `Session's working directory is not a git repo: ${sessionUri}`);
72 }
74 > const hasUncommitted = await this._gitService.hasUncommittedChanges(workingDirectory);
75 > if (!hasUncommitted) {
76 > return { message: { markdown: localize('agentHost.changeset.commit.noChanges', "No uncommitted changes to commit.") } }; agentHostCommitOperationHandler.ts ×1
77 > }
78 > this._throwIfCancelled(token); agentHostCommitOperationHandler.ts ×12
79 >
80 > const copilotResource = this._gitHubEndpointService.getCopilotResource();
81 > const authToken = this._agentService.getAuthToken({
82 > resource: copilotResource.resource,
83 > scopes: copilotResource.scopes_supported,
84 > });
85 > if (!authToken) {
86 throw new ProtocolError(
87 AHP_AUTH_REQUIRED,
88 localize('agentHost.changeset.commit.authRequired', "Sign in to GitHub Copilot to generate a commit message."),
89 [copilotResource],
90 );
91 }
93 > const diffs = await this._gitService.computeSessionFileDiffs(workingDirectory, { sessionUri });
94 > if (!diffs || diffs.length === 0) { agentHostCommitOperationHandler.ts ×9
95 throw new ProtocolError(JsonRpcErrorCodes.InternalError, localize('agentHost.changeset.commit.diffFailed', "Could not compute uncommitted changes to generate a commit message."));
96 }
97 > this._throwIfCancelled(token); agentHostCommitOperationHandler.ts ×12
98 >
99 > let message: string;
100 > try {
101 > message = this._cleanCommitMessage(await this._copilotApiService.utilityChatCompletion(authToken, {
102 > messages: this._buildCommitMessagePrompt(workingDirectory, gitState.branchName, diffs),
103 > }, { signal }));
104 > } catch (err) {
105 > this._throwIfCancelled(token);
106 > if (this._isAuthFailure(err)) {
107 > throw new ProtocolError(
108 > AHP_AUTH_REQUIRED,
109 > localize('agentHost.changeset.commit.authExpired', "Authentication is required to generate a commit message. Please sign in to GitHub Copilot and try again."),
110 > [copilotResource],
111 > );
112 > }
113 throw err;
114 }
115 if (!message) {
116 throw new ProtocolError(JsonRpcErrorCodes.InternalError, localize('agentHost.changeset.commit.emptyMessage', "Generated commit message was empty."));
117 }
118 this._throwIfCancelled(token);
119
120 this._logService.info(`[AgentHostCommitOperationHandler] Committing uncommitted changes for session ${sessionUri}`);
121 try {
122 await this._gitService.commitAll(workingDirectory, message);
123 } catch (err) {
124 this._throwIfCancelled(token);
125 throw new ProtocolError(JsonRpcErrorCodes.InternalError, `Failed to commit changes: ${err instanceof Error ? err.message : String(err)}`);
126 }
127
128 try {
129 await this._onCommitted(sessionUri);
130 } catch (err) {
131 this._logService.warn(`[AgentHostCommitOperationHandler] Post-commit refresh failed for session ${sessionUri}: ${err instanceof Error ? err.message : String(err)}`);
132 }
133
134 return { message: { markdown: localize('agentHost.changeset.commit.committed', "Committed changes with message: `{0}`", message.split('\n')[0]) } };
137 > private _buildCommitMessagePrompt(workingDirectory: URI, branchName: string | undefined, diffs: readonly ISessionFileDiff[]): { role: 'system' | 'user'; content: string }[] {
138 > const changeSummary = this._summarizeDiffsForPrompt(diffs); agentHostCommitOperationHandler.ts ×12
139 > return [
140 > {
141 > role: 'system',
142 > content: [
143 > 'You generate concise Git commit messages.',
144 > 'Return only the commit message text, with no markdown or code fences.',
145 > 'Use imperative mood. Keep the subject line under 72 characters.',
146 > 'Add a body only when it helps explain multiple related changes.',
147 > ].join(' '),
148 > },
149 > {
150 > role: 'user',
151 > content: [
152 > `Repository: ${basename(workingDirectory)}`,
153 > `Branch: ${branchName ?? 'unknown'}`,
154 > 'Changed files:',
155 > changeSummary,
156 > ].join('\n'),
157 > },
158 > ];
159 > }
161 > private _summarizeDiffsForPrompt(diffs: readonly ISessionFileDiff[]): string {
162 > const lines: string[] = []; agentHostCommitOperationHandler.ts ×12
163 > for (const diff of diffs) {
164 > const before = diff.before?.uri;
165 > const after = diff.after?.uri;
166 > const path = after ?? before ?? '(unknown)';
167 > let kind = 'Edit';
168 > if (!before && after) {
169 > kind = 'Create';
170 > } else if (before && !after) {
171 kind = 'Delete';
172 } else if (before && after && before !== after) {
173 kind = 'Rename';
174 }
175 > lines.push(`- ${kind}: ${this._displayUri(path)} (+${diff.diff?.added ?? 0} -${diff.diff?.removed ?? 0})`); agentHostCommitOperationHandler.ts ×12
176 > if (lines.join('\n').length > MAX_CHANGE_SUMMARY_PROMPT_CHARS) {
177 lines.push('[file list truncated]');
178 break;
179 }
181 > return lines.join('\n');
182 > }
184 > private _displayUri(uri: string): string {
186 > const parsed = URI.parse(uri);
187 > return parsed.scheme === 'file' ? parsed.fsPath : parsed.path || uri;
188 > } catch {
189 return uri;
190 }
193 > private _cleanCommitMessage(raw: string): string {
194 let text = raw.trim().replace(/\r\n/g, '\n');
195 const fenced = /^```(?:text|gitcommit)?\s*([\s\S]*?)\s*```$/i.exec(text);
196 if (fenced) {
197 text = fenced[1].trim();
198 }
199 return text;
200 }
202 > private _isAuthFailure(err: unknown): boolean {
203 > if (err instanceof CopilotApiError) { agentHostCommitOperationHandler.ts ×12
204 > return err.status === 401 || err.status === 403; agentHostCommitOperationHandler.ts ×1
205 > }
206 > const message = err instanceof Error ? err.message : String(err); agentHostCommitOperationHandler.ts ×12
207 > return /\b(401|403)\b/.test(message)
208 > && /\b(auth|authorization|unauthorized|forbidden|token|copilot endpoint discovery|copilot session token mint)\b/i.test(message); agentHostCommitOperationHandler.ts ×1
211 > private _throwIfCancelled(token: CancellationToken): void {
212 > if (token.isCancellationRequested) { agentHostCommitOperationHandler.ts ×9
213 > throw new ProtocolError(JsonRpcErrorCodes.InternalError, localize('agentHost.changeset.commit.cancelled', "Commit operation was cancelled.")); agentHostCommitOperationHandler.ts ×2
214 > }