From 0c6eab1880362f969cb0af9388a086fd310339c2 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 04:30:43 +0100 Subject: [PATCH 01/20] Editor window: offer the worktrees that agent host sessions work in as locations of the window's folder A window with a single local folder can now move that folder to the worktrees its local agent host sessions work in, behind the experimental setting chat.editorWindow.enableWorktree (off by default, experiment-controlled). - AgentHostWorktreeLocationProvider: the locations of a folder are the distinct working directories of the local agent host's sessions (not archived; local chats and extension sessions belong to the folder itself). A working directory counts when it is a linked checkout of the folder's git repository, as the editor window decides that a folder belongs to its repository, and when the repository's entry for it names it back, so a folder that only points into the repository does not inherit the folder's trust. Any such checkout resolves, also before the sessions load, to restore the location the folder was at. There is no discovery of the repository's worktrees. - It is registered as a built-in provider while the setting is on, not in the Agents window. - readFolderGitCheckout moves from WorkspaceFolderRepositories to services/workspaces/common, so that both can read a folder's checkout; WorkspaceFolderRepositories is unchanged otherwise. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 188 ++++++++++++++++++ .../agentSessions.contribution.ts | 1 + .../contrib/chat/common/constants.ts | 5 + .../agentHostWorktreeLocations.test.ts | 113 +++++++++++ .../browser/workspaceFolderRepositories.ts | 39 +--- .../workspaces/common/gitFolderCheckout.ts | 50 +++++ 6 files changed, 360 insertions(+), 36 deletions(-) create mode 100644 src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts create mode 100644 src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts create mode 100644 src/vs/workbench/services/workspaces/common/gitFolderCheckout.ts diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts new file mode 100644 index 00000000000000..b05f054c5a45a6 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -0,0 +1,188 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken } from '../../../../../../base/common/cancellation.js'; +import { Codicon } from '../../../../../../base/common/codicons.js'; +import { Disposable, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; +import { Schemas } from '../../../../../../base/common/network.js'; +import { isAbsolute } from '../../../../../../base/common/path.js'; +import { basename, extUriBiasedIgnorePathCase, joinPath } from '../../../../../../base/common/resources.js'; +import { isDefined } from '../../../../../../base/common/types.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { localize } from '../../../../../../nls.js'; +import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; +import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../../platform/configuration/common/configurationRegistry.js'; +import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../../../platform/files/common/files.js'; +import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; +import { ILogService } from '../../../../../../platform/log/common/log.js'; +import { Registry } from '../../../../../../platform/registry/common/platform.js'; +import { IFolderLocation, IWorkspaceFolderLocationProvider, IWorkspaceFolderLocationService } from '../../../../../../platform/workspace/common/folderLocations.js'; +import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../../common/contributions.js'; +import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; +import { readFolderGitCheckout } from '../../../../../services/workspaces/common/gitFolderCheckout.js'; +import { isLocalAgentHostTarget } from '../../../common/chatSessionsService.js'; +import { ChatConfiguration } from '../../../common/constants.js'; +import { IAgentSession } from '../agentSessionsModel.js'; +import { IAgentSessionsService } from '../agentSessionsService.js'; + +/** The id of the provider of the worktrees that the local agent host's sessions work in. */ +export const AGENT_HOST_WORKTREE_LOCATIONS_PROVIDER_ID = 'agentHost.sessionWorktrees'; + +/** + * The working directories of the local agent host's sessions in `sessions`, without duplicates: the folders their agents + * work in, such as a worktree a session created. Archived sessions and those of other providers, such as local chats, + * which belong to the window's primary folder, are left out. + */ +export function getAgentHostSessionWorkingDirectories(sessions: readonly IAgentSession[]): URI[] { + const result: URI[] = []; + for (const session of sessions) { + const path = session.metadata?.workingDirectoryPath; + if (!isLocalAgentHostTarget(session.providerType) || session.isArchived() || typeof path !== 'string' || !path) { + continue; + } + const directory = URI.file(path); + if (!result.some(candidate => extUriBiasedIgnorePathCase.isEqual(candidate, directory))) { + result.push(directory); + } + } + return result; +} + +/** + * The alternate locations of a local folder that its agent host sessions know: the worktrees of the folder's git + * repository that sessions work in. There is no discovery of the repository's worktrees; a session's working directory is + * one only when it is a linked checkout of that repository, as the editor window decides that a folder belongs to a + * window's repository (see `WorkspaceFolderRepositories`), and when that repository's entry for it names its `.git` back. + * That keeps a folder that only points into the repository from inheriting the primary's trust. + */ +export class AgentHostWorktreeLocationProvider implements IWorkspaceFolderLocationProvider { + + readonly id = AGENT_HOST_WORKTREE_LOCATIONS_PROVIDER_ID; + + constructor( + @IAgentSessionsService private readonly _agentSessionsService: IAgentSessionsService, + @IFileService private readonly _fileService: IFileService, + @ILogService private readonly _logService: ILogService, + ) { } + + async provideLocations(primary: URI, token: CancellationToken): Promise { + const repository = await this._readRepository(primary); + if (!repository || token.isCancellationRequested) { + return []; + } + const candidates = getAgentHostSessionWorkingDirectories(this._agentSessionsService.model.sessions) + .filter(directory => !extUriBiasedIgnorePathCase.isEqual(directory, primary)); + const locations = await Promise.all(candidates.map(candidate => this._resolve(repository, candidate))); + return token.isCancellationRequested ? [] : locations.filter(isDefined); + } + + async resolveLocation(primary: URI, location: URI, token: CancellationToken): Promise { + // Any linked checkout of the repository resolves, also before the sessions load, such as to restore the location + // that the window's folder was at + if (extUriBiasedIgnorePathCase.isEqual(location, primary)) { + return undefined; + } + const repository = await this._readRepository(primary); + if (!repository || token.isCancellationRequested) { + return undefined; + } + return this._resolve(repository, location); + } + + /** The git repository of the local folder `folder` is a checkout of, if any. */ + private async _readRepository(folder: URI): Promise { + if (folder.scheme !== Schemas.file) { + return undefined; + } + try { + return (await readFolderGitCheckout(this._fileService, folder))?.repository; + } catch (error) { + this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git repository of ${folder.toString()}`, error); + return undefined; + } + } + + /** `candidate` as a location of `repository`'s folder, when it is a linked checkout of that repository. */ + private async _resolve(repository: URI, candidate: URI): Promise { + if (candidate.scheme !== Schemas.file) { + return undefined; + } + try { + const checkout = await readFolderGitCheckout(this._fileService, candidate); + if (!checkout?.worktreeGitDir || !extUriBiasedIgnorePathCase.isEqual(checkout.repository, repository) || !await this._namesBack(checkout.worktreeGitDir, candidate)) { + return undefined; + } + } catch (error) { + this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git checkout of ${candidate.toString()}`, error); + return undefined; + } + return { uri: candidate, label: basename(candidate), icon: Codicon.gitBranchCheckout }; + } + + /** Whether the repository's entry for a worktree, `worktreeGitDir`, names the `.git` of `folder` back. */ + private async _namesBack(worktreeGitDir: URI, folder: URI): Promise { + let content: string; + try { + content = (await this._fileService.readFile(joinPath(worktreeGitDir, 'gitdir'))).value.toString().trim(); + } catch (error) { + if (error instanceof Error && toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND) { + return false; + } + throw error; + } + return !!content && extUriBiasedIgnorePathCase.isEqual(isAbsolute(content) ? URI.file(content) : joinPath(worktreeGitDir, content), joinPath(folder, '.git')); + } +} + +/** Offers the worktrees of the agent host's sessions as locations of an editor window's folder, while the setting is on. */ +export class AgentHostWorktreeLocationsContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'workbench.contrib.agentHostWorktreeLocations'; + + private readonly _registration = this._register(new MutableDisposable()); + + constructor( + @IConfigurationService private readonly _configurationService: IConfigurationService, + @IWorkspaceFolderLocationService private readonly _folderLocationService: IWorkspaceFolderLocationService, + @IInstantiationService private readonly _instantiationService: IInstantiationService, + @IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService, + ) { + super(); + if (environmentService.isSessionsWindow) { + return; + } + this._update(); + this._register(_configurationService.onDidChangeConfiguration(e => { + if (e.affectsConfiguration(ChatConfiguration.EditorWindowEnableWorktree)) { + this._update(); + } + })); + } + + private _update(): void { + if (!this._configurationService.getValue(ChatConfiguration.EditorWindowEnableWorktree)) { + this._registration.clear(); + } else if (!this._registration.value) { + this._registration.value = this._folderLocationService.registerProvider(this._instantiationService.createInstance(AgentHostWorktreeLocationProvider), { builtIn: true }); + } + } +} + +Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ + id: 'chatSidebar', + title: localize('chatConfigurationTitle', "Chat"), + type: 'object', + properties: { + [ChatConfiguration.EditorWindowEnableWorktree]: { + type: 'boolean', + default: false, + tags: ['experimental'], + experiment: { mode: 'auto' }, + markdownDescription: localize('chat.editorWindow.enableWorktree', "Controls whether a window with a single local folder can move that folder to the worktrees its agent host sessions work in, and back to the folder's own location."), + }, + }, +}); + +registerWorkbenchContribution2(AgentHostWorktreeLocationsContribution.ID, AgentHostWorktreeLocationsContribution, WorkbenchPhase.BlockRestore); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts index 9fd8154696b322..506c70e08cb0c8 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts @@ -21,6 +21,7 @@ import { AgentHostPermissionUiContribution } from './agentHost/agentHostPermissi import { registerExternalSessionsFilterMenu } from './externalSessionsFilterMenu.js'; import './agentHost/agentHostChatInputPicker.contribution.js'; import './agentHost/agentHostModeSynchronizer.js'; +import './agentHost/agentHostWorktreeLocations.js'; import { ChatSessionArchiveActionWordingSettingId, getChatSessionArchiveActionWording } from '../../../../../platform/chat/common/sessionArchiveActions.js'; import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; diff --git a/src/vs/workbench/contrib/chat/common/constants.ts b/src/vs/workbench/contrib/chat/common/constants.ts index 8ef96a99bf1bc3..134e29231a4374 100644 --- a/src/vs/workbench/contrib/chat/common/constants.ts +++ b/src/vs/workbench/contrib/chat/common/constants.ts @@ -52,6 +52,11 @@ export enum ChatConfiguration { AgentsPickerInAttachContextMenu = 'sessions.chat.experimental.agentsPickerInAttachContextMenu', /** Desktop only: lets chat attach a screenshot of the window of another app. */ AppWindowScreenshotsEnabled = 'chat.appWindowScreenshots.enabled', + /** + * Lets an editor window with one local folder move that folder between its primary location and the worktrees its + * agent host sessions work in, and offer them when starting a session. + */ + EditorWindowEnableWorktree = 'chat.editorWindow.enableWorktree', PlanAgentDefaultModel = 'chat.planAgent.defaultModel', ExploreAgentDefaultModel = 'chat.exploreAgent.defaultModel', UtilityModel = 'chat.utilityModel', diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts new file mode 100644 index 00000000000000..9fa274f2adaed0 --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -0,0 +1,113 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { VSBuffer } from '../../../../../../../base/common/buffer.js'; +import { CancellationToken } from '../../../../../../../base/common/cancellation.js'; +import { URI } from '../../../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; +import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStatWithMetadata } from '../../../../../../../platform/files/common/files.js'; +import { TestInstantiationService } from '../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { ILogService, NullLogService } from '../../../../../../../platform/log/common/log.js'; +import { AgentHostWorktreeLocationProvider, getAgentHostSessionWorkingDirectories } from '../../../../browser/agentSessions/agentHost/agentHostWorktreeLocations.js'; +import { IAgentSession } from '../../../../browser/agentSessions/agentSessionsModel.js'; +import { IAgentSessionsService } from '../../../../browser/agentSessions/agentSessionsService.js'; +import { SessionType } from '../../../../common/chatSessionsService.js'; + +suite('AgentHostWorktreeLocations', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + function session(providerType: string, workingDirectoryPath: string | undefined, archived = false): IAgentSession { + return upcastPartial({ providerType, metadata: workingDirectoryPath ? { workingDirectoryPath } : undefined, isArchived: () => archived }); + } + + /** + * A provider over git entries: `true` is a `.git` directory, and a string the content of a file, such as a worktree's + * `.git` file or its entry's `gitdir` file in the repository. + */ + function createProvider(entries: Record, sessions: readonly IAgentSession[]) { + const fileService = upcastPartial({ + stat: async (resource: URI) => { + const entry = entries[resource.path]; + if (entry === undefined) { + throw new FileOperationError('not found', FileOperationResult.FILE_NOT_FOUND); + } + return upcastPartial({ isDirectory: entry === true }); + }, + readFile: async (resource: URI) => { + const entry = entries[resource.path]; + if (typeof entry !== 'string') { + throw new FileOperationError('not found', FileOperationResult.FILE_NOT_FOUND); + } + return upcastPartial({ value: VSBuffer.fromString(entry) }); + }, + }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IFileService, fileService); + instantiationService.stub(ILogService, new NullLogService()); + instantiationService.stub(IAgentSessionsService, upcastPartial({ model: upcastPartial({ sessions: [...sessions] }) })); + return instantiationService.createInstance(AgentHostWorktreeLocationProvider); + } + + const repository = { + '/work/vscode/.git': true, + // A worktree whose repository entry names it back + '/work/vscode.worktrees/feature/.git': 'gitdir: /work/vscode/.git/worktrees/feature\n', + '/work/vscode/.git/worktrees/feature/gitdir': '/work/vscode.worktrees/feature/.git\n', + // One with a relative link back + '/work/vscode.worktrees/relative/.git': 'gitdir: /work/vscode/.git/worktrees/relative', + '/work/vscode/.git/worktrees/relative/gitdir': '../../../../vscode.worktrees/relative/.git', + // A folder that points into the repository, but that the repository does not name back + '/work/impostor/.git': 'gitdir: /work/vscode/.git/worktrees/feature', + // A worktree of another repository + '/work/tools/.git': true, + '/work/tools.worktrees/fix/.git': 'gitdir: /work/tools/.git/worktrees/fix', + '/work/tools/.git/worktrees/fix/gitdir': '/work/tools.worktrees/fix/.git', + }; + + test('the working directories of the local agent host\'s sessions, without duplicates, archived sessions or other providers\' sessions', () => { + const directories = getAgentHostSessionWorkingDirectories([ + session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/feature'), + session(SessionType.AgentHostClaude, '/work/vscode.worktrees/feature'), + session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/archived', true), + session(SessionType.Local, '/work/vscode.worktrees/local'), + session(SessionType.CopilotCLI, '/work/vscode.worktrees/extension'), + session(SessionType.AgentHostCopilot, undefined), + session(SessionType.AgentHostCopilot, '/work/vscode'), + ]); + assert.deepStrictEqual(directories.map(directory => directory.path), ['/work/vscode.worktrees/feature', '/work/vscode']); + }); + + test('offers the worktrees of the folder\'s repository that sessions work in, which the repository names back, and resolves any of them', async () => { + const provider = createProvider(repository, [ + session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/feature'), + session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/relative'), + session(SessionType.AgentHostCopilot, '/work/vscode'), + session(SessionType.AgentHostCopilot, '/work/impostor'), + session(SessionType.AgentHostCopilot, '/work/tools.worktrees/fix'), + session(SessionType.AgentHostCopilot, '/work/missing'), + session(SessionType.Local, '/work/vscode.worktrees/local'), + ]); + const resolve = async (location: string) => (await provider.resolveLocation(URI.file('/work/vscode'), URI.file(location), CancellationToken.None))?.label; + + assert.deepStrictEqual({ + locations: (await provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None)).map(location => ({ path: location.uri.path, label: location.label })), + ofAFolderWithoutRepository: await provider.provideLocations(URI.file('/work/plain'), CancellationToken.None), + // A location that no session lists any more still resolves, as to restore it + resolved: await resolve('/work/vscode.worktrees/relative'), + impostor: await resolve('/work/impostor'), + otherRepository: await resolve('/work/tools.worktrees/fix'), + primary: await resolve('/work/vscode'), + }, { + locations: [{ path: '/work/vscode.worktrees/feature', label: 'feature' }, { path: '/work/vscode.worktrees/relative', label: 'relative' }], + ofAFolderWithoutRepository: [], + resolved: 'relative', + impostor: undefined, + otherRepository: undefined, + primary: undefined, + }); + }); +}); diff --git a/src/vs/workbench/contrib/sessions/browser/workspaceFolderRepositories.ts b/src/vs/workbench/contrib/sessions/browser/workspaceFolderRepositories.ts index a46d51811d4f78..76839f211c1837 100644 --- a/src/vs/workbench/contrib/sessions/browser/workspaceFolderRepositories.ts +++ b/src/vs/workbench/contrib/sessions/browser/workspaceFolderRepositories.ts @@ -7,8 +7,7 @@ import { Disposable } from '../../../../base/common/lifecycle.js'; import { ResourceMap } from '../../../../base/common/map.js'; import { Schemas } from '../../../../base/common/network.js'; import { IObservable, observableFromEvent, observableValue, transaction } from '../../../../base/common/observable.js'; -import { isAbsolute } from '../../../../base/common/path.js'; -import { basename, dirname, isEqual, joinPath } from '../../../../base/common/resources.js'; +import { isEqual, joinPath } from '../../../../base/common/resources.js'; import { isDefined } from '../../../../base/common/types.js'; import { URI } from '../../../../base/common/uri.js'; import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../platform/files/common/files.js'; @@ -16,6 +15,7 @@ import { ILogService } from '../../../../platform/log/common/log.js'; import { IWorkspaceContextService } from '../../../../platform/workspace/common/workspace.js'; import { ISessionsListingScope } from '../common/sessionsProvider.js'; import { parseGitHubRepositoryFromGitConfig } from './gitHubRepositoryResolver.js'; +import { readFolderGitCheckout } from '../../../services/workspaces/common/gitFolderCheckout.js'; /** The hosts of the GitHub repositories that Copilot Cloud sessions work in (`github-remote-file://github/...`). */ const GITHUB_HOSTS = ['github.com']; @@ -111,7 +111,7 @@ export class WorkspaceFolderRepositories extends Disposable implements ISessions /** The checkout of `folder`, and whether to read it again as the folders change, as its `origin` could not be read. */ private async _readCheckout(folder: URI): Promise<{ readonly checkout: IFolderCheckout; readonly readAgain: boolean }> { - const repository = await WorkspaceFolderRepositories._readFolderGitRepository(this._fileService, folder); + const repository = (await readFolderGitCheckout(this._fileService, folder))?.repository; if (!repository) { return { checkout: { repository, gitHubRepository: undefined }, readAgain: false }; } @@ -124,39 +124,6 @@ export class WorkspaceFolderRepositories extends Disposable implements ISessions } } - /** - * The git repository that a local folder is a checkout of, read from its `.git`: the folder itself when `.git` is a - * directory, and the main checkout when `.git` is the file of a worktree (`gitdir: /.git/worktrees/`). - * `undefined` for a folder without `.git`, or whose `.git` names no worktree, such as a submodule's. Throws when `.git` - * exists but cannot be read. - */ - private static async _readFolderGitRepository(fileService: IFileService, folder: URI): Promise { - const dotGit = joinPath(folder, '.git'); - let isDirectory: boolean; - try { - isDirectory = (await fileService.stat(dotGit)).isDirectory; - } catch (error) { - if (error instanceof Error && toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND) { - return undefined; - } - throw error; - } - if (isDirectory) { - return folder; - } - const content = (await fileService.readFile(dotGit)).value.toString(); - const gitdir = /^gitdir:\s*(?.+?)\s*$/m.exec(content)?.groups?.path; - if (!gitdir) { - return undefined; - } - const worktreeGitDir = isAbsolute(gitdir) ? URI.file(gitdir) : joinPath(folder, gitdir); - const worktreesDir = dirname(worktreeGitDir); - const commonGitDir = dirname(worktreesDir); - return basename(worktreesDir) === 'worktrees' && basename(commonGitDir) === '.git' && !isEqual(commonGitDir, worktreesDir) - ? dirname(commonGitDir) - : undefined; - } - /** * The GitHub repository, as lowercase `owner/repo`, that the `origin` remote of a git `config` names, such as * `https://github.com/owner/repo.git` or `git@github.com:owner/repo`; `undefined` for another host or without `origin`. diff --git a/src/vs/workbench/services/workspaces/common/gitFolderCheckout.ts b/src/vs/workbench/services/workspaces/common/gitFolderCheckout.ts new file mode 100644 index 00000000000000..396815f54f41f1 --- /dev/null +++ b/src/vs/workbench/services/workspaces/common/gitFolderCheckout.ts @@ -0,0 +1,50 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { isAbsolute } from '../../../../base/common/path.js'; +import { basename, dirname, isEqual, joinPath } from '../../../../base/common/resources.js'; +import { URI } from '../../../../base/common/uri.js'; +import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../platform/files/common/files.js'; + +/** What a local folder is a checkout of, read from its `.git` (see {@link readFolderGitCheckout}). */ +export interface IFolderGitCheckout { + /** The git repository: the folder itself, or the main checkout of a worktree. */ + readonly repository: URI; + /** For a worktree, its entry in the repository's `.git/worktrees`, which its `.git` file names. */ + readonly worktreeGitDir?: URI; +} + +/** + * The git repository that a local folder is a checkout of, read from its `.git`: the folder itself when `.git` is a + * directory, and the main checkout when `.git` is the file of a worktree (`gitdir: /.git/worktrees/`). + * `undefined` for a folder without `.git`, or whose `.git` names no worktree, such as a submodule's. Throws when `.git` + * exists but cannot be read. + */ +export async function readFolderGitCheckout(fileService: IFileService, folder: URI): Promise { + const dotGit = joinPath(folder, '.git'); + let isDirectory: boolean; + try { + isDirectory = (await fileService.stat(dotGit)).isDirectory; + } catch (error) { + if (error instanceof Error && toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND) { + return undefined; + } + throw error; + } + if (isDirectory) { + return { repository: folder }; + } + const content = (await fileService.readFile(dotGit)).value.toString(); + const gitdir = /^gitdir:\s*(?.+?)\s*$/m.exec(content)?.groups?.path; + if (!gitdir) { + return undefined; + } + const worktreeGitDir = isAbsolute(gitdir) ? URI.file(gitdir) : joinPath(folder, gitdir); + const worktreesDir = dirname(worktreeGitDir); + const commonGitDir = dirname(worktreesDir); + return basename(worktreesDir) === 'worktrees' && basename(commonGitDir) === '.git' && !isEqual(commonGitDir, worktreesDir) + ? { repository: dirname(commonGitDir), worktreeGitDir } + : undefined; +} From 56a16a82730f67ff7df2754bd500213a8a8f54bb Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 04:48:45 +0100 Subject: [PATCH 02/20] Workbench: a shown-session seam for chat view hosts, and shared folder picker sections (infra, unused) Infra for worktree support in the editor window; nothing registers or uses it yet. - IChatViewHostService.shownSession, with IChatViewHost.shownSession and IChatViewHostShownSession { resource, reason: 'open' | 'restore' }: the chat that the host in use shows, and whether the user brought it up or the host restored it. The Chat view reports it: 'restore' for the chat it restores, 'open' for a chat picked in its sessions list, a new chat, and a new chat that its first request made real. A host that replaces the Chat view reports its own; one that reports none leaves it undefined. - folderLocationSections.ts: the sections that every picker of a window's folders and their worktrees shows (Folder or Folders, then Worktrees, each with the current folder first), and their labels, so that the pickers share them. - AgentHostWorktreeLocationProvider is no longer registered here, and the setting moves out with its registration: the feature that uses them registers them. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 62 +------------------ .../agentSessions.contribution.ts | 1 - .../contrib/chat/browser/chatViewHost.ts | 16 +++++ .../viewPane/chatViewHostService.ts | 24 ++++++- .../widgetHosts/viewPane/chatViewPane.ts | 17 ++++- .../contrib/chat/common/constants.ts | 5 -- .../viewPane/chatViewHostService.test.ts | 42 ++++++++++++- .../common/folderLocationSections.ts | 52 ++++++++++++++++ .../common/folderLocationSections.test.ts | 39 ++++++++++++ 9 files changed, 185 insertions(+), 73 deletions(-) create mode 100644 src/vs/workbench/services/workspaces/common/folderLocationSections.ts create mode 100644 src/vs/workbench/services/workspaces/test/common/folderLocationSections.test.ts diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index b05f054c5a45a6..f9f07f83b22e96 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -5,25 +5,16 @@ import { CancellationToken } from '../../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; -import { Disposable, MutableDisposable } from '../../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../../base/common/network.js'; import { isAbsolute } from '../../../../../../base/common/path.js'; import { basename, extUriBiasedIgnorePathCase, joinPath } from '../../../../../../base/common/resources.js'; import { isDefined } from '../../../../../../base/common/types.js'; import { URI } from '../../../../../../base/common/uri.js'; -import { localize } from '../../../../../../nls.js'; -import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; -import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from '../../../../../../platform/configuration/common/configurationRegistry.js'; import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../../../platform/files/common/files.js'; -import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../../../platform/log/common/log.js'; -import { Registry } from '../../../../../../platform/registry/common/platform.js'; -import { IFolderLocation, IWorkspaceFolderLocationProvider, IWorkspaceFolderLocationService } from '../../../../../../platform/workspace/common/folderLocations.js'; -import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../../common/contributions.js'; -import { IWorkbenchEnvironmentService } from '../../../../../services/environment/common/environmentService.js'; +import { IFolderLocation, IWorkspaceFolderLocationProvider } from '../../../../../../platform/workspace/common/folderLocations.js'; import { readFolderGitCheckout } from '../../../../../services/workspaces/common/gitFolderCheckout.js'; import { isLocalAgentHostTarget } from '../../../common/chatSessionsService.js'; -import { ChatConfiguration } from '../../../common/constants.js'; import { IAgentSession } from '../agentSessionsModel.js'; import { IAgentSessionsService } from '../agentSessionsService.js'; @@ -135,54 +126,3 @@ export class AgentHostWorktreeLocationProvider implements IWorkspaceFolderLocati return !!content && extUriBiasedIgnorePathCase.isEqual(isAbsolute(content) ? URI.file(content) : joinPath(worktreeGitDir, content), joinPath(folder, '.git')); } } - -/** Offers the worktrees of the agent host's sessions as locations of an editor window's folder, while the setting is on. */ -export class AgentHostWorktreeLocationsContribution extends Disposable implements IWorkbenchContribution { - - static readonly ID = 'workbench.contrib.agentHostWorktreeLocations'; - - private readonly _registration = this._register(new MutableDisposable()); - - constructor( - @IConfigurationService private readonly _configurationService: IConfigurationService, - @IWorkspaceFolderLocationService private readonly _folderLocationService: IWorkspaceFolderLocationService, - @IInstantiationService private readonly _instantiationService: IInstantiationService, - @IWorkbenchEnvironmentService environmentService: IWorkbenchEnvironmentService, - ) { - super(); - if (environmentService.isSessionsWindow) { - return; - } - this._update(); - this._register(_configurationService.onDidChangeConfiguration(e => { - if (e.affectsConfiguration(ChatConfiguration.EditorWindowEnableWorktree)) { - this._update(); - } - })); - } - - private _update(): void { - if (!this._configurationService.getValue(ChatConfiguration.EditorWindowEnableWorktree)) { - this._registration.clear(); - } else if (!this._registration.value) { - this._registration.value = this._folderLocationService.registerProvider(this._instantiationService.createInstance(AgentHostWorktreeLocationProvider), { builtIn: true }); - } - } -} - -Registry.as(ConfigurationExtensions.Configuration).registerConfiguration({ - id: 'chatSidebar', - title: localize('chatConfigurationTitle', "Chat"), - type: 'object', - properties: { - [ChatConfiguration.EditorWindowEnableWorktree]: { - type: 'boolean', - default: false, - tags: ['experimental'], - experiment: { mode: 'auto' }, - markdownDescription: localize('chat.editorWindow.enableWorktree', "Controls whether a window with a single local folder can move that folder to the worktrees its agent host sessions work in, and back to the folder's own location."), - }, - }, -}); - -registerWorkbenchContribution2(AgentHostWorktreeLocationsContribution.ID, AgentHostWorktreeLocationsContribution, WorkbenchPhase.BlockRestore); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts index 506c70e08cb0c8..9fd8154696b322 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentSessions.contribution.ts @@ -21,7 +21,6 @@ import { AgentHostPermissionUiContribution } from './agentHost/agentHostPermissi import { registerExternalSessionsFilterMenu } from './externalSessionsFilterMenu.js'; import './agentHost/agentHostChatInputPicker.contribution.js'; import './agentHost/agentHostModeSynchronizer.js'; -import './agentHost/agentHostWorktreeLocations.js'; import { ChatSessionArchiveActionWordingSettingId, getChatSessionArchiveActionWording } from '../../../../../platform/chat/common/sessionArchiveActions.js'; import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; diff --git a/src/vs/workbench/contrib/chat/browser/chatViewHost.ts b/src/vs/workbench/contrib/chat/browser/chatViewHost.ts index fc6589af2b9484..226d8e995e7d8f 100644 --- a/src/vs/workbench/contrib/chat/browser/chatViewHost.ts +++ b/src/vs/workbench/contrib/chat/browser/chatViewHost.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { IDisposable } from '../../../../base/common/lifecycle.js'; +import { IObservable } from '../../../../base/common/observable.js'; import { URI } from '../../../../base/common/uri.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; import { SessionTypeSelectionReason } from '../common/constants.js'; @@ -11,6 +12,16 @@ import { IChatWidget } from './chat.js'; export const IChatViewHostService = createDecorator('chatViewHostService'); +/** The chat that a host shows ({@link IChatViewHost.shownSession}), and why it shows it. */ +export interface IChatViewHostShownSession { + readonly resource: URI; + /** + * `open` when the user brought the chat up, such as by picking it in the sessions list, starting a new chat or sending + * the first request of one; `restore` when the host shows the chat it last showed, such as as the window starts. + */ + readonly reason: 'open' | 'restore'; +} + /** How {@link IChatViewHost.reveal} shows the host. */ export interface IChatViewHostRevealOptions { /** @@ -70,6 +81,8 @@ export interface IChatViewHost { toggle(): Promise; /** Starts showing the session of `sessionResource`, which its caller may send a first request to. */ startSession(sessionResource: URI, options: IChatViewHostSessionStartOptions): Promise; + /** The chat the host shows; a host that does not implement it reports none. */ + readonly shownSession?: IObservable; } /** @@ -81,6 +94,9 @@ export interface IChatViewHostService extends IChatViewHost { revealIfShowing(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise; + /** The chat that the host in use shows; none while a host that does not report one ({@link IChatViewHost.shownSession}) is in use. */ + readonly shownSession: IObservable; + /** * Replaces the Chat view with `host` until the returned disposable is disposed. The host registered last is the one in * use; disposing it gives the use back to the one before. diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index d433fe430427aa..b3358545b032f1 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -5,6 +5,7 @@ import { DeferredPromise, raceTimeout } from '../../../../../../base/common/async.js'; import { DisposableStore, IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { derived, IObservable, ISettableObservable, observableFromEvent, observableValue } from '../../../../../../base/common/observable.js'; import { isEqual } from '../../../../../../base/common/resources.js'; import { URI } from '../../../../../../base/common/uri.js'; import { IInstantiationService } from '../../../../../../platform/instantiation/common/instantiation.js'; @@ -13,7 +14,7 @@ import { IViewDescriptorService, ViewContainerLocation } from '../../../../../co import { IWorkbenchLayoutService, Parts } from '../../../../../services/layout/browser/layoutService.js'; import { IViewsService } from '../../../../../services/views/common/viewsService.js'; import { ChatViewId, IChatWidget } from '../../chat.js'; -import { IChatViewHost, IChatViewHostOpenOptions, IChatViewHostRevealOptions, IChatViewHostService, IChatViewHostSessionStart, IChatViewHostSessionStartOptions } from '../../chatViewHost.js'; +import { IChatViewHost, IChatViewHostOpenOptions, IChatViewHostRevealOptions, IChatViewHostService, IChatViewHostSessionStart, IChatViewHostSessionStartOptions, IChatViewHostShownSession } from '../../chatViewHost.js'; import { ChatViewPane } from './chatViewPane.js'; /** The Chat view, as the host of its chats. */ @@ -27,7 +28,13 @@ export class ChatViewPaneHost implements IChatViewHost { @IViewDescriptorService private readonly viewDescriptorService: IViewDescriptorService, @IWorkbenchLayoutService private readonly layoutService: IWorkbenchLayoutService, @IProgressService private readonly progressService: IProgressService, - ) { } + ) { + // The view exists once it first shows; it keeps its chat while hidden + const view = observableFromEvent(this, viewsService.onDidChangeViewVisibility, () => viewsService.getViewWithId(ChatViewId)); + this.shownSession = derived(this, reader => view.read(reader)?.shownSession.read(reader)); + } + + readonly shownSession: IObservable; async reveal(preserveFocus?: boolean, options?: IChatViewHostRevealOptions): Promise { const view = await this.viewsService.openView(ChatViewId, !preserveFocus); @@ -130,28 +137,39 @@ export class ChatViewHostService implements IChatViewHostService { private readonly chatViewHost: IChatViewHost; /** The registrations of the hosts that replace the Chat view, the one in use last: one each, also of the same host. */ private readonly registrations: { readonly host: IChatViewHost }[] = []; + private readonly hostInUse: ISettableObservable; + + readonly shownSession: IObservable; constructor( @IInstantiationService instantiationService: IInstantiationService, ) { this.chatViewHost = instantiationService.createInstance(ChatViewPaneHost); + this.hostInUse = observableValue(this, this.chatViewHost); + this.shownSession = derived(this, reader => this.hostInUse.read(reader).shownSession?.read(reader)); } private get host(): IChatViewHost { - return this.registrations.at(-1)?.host ?? this.chatViewHost; + return this.hostInUse.get(); } registerHost(host: IChatViewHost): IDisposable { const registration = { host }; this.registrations.push(registration); + this.updateHostInUse(); return toDisposable(() => { const index = this.registrations.indexOf(registration); if (index >= 0) { this.registrations.splice(index, 1); + this.updateHostInUse(); } }); } + private updateHostInUse(): void { + this.hostInUse.set(this.registrations.at(-1)?.host ?? this.chatViewHost, undefined); + } + reveal(preserveFocus?: boolean, options?: IChatViewHostRevealOptions): Promise { return this.host.reveal(preserveFocus, options); } diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index ff50f904ca9847..43fa62ff15327f 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -71,6 +71,7 @@ import { IWorkbenchLayoutService, LayoutSettings, Position } from '../../../../. import { AgentSessionsViewerOrientation, AgentSessionsViewerPosition } from '../../agentSessions/agentSessions.js'; import { IProgressService } from '../../../../../../platform/progress/common/progress.js'; import { CHAT_WIDGET_VIEW_STATE_CACHE_LIMIT, ChatViewId, IChatWidgetService, IChatWidgetViewState, setModelPreservingInputTypedWhileLoading } from '../../chat.js'; +import { IChatViewHostShownSession } from '../../chatViewHost.js'; import { IActivityService, ProgressBadge } from '../../../../../services/activity/common/activity.js'; import { DeferredPromise, disposableTimeout, raceCancellation, RunOnceScheduler } from '../../../../../../base/common/async.js'; import { AgentSessionsFilter, AgentSessionsGrouping } from '../../agentSessions/agentSessionsFilter.js'; @@ -169,6 +170,11 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private readonly activityBadge = this._register(new MutableDisposable()); private readonly _currentSessionResource = observableValue(this, undefined); + /** Whether the view restores the chat it last showed, rather than showing one that the user brought up. */ + private _restoringModel = false; + private readonly _shownSession = observableValue(this, undefined); + /** The chat the view shows, and whether it shows it as the user brought it up or as it restored it. */ + readonly shownSession: IObservable = this._shownSession; private readonly customizationMigrationsAvailable = observableValue(this, false); /** * Session resource of the last-focused chat widget, or this pane's own @@ -378,8 +384,10 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { try { this._widget.setVisible(false); + this._restoringModel = true; await this.showModel(cts.token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason); } finally { + this._restoringModel = false; this._widget.setVisible(wasVisible); } }).catch(error => { @@ -1246,6 +1254,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { const model = chatWidget.viewModel?.model; this.titleControl?.update(model); this._currentSessionResource.set(chatWidget.viewModel?.sessionResource, undefined); + const shownResource = chatWidget.viewModel?.sessionResource; + this._shownSession.set(shownResource && { resource: shownResource, reason: this._restoringModel ? 'restore' : 'open' }, undefined); if (this.sessionsViewerOrientation === AgentSessionsViewerOrientation.Stacked) { return; // only reveal in side-by-side mode @@ -1385,7 +1395,12 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private async _applyModel(token: CancellationToken): Promise { const session = await this.acquireTransferredOrPersistedSession(token, 'ChatViewPane#applyModel'); - await this.showModel(token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason); + this._restoringModel = true; + try { + await this.showModel(token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason); + } finally { + this._restoringModel = false; + } } /** diff --git a/src/vs/workbench/contrib/chat/common/constants.ts b/src/vs/workbench/contrib/chat/common/constants.ts index 134e29231a4374..8ef96a99bf1bc3 100644 --- a/src/vs/workbench/contrib/chat/common/constants.ts +++ b/src/vs/workbench/contrib/chat/common/constants.ts @@ -52,11 +52,6 @@ export enum ChatConfiguration { AgentsPickerInAttachContextMenu = 'sessions.chat.experimental.agentsPickerInAttachContextMenu', /** Desktop only: lets chat attach a screenshot of the window of another app. */ AppWindowScreenshotsEnabled = 'chat.appWindowScreenshots.enabled', - /** - * Lets an editor window with one local folder move that folder between its primary location and the worktrees its - * agent host sessions work in, and offer them when starting a session. - */ - EditorWindowEnableWorktree = 'chat.editorWindow.enableWorktree', PlanAgentDefaultModel = 'chat.planAgent.defaultModel', ExploreAgentDefaultModel = 'chat.exploreAgent.defaultModel', UtilityModel = 'chat.utilityModel', diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts index 25db610ef256bf..4408658d2fb144 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -5,7 +5,9 @@ import assert from 'assert'; import { DeferredPromise, timeout } from '../../../../../../../base/common/async.js'; +import { Emitter } from '../../../../../../../base/common/event.js'; import { toDisposable } from '../../../../../../../base/common/lifecycle.js'; +import { observableValue } from '../../../../../../../base/common/observable.js'; import { URI } from '../../../../../../../base/common/uri.js'; import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; @@ -16,7 +18,7 @@ import { IWorkbenchLayoutService, Parts } from '../../../../../../services/layou import { IViewsService } from '../../../../../../services/views/common/viewsService.js'; import { ChatViewId } from '../../../../browser/chat.js'; import { ChatWidget } from '../../../../browser/widget/chatWidget.js'; -import { IChatViewHost } from '../../../../browser/chatViewHost.js'; +import { IChatViewHost, IChatViewHostShownSession } from '../../../../browser/chatViewHost.js'; import { ChatViewHostService } from '../../../../browser/widgetHosts/viewPane/chatViewHostService.js'; import { ChatViewPane } from '../../../../browser/widgetHosts/viewPane/chatViewPane.js'; @@ -30,7 +32,11 @@ suite('ChatViewHostService', () => { const widget = upcastPartial({}); const created = new DeferredPromise(); let accesses = 0; + const shownSession = observableValue('shownSession', undefined); + const viewVisibility = disposables.add(new Emitter<{ id: string; visible: boolean }>()); + let viewCreated = false; const view = upcastPartial({ + shownSession, widget: options.widgetCreatedLater ? undefined : widget, get whenWidget() { accesses++; return created.p; }, loadSession: async (resource: URI, reason?: string) => { calls.push(`loadSession ${resource.toString()} reason=${reason}`); return undefined; }, @@ -43,13 +49,16 @@ suite('ChatViewHostService', () => { instantiationService.stub(IViewsService, upcastPartial({ openView: (async (id: string, focus?: boolean) => { calls.push(`openView ${id} focus=${focus}`); return view; }) as IViewsService['openView'], isViewVisible: () => !!options.chatVisible, + onDidChangeViewVisibility: viewVisibility.event, + getViewWithId: (() => (viewCreated ? view : undefined) as T | null) as IViewsService['getViewWithId'], })); instantiationService.stub(IViewDescriptorService, upcastPartial({ getViewLocationById: () => ViewContainerLocation.AuxiliaryBar })); instantiationService.stub(IWorkbenchLayoutService, upcastPartial({ setPartHidden: (hidden, part) => { calls.push(`setPartHidden ${hidden} ${part}`); } })); instantiationService.stub(IProgressService, upcastPartial({ withProgress: (async (_options: unknown, task: () => Promise) => { calls.push('progress'); await task(); calls.push('progress done'); }) as IProgressService['withProgress'], })); - return { service: instantiationService.createInstance(ChatViewHostService), widget, view, created, calls, accesses: () => accesses }; + const showView = () => { viewCreated = true; viewVisibility.fire({ id: ChatViewId, visible: true }); }; + return { service: instantiationService.createInstance(ChatViewHostService), widget, view, created, calls, accesses: () => accesses, shownSession, showView }; } test('without a host that replaces it, the Chat view shows the chats as before', async () => { @@ -134,4 +143,33 @@ suite('ChatViewHostService', () => { created.complete(widget); assert.deepStrictEqual({ unchanged, waiting, revealed: await pending === widget }, { unchanged: undefined, waiting: { accesses: 1, settled: false }, revealed: true }); }); + + test('the shown chat is the one of the host in use: the Chat view\'s once it exists, a registered host\'s while it is registered, if it reports one', () => { + const { service, shownSession, showView } = createService(); + const shown = () => service.shownSession.get()?.resource.path ?? service.shownSession.get(); + const steps: Record = {}; + const chat = URI.parse('test:/chat'); + const other = URI.parse('test:/other'); + + shownSession.set({ resource: chat, reason: 'restore' }, undefined); + steps.beforeTheViewExists = shown(); + showView(); + steps.view = service.shownSession.get(); + const hostShown = observableValue('hostShown', { resource: other, reason: 'open' }); + const registration = service.registerHost({ ...upcastPartial({}), shownSession: hostShown }); + steps.registeredHost = shown(); + const silentRegistration = service.registerHost(upcastPartial({})); + steps.hostWithoutOne = shown(); + silentRegistration.dispose(); + registration.dispose(); + steps.backToTheView = shown(); + + assert.deepStrictEqual(steps, { + beforeTheViewExists: undefined, + view: { resource: chat, reason: 'restore' }, + registeredHost: '/other', + hostWithoutOne: undefined, + backToTheView: '/chat', + }); + }); }); diff --git a/src/vs/workbench/services/workspaces/common/folderLocationSections.ts b/src/vs/workbench/services/workspaces/common/folderLocationSections.ts new file mode 100644 index 00000000000000..80b0c34923304c --- /dev/null +++ b/src/vs/workbench/services/workspaces/common/folderLocationSections.ts @@ -0,0 +1,52 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { localize } from '../../../../nls.js'; + +/** What a folder that a picker offers is: a folder of the window, such as its primary checkout, or a worktree of it. */ +export type FolderLocationKind = 'folder' | 'worktree'; + +/** A folder that a picker offers, with what it is and whether the window's folder is there now. */ +export interface IFolderLocationPickerEntry { + readonly item: T; + readonly kind: FolderLocationKind; + readonly current: boolean; +} + +/** A section of a folder picker: its title and its items, in the order they show. */ +export interface IFolderLocationPickerSection { + readonly kind: FolderLocationKind; + readonly title: string; + readonly items: readonly T[]; +} + +/** + * The sections of a picker that offers a window's folders and their worktrees, as every such picker shows them: after New + * Worktree, which comes first, a Folder section (Folders with several) and a Worktrees section. Each lists the folder that + * the window's folder is at now first, which shows {@link getCurrentFolderLocationDescription} as its description, and + * then the others in their order. A section without items is left out. + */ +export function groupFolderLocations(entries: readonly IFolderLocationPickerEntry[]): IFolderLocationPickerSection[] { + const sections: IFolderLocationPickerSection[] = []; + const section = (kind: FolderLocationKind, title: (count: number) => string) => { + const ofKind = entries.filter(entry => entry.kind === kind); + if (ofKind.length) { + sections.push({ kind, title: title(ofKind.length), items: [...ofKind.filter(entry => entry.current), ...ofKind.filter(entry => !entry.current)].map(entry => entry.item) }); + } + }; + section('folder', count => count > 1 ? localize('folderLocations.folders', "Folders") : localize('folderLocations.folder', "Folder")); + section('worktree', () => localize('folderLocations.worktrees', "Worktrees")); + return sections; +} + +/** The description of the folder that the window's folder is at now, in a picker of {@link groupFolderLocations}. */ +export function getCurrentFolderLocationDescription(): string { + return localize('folderLocations.current', "Current"); +} + +/** The label of the choice, first in a picker of {@link groupFolderLocations}, that starts a session in a new worktree. */ +export function getNewWorktreeLabel(): string { + return localize('folderLocations.newWorktree', "New Worktree"); +} diff --git a/src/vs/workbench/services/workspaces/test/common/folderLocationSections.test.ts b/src/vs/workbench/services/workspaces/test/common/folderLocationSections.test.ts new file mode 100644 index 00000000000000..06587ca46e99b6 --- /dev/null +++ b/src/vs/workbench/services/workspaces/test/common/folderLocationSections.test.ts @@ -0,0 +1,39 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { groupFolderLocations } from '../../common/folderLocationSections.js'; + +suite('FolderLocationSections', () => { + ensureNoDisposablesAreLeakedInTestSuite(); + + test('a Folder section and a Worktrees section, each with the current folder first and the others in their order, without empty sections', () => { + const sections = (entries: Parameters>[0]) => groupFolderLocations(entries).map(section => `${section.title}: ${section.items.join(', ')}`); + + assert.deepStrictEqual({ + atWorktree: sections([ + { item: 'a', kind: 'worktree', current: false }, + { item: 'vscode', kind: 'folder', current: false }, + { item: 'b', kind: 'worktree', current: true }, + { item: 'c', kind: 'worktree', current: false }, + ]), + atFolder: sections([ + { item: 'a', kind: 'worktree', current: false }, + { item: 'vscode', kind: 'folder', current: true }, + ]), + severalFolders: sections([ + { item: 'vscode', kind: 'folder', current: false }, + { item: 'tools', kind: 'folder', current: true }, + ]), + none: sections([]), + }, { + atWorktree: ['Folder: vscode', 'Worktrees: b, a, c'], + atFolder: ['Folder: vscode', 'Worktrees: a'], + severalFolders: ['Folders: tools, vscode'], + none: [], + }); + }); +}); From 6ad6b5f6ade89eaa1352cbdc0641de7221582dd5 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 05:07:17 +0100 Subject: [PATCH 03/20] Chat view: report 'restore' only for the chat that the view restores, not one that the user loads meanwhile The Chat view marked every chat it showed while its restore was under way as restored, also a chat that the user loaded meanwhile and that superseded the restore. It now passes the reason with the chat it shows, and reports it only while it sets that chat. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../widgetHosts/viewPane/chatViewPane.ts | 35 ++++++++------ .../widgetHosts/viewPane/chatViewPane.test.ts | 48 ++++++++++++++++++- 2 files changed, 67 insertions(+), 16 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index 43fa62ff15327f..f6fb97b444ca79 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -170,8 +170,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private readonly activityBadge = this._register(new MutableDisposable()); private readonly _currentSessionResource = observableValue(this, undefined); - /** Whether the view restores the chat it last showed, rather than showing one that the user brought up. */ - private _restoringModel = false; + /** Why the view sets the chat it shows, while it sets it: it restores the chat it last showed, or the user brought one up. */ + private _showReason: IChatViewHostShownSession['reason'] = 'open'; private readonly _shownSession = observableValue(this, undefined); /** The chat the view shows, and whether it shows it as the user brought it up or as it restored it. */ readonly shownSession: IObservable = this._shownSession; @@ -384,10 +384,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { try { this._widget.setVisible(false); - this._restoringModel = true; - await this.showModel(cts.token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason); + await this.showModel(cts.token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason, 'restore'); } finally { - this._restoringModel = false; this._widget.setVisible(wasVisible); } }).catch(error => { @@ -1254,8 +1252,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { const model = chatWidget.viewModel?.model; this.titleControl?.update(model); this._currentSessionResource.set(chatWidget.viewModel?.sessionResource, undefined); - const shownResource = chatWidget.viewModel?.sessionResource; - this._shownSession.set(shownResource && { resource: shownResource, reason: this._restoringModel ? 'restore' : 'open' }, undefined); + this.updateShownSession(); if (this.sessionsViewerOrientation === AgentSessionsViewerOrientation.Stacked) { return; // only reveal in side-by-side mode @@ -1395,12 +1392,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private async _applyModel(token: CancellationToken): Promise { const session = await this.acquireTransferredOrPersistedSession(token, 'ChatViewPane#applyModel'); - this._restoringModel = true; - try { - await this.showModel(token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason); - } finally { - this._restoringModel = false; - } + await this.showModel(token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason, 'restore'); } /** @@ -1510,7 +1502,14 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { && sessionType === localChatSessionType; } - private async showModel(token: CancellationToken, modelRef?: IChatModelReference | undefined, startNewSession = true, ignoreTransferredSession = false, inputBeforeLoad?: string, localFallbackSelectionReason?: SessionTypeSelectionReason): Promise { + /** Reports the chat that the view shows now ({@link shownSession}), as its widget's chat changes. */ + private updateShownSession(): void { + const shownResource = this._widget.viewModel?.sessionResource; + this._shownSession.set(shownResource && { resource: shownResource, reason: this._showReason }, undefined); + } + + /** @param showReason why it shows the chat ({@link shownSession}): only the view's own restore passes `restore`. */ + private async showModel(token: CancellationToken, modelRef?: IChatModelReference | undefined, startNewSession = true, ignoreTransferredSession = false, inputBeforeLoad?: string, localFallbackSelectionReason?: SessionTypeSelectionReason, showReason: IChatViewHostShownSession['reason'] = 'open'): Promise { if (token.isCancellationRequested || this._store.isDisposed) { modelRef?.dispose(); return undefined; @@ -1572,7 +1571,13 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { this._widget.unlockFromCodingAgent(); } this.viewState.sessionResource = model.sessionResource; - setModelPreservingInputTypedWhileLoading(this._widget, baselineInput, () => this._widget.setModel(model)); + // The reason holds only while the model is set, so a chat shown meanwhile never takes another's reason + this._showReason = showReason; + try { + setModelPreservingInputTypedWhileLoading(this._widget, baselineInput, () => this._widget.setModel(model)); + } finally { + this._showReason = 'open'; + } const widgetViewState = this.widgetViewStates.get(getComparisonKey(model.sessionResource)); if (widgetViewState) { this._widget.restoreViewState(widgetViewState); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 17c349b7be14c0..1519cbf2e27c49 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -8,7 +8,7 @@ import { CancellationToken, CancellationTokenSource } from '../../../../../../.. import { CancellationError } from '../../../../../../../base/common/errors.js'; import { DeferredPromise, RunOnceScheduler, timeout } from '../../../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../../../base/common/event.js'; -import { constObservable } from '../../../../../../../base/common/observable.js'; +import { constObservable, IObservable, observableValue } from '../../../../../../../base/common/observable.js'; import { DisposableStore, MutableDisposable, toDisposable } from '../../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; @@ -20,6 +20,7 @@ import { NullLogService } from '../../../../../../../platform/log/common/log.js' import { AccountPolicyGateState } from '../../../../../../services/policies/common/accountPolicyService.js'; import { TestContextService, TestStorageService } from '../../../../../../test/common/workbenchTestServices.js'; import { ChatViewPane } from '../../../../browser/widgetHosts/viewPane/chatViewPane.js'; +import { IChatViewHostShownSession } from '../../../../browser/chatViewHost.js'; import { ChatWidget } from '../../../../browser/widget/chatWidget.js'; import { mainWindow } from '../../../../../../../base/browser/window.js'; import { ChatOpenDiagnosticsService } from '../../../../common/chatOpenDiagnosticsService.js'; @@ -166,11 +167,14 @@ suite('ChatViewPane session transitions', () => { function createPane(resolving: Promise = Promise.resolve(), preparing: Promise = Promise.resolve()) { const previousModel = upcastPartial({ sessionResource: previousResource }); const nextModel = upcastPartial({ sessionResource: nextResource }); + const shownSession = observableValue('shownSession', undefined); let shown: IChatModel | undefined = previousModel; let input = 'previous draft'; const bindings: (URI | undefined)[] = []; const disposed: URI[] = []; const locks: string[] = []; + /** Tells the pane its widget's chat changed, as the widget's onDidChangeViewModel does. */ + let didChangeViewModel = () => { }; const paneStore = store.add(new DisposableStore()); const modelRef = paneStore.add(new MutableDisposable()); const createReference = (model: IChatModel): IChatModelReference => Object.assign(toDisposable(() => { @@ -188,6 +192,7 @@ suite('ChatViewPane session transitions', () => { shown = model; input = ''; bindings.push(model?.sessionResource); + didChangeViewModel(); }, lockToCodingAgent: (_name: string, _displayName: string, sessionType: string) => { locks.push(sessionType); }, unlockFromCodingAgent: () => { locks.push('local'); }, @@ -200,8 +205,12 @@ suite('ChatViewPane session transitions', () => { loadSession(resource: URI): Promise; applyModel(): void; restoringSession: Promise | undefined; + readonly shownSession: IObservable; } = Object.assign(Object.create(ChatViewPane.prototype), { _store: paneStore, + _showReason: 'open', + _shownSession: shownSession, + shownSession, modelRef, widgetViewStates: new Map(), viewState: {}, @@ -222,6 +231,7 @@ suite('ChatViewPane session transitions', () => { agentSessionsService: { model: { getSession: () => undefined } }, updateActions: () => { }, }); + didChangeViewModel = () => (Reflect.get(pane, 'updateShownSession') as () => void).call(pane); return { pane, paneStore, widget, modelRef, nextModel, nextRef, bindings, disposed, locks }; } @@ -270,6 +280,42 @@ suite('ChatViewPane session transitions', () => { }); } + test('reports a restored chat as restored and a chat that the user loads as opened, also one that supersedes a restore under way', async () => { + const shown = (rig: ReturnType) => { const value = rig.pane.shownSession.get(); return value && `${value.resource.path} ${value.reason}`; }; + const savedResource = nextResource.with({ path: '/saved' }); + const savedReference = () => Object.assign(toDisposable(() => { }), { object: upcastPartial({ sessionResource: savedResource }) }); + + const restored = createPane(); + Object.assign(restored.pane, { acquireTransferredOrPersistedSession: async () => ({ modelRef: restored.nextRef }) }); + restored.pane.applyModel(); + await restored.pane.restoringSession; + const afterRestore = shown(restored); + Object.assign(restored.pane, { chatService: { acquireOrLoadSession: async () => savedReference() } }); + await restored.pane.loadSession(savedResource); + const afterLoad = shown(restored); + + // The user loads a chat while the restore still prepares its chat's configuration + const preparing = new DeferredPromise(); + const superseded = createPane(Promise.resolve(), preparing.p); + Object.assign(superseded.pane, { + acquireTransferredOrPersistedSession: async () => ({ modelRef: superseded.nextRef }), + chatService: { acquireOrLoadSession: async () => savedReference() }, + }); + superseded.pane.applyModel(); + const restoration = superseded.pane.restoringSession; + await timeout(0); + const loading = superseded.pane.loadSession(savedResource); + await preparing.complete(); + await loading; + await restoration; + + assert.deepStrictEqual({ afterRestore, afterLoad, superseded: shown(superseded) }, { + afterRestore: '/untitled-next restore', + afterLoad: '/saved open', + superseded: '/saved open', + }); + }); + test('cancelling a replacement releases its pending reference before provider activation completes', async () => { const resolving = new DeferredPromise(); const rig = createPane(resolving.p); From ecd54bd23314c2132b9dbe4851bb7237a36e1559 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 05:26:07 +0100 Subject: [PATCH 04/20] Worktree infra: wait for the sessions list before reading working directories, and report an explicitly opened chat as opened Copilot code review fixes: - AgentHostWorktreeLocationProvider waits for the sessions list to resolve before reading the working directories of its sessions, so the worktrees of sessions that it did not cache are not missing. - The Chat view reports a chat that the user opens or reveals as opened, also one that it shows already, such as one it restored that the user picks in a sessions list (ChatViewPane.reportOpened, from the Chat view host's openSession and revealIfShowing). Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 11 ++++++++++- .../widgetHosts/viewPane/chatViewHostService.ts | 3 +++ .../browser/widgetHosts/viewPane/chatViewPane.ts | 11 +++++++++++ .../test/browser/actions/chatMoveActions.test.ts | 1 + .../agentHost/agentHostWorktreeLocations.test.ts | 12 ++++++++++-- .../test/browser/widget/chatWidgetService.test.ts | 4 ++-- .../widgetHosts/viewPane/chatViewHostService.test.ts | 3 ++- .../widgetHosts/viewPane/chatViewPane.test.ts | 10 +++++++++- 8 files changed, 48 insertions(+), 7 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index f9f07f83b22e96..3f15cdde56ff82 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { raceCancellation } from '../../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { Schemas } from '../../../../../../base/common/network.js'; @@ -63,7 +64,15 @@ export class AgentHostWorktreeLocationProvider implements IWorkspaceFolderLocati if (!repository || token.isCancellationRequested) { return []; } - const candidates = getAgentHostSessionWorkingDirectories(this._agentSessionsService.model.sessions) + // Before the sessions list first resolves, it has only the sessions it cached: wait for the ones it has not + const model = this._agentSessionsService.model; + if (!model.resolved) { + await raceCancellation(model.resolve(undefined, undefined, 'automatic'), token); + if (token.isCancellationRequested) { + return []; + } + } + const candidates = getAgentHostSessionWorkingDirectories(model.sessions) .filter(directory => !extUriBiasedIgnorePathCase.isEqual(directory, primary)); const locations = await Promise.all(candidates.map(candidate => this._resolve(repository, candidate))); return token.isCancellationRequested ? [] : locations.filter(isDefined); diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index b3358545b032f1..fd9906d05b0d13 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -53,6 +53,7 @@ export class ChatViewPaneHost implements IChatViewHost { if (view && !options?.preserveFocus) { view.focus(); } + view?.reportOpened(sessionResource); return view?.widget; } @@ -60,6 +61,8 @@ export class ChatViewPaneHost implements IChatViewHost { const chatView = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); if (chatView) { await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason); + // Also a chat it showed already, which loading does not set again + chatView.reportOpened(sessionResource); if (!options?.preserveFocus) { chatView.focusInput(); } diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index f6fb97b444ca79..f906948705e79a 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -1502,6 +1502,17 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { && sessionType === localChatSessionType; } + /** + * Reports the chat of `sessionResource` as one that the user brought up, also where the view shows it already, such as + * one it restored that the user picks in a sessions list. + */ + reportOpened(sessionResource: URI): void { + const shown = this._shownSession.get(); + if (shown?.reason === 'restore' && isEqual(shown.resource, sessionResource)) { + this._shownSession.set({ resource: sessionResource, reason: 'open' }, undefined); + } + } + /** Reports the chat that the view shows now ({@link shownSession}), as its widget's chat changes. */ private updateShownSession(): void { const shownResource = this._widget.viewModel?.sessionResource; diff --git a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts index 028b8050633834..2c04a11d900ba8 100644 --- a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts @@ -91,6 +91,7 @@ suite('Chat move actions', () => { return model; }, focusInput() { }, + reportOpened() { }, }); const viewsService = upcastPartial({ openView: mockObject()().openView.resolves(view), diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index 9fa274f2adaed0..174b5726638b09 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -28,7 +28,7 @@ suite('AgentHostWorktreeLocations', () => { * A provider over git entries: `true` is a `.git` directory, and a string the content of a file, such as a worktree's * `.git` file or its entry's `gitdir` file in the repository. */ - function createProvider(entries: Record, sessions: readonly IAgentSession[]) { + function createProvider(entries: Record, sessions: readonly IAgentSession[], uncached: readonly IAgentSession[] = []) { const fileService = upcastPartial({ stat: async (resource: URI) => { const entry = entries[resource.path]; @@ -48,7 +48,9 @@ suite('AgentHostWorktreeLocations', () => { const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(IFileService, fileService); instantiationService.stub(ILogService, new NullLogService()); - instantiationService.stub(IAgentSessionsService, upcastPartial({ model: upcastPartial({ sessions: [...sessions] }) })); + // The sessions it cached, and those the list has only once it resolved + const model = { sessions: [...sessions], resolved: !uncached.length, resolve: async () => { model.sessions.push(...uncached); model.resolved = true; } }; + instantiationService.stub(IAgentSessionsService, upcastPartial({ model: upcastPartial(model) })); return instantiationService.createInstance(AgentHostWorktreeLocationProvider); } @@ -110,4 +112,10 @@ suite('AgentHostWorktreeLocations', () => { primary: undefined, }); }); + + test('waits for the sessions list to resolve before reading the working directories of sessions it did not cache', async () => { + const provider = createProvider(repository, [session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/feature')], [session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/relative')]); + const locations = await provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None); + assert.deepStrictEqual(locations.map(location => location.label), ['feature', 'relative']); + }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts index b0a653dd42ac82..ef9c2aa54f5400 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts @@ -218,7 +218,7 @@ suite('ChatWidgetService', () => { const oldWidget = createWidget(session); const emptyOldWidget = createWidget(undefined); const hostWidget = upcastPartial({}); - const view = { widget: oldWidget, focus: () => calls.push('view.focus'), loadSession: async () => { calls.push('view.loadSession'); } }; + const view = { widget: oldWidget, focus: () => calls.push('view.focus'), loadSession: async () => { calls.push('view.loadSession'); }, reportOpened: () => calls.push('view.reportOpened') }; instantiationService.stub(IEditorGroupsService, { groups: [] }); instantiationService.stub(IViewsService, { getViewWithId: (() => view) as unknown as IViewsService['getViewWithId'], @@ -275,7 +275,7 @@ suite('ChatWidgetService', () => { const widget = await service.openSession(session); - assert.deepStrictEqual({ shown: widget === oldWidget, calls }, { shown: true, calls: [`openView ${ChatViewId}`, 'view.focus'] }); + assert.deepStrictEqual({ shown: widget === oldWidget, calls }, { shown: true, calls: [`openView ${ChatViewId}`, 'view.focus', 'view.reportOpened'] }); }); }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts index 4408658d2fb144..abbfa90a26e95f 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -43,6 +43,7 @@ suite('ChatViewHostService', () => { startNewLocalSession: async () => { calls.push('startNewLocalSession'); return undefined; }, focus: () => { calls.push('focus'); }, focusInput: () => { calls.push('focusInput'); }, + reportOpened: (resource: URI) => { calls.push(`reportOpened ${resource.toString()}`); }, beginSessionsListSuppression: () => { calls.push('suppress'); return toDisposable(() => calls.push('unsuppress')); }, }); const instantiationService = disposables.add(new TestInstantiationService()); @@ -83,7 +84,7 @@ suite('ChatViewHostService', () => { calls: [ `openView ${ChatViewId} focus=true`, `openView ${ChatViewId} focus=false`, - `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'focusInput', + `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'reportOpened test:/session', 'focusInput', `setPartHidden false ${Parts.AUXILIARYBAR_PART}`, `openView ${ChatViewId} focus=undefined`, 'beforeOpen', 'suppress', 'progress', 'loadSession test:/session reason=explicitOverride', 'focus', `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined', diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 1519cbf2e27c49..4e888b7ec9db8c 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -206,6 +206,7 @@ suite('ChatViewPane session transitions', () => { applyModel(): void; restoringSession: Promise | undefined; readonly shownSession: IObservable; + reportOpened(sessionResource: URI): void; } = Object.assign(Object.create(ChatViewPane.prototype), { _store: paneStore, _showReason: 'open', @@ -290,6 +291,11 @@ suite('ChatViewPane session transitions', () => { restored.pane.applyModel(); await restored.pane.restoringSession; const afterRestore = shown(restored); + // The user picks the restored chat that the view shows already, such as in a sessions list + restored.pane.reportOpened(previousResource); + const otherReported = shown(restored); + restored.pane.reportOpened(nextResource); + const reopened = shown(restored); Object.assign(restored.pane, { chatService: { acquireOrLoadSession: async () => savedReference() } }); await restored.pane.loadSession(savedResource); const afterLoad = shown(restored); @@ -309,8 +315,10 @@ suite('ChatViewPane session transitions', () => { await loading; await restoration; - assert.deepStrictEqual({ afterRestore, afterLoad, superseded: shown(superseded) }, { + assert.deepStrictEqual({ afterRestore, otherReported, reopened, afterLoad, superseded: shown(superseded) }, { afterRestore: '/untitled-next restore', + otherReported: '/untitled-next restore', + reopened: '/untitled-next open', afterLoad: '/saved open', superseded: '/saved open', }); From 1272926d0948ffa1704fba9831b7c81831de6633 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 05:37:34 +0100 Subject: [PATCH 05/20] Worktree infra: describe worktrees by branch, compare real paths, and report first sends and restored opens - The location provider resolves through real paths (a symlinked primary or worktree keeps its identity), reads the entry's HEAD for the branch or short commit, and no longer drops all locations when one fails to read. - IChatViewHostShownSession gains reason 'commit' for the chat a first request made; IChatViewHostOpenOptions gains restore to show a session without reporting it as opened. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 107 ++++++++++++------ .../contrib/chat/browser/chatViewHost.ts | 13 ++- .../viewPane/chatViewHostService.ts | 10 +- .../widgetHosts/viewPane/chatViewPane.ts | 10 +- .../agentHostWorktreeLocations.test.ts | 29 ++++- .../viewPane/chatViewHostService.test.ts | 5 +- .../widgetHosts/viewPane/chatViewPane.test.ts | 10 +- 7 files changed, 135 insertions(+), 49 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index 3f15cdde56ff82..904f53daca7fa6 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -8,7 +8,7 @@ import { CancellationToken } from '../../../../../../base/common/cancellation.js import { Codicon } from '../../../../../../base/common/codicons.js'; import { Schemas } from '../../../../../../base/common/network.js'; import { isAbsolute } from '../../../../../../base/common/path.js'; -import { basename, extUriBiasedIgnorePathCase, joinPath } from '../../../../../../base/common/resources.js'; +import { basename, dirname, extUriBiasedIgnorePathCase, joinPath, normalizePath } from '../../../../../../base/common/resources.js'; import { isDefined } from '../../../../../../base/common/types.js'; import { URI } from '../../../../../../base/common/uri.js'; import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../../../platform/files/common/files.js'; @@ -60,8 +60,8 @@ export class AgentHostWorktreeLocationProvider implements IWorkspaceFolderLocati ) { } async provideLocations(primary: URI, token: CancellationToken): Promise { - const repository = await this._readRepository(primary); - if (!repository || token.isCancellationRequested) { + const worktreesDir = await this._worktreesDir(primary); + if (!worktreesDir || token.isCancellationRequested) { return []; } // Before the sessions list first resolves, it has only the sessions it cached: wait for the ones it has not @@ -74,64 +74,101 @@ export class AgentHostWorktreeLocationProvider implements IWorkspaceFolderLocati } const candidates = getAgentHostSessionWorkingDirectories(model.sessions) .filter(directory => !extUriBiasedIgnorePathCase.isEqual(directory, primary)); - const locations = await Promise.all(candidates.map(candidate => this._resolve(repository, candidate))); + const locations = await Promise.all(candidates.map(async candidate => { + try { + return await this._resolve(worktreesDir, primary, candidate); + } catch (error) { + // One working directory that fails to read, such as a pruned worktree, does not hide the others + this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git checkout of ${candidate.toString()}`, error); + return undefined; + } + })); return token.isCancellationRequested ? [] : locations.filter(isDefined); } async resolveLocation(primary: URI, location: URI, token: CancellationToken): Promise { // Any linked checkout of the repository resolves, also before the sessions load, such as to restore the location // that the window's folder was at - if (extUriBiasedIgnorePathCase.isEqual(location, primary)) { - return undefined; - } - const repository = await this._readRepository(primary); - if (!repository || token.isCancellationRequested) { - return undefined; - } - return this._resolve(repository, location); + const worktreesDir = await this._worktreesDir(primary); + return worktreesDir && !token.isCancellationRequested ? this._resolve(worktreesDir, primary, location) : undefined; } - /** The git repository of the local folder `folder` is a checkout of, if any. */ - private async _readRepository(folder: URI): Promise { - if (folder.scheme !== Schemas.file) { + /** Where the worktrees of the repository of the local folder `primary` are kept: `.git/worktrees` of its real path. */ + private async _worktreesDir(primary: URI): Promise { + if (primary.scheme !== Schemas.file) { return undefined; } try { - return (await readFolderGitCheckout(this._fileService, folder))?.repository; + const checkout = await readFolderGitCheckout(this._fileService, await this._real(primary)); + return checkout && joinPath(await this._real(checkout.repository), '.git', 'worktrees'); } catch (error) { - this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git repository of ${folder.toString()}`, error); + this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git repository of ${primary.toString()}`, error); return undefined; } } - /** `candidate` as a location of `repository`'s folder, when it is a linked checkout of that repository. */ - private async _resolve(repository: URI, candidate: URI): Promise { - if (candidate.scheme !== Schemas.file) { + /** + * `location` as a location of the folder at `primary`, when git links it both ways with an entry of `worktreesDir`: its + * `.git` file names the entry, and the entry's `gitdir` file names its `.git` back, by their real paths, such as of a + * folder reached through a symbolic link. + */ + private async _resolve(worktreesDir: URI, primary: URI, location: URI): Promise { + if (location.scheme !== Schemas.file) { return undefined; } - try { - const checkout = await readFolderGitCheckout(this._fileService, candidate); - if (!checkout?.worktreeGitDir || !extUriBiasedIgnorePathCase.isEqual(checkout.repository, repository) || !await this._namesBack(checkout.worktreeGitDir, candidate)) { - return undefined; - } - } catch (error) { - this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git checkout of ${candidate.toString()}`, error); + const realLocation = await this._real(location); + if (extUriBiasedIgnorePathCase.isEqual(await this._real(primary), realLocation)) { + return undefined; + } + const locationGitFile = joinPath(realLocation, '.git'); + const entry = await this._readLink(locationGitFile, dirname(locationGitFile), /^gitdir:\s*(?.+?)\s*$/m); + if (!entry || !extUriBiasedIgnorePathCase.isEqual(dirname(await this._real(entry)), worktreesDir)) { return undefined; } - return { uri: candidate, label: basename(candidate), icon: Codicon.gitBranchCheckout }; + const backlink = await this._readLink(joinPath(entry, 'gitdir'), entry); + if (!backlink || !extUriBiasedIgnorePathCase.isEqual(await this._real(backlink), locationGitFile)) { + return undefined; + } + // Its branch, from the entry's HEAD: read again each time the location is resolved + const head = await this._readOrUndefined(async () => (await this._fileService.readFile(joinPath(entry, 'HEAD'))).value.toString()); + return { uri: location, label: basename(location), description: head !== undefined ? parseGitHead(head) : undefined, icon: Codicon.gitBranchCheckout }; + } + + /** The path a link file names, absolute and normalized: its content, or the `pattern`'s `path` group of it, relative to `base`. */ + private async _readLink(file: URI, base: URI, pattern?: RegExp): Promise { + const content = await this._readOrUndefined(async () => (await this._fileService.readFile(file)).value.toString()); + const path = content && (pattern ? pattern.exec(content)?.groups?.path : content.trim()); + if (!path) { + return undefined; + } + return normalizePath(isAbsolute(path) ? URI.file(path) : joinPath(base, path)); } - /** Whether the repository's entry for a worktree, `worktreeGitDir`, names the `.git` of `folder` back. */ - private async _namesBack(worktreeGitDir: URI, folder: URI): Promise { - let content: string; + /** `resource` with its symbolic links resolved, or itself where it is not there. */ + private async _real(resource: URI): Promise { + return normalizePath(await this._readOrUndefined(() => this._fileService.realpath(resource)) ?? resource); + } + + /** The result of `read`, or `undefined` where what it reads is not there or is a folder, such as an ordinary checkout's `.git`; any other failure throws. */ + private async _readOrUndefined(read: () => Promise): Promise { try { - content = (await this._fileService.readFile(joinPath(worktreeGitDir, 'gitdir'))).value.toString().trim(); + return await read(); } catch (error) { - if (error instanceof Error && toFileOperationResult(error) === FileOperationResult.FILE_NOT_FOUND) { - return false; + const result = error instanceof Error ? toFileOperationResult(error) : undefined; + if (result === FileOperationResult.FILE_NOT_FOUND || result === FileOperationResult.FILE_IS_DIRECTORY) { + return undefined; } throw error; } - return !!content && extUriBiasedIgnorePathCase.isEqual(isAbsolute(content) ? URI.file(content) : joinPath(worktreeGitDir, content), joinPath(folder, '.git')); } } + +/** The branch a git HEAD names (`ref: refs/heads/`), the short commit of a detached one, or `undefined`. */ +export function parseGitHead(head: string): string | undefined { + const content = head.trim(); + const branch = /^ref:\s*refs\/heads\/(?.+)$/.exec(content)?.groups?.branch; + if (branch) { + return branch; + } + return /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/i.test(content) ? content.slice(0, 7) : undefined; +} diff --git a/src/vs/workbench/contrib/chat/browser/chatViewHost.ts b/src/vs/workbench/contrib/chat/browser/chatViewHost.ts index 226d8e995e7d8f..023643c1774412 100644 --- a/src/vs/workbench/contrib/chat/browser/chatViewHost.ts +++ b/src/vs/workbench/contrib/chat/browser/chatViewHost.ts @@ -16,10 +16,12 @@ export const IChatViewHostService = createDecorator('chatV export interface IChatViewHostShownSession { readonly resource: URI; /** - * `open` when the user brought the chat up, such as by picking it in the sessions list, starting a new chat or sending - * the first request of one; `restore` when the host shows the chat it last showed, such as as the window starts. + * `open` when the user brought the chat up, such as by picking it in the sessions list or starting a new chat; + * `commit` when the first request of a new chat made it the session it became, which the user did not pick; `restore` + * when the host shows a chat that it does not bring up for the user, such as the chat it last showed as the window + * starts, or one opened with {@link IChatViewHostOpenOptions.restore}. */ - readonly reason: 'open' | 'restore'; + readonly reason: 'open' | 'commit' | 'restore'; } /** How {@link IChatViewHost.reveal} shows the host. */ @@ -35,6 +37,11 @@ export interface IChatViewHostRevealOptions { export interface IChatViewHostOpenOptions { readonly preserveFocus?: boolean; readonly sessionTypeSelectionReason?: SessionTypeSelectionReason; + /** + * Shows the session as one the host restores ({@link IChatViewHostShownSession.reason} `restore`) rather than one + * the user opens, such as the chat that was last shown where the user moved the window's folder. + */ + readonly restore?: boolean; } /** How {@link IChatViewHost.startSession} starts a session that its caller may send a first request to. */ diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index fd9906d05b0d13..0769a48767e0d5 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -53,16 +53,20 @@ export class ChatViewPaneHost implements IChatViewHost { if (view && !options?.preserveFocus) { view.focus(); } - view?.reportOpened(sessionResource); + if (!options?.restore) { + view?.reportOpened(sessionResource); + } return view?.widget; } async openSession(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise { const chatView = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); if (chatView) { - await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason); + await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason, options?.restore ? 'restore' : 'open'); // Also a chat it showed already, which loading does not set again - chatView.reportOpened(sessionResource); + if (!options?.restore) { + chatView.reportOpened(sessionResource); + } if (!options?.preserveFocus) { chatView.focusInput(); } diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index f906948705e79a..433bd71e7c30f3 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -345,7 +345,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { } const modelRef = await this.chatService.acquireOrLoadSession(e.committed, ChatAgentLocation.Chat, CancellationToken.None, 'ChatViewPane#onDidCommitSession'); - await this.showModel(CancellationToken.None, modelRef); + // The chat the first request made: a session the user did not pick + await this.showModel(CancellationToken.None, modelRef, undefined, undefined, undefined, undefined, 'commit'); })); // Layout changes @@ -1519,7 +1520,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { this._shownSession.set(shownResource && { resource: shownResource, reason: this._showReason }, undefined); } - /** @param showReason why it shows the chat ({@link shownSession}): only the view's own restore passes `restore`. */ + /** @param showReason why it shows the chat ({@link shownSession}). */ private async showModel(token: CancellationToken, modelRef?: IChatModelReference | undefined, startNewSession = true, ignoreTransferredSession = false, inputBeforeLoad?: string, localFallbackSelectionReason?: SessionTypeSelectionReason, showReason: IChatViewHostShownSession['reason'] = 'open'): Promise { if (token.isCancellationRequested || this._store.isDisposed) { modelRef?.dispose(); @@ -1672,7 +1673,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { this.updateActions(); } - async loadSession(sessionResource: URI, sessionTypeSelectionReason?: SessionTypeSelectionReason): Promise { + /** @param showReason why it shows the chat ({@link shownSession}). */ + async loadSession(sessionResource: URI, sessionTypeSelectionReason?: SessionTypeSelectionReason, showReason: 'open' | 'restore' = 'open'): Promise { const t0 = Date.now(); this.logService.trace(`[ChatViewPane] loadSession start uri=${sessionResource.toString()}`); @@ -1730,7 +1732,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { } const localFallbackSelectionReason = getLocalFallbackSessionTypeSelectionReason(getChatSessionType(sessionResource), !!newModelRef); - const result = await this.showModel(token, newModelRef, true, false, inputBeforeLoad, localFallbackSelectionReason); + const result = await this.showModel(token, newModelRef, true, false, inputBeforeLoad, localFallbackSelectionReason, showReason); this.logService.trace(`[ChatViewPane] loadSession done total=${Date.now() - t0}ms uri=${sessionResource.toString()}`); return result; } catch (err) { diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index 174b5726638b09..0c1af172077e39 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -28,7 +28,7 @@ suite('AgentHostWorktreeLocations', () => { * A provider over git entries: `true` is a `.git` directory, and a string the content of a file, such as a worktree's * `.git` file or its entry's `gitdir` file in the repository. */ - function createProvider(entries: Record, sessions: readonly IAgentSession[], uncached: readonly IAgentSession[] = []) { + function createProvider(entries: Record, sessions: readonly IAgentSession[], uncached: readonly IAgentSession[] = [], links: Record = {}) { const fileService = upcastPartial({ stat: async (resource: URI) => { const entry = entries[resource.path]; @@ -37,6 +37,11 @@ suite('AgentHostWorktreeLocations', () => { } return upcastPartial({ isDirectory: entry === true }); }, + // A path through a symbolic link, such as `links['/link/vscode'] = '/work/vscode'`, is the path it links to + realpath: async (resource: URI) => { + const link = Object.keys(links).find(path => resource.path === path || resource.path.startsWith(`${path}/`)); + return link ? URI.file(links[link] + resource.path.slice(link.length)) : resource; + }, readFile: async (resource: URI) => { const entry = entries[resource.path]; if (typeof entry !== 'string') { @@ -59,6 +64,11 @@ suite('AgentHostWorktreeLocations', () => { // A worktree whose repository entry names it back '/work/vscode.worktrees/feature/.git': 'gitdir: /work/vscode/.git/worktrees/feature\n', '/work/vscode/.git/worktrees/feature/gitdir': '/work/vscode.worktrees/feature/.git\n', + '/work/vscode/.git/worktrees/feature/HEAD': 'ref: refs/heads/agents/feature\n', + // A worktree at a detached commit + '/work/vscode.worktrees/detached/.git': 'gitdir: /work/vscode/.git/worktrees/detached\n', + '/work/vscode/.git/worktrees/detached/gitdir': '/work/vscode.worktrees/detached/.git\n', + '/work/vscode/.git/worktrees/detached/HEAD': '0123456789abcdef0123456789abcdef01234567\n', // One with a relative link back '/work/vscode.worktrees/relative/.git': 'gitdir: /work/vscode/.git/worktrees/relative', '/work/vscode/.git/worktrees/relative/gitdir': '../../../../vscode.worktrees/relative/.git', @@ -118,4 +128,21 @@ suite('AgentHostWorktreeLocations', () => { const locations = await provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None); assert.deepStrictEqual(locations.map(location => location.label), ['feature', 'relative']); }); + + test('a worktree is described by its branch, the short commit of a detached HEAD, or nothing without HEAD', async () => { + const provider = createProvider(repository, []); + const describe = async (path: string) => (await provider.resolveLocation(URI.file('/work/vscode'), URI.file(path), CancellationToken.None))?.description; + assert.deepStrictEqual({ branch: await describe('/work/vscode.worktrees/feature'), detached: await describe('/work/vscode.worktrees/detached'), withoutHead: await describe('/work/vscode.worktrees/relative') }, { branch: 'agents/feature', detached: '0123456', withoutHead: undefined }); + }); + + test('compares the folder and its worktrees by their real paths, such as through a symbolic link', async () => { + const provider = createProvider(repository, [session(SessionType.AgentHostCopilot, '/alias/feature')], [], { '/link/vscode': '/work/vscode', '/alias/feature': '/work/vscode.worktrees/feature' }); + const resolve = async (primary: string, location: string) => (await provider.resolveLocation(URI.file(primary), URI.file(location), CancellationToken.None))?.label ?? 'none'; + assert.deepStrictEqual({ + throughLinkedPrimary: await resolve('/link/vscode', '/work/vscode.worktrees/feature'), + linkedWorktree: await resolve('/work/vscode', '/alias/feature'), + primaryItself: await resolve('/link/vscode', '/work/vscode'), + offered: (await provider.provideLocations(URI.file('/link/vscode'), CancellationToken.None)).map(location => location.uri.path), + }, { throughLinkedPrimary: 'feature', linkedWorktree: 'feature', primaryItself: 'none', offered: ['/alias/feature'] }); + }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts index abbfa90a26e95f..60c1a5f36aff1d 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -39,7 +39,7 @@ suite('ChatViewHostService', () => { shownSession, widget: options.widgetCreatedLater ? undefined : widget, get whenWidget() { accesses++; return created.p; }, - loadSession: async (resource: URI, reason?: string) => { calls.push(`loadSession ${resource.toString()} reason=${reason}`); return undefined; }, + loadSession: async (resource: URI, reason?: string, showReason?: string) => { calls.push(`loadSession ${resource.toString()} reason=${reason}${showReason === 'restore' ? ' restore' : ''}`); return undefined; }, startNewLocalSession: async () => { calls.push('startNewLocalSession'); return undefined; }, focus: () => { calls.push('focus'); }, focusInput: () => { calls.push('focusInput'); }, @@ -70,6 +70,8 @@ suite('ChatViewHostService', () => { results.reveal = await service.reveal(false) === widget; results.revealPreservingFocus = await service.reveal(true) === widget; results.openSession = await service.openSession(resource, { sessionTypeSelectionReason: 'explicitOverride' }) === widget; + // One to restore is not reported as opened + await service.openSession(resource, { preserveFocus: true, restore: true }); results.toggle = await service.toggle(); const start = await service.startSession(resource, { local: false, importingConversation: true, beforeOpen: () => calls.push('beforeOpen') }); await start.moved(URI.parse('test:/moved')); @@ -85,6 +87,7 @@ suite('ChatViewHostService', () => { `openView ${ChatViewId} focus=true`, `openView ${ChatViewId} focus=false`, `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'reportOpened test:/session', 'focusInput', + `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined restore', `setPartHidden false ${Parts.AUXILIARYBAR_PART}`, `openView ${ChatViewId} focus=undefined`, 'beforeOpen', 'suppress', 'progress', 'loadSession test:/session reason=explicitOverride', 'focus', `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined', diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 4e888b7ec9db8c..0c0bddde5e2e63 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -202,7 +202,7 @@ suite('ChatViewPane session transitions', () => { const nextRef = createReference(nextModel); const pane: { showModel(token: CancellationToken, ref: IChatModelReference): Promise; - loadSession(resource: URI): Promise; + loadSession(resource: URI, sessionTypeSelectionReason?: undefined, showReason?: 'open' | 'restore'): Promise; applyModel(): void; restoringSession: Promise | undefined; readonly shownSession: IObservable; @@ -299,6 +299,11 @@ suite('ChatViewPane session transitions', () => { Object.assign(restored.pane, { chatService: { acquireOrLoadSession: async () => savedReference() } }); await restored.pane.loadSession(savedResource); const afterLoad = shown(restored); + // A chat loaded as one to restore, such as the last chat of where the user moved the folder + const recalledResource = nextResource.with({ path: '/recalled' }); + Object.assign(restored.pane, { chatService: { acquireOrLoadSession: async () => Object.assign(toDisposable(() => { }), { object: upcastPartial({ sessionResource: recalledResource }) }) } }); + await restored.pane.loadSession(recalledResource, undefined, 'restore'); + const loadedToRestore = shown(restored); // The user loads a chat while the restore still prepares its chat's configuration const preparing = new DeferredPromise(); @@ -315,11 +320,12 @@ suite('ChatViewPane session transitions', () => { await loading; await restoration; - assert.deepStrictEqual({ afterRestore, otherReported, reopened, afterLoad, superseded: shown(superseded) }, { + assert.deepStrictEqual({ afterRestore, otherReported, reopened, afterLoad, loadedToRestore, superseded: shown(superseded) }, { afterRestore: '/untitled-next restore', otherReported: '/untitled-next restore', reopened: '/untitled-next open', afterLoad: '/saved open', + loadedToRestore: '/recalled restore', superseded: '/saved open', }); }); From 039d4528da2ed20c74b9bef11ddf6bf0f4967204 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 05:47:46 +0100 Subject: [PATCH 06/20] Worktree infra: an open to restore the chat that a host shows already reports it as restored Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../widgetHosts/viewPane/chatViewHostService.ts | 8 ++++++-- .../browser/widgetHosts/viewPane/chatViewPane.ts | 16 ++++++++++++++-- .../viewPane/chatViewHostService.test.ts | 3 ++- .../widgetHosts/viewPane/chatViewPane.test.ts | 8 +++++++- 4 files changed, 29 insertions(+), 6 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index 0769a48767e0d5..909d034271a63f 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -53,7 +53,9 @@ export class ChatViewPaneHost implements IChatViewHost { if (view && !options?.preserveFocus) { view.focus(); } - if (!options?.restore) { + if (options?.restore) { + view?.reportRestored(sessionResource); + } else { view?.reportOpened(sessionResource); } return view?.widget; @@ -64,7 +66,9 @@ export class ChatViewPaneHost implements IChatViewHost { if (chatView) { await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason, options?.restore ? 'restore' : 'open'); // Also a chat it showed already, which loading does not set again - if (!options?.restore) { + if (options?.restore) { + chatView.reportRestored(sessionResource); + } else { chatView.reportOpened(sessionResource); } if (!options?.preserveFocus) { diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index 433bd71e7c30f3..78f9ac81e7e7cb 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -1508,9 +1508,21 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { * one it restored that the user picks in a sessions list. */ reportOpened(sessionResource: URI): void { + this._reportShown(sessionResource, 'open'); + } + + /** + * Reports the chat of `sessionResource` as one that it restores, also where the view shows it already as opened, such + * as the last chat of where the user moved the window's folder. + */ + reportRestored(sessionResource: URI): void { + this._reportShown(sessionResource, 'restore'); + } + + private _reportShown(sessionResource: URI, reason: 'open' | 'restore'): void { const shown = this._shownSession.get(); - if (shown?.reason === 'restore' && isEqual(shown.resource, sessionResource)) { - this._shownSession.set({ resource: sessionResource, reason: 'open' }, undefined); + if (shown && shown.reason !== reason && isEqual(shown.resource, sessionResource)) { + this._shownSession.set({ resource: sessionResource, reason }, undefined); } } diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts index 60c1a5f36aff1d..98e0d28e5c0f94 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -44,6 +44,7 @@ suite('ChatViewHostService', () => { focus: () => { calls.push('focus'); }, focusInput: () => { calls.push('focusInput'); }, reportOpened: (resource: URI) => { calls.push(`reportOpened ${resource.toString()}`); }, + reportRestored: (resource: URI) => { calls.push(`reportRestored ${resource.toString()}`); }, beginSessionsListSuppression: () => { calls.push('suppress'); return toDisposable(() => calls.push('unsuppress')); }, }); const instantiationService = disposables.add(new TestInstantiationService()); @@ -87,7 +88,7 @@ suite('ChatViewHostService', () => { `openView ${ChatViewId} focus=true`, `openView ${ChatViewId} focus=false`, `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'reportOpened test:/session', 'focusInput', - `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined restore', + `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined restore', 'reportRestored test:/session', `setPartHidden false ${Parts.AUXILIARYBAR_PART}`, `openView ${ChatViewId} focus=undefined`, 'beforeOpen', 'suppress', 'progress', 'loadSession test:/session reason=explicitOverride', 'focus', `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined', diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 0c0bddde5e2e63..080b0074bbf8df 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -207,6 +207,7 @@ suite('ChatViewPane session transitions', () => { restoringSession: Promise | undefined; readonly shownSession: IObservable; reportOpened(sessionResource: URI): void; + reportRestored(sessionResource: URI): void; } = Object.assign(Object.create(ChatViewPane.prototype), { _store: paneStore, _showReason: 'open', @@ -304,6 +305,10 @@ suite('ChatViewPane session transitions', () => { Object.assign(restored.pane, { chatService: { acquireOrLoadSession: async () => Object.assign(toDisposable(() => { }), { object: upcastPartial({ sessionResource: recalledResource }) }) } }); await restored.pane.loadSession(recalledResource, undefined, 'restore'); const loadedToRestore = shown(restored); + // The chat it shows, opened again as one to restore, such as where it was opened before + restored.pane.reportOpened(recalledResource); + restored.pane.reportRestored(recalledResource); + const reopenedToRestore = shown(restored); // The user loads a chat while the restore still prepares its chat's configuration const preparing = new DeferredPromise(); @@ -320,12 +325,13 @@ suite('ChatViewPane session transitions', () => { await loading; await restoration; - assert.deepStrictEqual({ afterRestore, otherReported, reopened, afterLoad, loadedToRestore, superseded: shown(superseded) }, { + assert.deepStrictEqual({ afterRestore, otherReported, reopened, afterLoad, loadedToRestore, reopenedToRestore, superseded: shown(superseded) }, { afterRestore: '/untitled-next restore', otherReported: '/untitled-next restore', reopened: '/untitled-next open', afterLoad: '/saved open', loadedToRestore: '/recalled restore', + reopenedToRestore: '/recalled restore', superseded: '/saved open', }); }); From 6680d51b6561856cda0994cb6c689c021c90c244 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 05:52:00 +0100 Subject: [PATCH 07/20] Worktree infra: report each explicit open of the chat a view shows, also one reported as opened already Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../chat/browser/widgetHosts/viewPane/chatViewPane.ts | 5 +++-- .../test/browser/widgetHosts/viewPane/chatViewPane.test.ts | 7 ++++++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index 78f9ac81e7e7cb..a5e2465fae8963 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -1505,7 +1505,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { /** * Reports the chat of `sessionResource` as one that the user brought up, also where the view shows it already, such as - * one it restored that the user picks in a sessions list. + * one it restored, or one the user picks again in a sessions list, which is reported again. */ reportOpened(sessionResource: URI): void { this._reportShown(sessionResource, 'open'); @@ -1521,7 +1521,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private _reportShown(sessionResource: URI, reason: 'open' | 'restore'): void { const shown = this._shownSession.get(); - if (shown && shown.reason !== reason && isEqual(shown.resource, sessionResource)) { + // Each time the user opens it, also where it is reported as opened already, as where it works may matter again + if (shown && (reason === 'open' || shown.reason !== reason) && isEqual(shown.resource, sessionResource)) { this._shownSession.set({ resource: sessionResource, reason }, undefined); } } diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 080b0074bbf8df..1aae367c7d6aa2 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -297,6 +297,10 @@ suite('ChatViewPane session transitions', () => { const otherReported = shown(restored); restored.pane.reportOpened(nextResource); const reopened = shown(restored); + // Picked again, such as after the user moved the window's folder away: reported again + const reportedBefore = restored.pane.shownSession.get(); + restored.pane.reportOpened(nextResource); + const reportedAgain = restored.pane.shownSession.get() !== reportedBefore; Object.assign(restored.pane, { chatService: { acquireOrLoadSession: async () => savedReference() } }); await restored.pane.loadSession(savedResource); const afterLoad = shown(restored); @@ -325,10 +329,11 @@ suite('ChatViewPane session transitions', () => { await loading; await restoration; - assert.deepStrictEqual({ afterRestore, otherReported, reopened, afterLoad, loadedToRestore, reopenedToRestore, superseded: shown(superseded) }, { + assert.deepStrictEqual({ afterRestore, otherReported, reopened, reportedAgain, afterLoad, loadedToRestore, reopenedToRestore, superseded: shown(superseded) }, { afterRestore: '/untitled-next restore', otherReported: '/untitled-next restore', reopened: '/untitled-next open', + reportedAgain: true, afterLoad: '/saved open', loadedToRestore: '/recalled restore', reopenedToRestore: '/recalled restore', From eb1c5194b09a02c836607cf230c7c0f7fb2e8730 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 05:53:59 +0100 Subject: [PATCH 08/20] Worktree infra: wait for the local agent host sessions to resolve, also once another provider resolved Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 26 +++++++-- .../agentHostWorktreeLocations.test.ts | 57 ++++++++++++++++--- 2 files changed, 68 insertions(+), 15 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index 904f53daca7fa6..90ab5600fb0c4b 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -6,6 +6,7 @@ import { raceCancellation } from '../../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; +import { Disposable } from '../../../../../../base/common/lifecycle.js'; import { Schemas } from '../../../../../../base/common/network.js'; import { isAbsolute } from '../../../../../../base/common/path.js'; import { basename, dirname, extUriBiasedIgnorePathCase, joinPath, normalizePath } from '../../../../../../base/common/resources.js'; @@ -15,7 +16,7 @@ import { FileOperationResult, IFileService, toFileOperationResult } from '../../ import { ILogService } from '../../../../../../platform/log/common/log.js'; import { IFolderLocation, IWorkspaceFolderLocationProvider } from '../../../../../../platform/workspace/common/folderLocations.js'; import { readFolderGitCheckout } from '../../../../../services/workspaces/common/gitFolderCheckout.js'; -import { isLocalAgentHostTarget } from '../../../common/chatSessionsService.js'; +import { IChatSessionsService, isLocalAgentHostTarget } from '../../../common/chatSessionsService.js'; import { IAgentSession } from '../agentSessionsModel.js'; import { IAgentSessionsService } from '../agentSessionsService.js'; @@ -49,25 +50,38 @@ export function getAgentHostSessionWorkingDirectories(sessions: readonly IAgentS * window's repository (see `WorkspaceFolderRepositories`), and when that repository's entry for it names its `.git` back. * That keeps a folder that only points into the repository from inheriting the primary's trust. */ -export class AgentHostWorktreeLocationProvider implements IWorkspaceFolderLocationProvider { +export class AgentHostWorktreeLocationProvider extends Disposable implements IWorkspaceFolderLocationProvider { readonly id = AGENT_HOST_WORKTREE_LOCATIONS_PROVIDER_ID; + /** The local agent host providers whose sessions the sessions list has resolved. */ + private readonly _resolvedProviders = new Set(); + constructor( @IAgentSessionsService private readonly _agentSessionsService: IAgentSessionsService, + @IChatSessionsService private readonly _chatSessionsService: IChatSessionsService, @IFileService private readonly _fileService: IFileService, @ILogService private readonly _logService: ILogService, - ) { } + ) { + super(); + this._register(_agentSessionsService.model.onDidResolve(provider => { + if (isLocalAgentHostTarget(provider)) { + this._resolvedProviders.add(provider); + } + })); + } async provideLocations(primary: URI, token: CancellationToken): Promise { const worktreesDir = await this._worktreesDir(primary); if (!worktreesDir || token.isCancellationRequested) { return []; } - // Before the sessions list first resolves, it has only the sessions it cached: wait for the ones it has not + // Before the sessions list first resolves a local agent host provider, it has only the sessions it cached of it: + // wait for that provider, also while others have resolved, and leave the others alone const model = this._agentSessionsService.model; - if (!model.resolved) { - await raceCancellation(model.resolve(undefined, undefined, 'automatic'), token); + const unresolved = this._chatSessionsService.getRegisteredChatSessionItemProviders().filter(provider => isLocalAgentHostTarget(provider) && !this._resolvedProviders.has(provider)); + if (unresolved.length) { + await raceCancellation(model.resolve(unresolved, undefined, 'automatic'), token); if (token.isCancellationRequested) { return []; } diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index 0c1af172077e39..6bb8d11ce4a5c5 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -4,8 +4,10 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { DeferredPromise } from '../../../../../../../base/common/async.js'; import { VSBuffer } from '../../../../../../../base/common/buffer.js'; import { CancellationToken } from '../../../../../../../base/common/cancellation.js'; +import { Emitter } from '../../../../../../../base/common/event.js'; import { URI } from '../../../../../../../base/common/uri.js'; import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; @@ -15,7 +17,7 @@ import { ILogService, NullLogService } from '../../../../../../../platform/log/c import { AgentHostWorktreeLocationProvider, getAgentHostSessionWorkingDirectories } from '../../../../browser/agentSessions/agentHost/agentHostWorktreeLocations.js'; import { IAgentSession } from '../../../../browser/agentSessions/agentSessionsModel.js'; import { IAgentSessionsService } from '../../../../browser/agentSessions/agentSessionsService.js'; -import { SessionType } from '../../../../common/chatSessionsService.js'; +import { IChatSessionsService, SessionType } from '../../../../common/chatSessionsService.js'; suite('AgentHostWorktreeLocations', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -28,7 +30,11 @@ suite('AgentHostWorktreeLocations', () => { * A provider over git entries: `true` is a `.git` directory, and a string the content of a file, such as a worktree's * `.git` file or its entry's `gitdir` file in the repository. */ - function createProvider(entries: Record, sessions: readonly IAgentSession[], uncached: readonly IAgentSession[] = [], links: Record = {}) { + /** + * @param uncached the sessions of the local agent host provider that the sessions list has only once that provider resolves, + * which `loading` holds, while another provider, `remote`, has resolved. + */ + function createProvider(entries: Record, sessions: readonly IAgentSession[], uncached: readonly IAgentSession[] = [], links: Record = {}, loading?: Promise) { const fileService = upcastPartial({ stat: async (resource: URI) => { const entry = entries[resource.path]; @@ -53,10 +59,28 @@ suite('AgentHostWorktreeLocations', () => { const instantiationService = store.add(new TestInstantiationService()); instantiationService.stub(IFileService, fileService); instantiationService.stub(ILogService, new NullLogService()); - // The sessions it cached, and those the list has only once it resolved - const model = { sessions: [...sessions], resolved: !uncached.length, resolve: async () => { model.sessions.push(...uncached); model.resolved = true; } }; + // The sessions it cached, and those the list has only once the local agent host provider resolved + const onDidResolve = store.add(new Emitter()); + const resolving: string[] = []; + const model = { + sessions: [...sessions], + resolved: false, + onDidResolve: onDidResolve.event, + resolve: async (providers: string[]) => { + resolving.push(...providers); + await loading; + model.sessions.push(...uncached); + model.resolved = true; + providers.forEach(provider => onDidResolve.fire(provider)); + }, + }; instantiationService.stub(IAgentSessionsService, upcastPartial({ model: upcastPartial(model) })); - return instantiationService.createInstance(AgentHostWorktreeLocationProvider); + instantiationService.stub(IChatSessionsService, upcastPartial({ getRegisteredChatSessionItemProviders: () => ['remote', SessionType.AgentHostCopilot] })); + const provider = store.add(instantiationService.createInstance(AgentHostWorktreeLocationProvider)); + // Another provider resolved first + model.resolved = true; + onDidResolve.fire('remote'); + return Object.assign(provider, { resolving }); } const repository = { @@ -123,10 +147,25 @@ suite('AgentHostWorktreeLocations', () => { }); }); - test('waits for the sessions list to resolve before reading the working directories of sessions it did not cache', async () => { - const provider = createProvider(repository, [session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/feature')], [session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/relative')]); - const locations = await provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None); - assert.deepStrictEqual(locations.map(location => location.label), ['feature', 'relative']); + test('waits for the local agent host sessions to resolve, also once another provider resolved, before reading the working directories of sessions it did not cache', async () => { + const loading = new DeferredPromise(); + const provider = createProvider(repository, [session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/feature')], [session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/relative')], {}, loading.p); + let locations: string[] | undefined; + const providing = provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None).then(result => locations = result.map(location => location.label)); + await new Promise(resolve => setTimeout(resolve, 0)); + const whileLoading = locations; + await loading.complete(); + await providing; + const resolvingBefore = [...provider.resolving]; + // Once resolved, it reads the sessions as the list has them + await provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None); + + assert.deepStrictEqual({ whileLoading, locations, resolving: resolvingBefore, again: provider.resolving }, { + whileLoading: undefined, + locations: ['feature', 'relative'], + resolving: [SessionType.AgentHostCopilot], + again: [SessionType.AgentHostCopilot], + }); }); test('a worktree is described by its branch, the short commit of a detached HEAD, or nothing without HEAD', async () => { From 259eb73bba8425d50c08031962beddbad90ca0ca Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 06:22:51 +0100 Subject: [PATCH 09/20] Worktree infra: report a first send's session as committed, also through an extension's commit, and follow symbolic links of worktree folders and .git files - ChatWidget marks the view model change to the session its first request made; the Chat view reports it as 'commit'. - IChatViewHostOpenOptions.commit: the extension commit path opens the committed session through the Chat view host as 'commit'. - The location provider compares the real paths of the repository's worktrees folder and of a worktree's .git file. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 8 +++-- src/vs/workbench/contrib/chat/browser/chat.ts | 2 ++ .../browser/chatSessions/chatSessionCommit.ts | 5 +++- .../contrib/chat/browser/chatViewHost.ts | 10 +++++++ .../contrib/chat/browser/widget/chatWidget.ts | 18 ++++++++++-- .../viewPane/chatViewHostService.ts | 17 ++++------- .../widgetHosts/viewPane/chatViewPane.ts | 24 +++++++++------ .../agentHostWorktreeLocations.test.ts | 29 ++++++++++++++----- .../viewPane/chatViewHostService.test.ts | 12 ++++---- .../widgetHosts/viewPane/chatViewPane.test.ts | 20 +++++++++++-- 10 files changed, 102 insertions(+), 43 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index 90ab5600fb0c4b..c41433318306f6 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -114,7 +114,8 @@ export class AgentHostWorktreeLocationProvider extends Disposable implements IWo } try { const checkout = await readFolderGitCheckout(this._fileService, await this._real(primary)); - return checkout && joinPath(await this._real(checkout.repository), '.git', 'worktrees'); + // Its real path also where `.git` or `.git/worktrees` is a symbolic link + return checkout && await this._real(joinPath(await this._real(checkout.repository), '.git', 'worktrees')); } catch (error) { this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git repository of ${primary.toString()}`, error); return undefined; @@ -135,12 +136,13 @@ export class AgentHostWorktreeLocationProvider extends Disposable implements IWo return undefined; } const locationGitFile = joinPath(realLocation, '.git'); - const entry = await this._readLink(locationGitFile, dirname(locationGitFile), /^gitdir:\s*(?.+?)\s*$/m); + const entry = await this._readLink(locationGitFile, realLocation, /^gitdir:\s*(?.+?)\s*$/m); if (!entry || !extUriBiasedIgnorePathCase.isEqual(dirname(await this._real(entry)), worktreesDir)) { return undefined; } const backlink = await this._readLink(joinPath(entry, 'gitdir'), entry); - if (!backlink || !extUriBiasedIgnorePathCase.isEqual(await this._real(backlink), locationGitFile)) { + // The `.git` file by its real path, also where it is a symbolic link + if (!backlink || !extUriBiasedIgnorePathCase.isEqual(await this._real(backlink), await this._real(locationGitFile))) { return undefined; } // Its branch, from the entry's HEAD: read again each time the location is resolved diff --git a/src/vs/workbench/contrib/chat/browser/chat.ts b/src/vs/workbench/contrib/chat/browser/chat.ts index 4fe575a02ab66b..4f53ff786eeae7 100644 --- a/src/vs/workbench/contrib/chat/browser/chat.ts +++ b/src/vs/workbench/contrib/chat/browser/chat.ts @@ -474,6 +474,8 @@ export interface IChatAcceptInputOptions { export interface IChatWidgetViewModelChangeEvent { readonly previousSessionResource: URI | undefined; readonly currentSessionResource: URI | undefined; + /** Whether the widget shows the session that its first request made of the one it showed, such as a new chat's. */ + readonly committed?: boolean; } /** diff --git a/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessionCommit.ts b/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessionCommit.ts index 46567efbbc57b7..beb3f4df8ae80a 100644 --- a/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessionCommit.ts +++ b/src/vs/workbench/contrib/chat/browser/chatSessions/chatSessionCommit.ts @@ -18,6 +18,7 @@ import { ChatAgentLocation } from '../../common/constants.js'; import { IChatArtifactsService } from '../../common/tools/chatArtifactsService.js'; import { IChatTodoListService } from '../../common/tools/chatTodoListService.js'; import { IChatWidgetService, isIChatViewViewContext } from '../chat.js'; +import { IChatViewHostService } from '../chatViewHost.js'; import { IChatEditorOptions } from '../widgetHosts/editor/chatEditor.js'; import { ChatEditorInput } from '../widgetHosts/editor/chatEditorInput.js'; @@ -31,6 +32,7 @@ export async function commitChatSession(accessor: ServicesAccessor, chatSessionT const chatSessionsService = accessor.get(IChatSessionsService); const chatService = accessor.get(IChatService); const chatWidgetService = accessor.get(IChatWidgetService); + const chatViewHostService = accessor.get(IChatViewHostService); const chatTodoListService = accessor.get(IChatTodoListService); const chatArtifactsService = accessor.get(IChatArtifactsService); const chatDebugService = accessor.get(IChatDebugService); @@ -108,7 +110,8 @@ export async function commitChatSession(accessor: ServicesAccessor, chatSessionT const chatViewWidget = chatWidgetService.getWidgetBySessionResource(originalResource); if (chatViewWidget && isIChatViewViewContext(chatViewWidget.viewContext)) { - await chatWidgetService.openSession(modifiedResource, undefined, { preserveFocus: true }); + // The session its first request made: a host reports it as such, not as one the user opened + await chatViewHostService.openSession(modifiedResource, { preserveFocus: true, commit: true }); } else if (!chatViewWidget) { // No widget currently shows the original session — eagerly load the // session so the transferred state set above is materialized into a diff --git a/src/vs/workbench/contrib/chat/browser/chatViewHost.ts b/src/vs/workbench/contrib/chat/browser/chatViewHost.ts index 023643c1774412..6638370bbe4e56 100644 --- a/src/vs/workbench/contrib/chat/browser/chatViewHost.ts +++ b/src/vs/workbench/contrib/chat/browser/chatViewHost.ts @@ -42,6 +42,16 @@ export interface IChatViewHostOpenOptions { * the user opens, such as the chat that was last shown where the user moved the window's folder. */ readonly restore?: boolean; + /** + * Shows the session as the one that the first request of the chat it shows made of it ({@link IChatViewHostShownSession.reason} + * `commit`), rather than one the user opens. + */ + readonly commit?: boolean; +} + +/** Why a host shows a session that it opens with `options`. */ +export function getChatViewHostOpenReason(options: IChatViewHostOpenOptions | undefined): IChatViewHostShownSession['reason'] { + return options?.commit ? 'commit' : options?.restore ? 'restore' : 'open'; } /** How {@link IChatViewHost.startSession} starts a session that its caller may send a first request to. */ diff --git a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts index df31cc80632d84..7570f34a9237f5 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/chatWidget.ts @@ -362,6 +362,8 @@ export class ChatWidget extends Disposable implements IChatWidget { private _onDidFocus = this._register(new Emitter()); readonly onDidFocus = this._onDidFocus.event; + /** Whether it sets the model of the session its first request made, which its view model change reports. */ + private _settingCommittedModel = false; private _onDidChangeViewModel = this._register(new Emitter()); readonly onDidChangeViewModel = this._onDidChangeViewModel.event; private readonly _onDidChangeDraft = this._register(new Emitter()); @@ -579,7 +581,7 @@ export class ChatWidget extends Disposable implements IChatWidget { this.logService.debug('ChatWidget#setViewModel: no viewModel'); } - this._onDidChangeViewModel.fire({ previousSessionResource, currentSessionResource: this._viewModel?.sessionResource }); + this._onDidChangeViewModel.fire({ previousSessionResource, currentSessionResource: this._viewModel?.sessionResource, committed: this._settingCommittedModel || undefined }); this.updateSessionStateIndicator(); } @@ -3257,6 +3259,16 @@ export class ChatWidget extends Disposable implements IChatWidget { this.listWidget?.setPaddingBottom(this._getListPaddingBottom()); } + /** Shows the session that its first request made of the one it shows, such as an untitled chat's committed session. */ + private setCommittedModel(model: IChatModel): void { + this._settingCommittedModel = true; + try { + this.setModel(model); + } finally { + this._settingCommittedModel = false; + } + } + setModel(model: IChatModel | undefined): void { if (!this.container || !this.inputPart) { // Widget hasn't finished rendering yet; skip rather than crash and @@ -4305,7 +4317,7 @@ export class ChatWidget extends Disposable implements IChatWidget { if (result.newSessionResource) { const newModel = this.chatService.getSession(result.newSessionResource); if (newModel) { - this.setModel(newModel); + this.setCommittedModel(newModel); } } return; @@ -4359,7 +4371,7 @@ export class ChatWidget extends Disposable implements IChatWidget { if (sent.newSessionResource) { const newModel = this.chatService.getSession(sent.newSessionResource); if (newModel) { - this.setModel(newModel); + this.setCommittedModel(newModel); } } diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index 909d034271a63f..852d04abf0ebfc 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -14,7 +14,7 @@ import { IViewDescriptorService, ViewContainerLocation } from '../../../../../co import { IWorkbenchLayoutService, Parts } from '../../../../../services/layout/browser/layoutService.js'; import { IViewsService } from '../../../../../services/views/common/viewsService.js'; import { ChatViewId, IChatWidget } from '../../chat.js'; -import { IChatViewHost, IChatViewHostOpenOptions, IChatViewHostRevealOptions, IChatViewHostService, IChatViewHostSessionStart, IChatViewHostSessionStartOptions, IChatViewHostShownSession } from '../../chatViewHost.js'; +import { getChatViewHostOpenReason, IChatViewHost, IChatViewHostOpenOptions, IChatViewHostRevealOptions, IChatViewHostService, IChatViewHostSessionStart, IChatViewHostSessionStartOptions, IChatViewHostShownSession } from '../../chatViewHost.js'; import { ChatViewPane } from './chatViewPane.js'; /** The Chat view, as the host of its chats. */ @@ -53,24 +53,17 @@ export class ChatViewPaneHost implements IChatViewHost { if (view && !options?.preserveFocus) { view.focus(); } - if (options?.restore) { - view?.reportRestored(sessionResource); - } else { - view?.reportOpened(sessionResource); - } + view?.reportShown(sessionResource, getChatViewHostOpenReason(options)); return view?.widget; } async openSession(sessionResource: URI, options?: IChatViewHostOpenOptions): Promise { const chatView = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); if (chatView) { - await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason, options?.restore ? 'restore' : 'open'); + const reason = getChatViewHostOpenReason(options); + await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason, reason); // Also a chat it showed already, which loading does not set again - if (options?.restore) { - chatView.reportRestored(sessionResource); - } else { - chatView.reportOpened(sessionResource); - } + chatView.reportShown(sessionResource, reason); if (!options?.preserveFocus) { chatView.focusInput(); } diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index a5e2465fae8963..bf22c302e18139 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -70,7 +70,7 @@ import { IChatViewsWelcomeDescriptor } from '../../viewsWelcome/chatViewsWelcome import { IWorkbenchLayoutService, LayoutSettings, Position } from '../../../../../services/layout/browser/layoutService.js'; import { AgentSessionsViewerOrientation, AgentSessionsViewerPosition } from '../../agentSessions/agentSessions.js'; import { IProgressService } from '../../../../../../platform/progress/common/progress.js'; -import { CHAT_WIDGET_VIEW_STATE_CACHE_LIMIT, ChatViewId, IChatWidgetService, IChatWidgetViewState, setModelPreservingInputTypedWhileLoading } from '../../chat.js'; +import { CHAT_WIDGET_VIEW_STATE_CACHE_LIMIT, ChatViewId, IChatWidgetService, IChatWidgetViewModelChangeEvent, IChatWidgetViewState, setModelPreservingInputTypedWhileLoading } from '../../chat.js'; import { IChatViewHostShownSession } from '../../chatViewHost.js'; import { IActivityService, ProgressBadge } from '../../../../../services/activity/common/activity.js'; import { DeferredPromise, disposableTimeout, raceCancellation, RunOnceScheduler } from '../../../../../../base/common/async.js'; @@ -1249,11 +1249,11 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { })); // Track the active chat model and reveal it in the sessions control if side-by-side - this._register(chatWidget.onDidChangeViewModel(() => { + this._register(chatWidget.onDidChangeViewModel(e => { const model = chatWidget.viewModel?.model; this.titleControl?.update(model); this._currentSessionResource.set(chatWidget.viewModel?.sessionResource, undefined); - this.updateShownSession(); + this.onDidChangeShownModel(e); if (this.sessionsViewerOrientation === AgentSessionsViewerOrientation.Stacked) { return; // only reveal in side-by-side mode @@ -1508,7 +1508,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { * one it restored, or one the user picks again in a sessions list, which is reported again. */ reportOpened(sessionResource: URI): void { - this._reportShown(sessionResource, 'open'); + this.reportShown(sessionResource, 'open'); } /** @@ -1516,10 +1516,11 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { * as the last chat of where the user moved the window's folder. */ reportRestored(sessionResource: URI): void { - this._reportShown(sessionResource, 'restore'); + this.reportShown(sessionResource, 'restore'); } - private _reportShown(sessionResource: URI, reason: 'open' | 'restore'): void { + /** Reports the chat of `sessionResource`, where the view shows it, as shown for `reason` ({@link shownSession}). */ + reportShown(sessionResource: URI, reason: IChatViewHostShownSession['reason']): void { const shown = this._shownSession.get(); // Each time the user opens it, also where it is reported as opened already, as where it works may matter again if (shown && (reason === 'open' || shown.reason !== reason) && isEqual(shown.resource, sessionResource)) { @@ -1527,10 +1528,15 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { } } + /** Reports the chat its widget shows now, such as the session that its first request made, which the user did not pick. */ + private onDidChangeShownModel(e: IChatWidgetViewModelChangeEvent): void { + this.updateShownSession(e.committed ? 'commit' : undefined); + } + /** Reports the chat that the view shows now ({@link shownSession}), as its widget's chat changes. */ - private updateShownSession(): void { + private updateShownSession(reason: IChatViewHostShownSession['reason'] = this._showReason): void { const shownResource = this._widget.viewModel?.sessionResource; - this._shownSession.set(shownResource && { resource: shownResource, reason: this._showReason }, undefined); + this._shownSession.set(shownResource && { resource: shownResource, reason }, undefined); } /** @param showReason why it shows the chat ({@link shownSession}). */ @@ -1687,7 +1693,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { } /** @param showReason why it shows the chat ({@link shownSession}). */ - async loadSession(sessionResource: URI, sessionTypeSelectionReason?: SessionTypeSelectionReason, showReason: 'open' | 'restore' = 'open'): Promise { + async loadSession(sessionResource: URI, sessionTypeSelectionReason?: SessionTypeSelectionReason, showReason: IChatViewHostShownSession['reason'] = 'open'): Promise { const t0 = Date.now(); this.logService.trace(`[ChatViewPane] loadSession start uri=${sessionResource.toString()}`); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index 6bb8d11ce4a5c5..5596642977a05a 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -35,21 +35,22 @@ suite('AgentHostWorktreeLocations', () => { * which `loading` holds, while another provider, `remote`, has resolved. */ function createProvider(entries: Record, sessions: readonly IAgentSession[], uncached: readonly IAgentSession[] = [], links: Record = {}, loading?: Promise) { + // A path through a symbolic link, such as `links['/link/vscode'] = '/work/vscode'`, is the path it links to + const real = (path: string) => { + const link = Object.keys(links).find(candidate => path === candidate || path.startsWith(`${candidate}/`)); + return link ? links[link] + path.slice(link.length) : path; + }; const fileService = upcastPartial({ stat: async (resource: URI) => { - const entry = entries[resource.path]; + const entry = entries[real(resource.path)]; if (entry === undefined) { throw new FileOperationError('not found', FileOperationResult.FILE_NOT_FOUND); } return upcastPartial({ isDirectory: entry === true }); }, - // A path through a symbolic link, such as `links['/link/vscode'] = '/work/vscode'`, is the path it links to - realpath: async (resource: URI) => { - const link = Object.keys(links).find(path => resource.path === path || resource.path.startsWith(`${path}/`)); - return link ? URI.file(links[link] + resource.path.slice(link.length)) : resource; - }, + realpath: async (resource: URI) => URI.file(real(resource.path)), readFile: async (resource: URI) => { - const entry = entries[resource.path]; + const entry = entries[real(resource.path)]; if (typeof entry !== 'string') { throw new FileOperationError('not found', FileOperationResult.FILE_NOT_FOUND); } @@ -184,4 +185,18 @@ suite('AgentHostWorktreeLocations', () => { offered: (await provider.provideLocations(URI.file('/link/vscode'), CancellationToken.None)).map(location => location.uri.path), }, { throughLinkedPrimary: 'feature', linkedWorktree: 'feature', primaryItself: 'none', offered: ['/alias/feature'] }); }); + + test('follows symbolic links of the repository\'s worktrees folder and of a worktree\'s .git file, and still rejects one that git does not link back', async () => { + // The repository's `.git/worktrees` is a link to another folder, and the worktree's `.git` file a link to another file + const linked = { + '/work/vscode/.git': true, + '/store/worktrees/feature/gitdir': '/store/feature.git\n', + '/store/feature.git': 'gitdir: /work/vscode/.git/worktrees/feature\n', + '/work/impostor/.git': 'gitdir: /work/vscode/.git/worktrees/feature\n', + }; + const provider = createProvider(linked, [], [], { '/work/vscode/.git/worktrees': '/store/worktrees', '/work/vscode.worktrees/feature/.git': '/store/feature.git' }); + const resolve = async (path: string) => (await provider.resolveLocation(URI.file('/work/vscode'), URI.file(path), CancellationToken.None))?.uri.path ?? 'none'; + + assert.deepStrictEqual({ linked: await resolve('/work/vscode.worktrees/feature'), impostor: await resolve('/work/impostor') }, { linked: '/work/vscode.worktrees/feature', impostor: 'none' }); + }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts index 98e0d28e5c0f94..69a52095d5bfa4 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -39,12 +39,11 @@ suite('ChatViewHostService', () => { shownSession, widget: options.widgetCreatedLater ? undefined : widget, get whenWidget() { accesses++; return created.p; }, - loadSession: async (resource: URI, reason?: string, showReason?: string) => { calls.push(`loadSession ${resource.toString()} reason=${reason}${showReason === 'restore' ? ' restore' : ''}`); return undefined; }, + loadSession: async (resource: URI, reason?: string, showReason?: string) => { calls.push(`loadSession ${resource.toString()} reason=${reason}${showReason && showReason !== 'open' ? ` ${showReason}` : ''}`); return undefined; }, startNewLocalSession: async () => { calls.push('startNewLocalSession'); return undefined; }, focus: () => { calls.push('focus'); }, focusInput: () => { calls.push('focusInput'); }, - reportOpened: (resource: URI) => { calls.push(`reportOpened ${resource.toString()}`); }, - reportRestored: (resource: URI) => { calls.push(`reportRestored ${resource.toString()}`); }, + reportShown: (resource: URI, reason: string) => { calls.push(`reportShown ${resource.toString()} ${reason}`); }, beginSessionsListSuppression: () => { calls.push('suppress'); return toDisposable(() => calls.push('unsuppress')); }, }); const instantiationService = disposables.add(new TestInstantiationService()); @@ -73,6 +72,8 @@ suite('ChatViewHostService', () => { results.openSession = await service.openSession(resource, { sessionTypeSelectionReason: 'explicitOverride' }) === widget; // One to restore is not reported as opened await service.openSession(resource, { preserveFocus: true, restore: true }); + // The session that the first request of the chat it shows made is reported as such + await service.openSession(resource, { preserveFocus: true, commit: true }); results.toggle = await service.toggle(); const start = await service.startSession(resource, { local: false, importingConversation: true, beforeOpen: () => calls.push('beforeOpen') }); await start.moved(URI.parse('test:/moved')); @@ -87,8 +88,9 @@ suite('ChatViewHostService', () => { calls: [ `openView ${ChatViewId} focus=true`, `openView ${ChatViewId} focus=false`, - `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'reportOpened test:/session', 'focusInput', - `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined restore', 'reportRestored test:/session', + `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'reportShown test:/session open', 'focusInput', + `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined restore', 'reportShown test:/session restore', + `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined commit', 'reportShown test:/session commit', `setPartHidden false ${Parts.AUXILIARYBAR_PART}`, `openView ${ChatViewId} focus=undefined`, 'beforeOpen', 'suppress', 'progress', 'loadSession test:/session reason=explicitOverride', 'focus', `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined', diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 1aae367c7d6aa2..3d0ab1e601e7b2 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -20,6 +20,7 @@ import { NullLogService } from '../../../../../../../platform/log/common/log.js' import { AccountPolicyGateState } from '../../../../../../services/policies/common/accountPolicyService.js'; import { TestContextService, TestStorageService } from '../../../../../../test/common/workbenchTestServices.js'; import { ChatViewPane } from '../../../../browser/widgetHosts/viewPane/chatViewPane.js'; +import { IChatWidgetViewModelChangeEvent } from '../../../../browser/chat.js'; import { IChatViewHostShownSession } from '../../../../browser/chatViewHost.js'; import { ChatWidget } from '../../../../browser/widget/chatWidget.js'; import { mainWindow } from '../../../../../../../base/browser/window.js'; @@ -174,7 +175,7 @@ suite('ChatViewPane session transitions', () => { const disposed: URI[] = []; const locks: string[] = []; /** Tells the pane its widget's chat changed, as the widget's onDidChangeViewModel does. */ - let didChangeViewModel = () => { }; + let didChangeViewModel = (_committed?: boolean) => { }; const paneStore = store.add(new DisposableStore()); const modelRef = paneStore.add(new MutableDisposable()); const createReference = (model: IChatModel): IChatModelReference => Object.assign(toDisposable(() => { @@ -194,6 +195,11 @@ suite('ChatViewPane session transitions', () => { bindings.push(model?.sessionResource); didChangeViewModel(); }, + /** As its first request makes the session it sends in, which the widget then shows */ + showCommitted: (model: IChatModel) => { + shown = model; + didChangeViewModel(true); + }, lockToCodingAgent: (_name: string, _displayName: string, sessionType: string) => { locks.push(sessionType); }, unlockFromCodingAgent: () => { locks.push('local'); }, visible: true, @@ -233,7 +239,7 @@ suite('ChatViewPane session transitions', () => { agentSessionsService: { model: { getSession: () => undefined } }, updateActions: () => { }, }); - didChangeViewModel = () => (Reflect.get(pane, 'updateShownSession') as () => void).call(pane); + didChangeViewModel = committed => (Reflect.get(pane, 'onDidChangeShownModel') as (e: IChatWidgetViewModelChangeEvent) => void).call(pane, { previousSessionResource: undefined, currentSessionResource: shown?.sessionResource, committed }); return { pane, paneStore, widget, modelRef, nextModel, nextRef, bindings, disposed, locks }; } @@ -301,6 +307,12 @@ suite('ChatViewPane session transitions', () => { const reportedBefore = restored.pane.shownSession.get(); restored.pane.reportOpened(nextResource); const reportedAgain = restored.pane.shownSession.get() !== reportedBefore; + // Its first request makes a session of the new chat, which the widget then shows: not one the user picked + restored.widget.showCommitted(upcastPartial({ sessionResource: nextResource.with({ path: '/committed' }) })); + const committed = shown(restored); + // The user opens it, also as the chat it shows + restored.pane.reportOpened(nextResource.with({ path: '/committed' })); + const committedOpened = shown(restored); Object.assign(restored.pane, { chatService: { acquireOrLoadSession: async () => savedReference() } }); await restored.pane.loadSession(savedResource); const afterLoad = shown(restored); @@ -329,11 +341,13 @@ suite('ChatViewPane session transitions', () => { await loading; await restoration; - assert.deepStrictEqual({ afterRestore, otherReported, reopened, reportedAgain, afterLoad, loadedToRestore, reopenedToRestore, superseded: shown(superseded) }, { + assert.deepStrictEqual({ afterRestore, otherReported, reopened, reportedAgain, committed, committedOpened, afterLoad, loadedToRestore, reopenedToRestore, superseded: shown(superseded) }, { afterRestore: '/untitled-next restore', otherReported: '/untitled-next restore', reopened: '/untitled-next open', reportedAgain: true, + committed: '/committed commit', + committedOpened: '/committed open', afterLoad: '/saved open', loadedToRestore: '/recalled restore', reopenedToRestore: '/recalled restore', From ee64ec290ce06e0bf22706ee665c2f2d20af60aa Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 06:27:17 +0100 Subject: [PATCH 10/20] Worktree infra: test mocks of the Chat view report shown chats through reportShown Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../contrib/chat/test/browser/actions/chatMoveActions.test.ts | 2 +- .../chat/test/browser/widget/chatWidgetService.test.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts index 2c04a11d900ba8..c7c7c3901267e9 100644 --- a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts @@ -91,7 +91,7 @@ suite('Chat move actions', () => { return model; }, focusInput() { }, - reportOpened() { }, + reportShown() { }, }); const viewsService = upcastPartial({ openView: mockObject()().openView.resolves(view), diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts index ef9c2aa54f5400..e31ea418567b98 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts @@ -218,7 +218,7 @@ suite('ChatWidgetService', () => { const oldWidget = createWidget(session); const emptyOldWidget = createWidget(undefined); const hostWidget = upcastPartial({}); - const view = { widget: oldWidget, focus: () => calls.push('view.focus'), loadSession: async () => { calls.push('view.loadSession'); }, reportOpened: () => calls.push('view.reportOpened') }; + const view = { widget: oldWidget, focus: () => calls.push('view.focus'), loadSession: async () => { calls.push('view.loadSession'); }, reportShown: (_resource: URI, reason: string) => calls.push(`view.reportShown ${reason}`) }; instantiationService.stub(IEditorGroupsService, { groups: [] }); instantiationService.stub(IViewsService, { getViewWithId: (() => view) as unknown as IViewsService['getViewWithId'], @@ -275,7 +275,7 @@ suite('ChatWidgetService', () => { const widget = await service.openSession(session); - assert.deepStrictEqual({ shown: widget === oldWidget, calls }, { shown: true, calls: [`openView ${ChatViewId}`, 'view.focus', 'view.reportOpened'] }); + assert.deepStrictEqual({ shown: widget === oldWidget, calls }, { shown: true, calls: [`openView ${ChatViewId}`, 'view.focus', 'view.reportShown open'] }); }); }); }); From 20aa95ffd2fe7d086e30744088167fc4787674c8 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 07:16:46 +0100 Subject: [PATCH 11/20] Worktree infra: a worktree's admin back-link must name the checkout itself, and an open through the Chat view host reports its chat once - The location provider accepts a candidate only where the folder of the .git file its entry names is the candidate, by real paths, so another folder whose .git links to the same file does not inherit the primary's trust. - ChatViewPaneHost reports a chat after loading it only where the load reported nothing, such as the chat it shows already. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 12 ++-- .../viewPane/chatViewHostService.ts | 7 ++- .../agentHostWorktreeLocations.test.ts | 58 ++++++++++++++++--- .../widgetHosts/viewPane/chatViewPane.test.ts | 50 +++++++++++++++- 4 files changed, 111 insertions(+), 16 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index c41433318306f6..2e51fd0ea2717f 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -124,8 +124,8 @@ export class AgentHostWorktreeLocationProvider extends Disposable implements IWo /** * `location` as a location of the folder at `primary`, when git links it both ways with an entry of `worktreesDir`: its - * `.git` file names the entry, and the entry's `gitdir` file names its `.git` back, by their real paths, such as of a - * folder reached through a symbolic link. + * `.git` file names the entry, and the entry's `gitdir` file names the location's `.git` back, by their real paths, such + * as of a folder reached through a symbolic link. */ private async _resolve(worktreesDir: URI, primary: URI, location: URI): Promise { if (location.scheme !== Schemas.file) { @@ -141,8 +141,12 @@ export class AgentHostWorktreeLocationProvider extends Disposable implements IWo return undefined; } const backlink = await this._readLink(joinPath(entry, 'gitdir'), entry); - // The `.git` file by its real path, also where it is a symbolic link - if (!backlink || !extUriBiasedIgnorePathCase.isEqual(await this._real(backlink), await this._real(locationGitFile))) { + // The entry names the checkout itself: the folder of the `.git` file it names is the location, by their real paths, + // and that file is the location's `.git`, also where it is a symbolic link. Another folder whose `.git` links to the + // same file is no checkout of the entry, and must not inherit the primary's trust. + if (!backlink + || !extUriBiasedIgnorePathCase.isEqual(await this._real(dirname(backlink)), realLocation) + || !extUriBiasedIgnorePathCase.isEqual(await this._real(backlink), await this._real(locationGitFile))) { return undefined; } // Its branch, from the entry's HEAD: read again each time the location is resolved diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index 852d04abf0ebfc..2e0d3fbb2c7827 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -61,9 +61,12 @@ export class ChatViewPaneHost implements IChatViewHost { const chatView = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); if (chatView) { const reason = getChatViewHostOpenReason(options); + const shownBefore = chatView.shownSession.get(); await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason, reason); - // Also a chat it showed already, which loading does not set again - chatView.reportShown(sessionResource, reason); + // A chat it showed already, which loading does not set again, is reported once: a chat that loading set is reported already + if (chatView.shownSession.get() === shownBefore) { + chatView.reportShown(sessionResource, reason); + } if (!options?.preserveFocus) { chatView.focusInput(); } diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index 5596642977a05a..4a6375469149e0 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -8,13 +8,16 @@ import { DeferredPromise } from '../../../../../../../base/common/async.js'; import { VSBuffer } from '../../../../../../../base/common/buffer.js'; import { CancellationToken } from '../../../../../../../base/common/cancellation.js'; import { Emitter } from '../../../../../../../base/common/event.js'; +import { extUri } from '../../../../../../../base/common/resources.js'; import { URI } from '../../../../../../../base/common/uri.js'; import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; import { FileOperationError, FileOperationResult, IFileContent, IFileService, IFileStatWithMetadata } from '../../../../../../../platform/files/common/files.js'; import { TestInstantiationService } from '../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogService, NullLogService } from '../../../../../../../platform/log/common/log.js'; -import { AgentHostWorktreeLocationProvider, getAgentHostSessionWorkingDirectories } from '../../../../browser/agentSessions/agentHost/agentHostWorktreeLocations.js'; +import { WorkbenchState } from '../../../../../../../platform/workspace/common/workspace.js'; +import { BrowserWorkspaceEditingService } from '../../../../../../services/workspaces/browser/workspaceEditingService.js'; +import { AGENT_HOST_WORKTREE_LOCATIONS_PROVIDER_ID, AgentHostWorktreeLocationProvider, getAgentHostSessionWorkingDirectories } from '../../../../browser/agentSessions/agentHost/agentHostWorktreeLocations.js'; import { IAgentSession } from '../../../../browser/agentSessions/agentSessionsModel.js'; import { IAgentSessionsService } from '../../../../browser/agentSessions/agentSessionsService.js'; import { IChatSessionsService, SessionType } from '../../../../common/chatSessionsService.js'; @@ -186,17 +189,58 @@ suite('AgentHostWorktreeLocations', () => { }, { throughLinkedPrimary: 'feature', linkedWorktree: 'feature', primaryItself: 'none', offered: ['/alias/feature'] }); }); - test('follows symbolic links of the repository\'s worktrees folder and of a worktree\'s .git file, and still rejects one that git does not link back', async () => { - // The repository's `.git/worktrees` is a link to another folder, and the worktree's `.git` file a link to another file + test('follows symbolic links of the repository\'s worktrees folder and of a worktree\'s .git file, and grants the primary\'s trust only to the checkout git links back, not to another folder whose .git links to the same file', async () => { + // The repository's `.git/worktrees` is a link to another folder, and the worktree's `.git` file a link to another + // file; git names the worktree's own `.git` back. The impostor's `.git` links to the same file. const linked = { '/work/vscode/.git': true, - '/store/worktrees/feature/gitdir': '/store/feature.git\n', + '/store/worktrees/feature/gitdir': '/work/vscode.worktrees/feature/.git\n', '/store/feature.git': 'gitdir: /work/vscode/.git/worktrees/feature\n', - '/work/impostor/.git': 'gitdir: /work/vscode/.git/worktrees/feature\n', }; - const provider = createProvider(linked, [], [], { '/work/vscode/.git/worktrees': '/store/worktrees', '/work/vscode.worktrees/feature/.git': '/store/feature.git' }); + const provider = createProvider(linked, [], [], { + '/work/vscode/.git/worktrees': '/store/worktrees', + '/work/vscode.worktrees/feature/.git': '/store/feature.git', + '/work/impostor/.git': '/store/feature.git', + }); const resolve = async (path: string) => (await provider.resolveLocation(URI.file('/work/vscode'), URI.file(path), CancellationToken.None))?.uri.path ?? 'none'; - assert.deepStrictEqual({ linked: await resolve('/work/vscode.worktrees/feature'), impostor: await resolve('/work/impostor') }, { linked: '/work/vscode.worktrees/feature', impostor: 'none' }); + // The workspace grants a location of a built-in provider the trust of the primary location + const primary = URI.file('/work/vscode'); + const trusted: string[] = []; + let current = primary; + const workspaceEditingService = store.add(new (BrowserWorkspaceEditingService as unknown as new (...args: unknown[]) => BrowserWorkspaceEditingService)( + undefined, + { + getWorkbenchState: () => WorkbenchState.FOLDER, + getWorkspace: () => ({ folders: [{ uri: current }], uri: primary }), + setFolderLocation: async (location: URI, o?: { onApplied?: () => void }) => { current = location; o?.onApplied?.(); return true; }, + }, + undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, + { confirm: async () => ({ confirmed: false }) }, + undefined, + { extUri }, + { isWorkspaceTrusted: () => true, getUriTrustInfo: async (uri: URI) => ({ trusted: extUri.isEqual(uri, primary) }), setUrisTrust: async (uris: URI[]) => { trusted.push(...uris.map(uri => uri.path)); } }, + undefined, undefined, undefined, + { + canSetLocation: () => true, + resolveLocation: async (folder: URI, location: URI) => { + const resolved = await provider.resolveLocation(folder, location, CancellationToken.None); + return resolved && { ...resolved, providerId: AGENT_HOST_WORKTREE_LOCATIONS_PROVIDER_ID, builtIn: true }; + }, + setLocation: () => { }, + }, + { isWorkspaceTrustEnabled: () => true } + )); + await workspaceEditingService.setFolderLocation(URI.file('/work/impostor')); + const impostorTrusted = [...trusted]; + await workspaceEditingService.setFolderLocation(primary); + await workspaceEditingService.setFolderLocation(URI.file('/work/vscode.worktrees/feature')); + + assert.deepStrictEqual({ linked: await resolve('/work/vscode.worktrees/feature'), impostor: await resolve('/work/impostor'), impostorTrusted, trusted }, { + linked: '/work/vscode.worktrees/feature', + impostor: 'none', + impostorTrusted: [], + trusted: ['/work/vscode.worktrees/feature'], + }); }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 3d0ab1e601e7b2..b3c9889571b12f 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -8,7 +8,11 @@ import { CancellationToken, CancellationTokenSource } from '../../../../../../.. import { CancellationError } from '../../../../../../../base/common/errors.js'; import { DeferredPromise, RunOnceScheduler, timeout } from '../../../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../../../base/common/event.js'; -import { constObservable, IObservable, observableValue } from '../../../../../../../base/common/observable.js'; +import { autorun, constObservable, IObservable, observableValue } from '../../../../../../../base/common/observable.js'; +import { TestInstantiationService } from '../../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IProgressService } from '../../../../../../../platform/progress/common/progress.js'; +import { IViewsService } from '../../../../../../services/views/common/viewsService.js'; +import { ChatViewHostService } from '../../../../browser/widgetHosts/viewPane/chatViewHostService.js'; import { DisposableStore, MutableDisposable, toDisposable } from '../../../../../../../base/common/lifecycle.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../../base/test/common/utils.js'; import { upcastPartial } from '../../../../../../../base/test/common/mock.js'; @@ -36,8 +40,8 @@ import { AgentSessionsFilter } from '../../../../browser/agentSessions/agentSess import { MenuWorkbenchToolBar } from '../../../../../../../platform/actions/browser/toolbar.js'; import { ChatConfiguration } from '../../../../common/constants.js'; import { AgentSessionsViewerOrientation } from '../../../../browser/agentSessions/agentSessions.js'; -import { Position } from '../../../../../../services/layout/browser/layoutService.js'; -import { ViewContainerLocation } from '../../../../../../common/views.js'; +import { IWorkbenchLayoutService, Position } from '../../../../../../services/layout/browser/layoutService.js'; +import { IViewDescriptorService, ViewContainerLocation } from '../../../../../../common/views.js'; suite('ChatViewPane sessions refresh', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -355,6 +359,46 @@ suite('ChatViewPane session transitions', () => { }); }); + test('through the Chat view host, each open reports the chat it shows exactly once: a chat it loads, the chat it shows already when picked again, to restore, and a committed one', async () => { + const rig = createPane(); + const savedResource = nextResource.with({ path: '/saved' }); + const committedResource = nextResource.with({ path: '/committed' }); + const reference = (resource: URI) => Object.assign(toDisposable(() => { }), { object: upcastPartial({ sessionResource: resource }) }); + Object.assign(rig.pane, { chatService: { acquireOrLoadSession: async (resource: URI) => reference(resource) } }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IViewsService, upcastPartial({ + openView: (async () => rig.pane) as IViewsService['openView'], + onDidChangeViewVisibility: Event.None, + getViewWithId: (() => rig.pane as T) as IViewsService['getViewWithId'], + })); + instantiationService.stub(IViewDescriptorService, upcastPartial({})); + instantiationService.stub(IWorkbenchLayoutService, upcastPartial({})); + instantiationService.stub(IProgressService, upcastPartial({})); + const host = instantiationService.createInstance(ChatViewHostService); + const stream: string[] = []; + store.add(autorun(reader => { + const shown = rig.pane.shownSession.read(reader); + stream.push(shown ? `${shown.resource.path} ${shown.reason}` : 'none'); + })); + const step = async (name: string, open: () => Promise) => { + const before = stream.length; + await open(); + return { [name]: stream.slice(before) }; + }; + + assert.deepStrictEqual(Object.assign({}, + await step('loaded', () => host.openSession(savedResource, { preserveFocus: true })), + await step('pickedAgain', () => host.openSession(savedResource, { preserveFocus: true })), + await step('restored', () => host.openSession(savedResource, { preserveFocus: true, restore: true })), + await step('committed', () => host.openSession(committedResource, { preserveFocus: true, commit: true })), + ), { + loaded: ['/saved open'], + pickedAgain: ['/saved open'], + restored: ['/saved restore'], + committed: ['/committed commit'], + }); + }); + test('cancelling a replacement releases its pending reference before provider activation completes', async () => { const resolving = new DeferredPromise(); const rig = createPane(resolving.p); From 1fbcf1a37efda4906e416d66003a2ffa734e05e9 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 07:19:09 +0100 Subject: [PATCH 12/20] Worktree infra: tests reach the trust consumer through a refused move, and Chat view mocks expose the shown session Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../chat/test/browser/actions/chatMoveActions.test.ts | 2 ++ .../agentHost/agentHostWorktreeLocations.test.ts | 6 ++++-- .../chat/test/browser/widget/chatWidgetService.test.ts | 2 +- .../test/browser/widgetHosts/viewPane/chatViewPane.test.ts | 3 +++ 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts index c7c7c3901267e9..c841a1aea003d0 100644 --- a/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts @@ -8,6 +8,7 @@ import { Event } from '../../../../../../base/common/event.js'; import { NullManagedSettingsService } from '../../../../../../platform/policy/common/copilotManagedSettings.js'; import { AccountPolicyGateState } from '../../../../../services/policies/common/accountPolicyService.js'; import { IReference, MutableDisposable, ReferenceCollection } from '../../../../../../base/common/lifecycle.js'; +import { constObservable } from '../../../../../../base/common/observable.js'; import { mockObject, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; @@ -91,6 +92,7 @@ suite('Chat move actions', () => { return model; }, focusInput() { }, + shownSession: constObservable(undefined), reportShown() { }, }); const viewsService = upcastPartial({ diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index 4a6375469149e0..fc7745c6093551 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -231,14 +231,16 @@ suite('AgentHostWorktreeLocations', () => { }, { isWorkspaceTrustEnabled: () => true } )); - await workspaceEditingService.setFolderLocation(URI.file('/work/impostor')); + // No provider knows the impostor: the workspace refuses to move there, and trusts nothing + const impostorMove = await workspaceEditingService.setFolderLocation(URI.file('/work/impostor')).then(() => 'moved', () => 'refused'); const impostorTrusted = [...trusted]; await workspaceEditingService.setFolderLocation(primary); await workspaceEditingService.setFolderLocation(URI.file('/work/vscode.worktrees/feature')); - assert.deepStrictEqual({ linked: await resolve('/work/vscode.worktrees/feature'), impostor: await resolve('/work/impostor'), impostorTrusted, trusted }, { + assert.deepStrictEqual({ linked: await resolve('/work/vscode.worktrees/feature'), impostor: await resolve('/work/impostor'), impostorMove, impostorTrusted, trusted }, { linked: '/work/vscode.worktrees/feature', impostor: 'none', + impostorMove: 'refused', impostorTrusted: [], trusted: ['/work/vscode.worktrees/feature'], }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts index e31ea418567b98..24c73a75a3f0d4 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/chatWidgetService.test.ts @@ -218,7 +218,7 @@ suite('ChatWidgetService', () => { const oldWidget = createWidget(session); const emptyOldWidget = createWidget(undefined); const hostWidget = upcastPartial({}); - const view = { widget: oldWidget, focus: () => calls.push('view.focus'), loadSession: async () => { calls.push('view.loadSession'); }, reportShown: (_resource: URI, reason: string) => calls.push(`view.reportShown ${reason}`) }; + const view = { widget: oldWidget, shownSession: constObservable(undefined), focus: () => calls.push('view.focus'), loadSession: async () => { calls.push('view.loadSession'); }, reportShown: (_resource: URI, reason: string) => calls.push(`view.reportShown ${reason}`) }; instantiationService.stub(IEditorGroupsService, { groups: [] }); instantiationService.stub(IViewsService, { getViewWithId: (() => view) as unknown as IViewsService['getViewWithId'], diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index b3c9889571b12f..71e6a0c5397c3d 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -191,6 +191,7 @@ suite('ChatViewPane session transitions', () => { const widget = { get viewModel() { return shown && { model: shown, sessionResource: shown.sessionResource }; }, getViewState: () => ({}), + restoreViewState: () => { }, getInput: () => input, setInput: (value: string) => { input = value; }, setModel: (model: IChatModel | undefined) => { @@ -361,6 +362,8 @@ suite('ChatViewPane session transitions', () => { test('through the Chat view host, each open reports the chat it shows exactly once: a chat it loads, the chat it shows already when picked again, to restore, and a committed one', async () => { const rig = createPane(); + // Each open below loads a chat of its own + rig.nextRef.dispose(); const savedResource = nextResource.with({ path: '/saved' }); const committedResource = nextResource.with({ path: '/committed' }); const reference = (resource: URI) => Object.assign(toDisposable(() => { }), { object: upcastPartial({ sessionResource: resource }) }); From 787f2466d9b19482b463e0d6171bde80ea84816f Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 07:39:49 +0100 Subject: [PATCH 13/20] Worktree infra: a Chat view load reports its chat itself, once, unless a later open supersedes it The host no longer infers from the shown session whether a load reported its chat: a superseded restore no longer reports its reason after the explicit open that superseded it. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../viewPane/chatViewHostService.ts | 6 +-- .../widgetHosts/viewPane/chatViewPane.ts | 10 ++++ .../viewPane/chatViewHostService.test.ts | 6 +-- .../widgetHosts/viewPane/chatViewPane.test.ts | 47 +++++++++++++++++++ 4 files changed, 61 insertions(+), 8 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index 2e0d3fbb2c7827..77362511cde31a 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -61,12 +61,8 @@ export class ChatViewPaneHost implements IChatViewHost { const chatView = await this.viewsService.openView(ChatViewId, !options?.preserveFocus); if (chatView) { const reason = getChatViewHostOpenReason(options); - const shownBefore = chatView.shownSession.get(); + // Loading reports the chat once, also one it showed already, unless a later open supersedes it await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason, reason); - // A chat it showed already, which loading does not set again, is reported once: a chat that loading set is reported already - if (chatView.shownSession.get() === shownBefore) { - chatView.reportShown(sessionResource, reason); - } if (!options?.preserveFocus) { chatView.focusInput(); } diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts index bf22c302e18139..e2ea89be5b9bdd 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewPane.ts @@ -173,6 +173,8 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { /** Why the view sets the chat it shows, while it sets it: it restores the chat it last showed, or the user brought one up. */ private _showReason: IChatViewHostShownSession['reason'] = 'open'; private readonly _shownSession = observableValue(this, undefined); + /** How often it reported the chat it shows ({@link shownSession}): whether a load reported its chat itself. */ + private _shownReports = 0; /** The chat the view shows, and whether it shows it as the user brought it up or as it restored it. */ readonly shownSession: IObservable = this._shownSession; private readonly customizationMigrationsAvailable = observableValue(this, false); @@ -1525,6 +1527,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { // Each time the user opens it, also where it is reported as opened already, as where it works may matter again if (shown && (reason === 'open' || shown.reason !== reason) && isEqual(shown.resource, sessionResource)) { this._shownSession.set({ resource: sessionResource, reason }, undefined); + this._shownReports++; } } @@ -1537,6 +1540,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private updateShownSession(reason: IChatViewHostShownSession['reason'] = this._showReason): void { const shownResource = this._widget.viewModel?.sessionResource; this._shownSession.set(shownResource && { resource: shownResource, reason }, undefined); + this._shownReports++; } /** @param showReason why it shows the chat ({@link shownSession}). */ @@ -1702,6 +1706,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { this.loadSessionCts.value?.cancel(); const cts = this.loadSessionCts.value = new CancellationTokenSource(); const token = cts.token; + const shownReports = this._shownReports; const open = this._openDiagnostics.value = !isUntitledChatSession(sessionResource) && this.layoutService.isRestored() ? this.chatOpenDiagnosticsService.startOpen('panel', sessionResource, token, alreadyShown) : undefined; @@ -1782,6 +1787,11 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { } else if (!token.isCancellationRequested) { open?.fail(new Error('Another chat was shown instead of the requested one')); } + // The chat it shows is reported once for this load: a chat it set is reported already, such as one it showed + // already is not, and a load that a later one superseded reports nothing, so the latest open's reason stands + if (!token.isCancellationRequested && this._shownReports === shownReports) { + this.reportShown(sessionResource, showReason); + } return loadedModel; } catch (error) { open?.fail(error); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts index 69a52095d5bfa4..ae2c33f81522d2 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -88,9 +88,9 @@ suite('ChatViewHostService', () => { calls: [ `openView ${ChatViewId} focus=true`, `openView ${ChatViewId} focus=false`, - `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'reportShown test:/session open', 'focusInput', - `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined restore', 'reportShown test:/session restore', - `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined commit', 'reportShown test:/session commit', + `openView ${ChatViewId} focus=true`, 'loadSession test:/session reason=explicitOverride', 'focusInput', + `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined restore', + `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined commit', `setPartHidden false ${Parts.AUXILIARYBAR_PART}`, `openView ${ChatViewId} focus=undefined`, 'beforeOpen', 'suppress', 'progress', 'loadSession test:/session reason=explicitOverride', 'focus', `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined', diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 71e6a0c5397c3d..8f48e6743a13a9 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -194,7 +194,11 @@ suite('ChatViewPane session transitions', () => { restoreViewState: () => { }, getInput: () => input, setInput: (value: string) => { input = value; }, + // Like ChatWidget: the chat it shows already is not set again, and its view model does not change setModel: (model: IChatModel | undefined) => { + if (model && shown && model.sessionResource.toString() === shown.sessionResource.toString()) { + return; + } shown = model; input = ''; bindings.push(model?.sessionResource); @@ -222,6 +226,7 @@ suite('ChatViewPane session transitions', () => { } = Object.assign(Object.create(ChatViewPane.prototype), { _store: paneStore, _showReason: 'open', + _shownReports: 0, _shownSession: shownSession, shownSession, modelRef, @@ -402,6 +407,46 @@ suite('ChatViewPane session transitions', () => { }); }); + test('through the Chat view host, an open of the chat it shows already that supersedes a restore of it under way reports the open, not the restore', async () => { + const rig = createPane(); + rig.nextRef.dispose(); + const chat = nextResource.with({ path: '/chat' }); + const reference = () => Object.assign(toDisposable(() => { }), { object: upcastPartial({ sessionResource: chat }) }); + // The restore's load and the explicit open's each wait, so that the superseded restore ends first + const restoring = new DeferredPromise(); + const opening = new DeferredPromise(); + const loads = [async () => reference(), async () => { await restoring.p; return reference(); }, async () => { await opening.p; return reference(); }]; + Object.assign(rig.pane, { chatService: { acquireOrLoadSession: () => loads.shift()!() } }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IViewsService, upcastPartial({ + openView: (async () => rig.pane) as IViewsService['openView'], + onDidChangeViewVisibility: Event.None, + getViewWithId: (() => rig.pane as T) as IViewsService['getViewWithId'], + })); + instantiationService.stub(IViewDescriptorService, upcastPartial({})); + instantiationService.stub(IWorkbenchLayoutService, upcastPartial({})); + instantiationService.stub(IProgressService, upcastPartial({})); + const host = instantiationService.createInstance(ChatViewHostService); + await host.openSession(chat, { preserveFocus: true }); + const stream: string[] = []; + store.add(autorun(reader => { + const shown = rig.pane.shownSession.read(reader); + stream.push(shown ? `${shown.resource.path} ${shown.reason}` : 'none'); + })); + stream.length = 0; + + const restore = host.openSession(chat, { preserveFocus: true, restore: true }); + await timeout(0); + const open = host.openSession(chat, { preserveFocus: true }); + await timeout(0); + await restoring.complete(); + await restore; + await opening.complete(); + await open; + + assert.deepStrictEqual({ stream, shown: rig.pane.shownSession.get()?.reason }, { stream: ['/chat open'], shown: 'open' }); + }); + test('cancelling a replacement releases its pending reference before provider activation completes', async () => { const resolving = new DeferredPromise(); const rig = createPane(resolving.p); @@ -580,6 +625,8 @@ suite('ChatViewPane chat open diagnostics', () => { notificationService: { error: () => { } }, progressService: { withProgress: (_: unknown, task: () => Promise) => task() }, loadSessionCts: { value: undefined, }, + _shownSession: observableValue('shownSession', undefined), + _shownReports: 0, _applyModelCts: { value: undefined }, element: { ownerDocument: { hidden: false } }, _widget: { viewModel: options.shown ? { sessionResource: options.shown } : undefined, visible: true, getInput: () => '' }, From 38e75c3a27b2c418e1b67a5351e66f5276b0dd11 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 07:50:21 +0100 Subject: [PATCH 14/20] Worktree infra: sources of where local agent host sessions work, besides the Chat view's sessions list IAgentHostWorktreeSessionSources lets another session layer, such as the editor window's, nominate where its sessions and chats work. AgentHostWorktreeLocationProvider offers the union of the Chat view's sessions and every source, deduplicated, and still accepts only a linked checkout that git names back. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 19 +++- .../agentHostWorktreeSessionSources.ts | 99 +++++++++++++++++++ .../agentHostWorktreeLocations.test.ts | 29 +++++- 3 files changed, 143 insertions(+), 4 deletions(-) create mode 100644 src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeSessionSources.ts diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index 2e51fd0ea2717f..f42facd1514749 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -7,6 +7,7 @@ import { raceCancellation } from '../../../../../../base/common/async.js'; import { CancellationToken } from '../../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { Disposable } from '../../../../../../base/common/lifecycle.js'; +import { ResourceMap } from '../../../../../../base/common/map.js'; import { Schemas } from '../../../../../../base/common/network.js'; import { isAbsolute } from '../../../../../../base/common/path.js'; import { basename, dirname, extUriBiasedIgnorePathCase, joinPath, normalizePath } from '../../../../../../base/common/resources.js'; @@ -19,6 +20,7 @@ import { readFolderGitCheckout } from '../../../../../services/workspaces/common import { IChatSessionsService, isLocalAgentHostTarget } from '../../../common/chatSessionsService.js'; import { IAgentSession } from '../agentSessionsModel.js'; import { IAgentSessionsService } from '../agentSessionsService.js'; +import { IAgentHostWorktreeSessionSources } from './agentHostWorktreeSessionSources.js'; /** The id of the provider of the worktrees that the local agent host's sessions work in. */ export const AGENT_HOST_WORKTREE_LOCATIONS_PROVIDER_ID = 'agentHost.sessionWorktrees'; @@ -60,6 +62,7 @@ export class AgentHostWorktreeLocationProvider extends Disposable implements IWo constructor( @IAgentSessionsService private readonly _agentSessionsService: IAgentSessionsService, @IChatSessionsService private readonly _chatSessionsService: IChatSessionsService, + @IAgentHostWorktreeSessionSources private readonly _sessionSources: IAgentHostWorktreeSessionSources, @IFileService private readonly _fileService: IFileService, @ILogService private readonly _logService: ILogService, ) { @@ -86,9 +89,19 @@ export class AgentHostWorktreeLocationProvider extends Disposable implements IWo return []; } } - const candidates = getAgentHostSessionWorkingDirectories(model.sessions) - .filter(directory => !extUriBiasedIgnorePathCase.isEqual(directory, primary)); - const locations = await Promise.all(candidates.map(async candidate => { + // Also where the sessions that other sources know work, such as those of the editor window's session layer: they + // only nominate a working directory, which is a location only once git links it to the primary below + await raceCancellation(this._sessionSources.whenReady(token), token); + if (token.isCancellationRequested) { + return []; + } + const candidates = new ResourceMap(uri => extUriBiasedIgnorePathCase.getComparisonKey(uri)); + for (const directory of [...getAgentHostSessionWorkingDirectories(model.sessions), ...this._sessionSources.getWorkingDirectories()]) { + if (!extUriBiasedIgnorePathCase.isEqual(directory, primary)) { + candidates.set(directory, directory); + } + } + const locations = await Promise.all([...candidates.values()].map(async candidate => { try { return await this._resolve(worktreesDir, primary, candidate); } catch (error) { diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeSessionSources.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeSessionSources.ts new file mode 100644 index 00000000000000..989a2982e09286 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeSessionSources.ts @@ -0,0 +1,99 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken } from '../../../../../../base/common/cancellation.js'; +import { Emitter, Event } from '../../../../../../base/common/event.js'; +import { Disposable, IDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { InstantiationType, registerSingleton } from '../../../../../../platform/instantiation/common/extensions.js'; +import { createDecorator } from '../../../../../../platform/instantiation/common/instantiation.js'; + +/** + * Knows where local agent host sessions work, such as the sessions of a session layer that the Chat view's sessions list + * does not list. It only nominates working directories: whether one is a location of the window's folder, and inherits + * its trust, is decided by `AgentHostWorktreeLocationProvider` alone. + */ +export interface IAgentHostWorktreeSessionSource { + /** Where the chat of `chatResource` works, if this source knows it. */ + getWorkingDirectory(chatResource: URI): URI | undefined; + /** Where the non-archived local agent host sessions it knows work. */ + getWorkingDirectories(): readonly URI[]; + /** Resolves once it knows its sessions, such as after their first load. */ + whenReady?(token: CancellationToken): Promise; + /** Fires as its sessions, or where they work, change. */ + readonly onDidChange: Event; +} + +export const IAgentHostWorktreeSessionSources = createDecorator('agentHostWorktreeSessionSources'); + +/** The {@link IAgentHostWorktreeSessionSource sources} of where local agent host sessions work, besides the Chat view's sessions list. */ +export interface IAgentHostWorktreeSessionSources { + readonly _serviceBrand: undefined; + + /** Fires as a source is registered or unregistered, or as one changes. */ + readonly onDidChange: Event; + + /** Counts `source` among the sources until the returned disposable is disposed. */ + registerSource(source: IAgentHostWorktreeSessionSource): IDisposable; + + /** Where the chat of `chatResource` works, as the first source that knows it has it. */ + getWorkingDirectory(chatResource: URI): URI | undefined; + + /** Where the sessions of all sources work. */ + getWorkingDirectories(): readonly URI[]; + + /** Resolves once every source knows its sessions. */ + whenReady(token: CancellationToken): Promise; +} + +export class AgentHostWorktreeSessionSources extends Disposable implements IAgentHostWorktreeSessionSources { + + declare readonly _serviceBrand: undefined; + + private readonly _sources = new Set<{ readonly source: IAgentHostWorktreeSessionSource; readonly listener: IDisposable }>(); + + private readonly _onDidChange = this._register(new Emitter()); + readonly onDidChange = this._onDidChange.event; + + registerSource(source: IAgentHostWorktreeSessionSource): IDisposable { + const registration = { source, listener: source.onDidChange(() => this._onDidChange.fire()) }; + this._sources.add(registration); + this._onDidChange.fire(); + return toDisposable(() => { + if (this._sources.delete(registration)) { + registration.listener.dispose(); + this._onDidChange.fire(); + } + }); + } + + getWorkingDirectory(chatResource: URI): URI | undefined { + for (const { source } of this._sources) { + const workingDirectory = source.getWorkingDirectory(chatResource); + if (workingDirectory) { + return workingDirectory; + } + } + return undefined; + } + + getWorkingDirectories(): readonly URI[] { + return [...this._sources].flatMap(({ source }) => source.getWorkingDirectories()); + } + + async whenReady(token: CancellationToken): Promise { + await Promise.all([...this._sources].map(({ source }) => source.whenReady?.(token))); + } + + override dispose(): void { + for (const { listener } of this._sources) { + listener.dispose(); + } + this._sources.clear(); + super.dispose(); + } +} + +registerSingleton(IAgentHostWorktreeSessionSources, AgentHostWorktreeSessionSources, InstantiationType.Delayed); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index fc7745c6093551..ca2d7f63854b67 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -21,6 +21,7 @@ import { AGENT_HOST_WORKTREE_LOCATIONS_PROVIDER_ID, AgentHostWorktreeLocationPro import { IAgentSession } from '../../../../browser/agentSessions/agentSessionsModel.js'; import { IAgentSessionsService } from '../../../../browser/agentSessions/agentSessionsService.js'; import { IChatSessionsService, SessionType } from '../../../../common/chatSessionsService.js'; +import { AgentHostWorktreeSessionSources, IAgentHostWorktreeSessionSources } from '../../../../browser/agentSessions/agentHost/agentHostWorktreeSessionSources.js'; suite('AgentHostWorktreeLocations', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -80,11 +81,13 @@ suite('AgentHostWorktreeLocations', () => { }; instantiationService.stub(IAgentSessionsService, upcastPartial({ model: upcastPartial(model) })); instantiationService.stub(IChatSessionsService, upcastPartial({ getRegisteredChatSessionItemProviders: () => ['remote', SessionType.AgentHostCopilot] })); + const sources = store.add(new AgentHostWorktreeSessionSources()); + instantiationService.stub(IAgentHostWorktreeSessionSources, sources); const provider = store.add(instantiationService.createInstance(AgentHostWorktreeLocationProvider)); // Another provider resolved first model.resolved = true; onDidResolve.fire('remote'); - return Object.assign(provider, { resolving }); + return Object.assign(provider, { resolving, sources }); } const repository = { @@ -245,4 +248,28 @@ suite('AgentHostWorktreeLocations', () => { trusted: ['/work/vscode.worktrees/feature'], }); }); + + test('also offers the worktrees that sessions of another source work in, such as the editor window\'s session layer, but only those git links back', async () => { + const provider = createProvider(repository, [session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/feature')]); + const ready = new DeferredPromise(); + const onDidChange = store.add(new Emitter()); + const nominated = ['/work/vscode.worktrees/relative', '/work/vscode.worktrees/feature', '/work/impostor', '/work/tools.worktrees/fix', '/work/vscode']; + store.add(provider.sources.registerSource({ + getWorkingDirectory: () => undefined, + getWorkingDirectories: () => nominated.map(path => URI.file(path)), + whenReady: () => ready.p, + onDidChange: onDidChange.event, + })); + let offered: string[] | undefined; + const providing = provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None).then(locations => offered = locations.map(location => location.uri.path)); + await new Promise(resolve => setTimeout(resolve, 0)); + const beforeReady = offered; + await ready.complete(); + await providing; + + assert.deepStrictEqual({ beforeReady, offered }, { + beforeReady: undefined, + offered: ['/work/vscode.worktrees/feature', '/work/vscode.worktrees/relative'], + }); + }); }); From dd8a60671d819665392394a93cb317f01de58b97 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 08:10:24 +0100 Subject: [PATCH 15/20] Worktree infra: the session that a started chat moves to after its first request is shown as committed Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../viewPane/chatViewHostService.ts | 3 +- .../viewPane/chatViewHostService.test.ts | 2 +- .../widgetHosts/viewPane/chatViewPane.test.ts | 32 +++++++++++++++++++ 3 files changed, 35 insertions(+), 2 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts index 77362511cde31a..72c14993bd08d0 100644 --- a/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/widgetHosts/viewPane/chatViewHostService.ts @@ -121,7 +121,8 @@ export class ChatViewPaneHost implements IChatViewHost { return { moved: async movedSessionResource => { const movedView = await this.viewsService.openView(ChatViewId) as ChatViewPane; - await movedView.loadSession(movedSessionResource); + // The session that the first request made: shown as committed, not as one the user opened + await movedView.loadSession(movedSessionResource, undefined, 'commit'); }, complete: async () => { transition.dispose(); diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts index ae2c33f81522d2..5e640336b907ea 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewHostService.test.ts @@ -93,7 +93,7 @@ suite('ChatViewHostService', () => { `openView ${ChatViewId} focus=false`, 'loadSession test:/session reason=undefined commit', `setPartHidden false ${Parts.AUXILIARYBAR_PART}`, `openView ${ChatViewId} focus=undefined`, 'beforeOpen', 'suppress', 'progress', 'loadSession test:/session reason=explicitOverride', 'focus', - `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined', + `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined commit', 'unsuppress', 'progress done', `openView ${ChatViewId} focus=undefined`, 'startNewLocalSession', 'focus', ], diff --git a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 8f48e6743a13a9..a2c6ce83f1f24b 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts @@ -447,6 +447,38 @@ suite('ChatViewPane session transitions', () => { assert.deepStrictEqual({ stream, shown: rig.pane.shownSession.get()?.reason }, { stream: ['/chat open'], shown: 'open' }); }); + test('through the Chat view host, the session that a started chat moves to after its first request stays reported as committed', async () => { + const rig = createPane(); + rig.nextRef.dispose(); + const untitled = nextResource.with({ path: '/untitled-started' }); + const committed = nextResource.with({ path: '/committed' }); + const reference = (resource: URI) => Object.assign(toDisposable(() => { }), { object: upcastPartial({ sessionResource: resource }) }); + Object.assign(rig.pane, { chatService: { acquireOrLoadSession: async (resource: URI) => reference(resource) }, focus: () => { } }); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IViewsService, upcastPartial({ + openView: (async () => rig.pane) as IViewsService['openView'], + onDidChangeViewVisibility: Event.None, + getViewWithId: (() => rig.pane as T) as IViewsService['getViewWithId'], + })); + instantiationService.stub(IViewDescriptorService, upcastPartial({})); + instantiationService.stub(IWorkbenchLayoutService, upcastPartial({})); + instantiationService.stub(IProgressService, upcastPartial({})); + const host = instantiationService.createInstance(ChatViewHostService); + const start = await host.startSession(untitled, { local: false, importingConversation: false }); + const stream: string[] = []; + store.add(autorun(reader => { + const shown = rig.pane.shownSession.read(reader); + stream.push(shown ? `${shown.resource.path} ${shown.reason}` : 'none'); + })); + stream.length = 0; + // The first request committed the session, which the host shows as committed, then the start moves to it + await host.openSession(committed, { preserveFocus: true, commit: true }); + await start.moved(committed); + start.dispose(); + + assert.deepStrictEqual(stream, ['/committed commit']); + }); + test('cancelling a replacement releases its pending reference before provider activation completes', async () => { const resolving = new DeferredPromise(); const rig = createPane(resolving.p); From acf5dd8b9d4a47f4f3c3647aa23f29a24529a6b2 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 21:22:43 +0100 Subject: [PATCH 16/20] Worktree infra: what a folder picker's folder and New Worktree do, to show below their names Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../workspaces/common/folderLocationSections.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/vs/workbench/services/workspaces/common/folderLocationSections.ts b/src/vs/workbench/services/workspaces/common/folderLocationSections.ts index 80b0c34923304c..1f526f95068909 100644 --- a/src/vs/workbench/services/workspaces/common/folderLocationSections.ts +++ b/src/vs/workbench/services/workspaces/common/folderLocationSections.ts @@ -50,3 +50,13 @@ export function getCurrentFolderLocationDescription(): string { export function getNewWorktreeLabel(): string { return localize('folderLocations.newWorktree', "New Worktree"); } + +/** What the window's folder does as a choice of a picker of {@link groupFolderLocations}, shown below its name. */ +export function getFolderLocationDetail(): string { + return localize('folderLocations.folderDetail', "Works in the folder already on this computer"); +} + +/** What New Worktree does, shown below its name, as the Agents window's isolation picker describes it. */ +export function getNewWorktreeDetail(): string { + return localize('folderLocations.newWorktreeDetail', "Creates a separate copy for this session"); +} From 6aa8ba049ebac1c37ad7020b2afe1800876adbae Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 21:32:54 +0100 Subject: [PATCH 17/20] Action list: a row with a description and a detail keeps its detail inside it Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../actionWidget/browser/actionWidget.css | 4 ++- .../test/browser/actionList.test.ts | 36 +++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/vs/platform/actionWidget/browser/actionWidget.css b/src/vs/platform/actionWidget/browser/actionWidget.css index 81c5a46d8e1e9f..9999cc5eb1694d 100644 --- a/src/vs/platform/actionWidget/browser/actionWidget.css +++ b/src/vs/platform/actionWidget/browser/actionWidget.css @@ -375,7 +375,9 @@ align-content: center; padding-right: 6px; - .title { + /* The list sets the row's line height to its height: the first line keeps to its text, so the detail fits below it */ + .title, + .description { line-height: 14px; } } diff --git a/src/vs/platform/actionWidget/test/browser/actionList.test.ts b/src/vs/platform/actionWidget/test/browser/actionList.test.ts index 201bfa86246018..23514ec57be42e 100644 --- a/src/vs/platform/actionWidget/test/browser/actionList.test.ts +++ b/src/vs/platform/actionWidget/test/browser/actionList.test.ts @@ -352,6 +352,42 @@ suite('ActionListWidget', () => { }); }); + test('a row with a description and a detail keeps its detail inside it, as one without a description does, also with descriptions inline', () => { + const layoutOf = (inlineDescription: boolean) => { + const widget = createActionListWidget(disposables, { + items: [{ ...action('without'), detail: 'Start without a backing workspace' }, { ...action('with'), description: '~/work', detail: 'Works in the folder already on this computer' }, action('next')], + listOptions: { showFilter: true, inlineDescription }, + }); + const wrapper = document.createElement('div'); + wrapper.classList.add('action-widget'); + widget.domNode.parentElement?.insertBefore(wrapper, widget.domNode); + wrapper.appendChild(widget.domNode); + disposables.add({ dispose: () => wrapper.remove() }); + widget.layout(600, 400); + const rows = [...widget.domNode.querySelectorAll('.monaco-list-row.action')]; + const offsets = (row: HTMLElement) => { + const bounds = row.getBoundingClientRect(); + const detail = row.querySelector('.detail')!.getBoundingClientRect(); + const title = row.querySelector('.title')!.getBoundingClientRect(); + return { title: title.top - bounds.top, detail: detail.top - bounds.top, detailInside: detail.bottom <= bounds.bottom }; + }; + return { + without: offsets(rows[0]), + with: offsets(rows[1]), + noOverlap: rows[2].getBoundingClientRect().top >= rows[1].querySelector('.detail')!.getBoundingClientRect().bottom, + }; + }; + const result = { stacked: layoutOf(false), inline: layoutOf(true) }; + + assert.deepStrictEqual({ + stacked: { detailInside: result.stacked.with.detailInside, sameAsWithout: result.stacked.with.detail === result.stacked.without.detail && result.stacked.with.title === result.stacked.without.title, noOverlap: result.stacked.noOverlap }, + inline: { detailInside: result.inline.with.detailInside, sameAsWithout: result.inline.with.detail === result.inline.without.detail && result.inline.with.title === result.inline.without.title, noOverlap: result.inline.noOverlap }, + }, { + stacked: { detailInside: true, sameAsWithout: true, noOverlap: true }, + inline: { detailInside: true, sameAsWithout: true, noOverlap: true }, + }); + }); + test('wrapped details resize rows without clipping or overlapping subsequent items', () => { const widget = createActionListWidget(disposables, { items: [{ ...action('Remote environment'), detail: 'Access agents on this machine from VS Code, vscode.dev/agents, GitHub apps, or github.com/copilot. '.repeat(3) }, action('Next')], From a82a018495096d833898f917bb9815afa9125a25 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 22:04:24 +0100 Subject: [PATCH 18/20] Action list: a row with a detail is laid out alike with descriptions inline, its detail as far below its label Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../actionWidget/browser/actionWidget.css | 4 ++-- .../test/browser/actionList.test.ts | 21 +++++++++++++++++++ 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/vs/platform/actionWidget/browser/actionWidget.css b/src/vs/platform/actionWidget/browser/actionWidget.css index 9999cc5eb1694d..6425f8193c9c8f 100644 --- a/src/vs/platform/actionWidget/browser/actionWidget.css +++ b/src/vs/platform/actionWidget/browser/actionWidget.css @@ -449,8 +449,8 @@ /* Inline description mode — description rendered right after the label */ .action-widget .inline-description .monaco-list-row.action { - /* Override the row gap so group-title and toolbar sit flush */ - gap: 0; + /* Override the gap between items so group-title and toolbar sit flush; a detail keeps the gap above it */ + column-gap: 0; .title { flex: 0 1 auto; diff --git a/src/vs/platform/actionWidget/test/browser/actionList.test.ts b/src/vs/platform/actionWidget/test/browser/actionList.test.ts index 23514ec57be42e..20497dbe09acda 100644 --- a/src/vs/platform/actionWidget/test/browser/actionList.test.ts +++ b/src/vs/platform/actionWidget/test/browser/actionList.test.ts @@ -388,6 +388,27 @@ suite('ActionListWidget', () => { }); }); + test('a row with a detail is laid out alike with descriptions inline or not: its label, and its detail below it as far apart', () => { + const offsets = (inlineDescription: boolean) => { + const widget = createActionListWidget(disposables, { + items: [{ ...action('New Worktree'), detail: 'Creates a separate copy for this session', group: { title: '', icon: Codicon.worktree } }], + listOptions: { showFilter: false, inlineDescription }, + }); + const wrapper = document.createElement('div'); + wrapper.classList.add('action-widget'); + widget.domNode.parentElement?.insertBefore(wrapper, widget.domNode); + wrapper.appendChild(widget.domNode); + disposables.add({ dispose: () => wrapper.remove() }); + widget.layout(600, 200); + const row = widget.domNode.querySelector('.monaco-list-row.action')!; + const bounds = row.getBoundingClientRect(); + const of = (selector: string) => { const b = row.querySelector(selector)!.getBoundingClientRect(); return { left: b.left - bounds.left, top: b.top - bounds.top }; }; + return { height: bounds.height, title: of('.title'), detail: of('.detail') }; + }; + + assert.deepStrictEqual(offsets(true), offsets(false)); + }); + test('wrapped details resize rows without clipping or overlapping subsequent items', () => { const widget = createActionListWidget(disposables, { items: [{ ...action('Remote environment'), detail: 'Access agents on this machine from VS Code, vscode.dev/agents, GitHub apps, or github.com/copilot. '.repeat(3) }, action('Next')], From 84b9a4dfb9aa37a07e0a824cc275442158b954c8 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sat, 14 Nov 2026 23:49:37 +0100 Subject: [PATCH 19/20] Revert the action list's detail row fixes, which the folder pickers apply to their own lists instead This reverts commits a82a0184950 and 6aa8ba049eb. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../actionWidget/browser/actionWidget.css | 8 +-- .../test/browser/actionList.test.ts | 57 ------------------- 2 files changed, 3 insertions(+), 62 deletions(-) diff --git a/src/vs/platform/actionWidget/browser/actionWidget.css b/src/vs/platform/actionWidget/browser/actionWidget.css index 6425f8193c9c8f..81c5a46d8e1e9f 100644 --- a/src/vs/platform/actionWidget/browser/actionWidget.css +++ b/src/vs/platform/actionWidget/browser/actionWidget.css @@ -375,9 +375,7 @@ align-content: center; padding-right: 6px; - /* The list sets the row's line height to its height: the first line keeps to its text, so the detail fits below it */ - .title, - .description { + .title { line-height: 14px; } } @@ -449,8 +447,8 @@ /* Inline description mode — description rendered right after the label */ .action-widget .inline-description .monaco-list-row.action { - /* Override the gap between items so group-title and toolbar sit flush; a detail keeps the gap above it */ - column-gap: 0; + /* Override the row gap so group-title and toolbar sit flush */ + gap: 0; .title { flex: 0 1 auto; diff --git a/src/vs/platform/actionWidget/test/browser/actionList.test.ts b/src/vs/platform/actionWidget/test/browser/actionList.test.ts index 20497dbe09acda..201bfa86246018 100644 --- a/src/vs/platform/actionWidget/test/browser/actionList.test.ts +++ b/src/vs/platform/actionWidget/test/browser/actionList.test.ts @@ -352,63 +352,6 @@ suite('ActionListWidget', () => { }); }); - test('a row with a description and a detail keeps its detail inside it, as one without a description does, also with descriptions inline', () => { - const layoutOf = (inlineDescription: boolean) => { - const widget = createActionListWidget(disposables, { - items: [{ ...action('without'), detail: 'Start without a backing workspace' }, { ...action('with'), description: '~/work', detail: 'Works in the folder already on this computer' }, action('next')], - listOptions: { showFilter: true, inlineDescription }, - }); - const wrapper = document.createElement('div'); - wrapper.classList.add('action-widget'); - widget.domNode.parentElement?.insertBefore(wrapper, widget.domNode); - wrapper.appendChild(widget.domNode); - disposables.add({ dispose: () => wrapper.remove() }); - widget.layout(600, 400); - const rows = [...widget.domNode.querySelectorAll('.monaco-list-row.action')]; - const offsets = (row: HTMLElement) => { - const bounds = row.getBoundingClientRect(); - const detail = row.querySelector('.detail')!.getBoundingClientRect(); - const title = row.querySelector('.title')!.getBoundingClientRect(); - return { title: title.top - bounds.top, detail: detail.top - bounds.top, detailInside: detail.bottom <= bounds.bottom }; - }; - return { - without: offsets(rows[0]), - with: offsets(rows[1]), - noOverlap: rows[2].getBoundingClientRect().top >= rows[1].querySelector('.detail')!.getBoundingClientRect().bottom, - }; - }; - const result = { stacked: layoutOf(false), inline: layoutOf(true) }; - - assert.deepStrictEqual({ - stacked: { detailInside: result.stacked.with.detailInside, sameAsWithout: result.stacked.with.detail === result.stacked.without.detail && result.stacked.with.title === result.stacked.without.title, noOverlap: result.stacked.noOverlap }, - inline: { detailInside: result.inline.with.detailInside, sameAsWithout: result.inline.with.detail === result.inline.without.detail && result.inline.with.title === result.inline.without.title, noOverlap: result.inline.noOverlap }, - }, { - stacked: { detailInside: true, sameAsWithout: true, noOverlap: true }, - inline: { detailInside: true, sameAsWithout: true, noOverlap: true }, - }); - }); - - test('a row with a detail is laid out alike with descriptions inline or not: its label, and its detail below it as far apart', () => { - const offsets = (inlineDescription: boolean) => { - const widget = createActionListWidget(disposables, { - items: [{ ...action('New Worktree'), detail: 'Creates a separate copy for this session', group: { title: '', icon: Codicon.worktree } }], - listOptions: { showFilter: false, inlineDescription }, - }); - const wrapper = document.createElement('div'); - wrapper.classList.add('action-widget'); - widget.domNode.parentElement?.insertBefore(wrapper, widget.domNode); - wrapper.appendChild(widget.domNode); - disposables.add({ dispose: () => wrapper.remove() }); - widget.layout(600, 200); - const row = widget.domNode.querySelector('.monaco-list-row.action')!; - const bounds = row.getBoundingClientRect(); - const of = (selector: string) => { const b = row.querySelector(selector)!.getBoundingClientRect(); return { left: b.left - bounds.left, top: b.top - bounds.top }; }; - return { height: bounds.height, title: of('.title'), detail: of('.detail') }; - }; - - assert.deepStrictEqual(offsets(true), offsets(false)); - }); - test('wrapped details resize rows without clipping or overlapping subsequent items', () => { const widget = createActionListWidget(disposables, { items: [{ ...action('Remote environment'), detail: 'Access agents on this machine from VS Code, vscode.dev/agents, GitHub apps, or github.com/copilot. '.repeat(3) }, action('Next')], From 0e6ee63b141f1707d7f51a7f0f83a39a8be313b1 Mon Sep 17 00:00:00 2001 From: Sandeep Somavarapu Date: Sun, 15 Nov 2026 03:44:21 +0100 Subject: [PATCH 20/20] Agent host: offer a worktree that sessions reach by several paths once (CCR) A worktree that sessions work in through a symbolic link and through its real path showed twice in the folder picker. Locations are now deduplicated by their real path, keeping the first. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../agentHost/agentHostWorktreeLocations.ts | 15 +++++++++++++-- .../agentHost/agentHostWorktreeLocations.test.ts | 6 ++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts index f42facd1514749..50fbf2d718c403 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -103,14 +103,25 @@ export class AgentHostWorktreeLocationProvider extends Disposable implements IWo } const locations = await Promise.all([...candidates.values()].map(async candidate => { try { - return await this._resolve(worktreesDir, primary, candidate); + const location = await this._resolve(worktreesDir, primary, candidate); + return location && { location, real: await this._real(candidate) }; } catch (error) { // One working directory that fails to read, such as a pruned worktree, does not hide the others this._logService.warn(`[AgentHostWorktreeLocations] Could not read the git checkout of ${candidate.toString()}`, error); return undefined; } })); - return token.isCancellationRequested ? [] : locations.filter(isDefined); + if (token.isCancellationRequested) { + return []; + } + // A worktree that sessions work in by several paths, such as through a symbolic link, is offered once, by the first + const offered = new ResourceMap(uri => extUriBiasedIgnorePathCase.getComparisonKey(uri)); + for (const resolved of locations.filter(isDefined)) { + if (!offered.has(resolved.real)) { + offered.set(resolved.real, resolved.location); + } + } + return [...offered.values()]; } async resolveLocation(primary: URI, location: URI, token: CancellationToken): Promise { diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts index ca2d7f63854b67..acb75b12d1246e 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -192,6 +192,12 @@ suite('AgentHostWorktreeLocations', () => { }, { throughLinkedPrimary: 'feature', linkedWorktree: 'feature', primaryItself: 'none', offered: ['/alias/feature'] }); }); + test('offers a worktree that sessions work in through a symbolic link and through its real path once, by the form a session named first', async () => { + const provider = createProvider(repository, [session(SessionType.AgentHostCopilot, '/alias/feature'), session(SessionType.AgentHostCopilot, '/work/vscode.worktrees/feature')], [], { '/alias/feature': '/work/vscode.worktrees/feature' }); + const offered = (await provider.provideLocations(URI.file('/work/vscode'), CancellationToken.None)).map(location => location.uri.path); + assert.deepStrictEqual(offered, ['/alias/feature']); + }); + test('follows symbolic links of the repository\'s worktrees folder and of a worktree\'s .git file, and grants the primary\'s trust only to the checkout git links back, not to another folder whose .git links to the same file', async () => { // The repository's `.git/worktrees` is a link to another folder, and the worktree's `.git` file a link to another // file; git names the worktree's own `.git` back. The impostor's `.git` links to the same file.