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..50fbf2d718c403 --- /dev/null +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostWorktreeLocations.ts @@ -0,0 +1,218 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * 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 { 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'; +import { isDefined } from '../../../../../../base/common/types.js'; +import { URI } from '../../../../../../base/common/uri.js'; +import { FileOperationResult, IFileService, toFileOperationResult } from '../../../../../../platform/files/common/files.js'; +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 { 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'; + +/** + * 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 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, + @IAgentHostWorktreeSessionSources private readonly _sessionSources: IAgentHostWorktreeSessionSources, + @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 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; + 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 []; + } + } + // 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 { + 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; + } + })); + 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 { + // 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 + const worktreesDir = await this._worktreesDir(primary); + return worktreesDir && !token.isCancellationRequested ? this._resolve(worktreesDir, primary, location) : undefined; + } + + /** 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 { + const checkout = await readFolderGitCheckout(this._fileService, await this._real(primary)); + // 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; + } + } + + /** + * `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 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) { + return undefined; + } + 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, 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); + // 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 + 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)); + } + + /** `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 { + return await read(); + } catch (error) { + const result = error instanceof Error ? toFileOperationResult(error) : undefined; + if (result === FileOperationResult.FILE_NOT_FOUND || result === FileOperationResult.FILE_IS_DIRECTORY) { + return undefined; + } + throw error; + } + } +} + +/** 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/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/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 fc6589af2b9484..6638370bbe4e56 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,18 @@ 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 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' | 'commit' | 'restore'; +} + /** How {@link IChatViewHost.reveal} shows the host. */ export interface IChatViewHostRevealOptions { /** @@ -24,6 +37,21 @@ 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; + /** + * 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. */ @@ -70,6 +98,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 +111,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/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 d433fe430427aa..72c14993bd08d0 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 { 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. */ @@ -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); @@ -46,13 +53,16 @@ export class ChatViewPaneHost implements IChatViewHost { if (view && !options?.preserveFocus) { view.focus(); } + 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); + const reason = getChatViewHostOpenReason(options); + // Loading reports the chat once, also one it showed already, unless a later open supersedes it + await chatView.loadSession(sessionResource, options?.sessionTypeSelectionReason, reason); if (!options?.preserveFocus) { chatView.focusInput(); } @@ -111,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(); @@ -130,28 +141,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..e2ea89be5b9bdd 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,8 @@ 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'; import { AgentSessionsFilter, AgentSessionsGrouping } from '../../agentSessions/agentSessionsFilter.js'; @@ -169,6 +170,13 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { private readonly activityBadge = this._register(new MutableDisposable()); private readonly _currentSessionResource = observableValue(this, undefined); + /** 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); /** * Session resource of the last-focused chat widget, or this pane's own @@ -339,7 +347,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 @@ -378,7 +387,7 @@ export class ChatViewPane extends ViewPane implements IViewWelcomeDelegate { try { this._widget.setVisible(false); - 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._widget.setVisible(wasVisible); } @@ -1242,10 +1251,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.onDidChangeShownModel(e); if (this.sessionsViewerOrientation === AgentSessionsViewerOrientation.Stacked) { return; // only reveal in side-by-side mode @@ -1385,7 +1395,7 @@ 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); + await this.showModel(token, session.modelRef, true, !session.modelRef, undefined, session.localFallbackSelectionReason, 'restore'); } /** @@ -1495,7 +1505,46 @@ 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 of `sessionResource` as one that the user brought up, also where the view shows it already, such as + * 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'); + } + + /** + * 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'); + } + + /** 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)) { + this._shownSession.set({ resource: sessionResource, reason }, undefined); + this._shownReports++; + } + } + + /** 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(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}). */ + 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; @@ -1557,7 +1606,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); @@ -1641,7 +1696,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: IChatViewHostShownSession['reason'] = 'open'): Promise { const t0 = Date.now(); this.logService.trace(`[ChatViewPane] loadSession start uri=${sessionResource.toString()}`); @@ -1650,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; @@ -1699,7 +1756,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) { @@ -1730,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/actions/chatMoveActions.test.ts b/src/vs/workbench/contrib/chat/test/browser/actions/chatMoveActions.test.ts index 028b8050633834..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,8 @@ suite('Chat move actions', () => { return model; }, focusInput() { }, + shownSession: constObservable(undefined), + reportShown() { }, }); 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 new file mode 100644 index 00000000000000..acb75b12d1246e --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHost/agentHostWorktreeLocations.test.ts @@ -0,0 +1,281 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { 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 { 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'; +import { AgentHostWorktreeSessionSources, IAgentHostWorktreeSessionSources } from '../../../../browser/agentSessions/agentHost/agentHostWorktreeSessionSources.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. + */ + /** + * @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) { + // 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[real(resource.path)]; + if (entry === undefined) { + throw new FileOperationError('not found', FileOperationResult.FILE_NOT_FOUND); + } + return upcastPartial({ isDirectory: entry === true }); + }, + realpath: async (resource: URI) => URI.file(real(resource.path)), + readFile: async (resource: URI) => { + const entry = entries[real(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()); + // 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) })); + 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, sources }); + } + + 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', + '/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', + // 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, + }); + }); + + 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 () => { + 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'] }); + }); + + 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. + const linked = { + '/work/vscode/.git': true, + '/store/worktrees/feature/gitdir': '/work/vscode.worktrees/feature/.git\n', + '/store/feature.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', + '/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'; + + // 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 } + )); + // 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'), impostorMove, impostorTrusted, trusted }, { + linked: '/work/vscode.worktrees/feature', + impostor: 'none', + impostorMove: 'refused', + impostorTrusted: [], + 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'], + }); + }); +}); 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..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'); } }; + 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'], @@ -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.reportShown open'] }); }); }); }); 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..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 @@ -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,26 +32,34 @@ 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; }, + 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'); }, + 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()); 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 () => { @@ -60,6 +70,10 @@ 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 }); + // 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')); @@ -75,9 +89,11 @@ suite('ChatViewHostService', () => { `openView ${ChatViewId} focus=true`, `openView ${ChatViewId} focus=false`, `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', + `openView ${ChatViewId} focus=undefined`, 'loadSession test:/moved reason=undefined commit', 'unsuppress', 'progress done', `openView ${ChatViewId} focus=undefined`, 'startNewLocalSession', 'focus', ], @@ -134,4 +150,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/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts b/src/vs/workbench/contrib/chat/test/browser/widgetHosts/viewPane/chatViewPane.test.ts index 17c349b7be14c0..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 @@ -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 } 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'; @@ -20,6 +24,8 @@ 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'; import { ChatOpenDiagnosticsService } from '../../../../common/chatOpenDiagnosticsService.js'; @@ -34,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(); @@ -166,11 +172,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 = (_committed?: boolean) => { }; const paneStore = store.add(new DisposableStore()); const modelRef = paneStore.add(new MutableDisposable()); const createReference = (model: IChatModel): IChatModelReference => Object.assign(toDisposable(() => { @@ -182,12 +191,23 @@ suite('ChatViewPane session transitions', () => { const widget = { get viewModel() { return shown && { model: shown, sessionResource: shown.sessionResource }; }, getViewState: () => ({}), + 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); + 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'); }, @@ -197,11 +217,18 @@ 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; + reportOpened(sessionResource: URI): void; + reportRestored(sessionResource: URI): void; } = Object.assign(Object.create(ChatViewPane.prototype), { _store: paneStore, + _showReason: 'open', + _shownReports: 0, + _shownSession: shownSession, + shownSession, modelRef, widgetViewStates: new Map(), viewState: {}, @@ -222,6 +249,7 @@ suite('ChatViewPane session transitions', () => { agentSessionsService: { model: { getSession: () => undefined } }, updateActions: () => { }, }); + 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 }; } @@ -270,6 +298,187 @@ 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); + // 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); + // 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; + // 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); + // 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 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(); + 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, 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', + superseded: '/saved open', + }); + }); + + 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 }) }); + 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('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('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); @@ -448,6 +657,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: () => '' }, 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/folderLocationSections.ts b/src/vs/workbench/services/workspaces/common/folderLocationSections.ts new file mode 100644 index 00000000000000..1f526f95068909 --- /dev/null +++ b/src/vs/workbench/services/workspaces/common/folderLocationSections.ts @@ -0,0 +1,62 @@ +/*--------------------------------------------------------------------------------------------- + * 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"); +} + +/** 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"); +} 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; +} 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: [], + }); + }); +});