Skip to content

Commit db2dbef

Browse files
lszomoruCopilot
andauthored
Agent Host - list files changed inside submodules in Branch and Uncommitted Changes (#350254)
* Agent Host - add failing tests for changes inside submodules Branch and Uncommitted Changes list a changed submodule as one `+0 -0` entry instead of the files changed inside it, and the baselines, discards and change fingerprint of those files don't use the submodule. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Agent Host - list files changed inside submodules in Branch and Uncommitted Changes Git reports a changed submodule as a single entry, if at all, so the Changes view showed `lib +0 -0` once a turn ended and dropped the files the agent had changed inside the submodule. List those files instead, diffed against the commit that the base records for the submodule, include submodules in the Branch Changes fingerprint, and read baselines and discard changes in the submodule. Fixes #316604 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Agent Host - ignore registered submodule paths that resolve outside the repository A `.gitmodules` path that is a symlink passed the lexical containment check, so `getSubmoduleRoot` could route `git show` for a `git-blob:` baseline into a repository outside the session. Only count a submodule whose folder resolves to its place inside the resolved repository root. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Agent Host - compare submodule test paths against the root Git reports On the Windows runners the temporary folder is an 8.3 short name, which `realpathSync` keeps, while Git reports the repository root with its long name. The test computed every changed path relative to the short name, so it failed although the diffs were right. Make the paths relative to the root that `getRepositoryRoot` reports, and stop resolving the folder so that macOS, where the temporary folder is a symlink, covers the same mismatch. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent c46521f commit db2dbef

7 files changed

Lines changed: 279 additions & 18 deletions

‎src/vs/platform/agentHost/common/agentHostGitService.ts‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -478,13 +478,27 @@ export interface IAgentHostGitService {
478478
* Returns `undefined` when {@link workingDirectory} is not a git work
479479
* tree, so callers can fall back to other diff sources.
480480
*
481+
* A changed submodule that is checked out is listed as the files changed
482+
* inside it, diffed against the commit the merge base records for it, so
483+
* the `git-blob:` baselines of those files belong to the submodule (see
484+
* {@link getSubmoduleRoot}).
485+
*
481486
* Each returned {@link ISessionFileDiff} has its `before.content` set to
482487
* a `git-blob:` URI ({@link buildGitBlobUri}); `after.content` is a
483488
* `file:` URI on the working-tree path. Adds and deletes drop the
484489
* missing side.
485490
*/
486491
computeSessionFileDiffs(workingDirectory: URI, options: IComputeSessionFileDiffsOptions): Promise<readonly ISessionFileDiff[] | undefined>;
487492

493+
/**
494+
* Returns the root of the checked-out submodule of the repository of
495+
* {@link workingDirectory} that contains `resource`, the innermost one
496+
* when submodules are nested, or `undefined` when none contains it. Only
497+
* submodules that `.gitmodules` registers inside the repository count, so
498+
* `resource` can't select a repository outside of it.
499+
*/
500+
getSubmoduleRoot?(workingDirectory: URI, resource: URI): Promise<URI | undefined>;
501+
488502
/**
489503
* Resolves the commit-ish the **Branch Changes** baseline is measured from:
490504
* the merge-base of `HEAD` and `baseBranch` (used exactly as given, e.g.
@@ -499,7 +513,8 @@ export interface IAgentHostGitService {
499513
/**
500514
* Returns a token that is equal across calls exactly while the Branch Changes of `workingDirectory` against
501515
* `baseBranch` stay the same: it covers HEAD, the merge base, and the paths `git status` reports together with their
502-
* on-disk size and modification time, so editing an already modified file changes it. It is much cheaper than
516+
* on-disk size and modification time, so editing an already modified file changes it, and the same for each changed
517+
* submodule. It is much cheaper than
503518
* computing the diff. `undefined` when it cannot be determined, in which case callers must compute the diff.
504519
*/
505520
getBranchDiffFingerprint?(workingDirectory: URI, baseBranch?: string): Promise<string | undefined>;

‎src/vs/platform/agentHost/node/agentHostDiscardChangesOperationHandler.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -174,10 +174,14 @@ export class AgentHostDiscardChangesOperationHandler implements IChangesetOperat
174174
if (!repositoryRoot) {
175175
throw new Error(`No changeset repository contains '${resource.fsPath}'.`);
176176
}
177+
const submoduleRoot = await this._agentHostGitService.getSubmoduleRoot?.(repositoryRoot, resource);
177178
this._throwIfCancelled(token);
178179

179-
if (parsed.kind === ChangesetKind.Branch) {
180-
await this._discardBranchChange(repositoryRoot, changesetFile, sessionUri, token);
180+
// Both changesets diff a file inside a submodule against the commit
181+
// that the repository records for the submodule, so restore it from
182+
// that baseline in the submodule.
183+
if (parsed.kind === ChangesetKind.Branch || submoduleRoot) {
184+
await this._discardBranchChange(submoduleRoot ?? repositoryRoot, changesetFile, sessionUri, token);
181185
} else {
182186
await this._discardUncommittedChange(repositoryRoot, resource, sessionUri, token);
183187
}

‎src/vs/platform/agentHost/node/agentHostGitService.ts‎

Lines changed: 105 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@ import { cp as copyFile } from '@vscode/fs-copyfile';
99
import { distinct } from '../../../base/common/arrays.js';
1010
import { Schemas } from '../../../base/common/network.js';
1111
import * as path from '../../../base/common/path.js';
12-
import { extUriBiasedIgnorePathCase } from '../../../base/common/resources.js';
12+
import { extUriBiasedIgnorePathCase, normalizePath } from '../../../base/common/resources.js';
13+
import { isDefined } from '../../../base/common/types.js';
1314
import { URI } from '../../../base/common/uri.js';
1415
import { VSBuffer } from '../../../base/common/buffer.js';
1516
import { generateUuid } from '../../../base/common/uuid.js';
@@ -860,6 +861,10 @@ export class AgentHostGitService extends Disposable implements IAgentHostGitServ
860861
// Resolve the merge-base commit the Branch Changes diff is anchored on.
861862
const mergeBaseCommit = await this._resolveBranchMergeBaseCommit(repositoryRoot, options.baseBranch);
862863

864+
return this._computeWorkingTreeDiffs(repositoryRoot, mergeBaseCommit, options.sessionUri);
865+
}
866+
867+
private async _computeWorkingTreeDiffs(repositoryRoot: URI, baseCommit: string, sessionUri: string): Promise<ISessionFileDiff[] | undefined> {
863868
// Detect whether the working tree has any untracked files. If so we
864869
// have to use the temp-index trick so the untracked content is
865870
// included in `--cached --raw` output; otherwise a plain `git diff`
@@ -872,17 +877,90 @@ export class AgentHostGitService extends Disposable implements IAgentHostGitServ
872877

873878
let rawDiffOutput: string | undefined;
874879
if (!hasUntracked) {
875-
rawDiffOutput = await this._runGit(repositoryRoot, ['diff', '--raw', '--numstat', '--diff-filter=ADMR', '-z', mergeBaseCommit, '--']);
880+
rawDiffOutput = await this._runGit(repositoryRoot, ['diff', '--raw', '--numstat', '--diff-filter=ADMR', '-z', baseCommit, '--']);
876881
} else {
877882
const changedPaths = parseChangedPaths(statusOut);
878-
rawDiffOutput = await this._runWithTempIndex(repositoryRoot, mergeBaseCommit, changedPaths);
883+
rawDiffOutput = await this._runWithTempIndex(repositoryRoot, baseCommit, changedPaths);
879884
}
880885

881886
if (rawDiffOutput === undefined) {
882887
return undefined;
883888
}
884889

885-
return parseGitDiffRawNumstat(rawDiffOutput, repositoryRoot, options.sessionUri, mergeBaseCommit);
890+
const diffs = parseGitDiffRawNumstat(rawDiffOutput, repositoryRoot, sessionUri, baseCommit);
891+
const submodules = await this._getSubmodules(repositoryRoot);
892+
if (!submodules.length) {
893+
return diffs;
894+
}
895+
896+
// Git reports a changed submodule as a single entry, if at all, so
897+
// list the files changed inside each changed submodule instead.
898+
const changedPaths = new Set(parseChangedPaths(statusOut));
899+
const diffUris = new Set(diffs.map(diff => diff.after?.uri ?? diff.before?.uri));
900+
const expanded = (await Promise.all(submodules.map(async submodule => {
901+
if (!changedPaths.has(submodule.path) && !diffUris.has(submodule.root.toString())) {
902+
return undefined;
903+
}
904+
// A submodule that is new since the base commit stays a single entry.
905+
const submoduleBaseCommit = await this.revParse(repositoryRoot, `${baseCommit}:${submodule.path}`);
906+
const submoduleDiffs = submoduleBaseCommit && await this._computeWorkingTreeDiffs(submodule.root, submoduleBaseCommit, sessionUri);
907+
return submoduleDiffs ? { uri: submodule.root.toString(), diffs: submoduleDiffs } : undefined;
908+
}))).filter(isDefined);
909+
const expandedUris = new Set(expanded.map(submodule => submodule.uri));
910+
return [
911+
...diffs.filter(diff => !expandedUris.has(diff.after?.uri ?? diff.before?.uri ?? '')),
912+
...expanded.flatMap(submodule => submodule.diffs),
913+
];
914+
}
915+
916+
/**
917+
* Returns the submodules that the repository's `.gitmodules` registers
918+
* inside it and that are checked out, in the order it registers them.
919+
*/
920+
private async _getSubmodules(repositoryRoot: URI): Promise<{ readonly path: string; readonly root: URI }[]> {
921+
try {
922+
await fsPromises.access(path.join(repositoryRoot.fsPath, '.gitmodules'));
923+
} catch {
924+
return [];
925+
}
926+
// Each `-z` entry is the key and the value, separated by a newline.
927+
const output = await this._runGit(repositoryRoot, ['config', '-z', '--file', '.gitmodules', '--get-regexp', '^submodule\\..*\\.path$']);
928+
const submodules = (output?.split('\x00') ?? [])
929+
.map(entry => entry.substring(entry.indexOf('\n') + 1))
930+
.filter(Boolean)
931+
.map(submodulePath => ({ path: submodulePath, root: URI.joinPath(repositoryRoot, submodulePath) }))
932+
.filter(submodule => extUriBiasedIgnorePathCase.isEqualOrParent(submodule.root, repositoryRoot) && !extUriBiasedIgnorePathCase.isEqual(submodule.root, repositoryRoot));
933+
// The folder of a submodule that isn't checked out has no `.git` and belongs to the repository itself.
934+
// Git doesn't check out a submodule through a symlink, so a registered path that resolves anywhere
935+
// but its place inside the repository isn't one of its submodules.
936+
let realRepositoryRoot: URI;
937+
try {
938+
realRepositoryRoot = URI.file(await fsPromises.realpath(repositoryRoot.fsPath));
939+
} catch {
940+
return [];
941+
}
942+
const checkedOut = await Promise.all(submodules.map(async submodule => {
943+
try {
944+
const realRoot = await fsPromises.realpath(submodule.root.fsPath);
945+
await fsPromises.access(path.join(realRoot, '.git'));
946+
return extUriBiasedIgnorePathCase.isEqual(URI.file(realRoot), URI.joinPath(realRepositoryRoot, submodule.path));
947+
} catch {
948+
return false;
949+
}
950+
}));
951+
return submodules.filter((_, index) => checkedOut[index]);
952+
}
953+
954+
async getSubmoduleRoot(workingDirectory: URI, resource: URI): Promise<URI | undefined> {
955+
const file = normalizePath(resource);
956+
let submoduleRoot: URI | undefined;
957+
let repositoryRoot = await this.getRepositoryRoot(workingDirectory);
958+
while (repositoryRoot) {
959+
const submodule = (await this._getSubmodules(repositoryRoot)).find(({ root }) => extUriBiasedIgnorePathCase.isEqualOrParent(file, root) && !extUriBiasedIgnorePathCase.isEqual(file, root));
960+
submoduleRoot = submodule?.root ?? submoduleRoot;
961+
repositoryRoot = submodule?.root;
962+
}
963+
return submoduleRoot;
886964
}
887965

888966
async resolveBranchBaselineCommit(workingDirectory: URI, baseBranch?: string): Promise<string | undefined> {
@@ -899,6 +977,10 @@ export class AgentHostGitService extends Disposable implements IAgentHostGitServ
899977
if (!repositoryRoot) {
900978
return undefined;
901979
}
980+
return this._computeBranchDiffFingerprint(repositoryRoot, baseBranch);
981+
}
982+
983+
private async _computeBranchDiffFingerprint(repositoryRoot: URI, baseBranch: string | undefined): Promise<string | undefined> {
902984
const [mergeBaseCommit, head, statusOut] = await Promise.all([
903985
this._resolveBranchMergeBaseCommit(repositoryRoot, baseBranch),
904986
this._runGit(repositoryRoot, ['rev-parse', 'HEAD']),
@@ -913,15 +995,25 @@ export class AgentHostGitService extends Disposable implements IAgentHostGitServ
913995
}
914996
const limiter = new Limiter<string>(16);
915997
try {
916-
const files = await Promise.all(changedPaths.map(changedPath => limiter.queue(async () => {
917-
try {
918-
const stat = await fsPromises.lstat(path.join(repositoryRoot.fsPath, changedPath), { bigint: true });
919-
return `${stat.size}:${stat.mtimeNs}`;
920-
} catch {
921-
return 'missing';
922-
}
923-
})));
924-
return JSON.stringify([mergeBaseCommit, head?.trim(), statusOut, files]);
998+
const [files, submodules] = await Promise.all([
999+
Promise.all(changedPaths.map(changedPath => limiter.queue(async () => {
1000+
try {
1001+
const stat = await fsPromises.lstat(path.join(repositoryRoot.fsPath, changedPath), { bigint: true });
1002+
return `${stat.size}:${stat.mtimeNs}`;
1003+
} catch {
1004+
return 'missing';
1005+
}
1006+
}))),
1007+
this._getSubmodules(repositoryRoot),
1008+
]);
1009+
// Edits inside a submodule leave its entry in the repository's status as it was.
1010+
const submoduleFingerprints = await Promise.all(submodules
1011+
.filter(submodule => changedPaths.includes(submodule.path))
1012+
.map(submodule => this._computeBranchDiffFingerprint(submodule.root, undefined)));
1013+
if (submoduleFingerprints.some(fingerprint => fingerprint === undefined)) {
1014+
return undefined;
1015+
}
1016+
return JSON.stringify([mergeBaseCommit, head?.trim(), statusOut, files, submoduleFingerprints]);
9251017
} finally {
9261018
limiter.dispose();
9271019
}

‎src/vs/platform/agentHost/node/resourceProviders/gitBlobResourceProvider.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,10 @@ export class GitBlobResourceProvider implements IAgentHostResourceProvider {
5959
if (!workingDirectory) {
6060
throw new ProtocolError(AhpErrorCodes.NotFound, `No session repository resolves git-blob path: ${fields.absolutePath || fields.repoRelativePath}`);
6161
}
62-
const blob = await this._gitService.showBlob(workingDirectory, fields.sha, fields.repoRelativePath);
62+
const submoduleRoot = fields.absolutePath
63+
? await this._gitService.getSubmoduleRoot?.(workingDirectory, workingDirectory.with({ path: fields.absolutePath }))
64+
: undefined;
65+
const blob = await this._gitService.showBlob(submoduleRoot ?? workingDirectory, fields.sha, fields.repoRelativePath);
6366
if (!blob) {
6467
throw new ProtocolError(AhpErrorCodes.NotFound, `git blob not found: ${fields.sha}:${fields.repoRelativePath}`);
6568
}

‎src/vs/platform/agentHost/test/node/agentHostDiscardChangesOperationHandler.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,9 +43,11 @@ class TestGitService extends TestAgentHostGitService {
4343
restoreError: Error | undefined;
4444
repositoryRoot: URI | undefined = URI.file('/repo');
4545
readonly repositoryRoots = new Map<string, URI | undefined>();
46+
submoduleRoot: URI | undefined;
4647
untrackedPaths: readonly string[] = [];
4748

4849
override async getRepositoryRoot(workingDirectory: URI): Promise<URI | undefined> { return this.repositoryRoots.get(workingDirectory.toString()) ?? this.repositoryRoot; }
50+
async getSubmoduleRoot(): Promise<URI | undefined> { return this.submoduleRoot; }
4951
override async hasUncommittedChanges(): Promise<boolean> { return true; }
5052
override async restore(workingDirectory: URI, paths: readonly string[], options?: { readonly staged?: boolean; readonly ref?: string }): Promise<void> {
5153
this.restoreCalls.push({ workingDirectory: workingDirectory.toString(), paths, options });
@@ -427,6 +429,38 @@ suite('AgentHostDiscardChangesOperationHandler', () => {
427429
]);
428430
});
429431

432+
test('restores a Branch or Uncommitted Changes file inside a submodule from its baseline in the submodule', async () => {
433+
const restoreCalls: Record<string, TestGitService['restoreCalls']> = {};
434+
for (const [kind, buildChangeset] of [[ChangesetKind.Branch, buildBranchChangesetUri], [ChangesetKind.Uncommitted, buildUncommittedChangesetUri]] as const) {
435+
const { handler, gitService, stateManager, session } = setup(disposables);
436+
const submodule = URI.file('/repo/lib');
437+
gitService.submoduleRoot = submodule;
438+
const owner = buildDefaultChatUri(session.toString());
439+
const channel = buildChangeset(owner);
440+
const target = URI.joinPath(submodule, 'lib.txt');
441+
addChangesetFile(stateManager, channel, {
442+
before: {
443+
uri: target.toString(),
444+
content: { uri: buildGitBlobUri(owner, 'submodule-baseline', 'lib.txt', target.path) },
445+
},
446+
after: { uri: target.toString(), content: { uri: target.toString() } },
447+
});
448+
449+
await handler.invoke({
450+
channel,
451+
operationId: AgentHostDiscardChangesOperationHandler.OPERATION_DISCARD_CHANGES,
452+
target: makeResourceTarget(target),
453+
}, CancellationToken.None);
454+
restoreCalls[kind] = gitService.restoreCalls;
455+
}
456+
457+
const fromBaseline = [
458+
{ workingDirectory: URI.file('/repo/lib').toString(), paths: ['lib.txt'], options: { staged: true, ref: 'submodule-baseline' } },
459+
{ workingDirectory: URI.file('/repo/lib').toString(), paths: ['lib.txt'], options: { ref: 'submodule-baseline' } },
460+
];
461+
assert.deepStrictEqual(restoreCalls, { [ChangesetKind.Branch]: fromBaseline, [ChangesetKind.Uncommitted]: fromBaseline });
462+
});
463+
430464
test('rejects a resource that is not part of Branch Changes', async () => {
431465
const { handler, gitService, stateManager, session } = setup(disposables);
432466
const owner = buildDefaultChatUri(session.toString());

0 commit comments

Comments
 (0)