Skip to content

Commit 4e32846

Browse files
sandy081Copilot
andauthored
agentHost: keep scratch work in workspace-less chats (#335526)
* agentHost: keep scratch work in workspace-less chats Clarify that attachment and generated-artifact work can use the scratch directory without converting the session. Reserve workspace conversion for repository changes and project-dependent commands while preserving the confirmation and isolation requirements.\n\nCo-authored-by: Copilot <[email protected]> * agentHost: isolate scratch customizations Keep workspace customization discovery away from mutable Quick Chat scratch roots while retaining user-level customizations. Strengthen the workspace conversion confirmation assertion. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]>
1 parent af459b6 commit 4e32846

10 files changed

Lines changed: 121 additions & 49 deletions

‎src/vs/platform/agentHost/node/codex/codexAgent.ts‎

Lines changed: 19 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1898,6 +1898,10 @@ export class CodexAgent extends Disposable implements IAgent {
18981898
return session.workingDirectories ?? (session.workingDirectory ? [session.workingDirectory] : []);
18991899
}
19001900

1901+
private _customizationWorkingDirectories(session: ICodexSession): readonly URI[] {
1902+
return session.managedWorkingDirectory ? [] : this._workingDirectories(session);
1903+
}
1904+
19011905
private _runtimeWorkspaceRoots(session: ICodexSession): string[] {
19021906
return distinctAbsolutePaths(this._workingDirectories(session).map(directory => directory.fsPath));
19031907
}
@@ -1926,8 +1930,8 @@ export class CodexAgent extends Disposable implements IAgent {
19261930
private async _buildCustomizationLaunch(session: ICodexSession): Promise<ICodexCustomizationLaunch> {
19271931
const plugins = this._enabledClientPlugins(session);
19281932
const [workspaceAgents, workspaceSkills] = await Promise.all([
1929-
discoverCodexWorkspaceAgents(this._workingDirectories(session), this._fileService),
1930-
discoverCodexWorkspaceSkills(this._workingDirectories(session), this._fileService),
1933+
discoverCodexWorkspaceAgents(this._customizationWorkingDirectories(session), this._fileService),
1934+
discoverCodexWorkspaceSkills(this._customizationWorkingDirectories(session), this._fileService),
19311935
]);
19321936
const customization = await codexCustomizationConfig(workspaceAgents.agents, plugins, session.agent, this._fileService);
19331937
const developerInstructions = [
@@ -7473,9 +7477,9 @@ export class CodexAgent extends Disposable implements IAgent {
74737477
this._refreshMcpCustomizationIds(session, controller);
74747478
}
74757479
const [workspaceAgents, workspaceInstructions, workspaceSkills, nativeSkillHookContainers] = await Promise.all([
7476-
discoverCodexWorkspaceAgents(this._workingDirectories(session), this._fileService),
7477-
discoverCodexWorkspaceInstructions(this._workingDirectories(session), this._fileService),
7478-
discoverCodexWorkspaceSkills(this._workingDirectories(session), this._fileService),
7480+
discoverCodexWorkspaceAgents(this._customizationWorkingDirectories(session), this._fileService),
7481+
discoverCodexWorkspaceInstructions(this._customizationWorkingDirectories(session), this._fileService),
7482+
discoverCodexWorkspaceSkills(this._customizationWorkingDirectories(session), this._fileService),
74797483
this._fetchSkillHookContainers(session),
74807484
]);
74817485
if (session.disposed || (catalogConnection !== undefined && !this._isCurrentConnection(catalogConnection))) {
@@ -7520,7 +7524,13 @@ export class CodexAgent extends Disposable implements IAgent {
75207524
client.request<'hooks/list', HooksListResponse>('hooks/list', { cwds: [cwd] })
75217525
.catch(err => { this._logService.warn(`[Codex] hooks/list failed: ${err instanceof Error ? err.message : String(err)}`); return undefined; }),
75227526
]);
7523-
return [...codexSkillsToContainers(skills), ...codexHooksToContainers(hooks)];
7527+
const effectiveSkills = session.managedWorkingDirectory && skills
7528+
? { ...skills, data: skills.data.map(entry => ({ ...entry, skills: entry.skills.filter(skill => skill.scope !== 'repo') })) }
7529+
: skills;
7530+
const effectiveHooks = session.managedWorkingDirectory && hooks
7531+
? { ...hooks, data: hooks.data.map(entry => ({ ...entry, hooks: entry.hooks.filter(hook => hook.source !== 'project') })) }
7532+
: hooks;
7533+
return [...codexSkillsToContainers(effectiveSkills), ...codexHooksToContainers(effectiveHooks)];
75247534
}
75257535

75267536
/**
@@ -7542,9 +7552,9 @@ export class CodexAgent extends Disposable implements IAgent {
75427552
}
75437553
const catalogConnection = this._connection.kind === 'ready' ? this._connection : undefined;
75447554
const [workspaceAgents, workspaceInstructions, workspaceSkills, nativeSkillHookContainers] = await Promise.all([
7545-
discoverCodexWorkspaceAgents(this._workingDirectories(session), this._fileService),
7546-
discoverCodexWorkspaceInstructions(this._workingDirectories(session), this._fileService),
7547-
discoverCodexWorkspaceSkills(this._workingDirectories(session), this._fileService),
7555+
discoverCodexWorkspaceAgents(this._customizationWorkingDirectories(session), this._fileService),
7556+
discoverCodexWorkspaceInstructions(this._customizationWorkingDirectories(session), this._fileService),
7557+
discoverCodexWorkspaceSkills(this._customizationWorkingDirectories(session), this._fileService),
75487558
this._fetchSkillHookContainers(session),
75497559
]);
75507560
if (session.disposed || (catalogConnection !== undefined && !this._isCurrentConnection(catalogConnection))) {

‎src/vs/platform/agentHost/node/copilot/copilotAgent.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6786,7 +6786,7 @@ class SessionPluginController extends Disposable {
67866786

67876787
if (!this._sessionDiscovered.value) {
67886788
this._sessionDiscovered.value = this._instantiationService.createInstance(SessionDiscoveredEntry,
6789-
[this._directory, ...this._additionalDirectories],
6789+
this._workspaceCustomizationDirectories(),
67906790
this._parent.getUserHome(),
67916791
() => this._parent.getClient(),
67926792
() => this._publish(() => ({
@@ -6799,12 +6799,13 @@ class SessionPluginController extends Disposable {
67996799
}
68006800

68016801
private _mcpDiscoveryEntry(): SessionMcpDiscovery | undefined {
6802-
if (!this._directory) {
6802+
const workingDirectories = this._workspaceCustomizationDirectories();
6803+
if (workingDirectories.length === 0) {
68036804
return undefined;
68046805
}
68056806
if (!this._sessionMcpDiscovery.value) {
68066807
const store = new DisposableStore();
6807-
const discovery = store.add(new SessionMcpDiscovery([this._directory, ...this._additionalDirectories], this._fileService));
6808+
const discovery = store.add(new SessionMcpDiscovery(workingDirectories, this._fileService));
68086809
store.add(discovery.onDidChange(() => this._publish(() => ({
68096810
type: ActionType.SessionCustomizationsChanged,
68106811
customizations: [...this.getCustomizations()],
@@ -6814,6 +6815,13 @@ class SessionPluginController extends Disposable {
68146815
return this._sessionMcpDiscovery.value.discovery;
68156816
}
68166817

6818+
private _workspaceCustomizationDirectories(): readonly URI[] {
6819+
if (!this._directory || isEqual(this._directory, workspacelessScratchDir(this._parent.getUserHome(), AgentSession.id(this._session)))) {
6820+
return [];
6821+
}
6822+
return [this._directory, ...this._additionalDirectories];
6823+
}
6824+
68176825
private _publish(action: () => SessionAction): void {
68186826
const publish = () => {
68196827
if (!this._store.isDisposed) {

‎src/vs/platform/agentHost/node/copilot/sessionCustomizationDiscovery.ts‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -220,13 +220,9 @@ function addWatch(map: ResourceMap<IWatchSpec>, watchUri: URI, recursive: boolea
220220
* Workspace roots take precedence over user-home roots when the same URI is
221221
* discovered through multiple paths (de-duped by URI).
222222
*
223-
* `_workingDirectories` MUST be **non-empty** and **primary-first**: index 0 is
224-
* the primary root (the process cwd / worktree) and is used as the anchor for
225-
* sources the SDK does not attribute to a specific root (see {@link discoverRules})
226-
* and as the sole root for hooks (see {@link _hookWorkingDirectories}); indices
227-
* 1..N are the additional multi-root folders. The constructor asserts this so a
228-
* caller that passes an empty set fails fast with a clear error instead of a
229-
* confusing `undefined`-root crash deep inside discovery.
223+
* `_workingDirectories` is primary-first when non-empty: index 0 is the primary
224+
* root and indices 1..N are additional multi-root folders. An empty set performs
225+
* user-home discovery only, which keeps workspace-less scratch content inert.
230226
*/
231227
export class SessionCustomizationDiscovery extends Disposable {
232228

@@ -245,12 +241,6 @@ export class SessionCustomizationDiscovery extends Disposable {
245241
@ILogService private readonly _logService: ILogService,
246242
) {
247243
super();
248-
if (_workingDirectories.length === 0) {
249-
// Dispose the base store before throwing so a rejected construction
250-
// does not leak a tracked (never-disposed) disposable.
251-
this.dispose();
252-
throw new Error('SessionCustomizationDiscovery requires at least one working directory (index 0 = primary root).');
253-
}
254244
this._register({ dispose: () => this._disposeAllWatchers() });
255245
this._register(this._fileService.onDidFilesChange(e => {
256246
for (const watcher of this._watchers.values()) {
@@ -652,7 +642,7 @@ export class SessionCustomizationDiscovery extends Disposable {
652642
// Resolve the relative source against the workspace root the SDK attributed
653643
// it to (`projectPath` disambiguates same-named files across multiple roots).
654644
// Fall back to the primary root for sources without an attributed project.
655-
const anchor = this._rootForProjectPath(instruction.projectPath) ?? this._workingDirectories[0];
645+
const anchor = this._rootForProjectPath(instruction.projectPath) ?? this._workingDirectories[0] ?? this._userHome;
656646
uri = joinPath(anchor, instruction.sourcePath);
657647
}
658648
const uriString = uri.toString();

‎src/vs/platform/agentHost/node/shared/sessionServerTools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,7 +167,7 @@ export const sessionServerToolDefinitions: IAgentServerToolDefinition[] = [
167167
{
168168
name: SessionServerToolName.SetWorkspace,
169169
title: 'Set Workspace',
170-
description: 'Set the current session\'s workspace when the task should continue in a workspace not yet attached to this session. This preserves the session, chat, and conversation history. Immediately before every call to this tool, always use the available user-input tool to ask the user to confirm both the workspace and whether the work should be isolated, even if the user previously mentioned or requested those choices. Tool approval is separate and does not replace this confirmation. Set `isolation` to true to create a managed Git worktree, or false to work directly in the folder. The workspace change is deferred until the current turn ends, then the host automatically continues the original task in the selected workspace. Make this the final tool call of the turn.',
170+
description: 'Attach a real workspace only to modify its files or run commands requiring its project environment. Do not use for self-contained scratch work on attachments, pasted/generated content, or throwaway/exportable artifacts. The session, chat, and history are preserved. Immediately before every call, use the available user-input tool to ask one question confirming both workspace and isolation, even if already specified; tool approval is not confirmation. Set `isolation` to true for a managed Git worktree or false for the folder directly. After this turn, the host attaches the workspace and continues the original task. Make this the turn\'s final tool call.',
171171
inputSchema: setWorkspaceInputSchema,
172172
annotations: { readOnlyHint: false },
173173
},

‎src/vs/platform/agentHost/node/shared/workspacelessInstructions.ts‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
*/
99
export const AGENT_HOST_WORKSPACELESS_INSTRUCTIONS = [
1010
'<workspaceless_chat>',
11-
'This is a lightweight workspace-less chat, not tied to any project or workspace. The user opens it for quick questions, navigation, and triage.',
11+
'This lightweight chat has a SCRATCH working directory, not a project or repository.',
1212
'',
13-
'- Your working directory is a SCRATCH directory for running commands and saving throwaway artifacts — it is NOT a code repository. Do not treat it as a project to build, test, or commit.',
14-
'- You MUST NOT create, edit, or delete files, or run builds, tests, linters, installs, or other project-changing commands in the scratch directory.',
15-
'- You may perform read-only inspection of a real repository when answering a question, but any task that requires project changes MUST first attach that repository with `set_workspace` and continue this same conversation. Do not create another session solely to move the work.',
16-
'- For project-changing work, follow this exact sequence before using any shell or file-mutation tool: use `list_sessions` to discover candidate workspaces when needed; make exactly one call to the available user-input tool (`request_user_input` in Codex or `ask_user` in Copilot) containing exactly one single-select question whose choices each combine an exact workspace with an isolation strategy (use an existing worktree, use the folder directly, or create a new isolated worktree); then call `set_workspace` as the final tool call of the turn using the selected choice. Do not ask workspace and isolation as separate questions. Never guess a workspace path. Tool approval is separate and does not replace user confirmation.',
13+
'- Keep attachment-, pasted-, or generated-content work here when outputs can remain throwaway/exportable. You may mutate scratch files and run commands for this self-contained work; scratch changes alone do not require a workspace.',
14+
'- Do not treat scratch as a project: do not build, test, lint, install for, or commit a real project there.',
15+
'- Read-only repository inspection is allowed. Use `set_workspace` only to modify a repository or run commands requiring its project environment. Continue this conversation; do not create a replacement session.',
16+
'- Before workspace-dependent work: use `list_sessions` if needed; ask exactly one single-select question via `request_user_input` (Codex) or `ask_user` (Copilot). Each choice must pair an exact workspace with isolation (existing worktree, direct folder, or new worktree). Then call `set_workspace` with that choice as the turn\'s final tool call. Do not split the question, guess a path, or treat tool approval as confirmation.',
1717
'</workspaceless_chat>',
1818
].join('\n');

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -217,17 +217,19 @@ suite('AgentHostPromptRegistry', () => {
217217
suite('workspace-less scratch/repoless wiring', () => {
218218
test('prefers attaching a workspace over creating a replacement session', () => {
219219
assert.deepStrictEqual({
220-
usesSetWorkspace: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('project changes MUST first attach that repository with `set_workspace`'),
221-
avoidsReplacementSession: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('Do not create another session solely to move the work'),
222-
blocksScratchMutation: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('MUST NOT create, edit, or delete files'),
223-
requiresConfirmation: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('follow this exact sequence before using any shell or file-mutation tool'),
224-
namesProviderTools: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('`request_user_input` in Codex or `ask_user` in Copilot'),
225-
combinesWorkspaceAndIsolation: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('exactly one single-select question whose choices each combine an exact workspace with an isolation strategy'),
226-
forbidsSplitQuestions: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('Do not ask workspace and isolation as separate questions'),
220+
usesSetWorkspace: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('Use `set_workspace` only to modify a repository or run commands requiring its project environment'),
221+
avoidsReplacementSession: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('do not create a replacement session'),
222+
allowsScratchArtifacts: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('scratch changes alone do not require a workspace'),
223+
keepsAttachmentWorkWorkspaceless: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('Keep attachment-, pasted-, or generated-content work here'),
224+
requiresConfirmation: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('ask exactly one single-select question'),
225+
namesProviderTools: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('`request_user_input` (Codex) or `ask_user` (Copilot)'),
226+
combinesWorkspaceAndIsolation: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('Each choice must pair an exact workspace with isolation'),
227+
forbidsSplitQuestions: AGENT_HOST_WORKSPACELESS_INSTRUCTIONS.includes('Do not split the question'),
227228
}, {
228229
usesSetWorkspace: true,
229230
avoidsReplacementSession: true,
230-
blocksScratchMutation: true,
231+
allowsScratchArtifacts: true,
232+
keepsAttachmentWorkWorkspaceless: true,
231233
requiresConfirmation: true,
232234
namesProviderTools: true,
233235
combinesWorkspaceAndIsolation: true,

‎src/vs/platform/agentHost/test/node/codex/codexPrewarmEviction.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,6 +1542,33 @@ suite('CodexAgent prewarm eviction', () => {
15421542
});
15431543
});
15441544

1545+
test('does not discover workspace customizations from managed scratch', async () => {
1546+
const agent = await createAgent(disposables);
1547+
agent['_schedulePrewarm'] = () => { };
1548+
const created = await createSession(agent);
1549+
const chat = defaultChatOf(created.session);
1550+
const entry = agent['_sessions'].get(AgentSession.id(created.session))!;
1551+
const scratch = URI.file('/scratch/quick-chat');
1552+
entry.workingDirectory = scratch;
1553+
entry.managedWorkingDirectory = scratch;
1554+
await Promise.all([
1555+
agent['_fileService'].writeFile(URI.joinPath(scratch, 'AGENTS.md'), VSBuffer.fromString('Scratch instructions')),
1556+
agent['_fileService'].writeFile(URI.joinPath(scratch, '.github', 'agents', 'scratch.agent.md'), VSBuffer.fromString('---\nname: Scratch\n---\nScratch agent')),
1557+
agent['_fileService'].writeFile(URI.joinPath(scratch, '.github', 'skills', 'scratch', 'SKILL.md'), VSBuffer.fromString('---\nname: scratch\ndescription: Scratch\n---\nScratch skill')),
1558+
]);
1559+
1560+
const customizations = await agent.getChatCustomizations(chat, chatContext(created.session, chat));
1561+
const launch = await agent['_buildCustomizationLaunch'](entry);
1562+
1563+
assert.deepStrictEqual({
1564+
customizations: customizations.map(customization => customization.uri),
1565+
agents: launch.config.agents,
1566+
}, {
1567+
customizations: [],
1568+
agents: undefined,
1569+
});
1570+
});
1571+
15451572
test('workspace skill roots stay session-scoped rather than process-global', async () => {
15461573
const agent = await createAgent(disposables);
15471574
agent['_schedulePrewarm'] = () => { };

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

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ import { IAgentHostReviewService, NULL_REVIEW_SERVICE } from '../../common/agent
7272
import { getCopilotHomePath } from '../../common/copilotHome.js';
7373
import { SessionConfigKey } from '../../common/sessionConfigKeys.js';
7474
import { SEMANTIC_SEARCH_TOOL_NAME } from '../../common/semanticSearchConstants.js';
75-
import { basename, join } from '../../../../base/common/path.js';
75+
import { basename, dirname, join } from '../../../../base/common/path.js';
7676
import { IAgentHostGitHubEndpointService } from '../../node/agentHostGitHubEndpointService.js';
7777
import { createTestGitHubEndpointService } from './testGitHubEndpointService.js';
7878
import { createNoopCustomizationEnablementService } from './testCustomizationEnablementService.js';
@@ -4072,6 +4072,32 @@ suite('CopilotAgent', () => {
40724072
}).timeout(30_000);
40734073

40744074
suite('quick chat scratch directory', () => {
4075+
test('does not discover workspace customizations from scratch', async () => {
4076+
const userHome = URI.file(await fs.mkdtemp(`${os.tmpdir()}/qc-home-`));
4077+
const agent = createTestAgent(disposables, { userHome });
4078+
try {
4079+
await agent.authenticate('https://api.github.com', 'token');
4080+
const session = AgentSession.uri('copilotcli', 'qc-customizations');
4081+
const result = await provisionSession(agent, { session });
4082+
const scratchDir = result.resolvedWorkingDirectory;
4083+
assert.ok(scratchDir);
4084+
const scratchInstructions = URI.joinPath(scratchDir, '.github', 'copilot-instructions.md');
4085+
await fs.mkdir(dirname(scratchInstructions.fsPath), { recursive: true });
4086+
await fs.writeFile(scratchInstructions.fsPath, 'scratch instructions');
4087+
4088+
const customizations = await getDefaultChatCustomizations(agent, session);
4089+
const uris = customizations.flatMap(customization => [
4090+
customization.uri,
4091+
...(customization.type === CustomizationType.Directory ? customization.children?.map(child => child.uri) ?? [] : []),
4092+
]);
4093+
4094+
assert.deepStrictEqual(uris.includes(scratchInstructions.toString()), false);
4095+
} finally {
4096+
await fs.rm(userHome.fsPath, { recursive: true, force: true });
4097+
await disposeAgent(agent);
4098+
}
4099+
}).timeout(30_000);
4100+
40754101
test('resume recreates a reaped quick chat scratch dir (ensure-exists on restore)', async () => {
40764102
const userHome = URI.file(await fs.mkdtemp(`${os.tmpdir()}/qc-home-`));
40774103
const sessionId = 'qc-resume';

0 commit comments

Comments
 (0)