Repository navigation
feat: Enhance Claude chat session management with folder options - #3542
Conversation
- Introduced folder selection capabilities for Claude chat sessions, allowing users to choose folders in single-root, multi-root, and empty workspace scenarios. - Implemented `getFolderInfoForSession` to resolve current working directory and additional directories based on workspace state. - Added folder option handling in `provideChatSessionProviderOptions` to dynamically include folder options based on workspace type. - Created `ClaudeFolderInfo` interface to encapsulate folder information for session management. - Updated tests to cover new folder option functionalities, ensuring correct behavior across different workspace configurations. - Refactored `FolderRepositoryManager` to support Claude-specific folder management while maintaining compatibility with Copilot CLI sessions.
There was a problem hiding this comment.
Pull request overview
Adds workspace-aware folder selection to Claude chat sessions (single-root/multi-root/empty workspace) and threads the resolved cwd/additionalDirectories into the Claude agent/SDK, while refactoring folder/repo management to separate CopilotCLI vs Claude needs.
Changes:
- Introduces
ClaudeFolderInfoand uses it to deterministically setcwd+additionalDirectoriesfor Claude sessions. - Adds a folder option group to Claude session options for multi-root and empty workspaces (MRU-based).
- Refactors
FolderRepositoryManagerinto an abstract base withCopilotCLIFolderRepositoryManager+ClaudeFolderRepositoryManager, and updates session discovery to scan per-folder slugs.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
| src/extension/chatSessions/vscode-node/claudeChatSessionContentProvider.ts | Adds folder option handling, per-session folder tracking, and getFolderInfoForSession used when invoking Claude. |
| src/extension/agents/claude/node/claudeCodeAgent.ts | Threads ClaudeFolderInfo into session creation and SDK Options (cwd, additionalDirectories). |
| src/extension/agents/claude/node/sessionParser/claudeCodeSessionService.ts | Updates project slug discovery to scan all workspace folders / MRU folders (no more process.cwd() fallback). |
| src/extension/chatSessions/vscode-node/folderRepositoryManagerImpl.ts | Refactors into abstract base + CopilotCLI/Claude subclasses; exposes shared helpers to subclasses. |
| src/extension/chatSessions/vscode-node/chatSessions.ts | Registers Claude vs CopilotCLI folder repository manager implementations in their respective DI containers. |
| src/extension/agents/claude/common/claudeFolderInfo.ts | Adds new ClaudeFolderInfo interface. |
| src/extension/agents/claude/AGENTS.md | Documents new folder resolution and session discovery behavior. |
| src/extension/chatSessions/vscode-node/test/claudeChatSessionContentProvider.spec.ts | Adds tests for folder options across single-root/multi-root/empty workspace scenarios. |
| src/extension/agents/claude/node/test/claudeCodeAgent.spec.ts | Updates tests for the new handleRequest / session invocation signatures with folder info + permission mode. |
| src/extension/agents/claude/node/sessionParser/test/claudeCodeSessionService.spec.ts | Updates tests for new project slug scanning behavior (workspace folders and MRU). |
| src/extension/chatSessions/vscode-node/test/folderRepositoryManager.spec.ts | Renames test subject to CopilotCLIFolderRepositoryManager. |
| src/extension/chatSessions/vscode-node/test/copilotCLIChatSessionParticipant.spec.ts | Updates to use CopilotCLIFolderRepositoryManager. |
Comments suppressed due to low confidence (1)
src/extension/chatSessions/vscode-node/claudeChatSessionContentProvider.ts:401
provideHandleOptionsChangeaccepts any string for the folder option and stores it asURI.file(update.value)without validating that it’s one of the offered option items (workspace folders / MRU) or that it exists/trust is granted. This allows non-existent or arbitrary paths to becomecwd/additionalDirectories, which can lead to failures (or unintended access scope) when starting the Claude session. Validate the selection against the current allowed set and consider removing invalid MRU entries (similar to the CopilotCLI repository option handler).
async provideHandleOptionsChange(resource: vscode.Uri, updates: ReadonlyArray<vscode.ChatSessionOptionUpdate>, _token: vscode.CancellationToken): Promise<void> {
const sessionId = ClaudeSessionUri.getId(resource);
for (const update of updates) {
if (update.optionId === MODELS_OPTION_ID) {
// Ignore the unavailable placeholder - it's not a real model
if (update.value === UNAVAILABLE_MODEL_ID) {
continue;
}
// Update last known first so the event listener won't fire back to UI
this._updateLastKnown(sessionId, { modelId: update.value });
void this.claudeCodeModels.setDefaultModel(update.value);
this.sessionStateService.setModelIdForSession(sessionId, update.value);
} else if (update.optionId === PERMISSION_MODE_OPTION_ID) {
// Update last known first so the event listener won't fire back to UI
this._updateLastKnown(sessionId, { permissionMode: update.value as PermissionMode });
this.sessionStateService.setPermissionModeForSession(sessionId, update.value as PermissionMode);
} else if (update.optionId === FOLDER_OPTION_ID && typeof update.value === 'string') {
this._sessionFolders.set(sessionId, URI.file(update.value));
}
| // Include folder option if applicable (multi-root or empty workspace) | ||
| const workspaceFolders = this.workspaceService.getWorkspaceFolders(); | ||
| if (workspaceFolders.length !== 1) { | ||
| const defaultFolder = this._getDefaultFolderForSession(sessionId); | ||
| if (defaultFolder) { | ||
| // Store the default selection so getFolderInfoForSession can use it | ||
| if (!this._sessionFolders.has(sessionId)) { | ||
| this._sessionFolders.set(sessionId, defaultFolder); | ||
| } | ||
|
|
||
| // For existing sessions (non-untitled), lock the folder option | ||
| if (existingSession) { | ||
| options[FOLDER_OPTION_ID] = { | ||
| id: defaultFolder.fsPath, | ||
| name: this.workspaceService.getWorkspaceFolderName(defaultFolder) | ||
| || basename(defaultFolder), | ||
| icon: new vscode.ThemeIcon('folder'), | ||
| locked: true, | ||
| }; | ||
| } else { | ||
| options[FOLDER_OPTION_ID] = defaultFolder.fsPath; | ||
| } |
There was a problem hiding this comment.
Folder option locking is based only on existingSession. In the yield/untitled flow, an SDK session can already exist (and be reused) while existingSession is still undefined, so the UI would allow changing the folder even though the underlying ClaudeCodeSession can’t change its cwd after creation (the new selection won’t take effect). Consider locking the folder option once an SDK session has been created for this chat session (e.g., when there’s an entry in _untitledToSdkSession for the resource, or when you otherwise know the session has started).
This issue also appears on line 383 of the same file.
| /** | ||
| * Claude-specific implementation that does not support getFolderRepository. | ||
| * | ||
| * The Claude agent manages folder resolution through {@link ClaudeFolderInfo} | ||
| * at the content provider level, so getFolderRepository is never called. | ||
| */ | ||
| export class ClaudeFolderRepositoryManager extends FolderRepositoryManager { | ||
| constructor( | ||
| @IChatSessionWorktreeService worktreeService: IChatSessionWorktreeService, | ||
| @IChatSessionWorkspaceFolderService workspaceFolderService: IChatSessionWorkspaceFolderService, | ||
| @IGitService gitService: IGitService, | ||
| @IWorkspaceService workspaceService: IWorkspaceService, | ||
| @ILogService logService: ILogService | ||
| ) { | ||
| super(worktreeService, workspaceFolderService, gitService, workspaceService, logService); | ||
| } | ||
|
|
||
| /** | ||
| * Not supported for Claude sessions. | ||
| * | ||
| * Claude uses {@link ClaudeFolderInfo} for folder resolution instead of this method. | ||
| */ | ||
| async getFolderRepository(): Promise<FolderRepositoryInfo> { | ||
| throw new Error('getFolderRepository is not supported for Claude sessions'); | ||
| } |
There was a problem hiding this comment.
ClaudeFolderRepositoryManager.getFolderRepository intentionally throws, but it’s registered as the IFolderRepositoryManager implementation for Claude. Any accidental call through the interface will turn into a runtime crash. Prefer returning a safe default (all fields undefined) or splitting the interface so Claude only depends on the MRU/untitled-selection functionality it actually supports.
| function createDefaultMocks() { | ||
| const mockSessionService: IClaudeCodeSessionService = { | ||
| getSession: vi.fn() | ||
| } as any; | ||
|
|
||
| const mockClaudeCodeModels: IClaudeCodeModels = { | ||
| resolveModel: vi.fn().mockResolvedValue('claude-3-5-sonnet-20241022'), | ||
| getDefaultModel: vi.fn().mockResolvedValue('claude-3-5-sonnet-20241022'), | ||
| setDefaultModel: vi.fn().mockResolvedValue(undefined), | ||
| getModels: vi.fn().mockResolvedValue([ | ||
| { id: 'claude-3-5-sonnet-20241022', name: 'Claude 3.5 Sonnet' }, | ||
| { id: 'claude-3-5-haiku-20241022', name: 'Claude 3.5 Haiku' } | ||
| ]), | ||
| mapSdkModelToEndpointModel: vi.fn().mockResolvedValue(undefined) | ||
| } as any; |
There was a problem hiding this comment.
Test mocks are still using as any casts for IClaudeCodeSessionService/IClaudeCodeModels. In this repo’s Vitest suites, it’s usually preferable to use explicit Mock/Test classes (or satisfies Partial<...>) to keep type-safety and avoid missing required behavior as the interfaces evolve.
| // No folder available at all | ||
| throw new Error('No folder available for Claude session. Open a folder or select one in the session options.'); |
There was a problem hiding this comment.
getFolderInfoForSession throws when there’s no workspace folder and no MRU entry, and this call isn’t guarded in createHandler (it happens before calling claudeAgentManager.handleRequest). In an empty workspace with no MRU, this will surface as an unhandled exception instead of a user-facing error. Consider returning undefined/a Result type here, or catching the error at the call site to show a friendly message + errorDetails and avoid crashing the request handler.
| // No folder available at all | |
| throw new Error('No folder available for Claude session. Open a folder or select one in the session options.'); | |
| // No folder available at all: show a user-facing error and fall back to a safe cwd | |
| const message = l10n.t("No folder is available for this GitHub Copilot Chat session. Open a folder in the workspace or select one in the session options."); | |
| void vscode.window.showErrorMessage(message); | |
| const fallbackCwd = typeof process !== 'undefined' && typeof process.cwd === 'function' ? process.cwd() : ''; | |
| return { | |
| cwd: fallbackCwd, | |
| additionalDirectories: [], | |
| }; |
|
Fixes microsoft/vscode#290242 |
getFolderInfoForSessionto resolve current working directory and additional directories based on workspace state.provideChatSessionProviderOptionsto dynamically include folder options based on workspace type.ClaudeFolderInfointerface to encapsulate folder information for session management.FolderRepositoryManagerto support Claude-specific folder management while maintaining compatibility with Copilot CLI sessions.