diff --git a/build/BUILD_EVENTS.md b/build/BUILD_EVENTS.md new file mode 100644 index 00000000000000..2a3f251b4ca024 --- /dev/null +++ b/build/BUILD_EVENTS.md @@ -0,0 +1,25 @@ +# Extension build lifecycle events + +Set `VSCODE_BUILD_EVENTS=1` to add machine-readable lifecycle events to extension TypeScript watch compilations (`watch-extension:*`) and extension builds using `extensions/esbuild-common.mts`. Other values, including an unset variable, disable events. Existing human-readable compilation logs remain available. + +Each event is one uncolored JSON object on its own stdout line. Human-readable logs remain interleaved with these records; stdout as a whole is not a JSONL-only stream. + +```jsonl +{"type":"vscode.build","version":1,"event":"start"} +{"type":"vscode.build","version":1,"event":"finish","success":true} +{"type":"vscode.build","version":1,"event":"finish","success":false} +``` + +`start` begins a cycle. Exactly one `finish` event follows once all overlapping builds in that cycle finish: `success: false` if any build failed, otherwise `success: true`. A later cycle starts with a clean failure state. Before-build hooks, esbuild plugins, and asynchronous postprocessing are part of the build: readiness is not reported until they finish, and their errors fail the cycle. + +Consumers should parse complete lines and recognize records by `type: "vscode.build"`. Version 1 defines `event: "start"` and `event: "finish"` with a required boolean `success` on finish. Ignore unrelated log lines and unknown additional fields; field order is not significant. Additional metadata can be introduced without a version bump. Incompatible changes require a new version, which consumers should report as unsupported rather than treating as successful completion. + +Aggregation is local to each runner process and lifecycle: the gulp extension watcher aggregates TypeScript compilations, and each esbuild runner process aggregates its concurrent builds. Consumers must keep separate processes' output separate; these events do not describe the readiness of the entire repository. Watcher subscription errors remain diagnostics, not completed build cycles. + +Without the opt-in, no event lines are printed. Build errors still follow the existing behavior: one-shot esbuild runners exit unsuccessfully, while watchers log failures and allow subsequent rebuilds. One-shot failures now allow overlapping builds to finish before the process exits, and print hook errors before exiting. + +Run the focused tests with Node 24 or later: + +```sh +node --test build/lib/test/buildEvents.test.ts extensions/esbuild-common.test.mts +``` diff --git a/build/gulpfile.extensions.ts b/build/gulpfile.extensions.ts index ef6906cc134dfb..e186339dd42c4a 100644 --- a/build/gulpfile.extensions.ts +++ b/build/gulpfile.extensions.ts @@ -23,6 +23,7 @@ import { createTsgoStream, spawnTsgo } from './lib/tsgo.ts'; import { getCompilerOptionsFromTsConfig } from './lib/tsconfigUtils.ts'; import * as util from './lib/util.ts'; import watcher from './lib/watch/index.ts'; +import { BuildLifecycle } from './lib/buildEvents.ts'; const root = path.dirname(import.meta.dirname); const commit = getVersion(root); @@ -30,21 +31,10 @@ const commit = getVersion(root); // Tracks active extension compilations to emit aggregate // "Starting compilation" / "Finished compilation" messages // that the problem matcher in tasks.json relies on. -let activeExtensionCompilations = 0; - -function onExtensionCompilationStart(): void { - if (activeExtensionCompilations === 0) { - fancyLog('Starting compilation'); - } - activeExtensionCompilations++; -} - -function onExtensionCompilationEnd(): void { - activeExtensionCompilations--; - if (activeExtensionCompilations === 0) { - fancyLog('Finished compilation'); - } -} +const extensionCompilation = new BuildLifecycle( + () => fancyLog('Starting compilation'), + () => fancyLog('Finished compilation'), +); // To save 250ms for each gulp startup, we are caching the result here // const compilations = glob.sync('**/tsconfig.json', { @@ -198,10 +188,10 @@ export function createExtensionTasks(tsconfigFile: string, repoRoot = root) { const watchTask = task.define(`watch-extension:${name}`, task.series(cleanTask, () => { const nonts = gulp.src(src, srcOpts).pipe(filter(['**', '!**/*.{ts,mts,cts}'], { dot: true })); - const watchInput = watcher(src, { ...srcOpts, ...{ readDelay: 200 } }); + const watchInput = watcher(path.relative(repoRoot, src).split(path.sep).join('/'), { ...srcOpts, ...{ readDelay: 200 } }); const watchNonTs = watchInput.pipe(filter(['**', '!**/*.{ts,mts,cts}'], { dot: true })).pipe(gulp.dest(out)); const tsgoStream = watchInput.pipe(util.debounce(() => { - onExtensionCompilationStart(); + const onExtensionCompilationEnd = extensionCompilation.start(); const stream = createTsgoStream(absolutePath, { taskName: 'extensions' }, () => rewriteTsgoSourceMappingUrlsIfNeeded(false, out, baseUrl)); // Wrap in a result stream that always emits 'end' (even on // error) so the debounce resets to idle and can process future @@ -214,7 +204,7 @@ export function createExtensionTasks(tsconfigFile: string, repoRoot = root) { result.emit('end'); }); stream.on('error', () => { - onExtensionCompilationEnd(); + onExtensionCompilationEnd(true); result.emit('end'); }); return result; diff --git a/build/lib/buildEvents.ts b/build/lib/buildEvents.ts new file mode 100644 index 00000000000000..1143c905a4f3dc --- /dev/null +++ b/build/lib/buildEvents.ts @@ -0,0 +1,47 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +export class BuildLifecycle { + private _activeBuilds = 0; + private _failed = false; + private readonly _onStart: (() => void) | undefined; + private readonly _onEnd: (() => void) | undefined; + + constructor(onStart?: () => void, onEnd?: () => void) { + this._onStart = onStart; + this._onEnd = onEnd; + } + + start(): (failed?: boolean) => void { + if (this._activeBuilds++ === 0) { + this._failed = false; + try { + this._onStart?.(); + this._emit({ event: 'start' }); + } catch (error) { + this._activeBuilds--; + throw error; + } + } + let completed = false; + return (failed = false) => { + if (completed) { + return; + } + completed = true; + this._failed ||= failed; + if (--this._activeBuilds === 0) { + this._onEnd?.(); + this._emit({ event: 'finish', success: !this._failed }); + } + }; + } + + private _emit(event: { event: 'start' } | { event: 'finish'; success: boolean }): void { + if (process.env.VSCODE_BUILD_EVENTS === '1') { + console.log(JSON.stringify({ type: 'vscode.build', version: 1, ...event })); + } + } +} diff --git a/build/lib/test/buildEvents.test.ts b/build/lib/test/buildEvents.test.ts new file mode 100644 index 00000000000000..c5c8039d7f37fd --- /dev/null +++ b/build/lib/test/buildEvents.test.ts @@ -0,0 +1,89 @@ +/*--------------------------------------------------------------------------------------------- + * 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 'node:assert/strict'; +import { test } from 'node:test'; +import { BuildLifecycle } from '../buildEvents.ts'; + +test('overlapping builds retain failures, finish once, and recover next cycle', t => { + const log = t.mock.method(console, 'log'); + const previous = process.env.VSCODE_BUILD_EVENTS; + t.after(() => restoreBuildEvents(previous)); + process.env.VSCODE_BUILD_EVENTS = '1'; + const messages = () => log.mock.calls.map(call => JSON.parse(call.arguments[0])); + const lifecycle = new BuildLifecycle(); + const first = lifecycle.start(); + const second = lifecycle.start(); + first(true); + assert.deepEqual(messages(), [{ type: 'vscode.build', version: 1, event: 'start' }]); + first(); + second(); + assert.deepEqual(messages(), [ + { type: 'vscode.build', version: 1, event: 'start' }, + { type: 'vscode.build', version: 1, event: 'finish', success: false }, + ]); + lifecycle.start()(); + assert.deepEqual(messages(), [ + { type: 'vscode.build', version: 1, event: 'start' }, + { type: 'vscode.build', version: 1, event: 'finish', success: false }, + { type: 'vscode.build', version: 1, event: 'start' }, + { type: 'vscode.build', version: 1, event: 'finish', success: true }, + ]); +}); + +test('events require an explicit opt-in and preserve existing log callbacks', t => { + const log = t.mock.method(console, 'log'); + const previous = process.env.VSCODE_BUILD_EVENTS; + t.after(() => restoreBuildEvents(previous)); + for (const value of [undefined, '', '0', 'true']) { + restoreBuildEvents(value); + const callbacks: string[] = []; + const lifecycle = new BuildLifecycle(() => callbacks.push('start'), () => callbacks.push('end')); + const first = lifecycle.start(); + const second = lifecycle.start(); + first(true); + second(); + assert.deepEqual(callbacks, ['start', 'end']); + } + assert.equal(log.mock.callCount(), 0); +}); + +function restoreBuildEvents(value: string | undefined): void { + if (value === undefined) { + delete process.env.VSCODE_BUILD_EVENTS; + } else { + process.env.VSCODE_BUILD_EVENTS = value; + } +} + +for (const phase of ['callback', 'emit']) { + test(`a failed start ${phase} does not leak an active build`, t => { + const previous = process.env.VSCODE_BUILD_EVENTS; + t.after(() => restoreBuildEvents(previous)); + process.env.VSCODE_BUILD_EVENTS = '1'; + let fail = true; + const messages: unknown[] = []; + t.mock.method(console, 'log', (message: string) => { + if (fail && phase === 'emit') { + throw new Error('emit failed'); + } + messages.push(JSON.parse(message)); + }); + let ended = 0; + const lifecycle = new BuildLifecycle(() => { + if (fail && phase === 'callback') { + throw new Error('callback failed'); + } + }, () => ended++); + assert.throws(() => lifecycle.start(), new RegExp(`${phase} failed`)); + fail = false; + lifecycle.start()(); + assert.equal(ended, 1); + assert.deepEqual(messages, [ + { type: 'vscode.build', version: 1, event: 'start' }, + { type: 'vscode.build', version: 1, event: 'finish', success: true }, + ]); + }); +} diff --git a/build/lib/test/extensionTranspilation.test.ts b/build/lib/test/extensionTranspilation.test.ts index 82f8e4411b8a30..bfbd2c5eb3c33a 100644 --- a/build/lib/test/extensionTranspilation.test.ts +++ b/build/lib/test/extensionTranspilation.test.ts @@ -4,16 +4,79 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { spawn } from 'child_process'; +import { once } from 'events'; import * as fs from 'fs/promises'; import * as os from 'os'; import * as path from 'path'; import { createRequire } from 'module'; import { pathToFileURL } from 'url'; import { suite, test } from 'node:test'; +import { setTimeout as delay } from 'timers/promises'; import { createExtensionTasks } from '../../gulpfile.extensions.ts'; import * as task from '../gulp/task.ts'; suite('extension transpilation pipeline', () => { + test('watcher recompiles source edits and recovers from compiler errors', async () => { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vscode-extension-watch-')); + try { + const extension = path.join(root, 'extensions', 'watch-fixture'); + const source = path.join(extension, 'src', 'entry.ts'); + const output = path.join(extension, 'out', 'entry.js'); + await fs.mkdir(path.dirname(source), { recursive: true }); + await fs.writeFile(path.join(extension, 'package.json'), '{"type":"commonjs"}'); + await fs.writeFile(path.join(extension, 'tsconfig.json'), JSON.stringify({ + compilerOptions: { module: 'commonjs', target: 'es2024', rootDir: './src', outDir: './out', types: [] }, + include: ['src/**/*'], + })); + await fs.writeFile(source, 'export const value: number = 1;'); + + const child = spawn(process.execPath, ['--input-type=module', '-e', ` + process.once('message', () => process.exit(0)); + const { createExtensionTasks } = await import(${JSON.stringify(new URL('../../gulpfile.extensions.ts', import.meta.url).href)}); + const task = await import(${JSON.stringify(new URL('../gulp/task.ts', import.meta.url).href)}); + await task.series(createExtensionTasks('extensions/watch-fixture/tsconfig.json', process.cwd()).watchTask)(); + `], { cwd: root, env: process.env, stdio: ['ignore', 'pipe', 'pipe', 'ipc'] }); + const exited = once(child, 'exit'); + let stdout = ''; + let stderr = ''; + child.stdout!.on('data', data => { stdout += data; }); + child.stderr!.on('data', data => { stderr += data; }); + + async function waitForCompilation(count: number) { + const deadline = Date.now() + 30_000; + while (stdout.split('Finished compilation').length - 1 < count) { + assert.strictEqual(child.exitCode, null, stdout + stderr); + assert.ok(Date.now() < deadline, `Timed out waiting for compilation ${count}:\n${stdout}${stderr}`); + await delay(50); + } + } + + try { + await waitForCompilation(1); + assert.match(await fs.readFile(output, 'utf8'), /value = 1/); + await fs.writeFile(source, 'export const value: number = 2;'); + await waitForCompilation(2); + assert.match(await fs.readFile(output, 'utf8'), /value = 2/); + + await fs.writeFile(source, 'export const value: number = "invalid";'); + await waitForCompilation(3); + assert.match(stdout, /error TS2322:/); + + await fs.writeFile(source, 'export const value: number = 3;'); + await waitForCompilation(4); + assert.match(await fs.readFile(output, 'utf8'), /value = 3/); + } finally { + if (child.connected) { + child.send('stop'); + } + await exited; + } + } finally { + await fs.rm(root, { recursive: true, force: true }); + } + }); + test('emits loadable modules for ts, mts and cts without copying sources or declarations', async () => { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'vscode-extension-pipeline-')); try { diff --git a/build/lib/test/tsgo.test.ts b/build/lib/test/tsgo.test.ts new file mode 100644 index 00000000000000..3d71b0392f3245 --- /dev/null +++ b/build/lib/test/tsgo.test.ts @@ -0,0 +1,78 @@ +/*--------------------------------------------------------------------------------------------- + * 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 'node:assert/strict'; +import * as fs from 'node:fs/promises'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { after, before, suite, test } from 'node:test'; +import { setImmediate } from 'node:timers/promises'; +import { createTsgoStream, spawnTsgo } from '../tsgo.ts'; + +suite('tsgo completion callbacks', () => { + let root: string; + let project: string; + + before(async () => { + root = await fs.mkdtemp(path.join(os.tmpdir(), 'vscode-tsgo-completion-')); + project = path.join(root, 'tsconfig.json'); + await fs.writeFile(project, JSON.stringify({ + compilerOptions: { types: [], target: 'es2024' }, + files: ['entry.ts'], + })); + await fs.writeFile(path.join(root, 'entry.ts'), 'export const value = 1;'); + }); + + after(async () => { + await fs.rm(root, { recursive: true, force: true }); + }); + + test('rejects a synchronous completion exception', async () => { + const failure = new Error('completion failed'); + await assert.rejects(spawnTsgo(project, { taskName: 'test', noEmit: true }, () => { + throw failure; + }), error => error === failure); + }); + + test('rejects an asynchronous completion failure', async () => { + const failure = new Error('completion failed'); + await assert.rejects(spawnTsgo(project, { taskName: 'test', noEmit: true }, () => Promise.reject(failure)), error => error === failure); + }); + + test('waits for asynchronous completion', async () => { + const started = Promise.withResolvers(); + const completion = Promise.withResolvers(); + let settled = false; + const build = spawnTsgo(project, { taskName: 'test', noEmit: true }, () => { + started.resolve(); + return completion.promise; + }).then(() => { settled = true; }); + await started.promise; + await setImmediate(); + try { + assert.equal(settled, false); + } finally { + completion.resolve(); + } + await build; + assert.equal(settled, true); + }); + + test('succeeds without a completion callback', async () => { + await spawnTsgo(project, { taskName: 'test', noEmit: true }); + }); + + test('reports a synchronous completion exception through the stream', async () => { + const failure = new Error('completion failed'); + const stream = createTsgoStream(project, { taskName: 'test', noEmit: true }, () => { + throw failure; + }); + const error = await new Promise((resolve, reject) => { + stream.once('end', () => reject(new Error('Expected a stream error'))); + stream.once('error', resolve); + }); + assert.equal(error, failure); + }); +}); diff --git a/build/lib/tsgo.ts b/build/lib/tsgo.ts index 8ec2cf162081c3..c218d131c0510c 100644 --- a/build/lib/tsgo.ts +++ b/build/lib/tsgo.ts @@ -70,7 +70,7 @@ export function spawnTsgo(projectPath: string, config: { taskName: string; noEmi runReporter(lines.join('\n')); if (code === 0) { - Promise.resolve(onComplete?.()).then(() => resolve(), reject); + Promise.resolve().then(() => onComplete?.()).then(() => resolve(), reject); } else { reject(new Error(`tsgo exited with code ${code ?? 'unknown'}`)); } diff --git a/extensions/copilot/src/extension/byok/vscode-node/byokContribution.ts b/extensions/copilot/src/extension/byok/vscode-node/byokContribution.ts index e9940d3d3a5b2f..b7b4897658b2ae 100644 --- a/extensions/copilot/src/extension/byok/vscode-node/byokContribution.ts +++ b/extensions/copilot/src/extension/byok/vscode-node/byokContribution.ts @@ -19,7 +19,7 @@ import { BYOKStorageService, IBYOKStorageService } from './byokStorageService'; import { CustomEndpointBYOKModelProvider } from './customEndpointProvider'; import { CustomOAIBYOKModelProvider } from './customOAIProvider'; import { GeminiNativeBYOKLMProvider } from './geminiNativeProvider'; -import { createGptLiveSession, GPT_LIVE_SESSION_PROVIDER_ID, GptLiveSessionResult, isGptLiveModelAvailable, USE_BYOK_VOICE_MODEL_SETTING } from './gptLiveSession'; +import { createGptLiveSession, GPT_LIVE_SESSION_PROVIDER_ID, GptLiveModelAvailability, GptLiveSessionResult, USE_BYOK_VOICE_MODEL_SETTING } from './gptLiveSession'; import { OllamaLMProvider } from './ollamaProvider'; import { OAIBYOKLMProvider } from './openAIProvider'; import { OpenRouterLMProvider } from './openRouterProvider'; @@ -34,6 +34,7 @@ export class BYOKContrib extends Disposable implements IExtensionContribution { private _knownModelsRefreshed = false; private _knownModelsRefreshTargets: ReadonlyArray = []; private _openAIProvider: OAIBYOKLMProvider | undefined; + private readonly _gptLiveModelAvailability: GptLiveModelAvailability; constructor( @IFetcherService private readonly _fetcherService: IFetcherService, @@ -44,6 +45,7 @@ export class BYOKContrib extends Disposable implements IExtensionContribution { @IConfigurationService private readonly _configurationService: IConfigurationService, ) { super(); + this._gptLiveModelAvailability = new GptLiveModelAvailability(this._fetcherService); this._byokStorageService = new BYOKStorageService(extensionContext); try { this._register(speech.registerVoiceLiveSessionProvider(GPT_LIVE_SESSION_PROVIDER_ID, { @@ -83,7 +85,7 @@ export class BYOKContrib extends Disposable implements IExtensionContribution { return { available: false }; } if (sdp === undefined) { - const isAvailable = await isGptLiveModelAvailable(this._fetcherService, apiKey, modelId, token); + const isAvailable = await this._gptLiveModelAvailability.isAvailable(apiKey, modelId, token); this._logService.info(`BYOK: configured GPT-Live model is ${isAvailable ? 'available' : 'unavailable'}.`); return isAvailable ? { available: true } diff --git a/extensions/copilot/src/extension/byok/vscode-node/gptLiveSession.ts b/extensions/copilot/src/extension/byok/vscode-node/gptLiveSession.ts index 3ac25f33b21609..ec7a7fa2319b5f 100644 --- a/extensions/copilot/src/extension/byok/vscode-node/gptLiveSession.ts +++ b/extensions/copilot/src/extension/byok/vscode-node/gptLiveSession.ts @@ -23,6 +23,29 @@ export interface GptLiveSessionResult { readonly session?: GptLiveSession; } +/** Reuses successful key-and-model-scoped checks for one minute; failures and cancellations are not cached. */ +export class GptLiveModelAvailability { + private _cached: { apiKey: string; modelId: string; expiresAt: number } | undefined; + + constructor(private readonly _fetcherService: IFetcherService) { } + + async isAvailable(apiKey: string, modelId: string, token: CancellationToken): Promise { + if (token.isCancellationRequested) { + throw new CancellationError(); + } + const cached = this._cached; + if (cached?.apiKey === apiKey && cached.modelId === modelId && cached.expiresAt > Date.now()) { + return true; + } + this._cached = undefined; + const available = await isGptLiveModelAvailable(this._fetcherService, apiKey, modelId, token); + if (available && !token.isCancellationRequested) { + this._cached = { apiKey, modelId, expiresAt: Date.now() + 60_000 }; + } + return available; + } +} + interface GptLiveSessionResponse { readonly session?: { readonly id?: unknown; diff --git a/extensions/copilot/src/extension/byok/vscode-node/openAIProvider.ts b/extensions/copilot/src/extension/byok/vscode-node/openAIProvider.ts index d8564ee7dfbbb8..21659a71540b8f 100644 --- a/extensions/copilot/src/extension/byok/vscode-node/openAIProvider.ts +++ b/extensions/copilot/src/extension/byok/vscode-node/openAIProvider.ts @@ -29,11 +29,19 @@ export class OAIBYOKLMProvider extends AbstractOpenAICompatibleLMProvider[]> } | undefined; get apiKey(): string | undefined { return this._apiKey; } + override updateKnownModels(knownModels: BYOKKnownModels | undefined): void { + super.updateKnownModels(knownModels); + if (knownModels) { + this._modelDiscovery = undefined; + } + } + constructor( knownModels: BYOKKnownModels, byokStorageService: IBYOKStorageService, @@ -56,9 +64,28 @@ export class OAIBYOKLMProvider extends AbstractOpenAICompatibleLMProvider[]> { this._apiKey = apiKey?.trim() || undefined; - return super.getAllModels(silent, apiKey, configuration); + if (!this._apiKey) { + // Model selection probes the unconfigured default group before the configured groups. + return super.getAllModels(silent, apiKey, configuration); + } + const cached = this._modelDiscovery; + if (silent && cached?.apiKey === this._apiKey && cached.expiresAt > Date.now()) { + return cached.models; + } + this._modelDiscovery = undefined; + const models = super.getAllModels(silent, apiKey, configuration); + const discovery = this._modelDiscovery = { apiKey: this._apiKey, expiresAt: Date.now() + 60_000, models }; + try { + return await models; + } catch (error) { + if (this._modelDiscovery === discovery) { + this._modelDiscovery = undefined; + } + throw error; + } } protected override getModelsBaseUrl(): string { diff --git a/extensions/copilot/src/extension/byok/vscode-node/test/gptLiveSession.spec.ts b/extensions/copilot/src/extension/byok/vscode-node/test/gptLiveSession.spec.ts index ac79c941b677df..07bddd80a71d57 100644 --- a/extensions/copilot/src/extension/byok/vscode-node/test/gptLiveSession.spec.ts +++ b/extensions/copilot/src/extension/byok/vscode-node/test/gptLiveSession.spec.ts @@ -8,7 +8,7 @@ import { Event } from '../../../../util/vs/base/common/event'; import { mock } from '../../../../util/common/test/simpleMock'; import { FetchOptions, IFetcherService, Response } from '../../../../platform/networking/common/fetcherService'; import { createFakeResponse } from '../../../../platform/test/node/fetcher'; -import { createGptLiveSession, isGptLiveModelAvailable } from '../gptLiveSession'; +import { createGptLiveSession, GptLiveModelAvailability, isGptLiveModelAvailable } from '../gptLiveSession'; import { CancellationToken, CancellationTokenSource } from '../../../../util/vs/base/common/cancellation'; class TestFetcherService extends mock() { @@ -89,6 +89,56 @@ describe('isGptLiveModelAvailable', () => { }); }); +describe('GptLiveModelAvailability', () => { + it('caches successful checks for one minute, scoped to the current key and model', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + try { + const fetcher = new TestFetcherService(); + fetcher.fetch.mockImplementation(async () => createFakeResponse(200, { data: [{ id: 'live-a' }, { id: 'live-b' }] })); + const availability = new GptLiveModelAvailability(fetcher); + const counts: number[] = []; + for (const [key, model] of [['first-key', 'live-a'], ['first-key', 'live-a'], ['second-key', 'live-a'], ['second-key', 'live-b']]) { + await availability.isAvailable(key, model, CancellationToken.None); + counts.push(fetcher.fetch.mock.calls.length); + } + vi.advanceTimersByTime(60_000); + await availability.isAvailable('second-key', 'live-b', CancellationToken.None); + counts.push(fetcher.fetch.mock.calls.length); + expect(counts).toEqual([1, 1, 2, 3, 4]); + } finally { + vi.useRealTimers(); + } + }); + + it('does not cache unavailable models or failures', async () => { + const fetcher = new TestFetcherService(); + fetcher.fetch + .mockResolvedValueOnce(createFakeResponse(200, { data: [] })) + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValueOnce(createFakeResponse(200, { data: [{ id: 'live' }] })); + const availability = new GptLiveModelAvailability(fetcher); + const unavailable = await availability.isAvailable('key', 'live', CancellationToken.None); + await expect(availability.isAvailable('key', 'live', CancellationToken.None)).rejects.toThrow('offline'); + const available = await availability.isAvailable('key', 'live', CancellationToken.None); + expect({ unavailable, available, requests: fetcher.fetch.mock.calls.length }).toEqual({ unavailable: false, available: true, requests: 3 }); + }); + + it('honors cancellation even on a cache hit', async () => { + const fetcher = new TestFetcherService(); + fetcher.fetch.mockResolvedValue(createFakeResponse(200, { data: [{ id: 'live' }] })); + const availability = new GptLiveModelAvailability(fetcher); + await availability.isAvailable('key', 'live', CancellationToken.None); + const source = new CancellationTokenSource(); + try { + source.cancel(); + await expect(availability.isAvailable('key', 'live', source.token)).rejects.toThrow('Canceled'); + expect(fetcher.fetch).toHaveBeenCalledTimes(1); + } finally { + source.dispose(); + } + }); +}); + describe('createGptLiveSession', () => { it('creates a client-delegation GPT-Live session without returning the API key or trimming the SDP terminator', async () => { const fetcher = new TestFetcherService(); diff --git a/extensions/copilot/src/extension/byok/vscode-node/test/openAIProvider.spec.ts b/extensions/copilot/src/extension/byok/vscode-node/test/openAIProvider.spec.ts index cffe3c6fe4db9c..144ea7d97cef43 100644 --- a/extensions/copilot/src/extension/byok/vscode-node/test/openAIProvider.spec.ts +++ b/extensions/copilot/src/extension/byok/vscode-node/test/openAIProvider.spec.ts @@ -3,7 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; import { IChatModelInformation } from '../../../../platform/endpoint/common/endpointProvider'; import { BlockedExtensionService, IBlockedExtensionService } from '../../../../platform/chat/common/blockedExtensionService'; import { IFetcherService } from '../../../../platform/networking/common/fetcherService'; @@ -19,11 +19,21 @@ import { IBYOKStorageService } from '../byokStorageService'; import { applyOpenAIProviderConfig, OAIBYOKLMProvider, OpenAIProviderConfig } from '../openAIProvider'; class TestOpenAIProvider extends OAIBYOKLMProvider { - discover(apiKey: string | undefined): Promise[]> { - return this.getAllModels(true, apiKey, undefined); + discover(apiKey: string | undefined, silent = true): Promise[]> { + return this.getAllModels(silent, apiKey, undefined); } } +function createProvider(store: DisposableStore, fetcher: IFetcherService): TestOpenAIProvider { + const services = store.add(createExtensionUnitTestingServices()); + services.define(IBlockedExtensionService, new SyncDescriptor(BlockedExtensionService)); + services.set(IFetcherService, fetcher); + const accessor = store.add(services.createTestingAccessor()); + return accessor.get(IInstantiationService).createInstance(TestOpenAIProvider, {}, new class extends mock() { + override async getAPIKey(): Promise { return undefined; } + }()); +} + function createModelInfo(zeroDataRetentionEnabled: boolean | undefined): IChatModelInformation { return { id: 'gpt-4.1', @@ -76,15 +86,9 @@ describe('OpenAI voice credential lifecycle', () => { it('forgets a removed key instead of retaining its live-session authority', async () => { const store = new DisposableStore(); try { - const services = store.add(createExtensionUnitTestingServices()); - services.define(IBlockedExtensionService, new SyncDescriptor(BlockedExtensionService)); - services.set(IFetcherService, new class extends mock() { + const provider = createProvider(store, new class extends mock() { override async fetch() { return createFakeResponse(200, { data: [] }); } }()); - const accessor = store.add(services.createTestingAccessor()); - const provider = accessor.get(IInstantiationService).createInstance(TestOpenAIProvider, {}, new class extends mock() { - override async getAPIKey(): Promise { return undefined; } - }()); await provider.discover('old-key'); const configured = provider.apiKey; await provider.discover(undefined); @@ -93,4 +97,54 @@ describe('OpenAI voice credential lifecycle', () => { store.dispose(); } }); + + it('reuses silent discovery across default-group probes but refreshes for expiry, a new key, explicit discovery, or updated metadata', async () => { + const store = new DisposableStore(); + vi.useFakeTimers({ toFake: ['Date'] }); + try { + const fetcher = new class extends mock() { + override fetch = vi.fn(async () => createFakeResponse(200, { data: [] })); + }(); + const provider = createProvider(store, fetcher); + const counts: number[] = []; + for (const [key, silent] of [ + ['first-key', true], ['first-key', true], ['second-key', true], ['second-key', false], ['second-key', true], + ] as const) { + await provider.discover(key, silent); + counts.push(fetcher.fetch.mock.calls.length); + } + vi.advanceTimersByTime(60_000); + await provider.discover('second-key'); + counts.push(fetcher.fetch.mock.calls.length); + provider.updateKnownModels({}); + await provider.discover('second-key'); + counts.push(fetcher.fetch.mock.calls.length); + await provider.discover(undefined); + await provider.discover('second-key'); + counts.push(fetcher.fetch.mock.calls.length); + expect({ counts, apiKey: provider.apiKey }).toEqual({ counts: [1, 1, 2, 3, 3, 4, 5, 5], apiKey: 'second-key' }); + } finally { + vi.useRealTimers(); + store.dispose(); + } + }); + + it('shares in-flight discovery but retries failures', async () => { + const store = new DisposableStore(); + try { + const fetcher = new class extends mock() { + override fetch = vi.fn() + .mockRejectedValueOnce(new Error('offline')) + .mockResolvedValue(createFakeResponse(200, { data: [] })); + }(); + const provider = createProvider(store, fetcher); + await expect(Promise.all([provider.discover('key'), provider.discover('key')])).rejects.toThrow('offline'); + const afterFailure = fetcher.fetch.mock.calls.length; + await provider.discover('key'); + await provider.discover('key'); + expect({ afterFailure, afterRetry: fetcher.fetch.mock.calls.length }).toEqual({ afterFailure: 1, afterRetry: 2 }); + } finally { + store.dispose(); + } + }); }); diff --git a/extensions/esbuild-common.mts b/extensions/esbuild-common.mts index 064ad01174e94e..064e9fc7f62854 100644 --- a/extensions/esbuild-common.mts +++ b/extensions/esbuild-common.mts @@ -5,6 +5,7 @@ import { stat } from 'node:fs/promises'; import path from 'node:path'; import esbuild from 'esbuild'; +import { BuildLifecycle } from '../build/lib/buildEvents.ts'; export interface RunConfig { readonly srcDir: string; @@ -18,20 +19,25 @@ export interface RunConfig { // `esbuild.stop()` shuts down the single esbuild service shared by all concurrent builds, so we // must only call it once no builds are in flight. Otherwise a finishing build would tear down the // service while a sibling build (e.g. running in the same `Promise.all`) is still using it. -let pendingBuilds = 0; +const buildLifecycle = new BuildLifecycle(undefined, () => esbuild.stop()); async function buildOnce( options: esbuild.BuildOptions, beforeBuild?: () => Promise | unknown, + didBuild?: () => Promise | unknown, ): Promise { - pendingBuilds++; + const complete = buildLifecycle.start(); + let failed = false; try { await beforeBuild?.(); - return await esbuild.build(options); + const result = await esbuild.build(options); + await didBuild?.(); + return result; + } catch (error) { + failed = true; + throw error; } finally { - if (--pendingBuilds === 0) { - esbuild.stop(); - } + complete(failed); } } @@ -70,10 +76,10 @@ export async function runBuild( ); } else { try { - await buildOnce(resolvedOptions, config.beforeBuild); - await didBuild?.(outdir); - } catch { - process.exit(1); + await buildOnce(resolvedOptions, config.beforeBuild, () => didBuild?.(outdir)); + } catch (error) { + console.error(error); + process.exitCode = 1; } } } @@ -95,10 +101,7 @@ async function watchWithParcel( try { // Also instead of retaining the esbuild context, we are re-running the entire build on each change. // This reduces memory usage since most projects don't need to be re-built often. - const result = await buildOnce(options, beforeBuild); - if (result.errors.length === 0) { - await didBuild?.(); - } + await buildOnce(options, beforeBuild, didBuild); } catch (error) { console.error('[watch] build error:', error); } diff --git a/extensions/esbuild-common.test.mts b/extensions/esbuild-common.test.mts new file mode 100644 index 00000000000000..5927ace9148d6a --- /dev/null +++ b/extensions/esbuild-common.test.mts @@ -0,0 +1,133 @@ +/*--------------------------------------------------------------------------------------------- + * 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 'node:assert/strict'; +import { execFile, spawn } from 'node:child_process'; +import { once } from 'node:events'; +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; +import { test } from 'node:test'; +import { promisify } from 'node:util'; + +const exec = promisify(execFile); +const runner = new URL('./esbuild-common.mts', import.meta.url).href; +const start = '{"type":"vscode.build","version":1,"event":"start"}'; +const success = '{"type":"vscode.build","version":1,"event":"finish","success":true}'; +const failure = '{"type":"vscode.build","version":1,"event":"finish","success":false}'; + +test('build lifecycle includes asynchronous hooks and preserves opt-out behavior', async () => { + const root = await mkdtemp(join(import.meta.dirname, '.build-events-test-')); + try { + const config = { srcDir: root, outdir: join(root, 'out'), entryPoints: [join(root, 'entry.js')] }; + await writeFile(config.entryPoints[0], 'export const value = 1;'); + const run = (hook: string, events = '1', beforeBuild = '') => exec(process.execPath, ['--input-type=module', '-e', + `import { runBuild } from ${JSON.stringify(runner)}; + await runBuild({ ...${JSON.stringify(config)}, beforeBuild: async () => { ${beforeBuild} } }, {}, [], async () => { ${hook} });`, + ], { env: { ...process.env, VSCODE_BUILD_EVENTS: events } }); + const hook = 'await new Promise(resolve => setTimeout(resolve, 20)); console.log("POSTPROCESS");'; + assert.equal((await run(hook)).stdout, `${start}\nPOSTPROCESS\n${success}\n`); + assert.equal((await run(hook, '')).stdout, 'POSTPROCESS\n'); + for (const phase of ['before', 'after']) { + const hookErrorCode = 'await new Promise(resolve => setTimeout(resolve, 20)); throw new Error("hook failed");'; + await assert.rejects(run(phase === 'after' ? hookErrorCode : '', '1', phase === 'before' ? hookErrorCode : ''), (error: Error & { stdout: string; stderr: string }) => { + assert.equal(error.stdout, `${start}\n${failure}\n`); + assert.match(error.stderr, /hook failed/); + return true; + }); + } + await writeFile(config.entryPoints[0], 'export const = ;'); + await assert.rejects(run('console.log("UNREACHABLE");'), (error: Error & { stdout: string }) => { + assert.equal(error.stdout, `${start}\n${failure}\n`); + return true; + }); + await assert.rejects(run('', ''), (error: Error & { stdout: string; code: number }) => { + assert.equal(error.stdout, ''); + assert.equal(error.code, 1); + return true; + }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('overlapping builds include all postprocessing and retain plugin failures', async () => { + const root = await mkdtemp(join(import.meta.dirname, '.build-events-test-')); + try { + const config = { srcDir: root, outdir: join(root, 'out'), entryPoints: [join(root, 'entry.js')] }; + await writeFile(config.entryPoints[0], 'export const value = 1;'); + const result = await exec(process.execPath, ['--input-type=module', '-e', + `import { runBuild } from ${JSON.stringify(runner)}; + const config = ${JSON.stringify(config)}; + await Promise.all([ + runBuild(config, {}, [], async () => { await new Promise(resolve => setTimeout(resolve, 100)); console.log("SLOW_POSTPROCESS"); }), + runBuild({ ...config, outdir: config.outdir + "2" }, {}, [], () => console.log("FAST_POSTPROCESS")), + ]);`, + ], { env: { ...process.env, VSCODE_BUILD_EVENTS: '1' } }); + assert.equal(result.stdout, `${start}\nFAST_POSTPROCESS\nSLOW_POSTPROCESS\n${success}\n`); + await assert.rejects(exec(process.execPath, ['--input-type=module', '-e', + `import { runBuild } from ${JSON.stringify(runner)}; + const config = ${JSON.stringify(config)}; + await Promise.all([ + runBuild(config, { plugins: [{ name: 'failure', setup(build) { build.onStart(() => { throw new Error('plugin failed'); }); } }] }, []), + runBuild({ ...config, outdir: config.outdir + "2" }, {}, [], async () => { + await new Promise(resolve => setTimeout(resolve, 100)); console.log("SIBLING_DONE"); + }), + ]);`, + ], { env: { ...process.env, VSCODE_BUILD_EVENTS: '1' } }), (error: Error & { stdout: string; stderr: string }) => { + assert.equal(error.stdout, `${start}\nSIBLING_DONE\n${failure}\n`); + assert.match(error.stderr, /plugin failed/); + return true; + }); + } finally { + await rm(root, { recursive: true, force: true }); + } +}); + +test('native watcher reports compilation and postprocessing failure and recovery', async () => { + const root = await mkdtemp(join(import.meta.dirname, '.build-events-watch-test-')); + await mkdir(join(root, 'src')); + const entry = join(root, 'src', 'entry.js'); + await writeFile(entry, 'export const value = 1;'); + const child = spawn(process.execPath, ['--input-type=module', '-e', + `import { readFile } from 'node:fs/promises'; + import { runBuild } from ${JSON.stringify(runner)}; + await runBuild(${JSON.stringify({ + srcDir: join(root, 'src'), outdir: join(root, 'out'), entryPoints: [entry], + })}, {}, ['--watch'], async () => { + if ((await readFile(${JSON.stringify(entry)}, 'utf8')).includes('postprocessError')) { throw new Error('postprocessing failed'); } + });`, + ], { env: { ...process.env, VSCODE_BUILD_EVENTS: '1' }, stdio: ['ignore', 'pipe', 'pipe'] }); + const exited = once(child, 'exit'); + let stdout = ''; + let stderr = ''; + child.stdout.on('data', data => { stdout += data; }); + child.stderr.on('data', data => { stderr += data; }); + async function waitFor(text: string, count = 1) { + const deadline = Date.now() + 15_000; + while (stdout.split(text).length - 1 < count) { + assert.equal(child.exitCode, null, stderr); + assert.ok(Date.now() < deadline, stdout + stderr); + await delay(50); + } + } + try { + await waitFor(success); + await writeFile(entry, 'export const = ;'); + await waitFor(failure); + await writeFile(entry, 'export const postprocessError = true;'); + await waitFor(failure, 2); + await writeFile(entry, 'export const value = 2;'); + await waitFor(success, 2); + assert.equal(stdout.split(start).length - 1, 4); + assert.match(stderr, /postprocessing failed/); + } finally { + if (child.exitCode === null && child.signalCode === null) { + child.kill(); + } + await exited; + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/code-oss-launcher/README.md b/scripts/code-oss-launcher/README.md new file mode 100644 index 00000000000000..b0cbfe33667bbb --- /dev/null +++ b/scripts/code-oss-launcher/README.md @@ -0,0 +1,70 @@ +# Managed Code OSS launcher + +A standalone, dependency-free Node.js launcher for a local VS Code source checkout. It does not require an agent skill, dev-workspace, Hub, or an extension. Use the Node.js version selected by the checkout's `.nvmrc` (at least Node.js 22.18 for native TypeScript support). + +From the VS Code repository root, in PowerShell: + +```powershell +node scripts\code-oss-launcher\launch.ts --repo . --wait --skip-prelaunch --session-title "My development window" --disable-workspace-trust '--' --extensionDevelopmentPath=D:\my-extension D:\my-workspace +``` + +On macOS/Linux, use `scripts/code-oss-launcher/launch.ts` and appropriate paths. When spawning from another program, pass an argument array, including the literal `--`, with no shell. Everything after `--` is forwarded verbatim. The launcher reserves the profile, extensions, shared-data and debugger arguments so callers cannot accidentally override run isolation. + +## Launch options + +| Option | Behavior | +| --- | --- | +| `--repo ROOT` | Source checkout to launch; defaults to the working directory. | +| `--wait` | Keep the launcher alive until Code OSS exits and return its exit code. POSIX SIGINT/SIGTERM stop the exact application process group. | +| `--skip-prelaunch` | Skip `build/lib/preLaunch.ts`; Electron, compiled output and built-ins must already exist. Without this flag, normal source prelaunch runs first. | +| `--session-title TITLE` | Set the isolated window title; with `--agents`, set the Agents command-center title instead. | +| `--disable-workspace-trust` | Forward this opt-in development setting to Code OSS. | +| `--source-user-data-dir DIR` | Seed from this Code OSS profile; defaults to `CODE_OSS_DEV_AUTHED_USER_DATA_DIR` or `~/.vscode-oss-dev`. A missing profile starts empty. | +| `--copy-extensions` | Copy all source-profile extensions. Default: empty isolated extensions directory. `--clone-extensions` is an alias. | +| `--copy-extensions=publisher.one,publisher.two` | Copy selected extensions and filter the extension manifest. Unknown IDs are usage errors. | +| `--full` | Copy the complete source profile, including extensions, instead of omitting caches, locks, logs and workspace history. | +| `--reuse` / `--fresh` | Reuse and synchronize a profile/extension-selection-specific run directory, or create a fresh one (default). Busy reused directories fall back to a fresh run. `CODE_OSS_DEV_REUSE=1` also enables reuse. | +| `--agents` | Launch the optional Agents window. | +| `--help` | Print usage and exit without launching. | + +The normal Windows source launcher is reproduced by launching Electron directly, avoiding `cmd.exe` argument mangling. macOS/Linux use `scripts/code.sh`. Host-only environment variables such as `ELECTRON_RUN_AS_NODE` are removed for the application. + +For an option value beginning with `--`, use the equals form, for example `--session-title=--example`. The space-separated form rejects such values to catch missing option arguments. + +## Readiness and lifetime contract + +Diagnostics go to stderr and application output to `/code.log`. After `/json/version` returns valid CDP metadata containing a WebSocket debugger URL, stdout receives **one JSON line**: + +```json +{"pid":1234,"cdpPort":9222,"extHostPort":9223,"mainPort":9224,"agentHostPort":9225,"userDataDir":"...","extensionsDir":"...","sharedDataDir":"...","runDir":"...","logFile":"...","repo":"...","agents":false,"reused":false,"timings":{"profileMs":100,"preLaunchMs":0,"cdpReadyMs":200,"totalMs":300}} +``` + +The ports are dynamically allocated. Readiness means the application process is alive and its browser CDP endpoint responds, not that a particular extension or workspace has finished activating. Readiness times out after 90 seconds; an early application exit or timeout fails without a readiness record and stops any remaining exact-run application processes. Usage errors exit with 2; launch failures exit with 1. + +With `--wait`, keep draining stderr after reading readiness and wait for process exit. Without it, Code OSS is detached and the launcher exits successfully after readiness. Abruptly killing a Windows launcher does not invoke JavaScript signal handlers: supervisors must explicitly run cleanup or terminate their owned process tree. The same applies to POSIX SIGKILL. Save `runDir` from readiness for cleanup. + +## Profile and authentication isolation + +Each run has separate user-data, extensions and shared-data directories. The source profile is read, never modified. Slim copies preserve authentication-related files and set `files.simpleDialog.enable` in the copy. On Windows the launcher also seeds application-shared storage from `CODE_OSS_DEV_AUTHED_SHARED_DATA_DIR`, `VSCODE_PORTABLE\shared-data`, or the product's default shared-data directory. Existing credentials remain subject to OS encryption and must be usable by the same local user/machine. Sign in to the source Code OSS profile first to seed future launches; no tokens are printed. + +Run directories **contain sensitive copies of local credentials**. Do not upload them or their logs. `CODE_OSS_DEV_RUN_ROOT` can select a private local directory; otherwise the launcher's per-user temporary run root is used. On POSIX, the root is owner-checked and made private. Keep the same environment override when invoking cleanup. Reused profiles are synchronized from the source on subsequent launches, so use the source profile for persistent authentication changes. + +## Exact-run cleanup + +```powershell +node scripts\code-oss-launcher\cleanup\cleanup.ts +``` + +Cleanup validates the run root and launcher state, then identifies processes by their exact `--user-data-dir` argument, not a potentially reused PID. It stops only that run's process tree, waits for its files to be released, and prints one JSON line: `{"runDir":"...","stopped":true,"removed":true}`. Fresh directories are removed. Reused directories are retained unless `--remove` is passed. `--run-dir ` is also supported. + +`cleanup.ts --gc ` removes abandoned runs in a recognized root, but never stops processes. A launch also performs garbage collection after readiness: unused fresh directories have a two-minute grace period and unused reused profiles expire after seven days. Logs and failed launch directories are retained until cleanup or collection, so failures can be diagnosed. + +On Windows, the lock probe briefly renames a run directory and restores it. Transient restoration failures are retried; if restoration still fails, the error names the retained recovery directory. Restore it before retrying rather than deleting the profile. + +## Tests + +```powershell +npm --prefix scripts\code-oss-launcher test +``` + +No dependency installation or VS Code build is needed. Tests cover slim profile copying, extension selection and synchronization, JSONC settings, CDP validation and deadlines, plus the real CLI against a synthetic Node-based application for readiness ordering, exit-code propagation, argument forwarding, profile isolation, early exit and cleanup isolation between two live runs. They do **not** validate a live Electron workbench or real encrypted credentials. diff --git a/scripts/code-oss-launcher/cleanup/cleanup.ts b/scripts/code-oss-launcher/cleanup/cleanup.ts new file mode 100644 index 00000000000000..8cc6b32451b978 --- /dev/null +++ b/scripts/code-oss-launcher/cleanup/cleanup.ts @@ -0,0 +1,111 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Stops the Code OSS instance of a launch and removes its run directory; reused run directories +// are kept unless --remove is passed. Prints one JSON line to stdout. Run it with Node.js. +// `--gc ` instead removes abandoned run directories below a run root, which +// the launcher runs in the background. + +import { existsSync } from 'node:fs'; +import * as path from 'node:path'; +import { collectGarbage, isInRunRoot, isRunDirInUse, readState, removeRunDir, stopCodeProcesses } from '../lib/runDirs.ts'; +import { writeStderr, writeStdout } from '../lib/output.ts'; + +const STOP_TIMEOUT_MS = 15_000; + +interface ICleanupOptions { + readonly kind: 'cleanup'; + readonly runDir: string; + readonly remove: boolean; +} + +interface IGarbageCollectionOptions { + readonly kind: 'gc'; + readonly root: string; +} + +class UsageError extends Error { } + +function parseArguments(args: readonly string[]): ICleanupOptions | IGarbageCollectionOptions { + let runDir: string | undefined; + let remove = false; + for (let index = 0; index < args.length; index++) { + const argument = args[index]; + const value = () => { + if (index + 1 >= args.length) { + throw new UsageError(`Missing value for ${argument}.`); + } + return args[++index]; + }; + switch (argument) { + case '--gc': return { kind: 'gc', root: value() }; + case '--run-dir': runDir = value(); break; + case '--remove': remove = true; break; + default: + if (argument.startsWith('--') || runDir !== undefined) { + throw new UsageError(`Unknown arg: ${argument}`); + } + runDir = argument; + } + } + if (!runDir) { + throw new UsageError('Usage: cleanup.ts [--remove]'); + } + return { kind: 'cleanup', runDir: path.resolve(runDir), remove }; +} + +async function cleanup(options: ICleanupOptions): Promise { + const { runDir } = options; + if (!existsSync(runDir)) { + throw new UsageError(`Run directory does not exist: ${runDir}`); + } + if (!isInRunRoot(runDir)) { + throw new UsageError(`Refusing to clean a directory outside the launch run roots: ${runDir}`); + } + const state = await readState(runDir); + if (!state) { + throw new UsageError(`Refusing to clean a directory without launcher state: ${runDir}`); + } + const stopped = stopCodeProcesses(runDir, state?.codePid); + + // Stopped processes release their files a moment later + const keep = path.basename(runDir).startsWith('reuse-') && !options.remove; + const deadline = Date.now() + STOP_TIMEOUT_MS; + for (; ;) { + try { + if (!await isRunDirInUse(runDir)) { + if (!keep) { + await removeRunDir(runDir); + } + break; + } + } catch { + // Not yet removable + } + if (Date.now() > deadline) { + throw new Error(`Code OSS processes still use the run directory: ${runDir}`); + } + await new Promise(resolve => setTimeout(resolve, 250)); + } + writeStdout(JSON.stringify({ runDir, stopped, removed: !keep }) + '\n'); +} + +try { + // The PowerShell wrapper passes arguments as JSON, which survives Windows PowerShell's native argument quoting + const json = process.env.CODE_OSS_DEV_SCRIPT_ARGS; + delete process.env.CODE_OSS_DEV_SCRIPT_ARGS; + const options = parseArguments(json ? JSON.parse(json) : process.argv.slice(2)); + if (options.kind === 'gc') { + if (!isInRunRoot(path.join(path.resolve(options.root), 'run'))) { + throw new UsageError(`Refusing to collect outside the launch run roots: ${options.root}`); + } + await collectGarbage(path.resolve(options.root)); + } else { + await cleanup(options); + } +} catch (error) { + writeStderr(`[cleanup] ${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = error instanceof UsageError ? 2 : 1; +} diff --git a/scripts/code-oss-launcher/fixtures/fakeCode.ts b/scripts/code-oss-launcher/fixtures/fakeCode.ts new file mode 100644 index 00000000000000..751a2646ea7d21 --- /dev/null +++ b/scripts/code-oss-launcher/fixtures/fakeCode.ts @@ -0,0 +1,33 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { existsSync, writeFileSync } from 'node:fs'; +import http from 'node:http'; + +const args = process.argv.slice(2); +const value = (name: string): string => { + const result = args.find(argument => argument.startsWith(`${name}=`))?.slice(name.length + 1); + if (result === undefined) { + throw new Error(`Missing fixture argument: ${name}`); + } + return result; +}; +writeFileSync(value('--fixture-started'), JSON.stringify(args)); +if (args.includes('--fixture-exit-before-ready')) { + process.exit(17); +} +let listening = false; +const server = http.createServer((_request, response) => { + response.end(JSON.stringify({ webSocketDebuggerUrl: 'ws://127.0.0.1/devtools/browser/fixture' })); +}); +setInterval(() => { + if (!listening && existsSync(value('--fixture-ready'))) { + listening = true; + server.listen(Number(value('--remote-debugging-port')), '127.0.0.1'); + } + if (existsSync(value('--fixture-exit'))) { + process.exit(23); + } +}, 25); diff --git a/scripts/code-oss-launcher/launch.ts b/scripts/code-oss-launcher/launch.ts new file mode 100644 index 00000000000000..6728c418d3cfb5 --- /dev/null +++ b/scripts/code-oss-launcher/launch.ts @@ -0,0 +1,507 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Launches Code OSS (VS Code from sources) with an isolated copy of a user-data-dir and unique +// debugger ports. Prints exactly one JSON line to stdout once the renderer's CDP endpoint is +// ready; all diagnostics go to stderr. With --wait the launcher owns the application's lifetime. + +import { spawn } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { closeSync, existsSync, openSync, promises as fs, readFileSync } from 'node:fs'; +import * as net from 'node:net'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { isExcludedFromProfileCopy, syncExtensions, syncTree, UnknownExtensionsError, validateExtensionSelection, type ExtensionSelection, type ITreeManifest } from './lib/profileCopy.ts'; +import { claimReuseRunDir, collectGarbage, createFreshRunDir, getRunRoot, getTempRunRoot, releaseClaim, stopCodeProcesses, writeState } from './lib/runDirs.ts'; +import { writeStderr, writeStdout } from './lib/output.ts'; +import { updateLaunchSettings } from './lib/settings.ts'; +import { waitForCdp } from './waitForCdp.ts'; + +const CDP_TIMEOUT_MS = 90_000; + +interface ILaunchOptions { + readonly agents: boolean; + readonly sessionTitle: string; + readonly sourceUserDataDir: string | undefined; + readonly repo: string | undefined; + /** `undefined` starts with an empty extensions folder */ + readonly extensions: ExtensionSelection | undefined; + readonly full: boolean; + readonly skipPreLaunch: boolean; + readonly disableWorkspaceTrust: boolean; + readonly reuse: boolean; + readonly wait: boolean; + readonly extraArgs: readonly string[]; +} + +/** + * What a reused run directory remembers about its copies, to sync them on the next launch. + */ +interface IReuseManifest { + readonly version: 1; + readonly profile?: ITreeManifest; + readonly sharedData?: ITreeManifest; + readonly extensionFolders?: readonly string[]; +} + +class UsageError extends Error { } + +function log(message: string): void { + writeStderr(`[launch] ${message}\n`); +} + +function readArguments(): { args: string[]; fromPowerShell: boolean } { + // The PowerShell wrapper passes arguments as JSON, which survives Windows PowerShell's native argument quoting + const json = process.env.CODE_OSS_DEV_SCRIPT_ARGS; + delete process.env.CODE_OSS_DEV_SCRIPT_ARGS; + return json ? { args: JSON.parse(json), fromPowerShell: true } : { args: process.argv.slice(2), fromPowerShell: false }; +} + +function parseArguments(args: readonly string[], fromPowerShell: boolean): ILaunchOptions { + let agents = false; + let sessionTitle = ''; + let sourceUserDataDir: string | undefined; + let repo: string | undefined; + let extensions: ExtensionSelection | undefined; + let full = false; + let skipPreLaunch = false; + let disableWorkspaceTrust = false; + let reuse = process.env.CODE_OSS_DEV_REUSE === '1'; + let wait = false; + let extraArgs: string[] = []; + + const value = (index: number, name: string) => { + if (index + 1 >= args.length || args[index + 1].startsWith('--')) { + throw new UsageError(`Missing value for ${name}.`); + } + return args[index + 1]; + }; + for (let index = 0; index < args.length; index++) { + const argument = args[index]; + const [name, inlineValue] = argument.startsWith('--') && argument.includes('=') ? [argument.slice(0, argument.indexOf('=')), argument.slice(argument.indexOf('=') + 1)] : [argument, undefined]; + switch (name) { + case '--help': + writeStdout('Usage: node scripts/code-oss-launcher/launch.ts --repo [--wait] [--skip-prelaunch] [--session-title ] [--source-user-data-dir <profile>] [--copy-extensions[=<id,...>]] [--full] [--reuse|--fresh] [--agents] [--disable-workspace-trust] -- <Code OSS arguments>\n'); + process.exit(0); + case '--agents': agents = true; break; + case '--session-title': sessionTitle = inlineValue ?? value(index++, name); break; + case '--source-user-data-dir': sourceUserDataDir = inlineValue ?? value(index++, name); break; + case '--repo': repo = inlineValue ?? value(index++, name); break; + case '--clone-extensions': + case '--copy-extensions': { + if (inlineValue === undefined) { + extensions = { kind: 'all' }; + break; + } + // Commas or spaces: PowerShell turns an unquoted `a,b` argument into `a b` + const ids = inlineValue.split(/[\s,]+/).filter(id => id.length > 0); + if (ids.length === 0) { + throw new UsageError(`Missing extension IDs for ${name}=<id,...>.`); + } + extensions = { kind: 'ids', ids }; + break; + } + case '--full': full = true; break; + case '--skip-prelaunch': skipPreLaunch = true; break; + case '--disable-workspace-trust': disableWorkspaceTrust = true; break; + case '--reuse': reuse = true; break; + case '--fresh': reuse = false; break; + case '--wait': wait = true; break; + case '--': extraArgs = args.slice(index + 1); index = args.length; break; + default: + // PowerShell drops an unquoted `--`, so a workspace path also starts the arguments for Code + if (!argument.startsWith('-')) { + extraArgs = args.slice(index); + index = args.length; + break; + } + throw new UsageError(`Unknown arg: ${argument}${fromPowerShell ? `. To pass it to Code OSS, put it after '--', quoted: PowerShell drops an unquoted --.` : ''}`); + } + } + for (const argument of extraArgs) { + if (/^--(?:user-data-dir|extensions-dir|shared-data-dir|remote-debugging-port|inspect(?:-extensions|-agenthost)?)(?:=|$)/.test(argument)) { + throw new UsageError(`The launcher owns ${argument.split('=')[0]}; it cannot be overridden.`); + } + } + return { agents, sessionTitle, sourceUserDataDir, repo, extensions, full, skipPreLaunch, disableWorkspaceTrust, reuse, wait, extraArgs }; +} + +async function main(): Promise<number> { + const startedAt = performance.now(); + const { args, fromPowerShell } = readArguments(); + const options = parseArguments(args, fromPowerShell); + + const repo = path.resolve(options.repo ?? process.cwd()); + const codeScript = path.join(repo, 'scripts', process.platform === 'win32' ? 'code.bat' : 'code.sh'); + if (!existsSync(codeScript)) { + throw new UsageError(options.repo ? `Could not find a Code OSS launcher at ${codeScript}. Pass --repo <vscode-repo-root>.` : `Could not find a vscode checkout in ${repo}. Pass --repo <vscode-repo-root>.`); + } + + const sourceUserDataDir = path.resolve(options.sourceUserDataDir ?? process.env.CODE_OSS_DEV_AUTHED_USER_DATA_DIR ?? path.join(os.homedir(), '.vscode-oss-dev')); + const sourceProfileExists = await isDirectory(sourceUserDataDir); + if (!sourceProfileExists) { + log(`no source profile at ${sourceUserDataDir}; launching with an empty isolated profile so the user can sign in.`); + } + const [cdpPort, extHostPort, mainPort, agentHostPort] = await allocatePorts(4); + if (options.extensions?.kind === 'ids' && sourceProfileExists && !options.full) { + await validateExtensionSelection(path.join(sourceUserDataDir, 'extensions'), options.extensions.ids); + } + + const { runDir, reused } = await createRunDir(repo, sourceUserDataDir, options); + let codePid: number | undefined; + let disposeSignalHandlers: (() => void) | undefined; + let receivedSignal: NodeJS.Signals | undefined; + try { + const userDataDir = path.join(runDir, 'user-data'); + const extensionsDir = path.join(userDataDir, 'extensions'); + const sharedDataDir = path.join(runDir, 'shared-data'); + const logFile = path.join(runDir, 'code.log'); + await fs.writeFile(logFile, ''); + log(`${reused ? 'reusing' : 'created'} run directory ${runDir}`); + + const preLaunch = options.skipPreLaunch ? undefined : runPreLaunch(repo, logFile); + const hasGitHubSession = await prepareProfile(repo, sourceUserDataDir, sourceProfileExists, runDir, userDataDir, extensionsDir, sharedDataDir, reused, options); + const profileReadyAt = performance.now(); + + if (preLaunch) { + if (!await preLaunch) { + log('pre-launch FAILED. Log tail:'); + writeLogTail(logFile); + return 1; + } + } else { + log('skipping pre-launch by request'); + } + const preLaunchReadyAt = performance.now(); + + const launchArgs = [ + ...(options.agents ? ['--agents'] : []), + `--user-data-dir=${userDataDir}`, + `--extensions-dir=${extensionsDir}`, + `--shared-data-dir=${sharedDataDir}`, + `--remote-debugging-port=${cdpPort}`, + `--inspect-extensions=${extHostPort}`, + `--inspect=${mainPort}`, + `--inspect-agenthost=${agentHostPort}`, + ...(options.disableWorkspaceTrust ? ['--disable-workspace-trust'] : []), + ...(options.agents && options.sessionTitle ? [`--session-title-base64=${Buffer.from(options.sessionTitle, 'utf8').toString('base64url')}`] : []), + ...options.extraArgs, + ]; + log(`logs: ${logFile}`); + const code = await startCode(repo, codeScript, launchArgs, logFile, options.wait); + const pid = code.pid; + codePid = pid; + if (options.wait) { + const onSignal = (signal: NodeJS.Signals) => { + receivedSignal = signal; + stopCodeProcesses(runDir, pid); + }; + process.on('SIGINT', onSignal); + process.on('SIGTERM', onSignal); + disposeSignalHandlers = () => { + process.off('SIGINT', onSignal); + process.off('SIGTERM', onSignal); + }; + } + await writeState(runDir, { kind: reused ? 'reuse' : 'fresh', codePid: pid, lastUsedAt: Date.now() }); + + log(`waiting for CDP on port ${cdpPort} (timeout ${CDP_TIMEOUT_MS / 1000}s)...`); + const ready = await waitForCdp(pid, cdpPort, CDP_TIMEOUT_MS); + if (ready.status !== 'ready') { + log(ready.status === 'timeout' ? `timed out waiting for CDP on port ${cdpPort}. Log tail:` : `Code OSS (PID ${pid}) exited before CDP came up. Log tail:`); + writeLogTail(logFile); + stopCodeProcesses(runDir, pid); + if (options.wait) { + await code.exited; + } + return 1; + } + log(`CDP ready after ${ready.elapsedMs}ms`); + if (hasGitHubSession === false) { + log(`WARNING: source profile ${sourceUserDataDir} has no stored GitHub session; the launched instance will prompt you to sign in.`); + log('Sign in to your source Code OSS profile before launching to seed authentication. Credentials are copied locally, never printed.'); + } + await collectGarbage(path.dirname(runDir)); + + const finishedAt = performance.now(); + writeStdout(JSON.stringify({ + pid, + cdpPort, + extHostPort, + mainPort, + agentHostPort, + userDataDir, + extensionsDir, + sharedDataDir, + runDir, + logFile, + repo, + agents: options.agents, + reused, + timings: { + profileMs: Math.round(profileReadyAt - startedAt), + preLaunchMs: Math.round(preLaunchReadyAt - profileReadyAt), + cdpReadyMs: Math.round(finishedAt - preLaunchReadyAt), + totalMs: Math.round(finishedAt - startedAt), + }, + }) + '\n'); + if (options.wait) { + const result = await code.exited; + if (receivedSignal) { + return receivedSignal === 'SIGINT' ? 130 : 143; + } + if (result.signal) { + throw new Error(`Code OSS exited with signal ${result.signal}.`); + } + return result.code ?? 1; + } + return 0; + } catch (error) { + if (codePid !== undefined) { + stopCodeProcesses(runDir, codePid); + } + throw error; + } finally { + disposeSignalHandlers?.(); + if (reused) { + await releaseClaim(runDir); + } + } +} + +async function createRunDir(repo: string, sourceUserDataDir: string, options: ILaunchOptions): Promise<{ runDir: string; reused: boolean }> { + const root = getRunRoot(repo); + if (options.reuse) { + // One reused run directory per source profile and copy selection, as their contents differ + const extensionsKey = !options.extensions ? 'none' : options.extensions.kind === 'all' ? 'all' : options.extensions.ids.map(id => id.toLowerCase()).sort().join(','); + const profileKey = process.platform === 'linux' ? sourceUserDataDir : sourceUserDataDir.toLowerCase(); + const key = createHash('sha256').update(JSON.stringify([profileKey, options.full, extensionsKey])).digest('hex').slice(0, 8); + const runDir = await claimReuseRunDir(root, key); + if (runDir) { + await writeState(runDir, { kind: 'reuse', launcherPid: process.pid, lastUsedAt: Date.now() }); + return { runDir, reused: true }; + } + log('the reused run directory is in use by another launch or Code OSS; using a fresh one'); + } + try { + return { runDir: await createFreshRunDir(root), reused: false }; + } catch (error) { + const fallbackRoot = getTempRunRoot(); + if (fallbackRoot === root) { + throw error; + } + log(`cannot create a run directory in ${root} (${(error as Error).message}); using ${fallbackRoot}`); + return { runDir: await createFreshRunDir(fallbackRoot), reused: false }; + } +} + +/** + * Copies or syncs the profile, shared data and extensions, and prepares settings. + * Returns whether the source profile has a stored GitHub session, where that can be determined. + */ +async function prepareProfile(repo: string, sourceUserDataDir: string, sourceProfileExists: boolean, runDir: string, userDataDir: string, extensionsDir: string, sharedDataDir: string, reused: boolean, options: ILaunchOptions): Promise<boolean | undefined> { + const manifestFile = path.join(runDir, 'launch-manifest.json'); + const previous: IReuseManifest = reused ? await readJson<IReuseManifest>(manifestFile).then(manifest => manifest?.version === 1 ? manifest : { version: 1 }) : { version: 1 }; + await fs.mkdir(userDataDir, { recursive: true }); + + // On Windows the GitHub session is APPLICATION_SHARED scoped, so it lives in the shared-data-dir + // and not in the profile - see useSharedStorage in src/vs/platform/secrets/common/secrets.ts. + // Without this copy the launched instance always prompts for sign-in. + const sourceSharedDataDir = getSourceSharedDataDir(repo); + const copiesSharedData = process.platform === 'win32' && await isDirectory(sourceSharedDataDir); + if (process.platform === 'win32' && !copiesSharedData) { + log(`no shared-data-dir at ${sourceSharedDataDir}; nothing to seed`); + } + + const sharedDataSync = copiesSharedData ? syncTree(sourceSharedDataDir, sharedDataDir, previous.sharedData) : fs.mkdir(sharedDataDir, { recursive: true }).then(() => undefined); + const profileSync = sourceProfileExists ? syncTree(sourceUserDataDir, userDataDir, previous.profile, options.full ? undefined : isExcludedFromProfileCopy) : Promise.resolve(undefined); + const copiesExtensions = !options.full && options.extensions !== undefined && sourceProfileExists; + const extensionsSync = copiesExtensions ? syncExtensions(path.join(sourceUserDataDir, 'extensions'), extensionsDir, options.extensions!, previous.extensionFolders) : fs.mkdir(extensionsDir, { recursive: true }).then(() => undefined); + const gitHubSessionCheck = process.platform === 'win32' && sourceProfileExists ? hasGitHubSession(sourceUserDataDir, sourceSharedDataDir, runDir) : Promise.resolve(sourceProfileExists ? undefined : false); + + log(`${sourceProfileExists ? `${options.full ? 'full' : 'slim'} ${reused ? 'sync' : 'copy'}: ${sourceUserDataDir}` : 'empty profile'} -> ${userDataDir}`); + if (copiesExtensions) { + log(`${reused ? 'syncing' : 'copying'} extensions ${options.extensions!.kind === 'all' ? '(all)' : options.extensions!.ids.join(', ')} -> ${extensionsDir}`); + } + const [sharedData, profile, extensionFolders, hasSession] = await Promise.all([sharedDataSync, profileSync, extensionsSync, gitHubSessionCheck]); + if (reused) { + const copied = (profile?.copiedFiles ?? 0) + (sharedData?.copiedFiles ?? 0); + const deleted = (profile?.deletedFiles ?? 0) + (sharedData?.deletedFiles ?? 0); + log(`synced: ${copied} files copied, ${deleted} deleted`); + const manifest: IReuseManifest = { version: 1, profile: profile?.manifest, sharedData: sharedData?.manifest, extensionFolders: extensionFolders ?? undefined }; + await fs.writeFile(manifestFile, JSON.stringify(manifest)); + } + + if (process.platform === 'win32' && sourceProfileExists && hasSession !== false) { + const missing = ['Local State', 'machineid', 'User/globalStorage/state.vscdb', 'Network'].filter(relative => !existsSync(path.join(userDataDir, relative))); + if (missing.length > 0) { + throw new Error(`Profile copy is missing auth-critical path(s): ${missing.join(', ')}. Refusing to launch a profile that cannot preserve Windows authentication.`); + } + } + + const settingsFile = path.join(userDataDir, 'User', 'settings.json'); + await fs.mkdir(path.dirname(settingsFile), { recursive: true }); + updateLaunchSettings(settingsFile, options.agents ? undefined : options.sessionTitle, path.join(sourceUserDataDir, 'User', 'settings.json')); + log(`ensured files.simpleDialog.enable=true in ${settingsFile}`); + if (options.sessionTitle) { + log(options.agents ? `set Agents command center title for session: ${options.sessionTitle}` : `set window.title for session: ${options.sessionTitle}`); + } + return hasSession; +} + +/** + * Mirrors IEnvironmentService.appSharedDataHome, minus the --shared-data-dir branch, which names + * the destination and not the source: VSCODE_PORTABLE\shared-data, else ~/<product.sharedDataFolderName>. + */ +function getSourceSharedDataDir(repo: string): string { + if (process.env.CODE_OSS_DEV_AUTHED_SHARED_DATA_DIR) { + return process.env.CODE_OSS_DEV_AUTHED_SHARED_DATA_DIR; + } + if (process.env.VSCODE_PORTABLE) { + return path.join(process.env.VSCODE_PORTABLE, 'shared-data'); + } + return path.join(os.homedir(), readProduct(repo).sharedDataFolderName ?? '.vscode-oss-shared'); +} + +/** + * Looks for a GitHub session in the databases the launch copies. On Windows it is stored in the + * shared-data-dir; older profiles may still hold it in globalStorage, so either one counts. + */ +async function hasGitHubSession(sourceUserDataDir: string, sourceSharedDataDir: string, runDir: string): Promise<boolean | undefined> { + let undetermined = false; + for (const database of [path.join(sourceSharedDataDir, 'sharedStorage', 'state.vscdb'), path.join(sourceUserDataDir, 'User', 'globalStorage', 'state.vscdb')]) { + if (!existsSync(database)) { + continue; + } + // Reads a copy, as a running Code instance may be writing to the database + const copy = path.join(runDir, `auth-preflight-${path.basename(path.dirname(database))}.vscdb`); + try { + await fs.copyFile(database, copy); + const { DatabaseSync } = await import('node:sqlite'); + const db = new DatabaseSync(copy, { readOnly: true }); + try { + if (db.prepare('SELECT 1 FROM ItemTable WHERE key LIKE ? LIMIT 1').get('secret://%github-authentication%')) { + return true; + } + } finally { + db.close(); + } + } catch { + undetermined = true; + } finally { + await fs.rm(copy, { force: true }); + } + } + return undetermined ? undefined : false; +} + +/** + * Runs build/lib/preLaunch.ts, which ensures Electron, compiled output and built-in extensions. + */ +function runPreLaunch(repo: string, logFile: string): Promise<boolean> { + log('running pre-launch (ensures electron + compiled output + built-ins)...'); + const logFd = openSync(logFile, 'a'); + return new Promise<boolean>(resolve => { + const child = spawn(process.execPath, ['build/lib/preLaunch.ts'], { cwd: repo, stdio: ['ignore', logFd, logFd] }); + child.on('error', () => resolve(false)); + child.on('exit', code => resolve(code === 0)); + }).finally(() => closeSync(logFd)); +} + +/** + * Starts Code OSS detached by default, or in the caller's process tree when waiting. + * On Windows, Electron is started directly as scripts/code.bat would after pre-launch, because + * passing arguments through cmd.exe breaks on characters such as `&` and `%`. + */ +async function startCode(repo: string, codeScript: string, launchArgs: readonly string[], logFile: string, wait: boolean) { + const env: NodeJS.ProcessEnv = { ...process.env, VSCODE_SKIP_PRELAUNCH: '1' }; + // Host-only configuration, commonly inherited from VS Code's integrated terminal and agent runtimes + for (const name of ['ELECTRON_RUN_AS_NODE', 'GIT_CONFIG_COUNT', 'GIT_CONFIG_PARAMETERS', 'CODE_OSS_DEV_REFS_VOLUMES', 'UV_THREADPOOL_SIZE']) { + delete env[name]; + } + + let command = codeScript; + let args = [...launchArgs]; + if (process.platform === 'win32') { + const electron = path.join(repo, '.build', 'electron', `${readProduct(repo).nameShort}.exe`); + if (!existsSync(electron)) { + throw new Error(`Electron is missing at ${electron}; launch without --skip-prelaunch to download it.`); + } + command = electron; + args = ['.', ...(launchArgs.includes('--extensionTestsPath') ? [] : ['--disable-extension=vscode.vscode-api-tests']), ...launchArgs]; + Object.assign(env, { NODE_ENV: 'development', VSCODE_DEV: '1', VSCODE_CLI: '1', ELECTRON_ENABLE_LOGGING: '1', ELECTRON_ENABLE_STACK_DUMPING: '1' }); + } + log(`launching: ${command} ${args.join(' ')}`); + + const logFd = openSync(logFile, 'a'); + try { + const child = spawn(command, args, { cwd: repo, env, detached: process.platform !== 'win32' || !wait, stdio: ['ignore', logFd, logFd] }); + const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(resolve => { + child.once('exit', (code, signal) => resolve({ code, signal })); + }); + await new Promise<void>((resolve, reject) => { + child.once('spawn', resolve); + child.once('error', reject); + }); + if (!wait) { + child.unref(); + } + return { pid: child.pid!, exited }; + } finally { + closeSync(logFd); + } +} + +async function allocatePorts(count: number): Promise<number[]> { + const servers = Array.from({ length: count }, () => net.createServer()); + try { + await Promise.all(servers.map(server => new Promise<void>((resolve, reject) => { + server.once('error', reject); + server.listen(0, '127.0.0.1', resolve); + }))); + return servers.map(server => (server.address() as net.AddressInfo).port); + } finally { + await Promise.all(servers.map(server => new Promise<void>(resolve => server.close(() => resolve())))); + } +} + +function readProduct(repo: string): { nameShort: string; sharedDataFolderName?: string } { + return JSON.parse(readFileSync(path.join(repo, 'product.json'), 'utf8')); +} + +function writeLogTail(logFile: string): void { + try { + writeStderr(readFileSync(logFile, 'utf8').split(/\r?\n/).slice(-80).join('\n') + '\n'); + } catch { + // No log yet + } +} + +async function isDirectory(directory: string): Promise<boolean> { + return fs.stat(directory).then(stat => stat.isDirectory(), () => false); +} + +async function readJson<T>(file: string): Promise<T | undefined> { + try { + return JSON.parse(await fs.readFile(file, 'utf8')); + } catch { + return undefined; + } +} + +try { + process.exitCode = await main(); +} catch (error) { + if (error instanceof UsageError) { + writeStderr(`${error.message}\n`); + process.exitCode = 2; + } else if (error instanceof UnknownExtensionsError) { + writeStderr(`Extensions not installed: ${error.unknownIds.join(', ')}\nInstalled: ${error.installedIds.join(', ')}\n`); + process.exitCode = 2; + } else { + log(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + } +} diff --git a/scripts/code-oss-launcher/lib/output.ts b/scripts/code-oss-launcher/lib/output.ts new file mode 100644 index 00000000000000..324d8e850c1245 --- /dev/null +++ b/scripts/code-oss-launcher/lib/output.ts @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Preserve optional file-based output for callers that cannot inherit stdio handles. +// The managed adapter uses ordinary stdout/stderr pipes. + +import { appendFileSync } from 'node:fs'; + +const stdoutFile = process.env.CODE_OSS_DEV_STDOUT_FILE; +const stderrFile = process.env.CODE_OSS_DEV_STDERR_FILE; +delete process.env.CODE_OSS_DEV_STDOUT_FILE; +delete process.env.CODE_OSS_DEV_STDERR_FILE; + +export function writeStdout(text: string): void { + if (stdoutFile) { + appendFileSync(stdoutFile, text); + } else { + process.stdout.write(text); + } +} + +export function writeStderr(text: string): void { + if (stderrFile) { + appendFileSync(stderrFile, text); + } else { + process.stderr.write(text); + } +} diff --git a/scripts/code-oss-launcher/lib/profileCopy.test.ts b/scripts/code-oss-launcher/lib/profileCopy.test.ts new file mode 100644 index 00000000000000..35383e0ccbae24 --- /dev/null +++ b/scripts/code-oss-launcher/lib/profileCopy.test.ts @@ -0,0 +1,113 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Run with: node --test scripts/code-oss-launcher/lib/profileCopy.test.ts + +import assert from 'node:assert/strict'; +import { mkdtempSync, promises as fs } from 'node:fs'; +import * as path from 'node:path'; +import { afterEach, beforeEach, suite, test } from 'node:test'; +import { isExcludedFromProfileCopy, syncExtensions, syncTree, UnknownExtensionsError } from './profileCopy.ts'; + +suite('isExcludedFromProfileCopy', () => { + test('matches top-level, nested and name patterns', () => { + const paths = [ + 'extensions', 'User/extensions', + 'workspaceStorage', 'User/workspaceStorage', 'Other/User/workspaceStorage', + 'User/History', 'User/globalStorage/state.vscdb', + 'logs', 'User/logs', + 'Cache', 'Partitions/vscode-browser/Cache', 'Partitions/other/Cache', + 'DawnGraphiteCache', 'DawnWebGPUCache', 'Partitions/vscode-browser/DawnWebGPUCache', + 'SingletonLock', 'User/SingletonLock', + 'code.lock', 'User/globalStorage/x.lock', 'main.sock', + 'Local State', 'Network/Cookies', 'machineid', + ]; + assert.deepStrictEqual(Object.fromEntries(paths.map(relative => [relative, isExcludedFromProfileCopy(relative.split('/'))])), { + 'extensions': true, 'User/extensions': false, + 'workspaceStorage': true, 'User/workspaceStorage': true, 'Other/User/workspaceStorage': true, + 'User/History': true, 'User/globalStorage/state.vscdb': false, + 'logs': true, 'User/logs': false, + 'Cache': true, 'Partitions/vscode-browser/Cache': true, 'Partitions/other/Cache': false, + 'DawnGraphiteCache': true, 'DawnWebGPUCache': true, 'Partitions/vscode-browser/DawnWebGPUCache': true, + 'SingletonLock': true, 'User/SingletonLock': false, + 'code.lock': true, 'User/globalStorage/x.lock': true, 'main.sock': true, + 'Local State': false, 'Network/Cookies': false, 'machineid': false, + }); + }); +}); + +suite('sync', () => { + let root: string; + beforeEach(() => { root = mkdtempSync(path.join(import.meta.dirname, '.profile-copy-test-')); }); + afterEach(() => fs.rm(root, { recursive: true, force: true })); + + async function write(relative: string, content: string, mtime = new Date(2026, 0, 1)): Promise<void> { + const file = path.join(root, relative); + await fs.mkdir(path.dirname(file), { recursive: true }); + await fs.writeFile(file, content); + await fs.utimes(file, mtime, mtime); + } + + async function readTree(directory: string): Promise<Record<string, string>> { + const entries = await fs.readdir(path.join(root, directory), { recursive: true, withFileTypes: true }); + const files = entries.filter(entry => entry.isFile()).map(entry => path.join(entry.parentPath, entry.name)); + return Object.fromEntries(await Promise.all(files.sort().map(async file => [path.relative(path.join(root, directory), file).replaceAll('\\', '/'), await fs.readFile(file, 'utf8')]))); + } + + test('copies, then syncs only changes and keeps files created in the copy', async () => { + await write('source/User/settings.json', 'settings'); + await write('source/User/globalStorage/state.vscdb', 'state'); + await write('source/logs/main.log', 'excluded'); + await write('source/removed.txt', 'removed later'); + const copy = await syncTree(path.join(root, 'source'), path.join(root, 'copy'), undefined, isExcludedFromProfileCopy); + const afterCopy = await readTree('copy'); + + await write('source/User/settings.json', 'changed in source', new Date(2026, 0, 2)); + await write('copy/User/globalStorage/state.vscdb', 'changed by Code', new Date(2026, 0, 3)); + await write('copy/Cache/data', 'created by Code'); + await fs.rm(path.join(root, 'source/removed.txt')); + const sync = await syncTree(path.join(root, 'source'), path.join(root, 'copy'), copy.manifest, isExcludedFromProfileCopy); + + assert.deepStrictEqual({ copied: copy.copiedFiles, afterCopy, synced: { copied: sync.copiedFiles, deleted: sync.deletedFiles }, afterSync: await readTree('copy') }, { + copied: 3, + afterCopy: { 'User/globalStorage/state.vscdb': 'state', 'User/settings.json': 'settings', 'removed.txt': 'removed later' }, + synced: { copied: 2, deleted: 1 }, + afterSync: { 'Cache/data': 'created by Code', 'User/globalStorage/state.vscdb': 'state', 'User/settings.json': 'changed in source' }, + }); + }); + + test('copies selected extensions with a filtered manifest and replaces unselected ones', async () => { + const manifest = [ + { identifier: { id: 'pub.a' }, relativeLocation: 'pub.a-1.0.0' }, + { identifier: { id: 'pub.big' }, relativeLocation: 'pub.big-2.0.0' }, + { identifier: { id: 'pub.linked' }, location: { fsPath: '/dev/linked' } }, + ]; + await write('source/extensions.json', JSON.stringify(manifest)); + await write('source/.obsolete', '{}'); + await write('source/pub.a-1.0.0/package.json', 'a'); + await write('source/pub.big-2.0.0/node_modules/x/index.js', 'big'); + const source = path.join(root, 'source'); + const destination = path.join(root, 'destination'); + + const all = await syncExtensions(source, destination, { kind: 'all' }, undefined); + const selected = await syncExtensions(source, destination, { kind: 'ids', ids: ['PUB.A', 'pub.linked'] }, all); + const destinationFiles = await readTree('destination'); + const unknown = await syncExtensions(source, destination, { kind: 'ids', ids: ['pub.a', 'pub.missing'] }, selected).catch(error => error); + + assert.deepStrictEqual({ + all, + selected, + files: Object.keys(destinationFiles), + manifest: JSON.parse(destinationFiles['extensions.json']).map((entry: { identifier: { id: string } }) => entry.identifier.id), + unknown: unknown instanceof UnknownExtensionsError ? { unknownIds: unknown.unknownIds, installedIds: unknown.installedIds } : unknown, + }, { + all: ['pub.a-1.0.0', 'pub.big-2.0.0'], + selected: ['pub.a-1.0.0'], + files: ['.obsolete', 'extensions.json', 'pub.a-1.0.0/package.json'], + manifest: ['pub.a', 'pub.linked'], + unknown: { unknownIds: ['pub.missing'], installedIds: ['pub.a', 'pub.big', 'pub.linked'] }, + }); + }); +}); diff --git a/scripts/code-oss-launcher/lib/profileCopy.ts b/scripts/code-oss-launcher/lib/profileCopy.ts new file mode 100644 index 00000000000000..99bdaba8cddcf3 --- /dev/null +++ b/scripts/code-oss-launcher/lib/profileCopy.ts @@ -0,0 +1,299 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Copies profile trees for the launcher. Copy time is dominated by per-file overhead, so files are +// copied concurrently. Reused run directories are synced: only files whose source changed, or +// whose copy Code changed, are copied again, and files removed from the source are removed. + +import { promises as fs } from 'node:fs'; +import * as path from 'node:path'; +import { writeStderr } from './output.ts'; + +/** + * What a slim profile copy leaves out: transient, regenerable, or known-unneeded state. + * Patterns starting with `/` match top-level entries; patterns containing `/` match consecutive + * path segments at any depth; other patterns match entry names. `*` is the only wildcard. + */ +const profileExcludePatterns: readonly string[] = [ + '/extensions', // copied separately + '/workspaceStorage', 'User/workspaceStorage', // per-workspace state, including chat sessions + 'User/History', // local file edit history + '/CachedExtensionVSIXs', + '/logs', + '/Cache', '/Code Cache', '/CachedData', '/component_crx_cache', + '/GPUCache', '/ShaderCache', '/Dawn*Cache', + 'Partitions/vscode-browser/Cache', 'Partitions/vscode-browser/Code Cache', + 'Partitions/vscode-browser/GPUCache', 'Partitions/vscode-browser/Dawn*Cache', + '/Backups', '/blob_storage', '/BrowserMetrics', '/Crashpad', + '/Session Storage', + '/Singleton*', + '*.lock', '*.sock', +]; + +type CompiledPattern = + | { readonly kind: 'topLevel' | 'name'; readonly regExp: RegExp } + | { readonly kind: 'segments'; readonly regExps: readonly RegExp[] }; + +// Matches the case sensitivity of the platform's default file system +const globFlags = process.platform === 'linux' ? '' : 'i'; + +function compileGlob(glob: string): RegExp { + const source = glob.split('*').map(part => part.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*'); + return new RegExp(`^${source}$`, globFlags); +} + +const compiledProfileExcludePatterns: readonly CompiledPattern[] = profileExcludePatterns.map((pattern): CompiledPattern => { + if (pattern.startsWith('/')) { + return { kind: 'topLevel', regExp: compileGlob(pattern.slice(1)) }; + } + if (pattern.includes('/')) { + return { kind: 'segments', regExps: pattern.split('/').map(compileGlob) }; + } + return { kind: 'name', regExp: compileGlob(pattern) }; +}); + +/** + * Whether a slim profile copy leaves out the entry at the given path segments, relative to the profile root. + */ +export function isExcludedFromProfileCopy(segments: readonly string[]): boolean { + const name = segments[segments.length - 1]; + for (const pattern of compiledProfileExcludePatterns) { + switch (pattern.kind) { + case 'topLevel': + if (segments.length === 1 && pattern.regExp.test(name)) { + return true; + } + break; + case 'name': + if (pattern.regExp.test(name)) { + return true; + } + break; + case 'segments': + for (let start = 0; start + pattern.regExps.length <= segments.length; start++) { + if (pattern.regExps.every((regExp, index) => regExp.test(segments[start + index]))) { + return true; + } + } + break; + } + } + return false; +} + +/** + * The files and directories of a copied tree, used to sync a reused copy. + * Files map relative paths to `[size, mtimeMs]` of the source at copy time. + */ +export interface ITreeManifest { + readonly files: Readonly<Record<string, readonly [number, number]>>; + readonly directories: readonly string[]; +} + +interface ITreeScan { + readonly files: Map<string, readonly [number, number]>; + readonly directories: string[]; +} + +export interface ISyncResult { + readonly manifest: ITreeManifest; + readonly copiedFiles: number; + readonly deletedFiles: number; +} + +/** + * Makes `destination` match `source`. Without a previous manifest, everything is copied. With one, + * only files that changed in the source or in the destination are copied, and files removed from + * the source are deleted. Files that only exist in the destination, such as caches Code created, + * are kept. + */ +export async function syncTree(source: string, destination: string, previous: ITreeManifest | undefined, isExcluded?: (segments: readonly string[]) => boolean): Promise<ISyncResult> { + const scan = await scanTree(source, isExcluded); + const previousDirectories = new Set(previous?.directories); + await createDirectories(destination, scan.directories.filter(directory => !previousDirectories.has(directory))); + + const toCopy: string[] = []; + await forEachConcurrent([...scan.files], 64, async ([relative, record]) => { + const previousRecord = previous?.files[relative]; + if (!previousRecord || !isSameRecord(previousRecord, record) || !isSameRecord(await statRecord(path.join(destination, relative)), record)) { + toCopy.push(relative); + } + }); + await copyFiles(source, destination, toCopy); + + const deleted = previous ? Object.keys(previous.files).filter(relative => !scan.files.has(relative)) : []; + await forEachConcurrent(deleted, 64, relative => fs.rm(path.join(destination, relative), { force: true })); + + return { + manifest: { files: Object.fromEntries(scan.files), directories: scan.directories }, + copiedFiles: toCopy.length, + deletedFiles: deleted.length, + }; +} + +/** + * Which extensions to copy: all of them, or only those with the given IDs. + */ +export type ExtensionSelection = { readonly kind: 'all' } | { readonly kind: 'ids'; readonly ids: readonly string[] }; + +interface IExtensionEntry { + readonly identifier: { readonly id: string }; + readonly relativeLocation?: string; +} + +export class UnknownExtensionsError extends Error { + readonly unknownIds: readonly string[]; + readonly installedIds: readonly string[]; + + constructor(unknownIds: readonly string[], installedIds: readonly string[]) { + super(`Extensions not installed: ${unknownIds.join(', ')}. Installed: ${installedIds.join(', ')}`); + this.unknownIds = unknownIds; + this.installedIds = installedIds; + } +} + +/** + * Throws {@link UnknownExtensionsError} unless all IDs are installed in the `source` extensions folder. + */ +export async function validateExtensionSelection(source: string, ids: readonly string[]): Promise<void> { + await selectExtensionEntries(source, ids); +} + +async function selectExtensionEntries(source: string, ids: readonly string[]): Promise<IExtensionEntry[]> { + const manifestText = await fs.readFile(path.join(source, 'extensions.json'), 'utf8').catch(() => '[]'); + const entries: IExtensionEntry[] = JSON.parse(manifestText); + const requestedIds = new Set(ids.map(id => id.toLowerCase())); + const selectedEntries = entries.filter(entry => requestedIds.has(entry.identifier.id.toLowerCase())); + const unknownIds = [...requestedIds].filter(id => !selectedEntries.some(entry => entry.identifier.id.toLowerCase() === id)); + if (unknownIds.length > 0) { + throw new UnknownExtensionsError(unknownIds, entries.map(entry => entry.identifier.id).sort()); + } + return selectedEntries; +} + +/** + * Makes the `destination` extensions folder contain the selected extensions. Extension folders are + * versioned and immutable, so a folder copied before is not compared file by file again. + * Returns the extension folders now in the destination. + */ +export async function syncExtensions(source: string, destination: string, selection: ExtensionSelection, previousFolders: readonly string[] | undefined): Promise<string[]> { + await fs.mkdir(destination, { recursive: true }); + const sourceEntries = await fs.readdir(source, { withFileTypes: true }).catch(() => []); + const sourceFolders = sourceEntries.filter(entry => entry.isDirectory()).map(entry => entry.name); + const topLevelFiles = sourceEntries.filter(entry => entry.isFile() && (selection.kind === 'all' || entry.name !== 'extensions.json')).map(entry => entry.name); + + let wantedFolders = sourceFolders; + const ownFiles = new Set(topLevelFiles); + if (selection.kind === 'ids') { + const selectedEntries = await selectExtensionEntries(source, selection.ids); + // Extensions installed outside the folder, for example linked for development, have no folder to copy + const selectedFolders = new Set(selectedEntries.map(entry => entry.relativeLocation).filter(location => location !== undefined)); + wantedFolders = sourceFolders.filter(folder => selectedFolders.has(folder)); + await fs.writeFile(path.join(destination, 'extensions.json'), JSON.stringify(selectedEntries)); + ownFiles.add('extensions.json'); + } + + // Folders copied completely before are kept; anything else is replaced + const wanted = new Set(wantedFolders); + const previous = new Set(previousFolders); + const destinationEntries = await fs.readdir(destination, { withFileTypes: true }); + const stale = destinationEntries.filter(entry => entry.isDirectory() ? !wanted.has(entry.name) || !previous.has(entry.name) : !ownFiles.has(entry.name)); + await forEachConcurrent(stale, 8, entry => fs.rm(path.join(destination, entry.name), { recursive: true, force: true, maxRetries: 3 })); + + const kept = new Set(destinationEntries.filter(entry => entry.isDirectory() && !stale.includes(entry)).map(entry => entry.name)); + const scans = await Promise.all(wantedFolders.filter(folder => !kept.has(folder)).map(async folder => ({ folder, scan: await scanTree(path.join(source, folder)) }))); + await createDirectories(destination, scans.flatMap(({ folder, scan }) => [folder, ...scan.directories.map(directory => path.join(folder, directory))])); + await copyFiles(source, destination, [...topLevelFiles, ...scans.flatMap(({ folder, scan }) => [...scan.files.keys()].map(file => path.join(folder, file)))]); + return wantedFolders; +} + +async function scanTree(root: string, isExcluded?: (segments: readonly string[]) => boolean): Promise<ITreeScan> { + const files = new Map<string, readonly [number, number]>(); + const directories: string[] = []; + + async function visit(relativeDirectory: string, segments: readonly string[]): Promise<void> { + const entries = await fs.readdir(path.join(root, relativeDirectory), { withFileTypes: true }); + await Promise.all(entries.map(async entry => { + const entrySegments = [...segments, entry.name]; + if (isExcluded?.(entrySegments)) { + return; + } + const relative = path.join(relativeDirectory, entry.name); + if (entry.isDirectory()) { + directories.push(relative); + await visit(relative, entrySegments); + } else { + const record = await statRecord(path.join(root, relative)); + if (record) { + files.set(relative, record); + } + } + })); + } + + await visit('', []); + return { files, directories }; +} + +async function statRecord(file: string): Promise<readonly [number, number] | undefined> { + try { + const stat = await fs.stat(file); + return stat.isFile() ? [stat.size, Math.trunc(stat.mtimeMs)] : undefined; + } catch { + return undefined; + } +} + +function isSameRecord(a: readonly [number, number] | undefined, b: readonly [number, number]): boolean { + return a !== undefined && a[0] === b[0] && a[1] === b[1]; +} + +async function createDirectories(root: string, relatives: readonly string[]): Promise<void> { + await forEachConcurrent(relatives, 32, relative => fs.mkdir(path.join(root, relative), { recursive: true })); +} + +async function copyFiles(sourceRoot: string, destinationRoot: string, relatives: readonly string[]): Promise<void> { + await forEachConcurrent(relatives, 64, relative => copyFile(path.join(sourceRoot, relative), path.join(destinationRoot, relative))); +} + +async function copyFile(source: string, destination: string): Promise<void> { + try { + await fs.copyFile(source, destination); + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + try { + if (code === 'ENOENT') { + await fs.mkdir(path.dirname(destination), { recursive: true }); + } else if (code === 'EPERM' || code === 'EACCES') { + // A read-only copy from an earlier launch + await fs.chmod(destination, 0o666); + } else { + throw error; + } + await fs.copyFile(source, destination); + } catch (retryError) { + // For example a file that a running Code instance keeps locked, or that was just deleted + writeStderr(`[launch] skipped ${source}: ${(retryError as NodeJS.ErrnoException).code ?? retryError}\n`); + return; + } + } + // Windows copies keep the modification time; elsewhere it is set so that copies can be compared later + if (process.platform !== 'win32') { + const stat = await fs.stat(source); + await fs.utimes(destination, stat.atime, stat.mtime); + } +} + +/** + * Runs `callback` for all items, at most `concurrency` at a time. + */ +export async function forEachConcurrent<T>(items: Iterable<T>, concurrency: number, callback: (item: T) => Promise<unknown>): Promise<void> { + const iterator = items[Symbol.iterator](); + await Promise.all(Array.from({ length: concurrency }, async () => { + for (let next = iterator.next(); !next.done; next = iterator.next()) { + await callback(next.value); + } + })); +} diff --git a/scripts/code-oss-launcher/lib/runDirs.test.ts b/scripts/code-oss-launcher/lib/runDirs.test.ts new file mode 100644 index 00000000000000..eb41e0c42d6dd7 --- /dev/null +++ b/scripts/code-oss-launcher/lib/runDirs.test.ts @@ -0,0 +1,49 @@ +/*--------------------------------------------------------------------------------------------- + * 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 'node:assert/strict'; +import { promises as fs } from 'node:fs'; +import * as path from 'node:path'; +import { test } from 'node:test'; +import { isRunDirInUse } from './runDirs.ts'; + +for (const persistent of [false, true]) { + test(`Windows lock probe restores its directory or reports the recovery path (${persistent})`, { skip: process.platform !== 'win32' }, async t => { + const root = await fs.mkdtemp(path.join(import.meta.dirname, '.run-dirs-test-')); + const runDir = path.join(root, 'run'); + await fs.mkdir(runDir); + await fs.writeFile(path.join(runDir, 'profile'), 'preserve'); + const rename = fs.rename; + let restoreAttempts = 0; + let probe: string | undefined; + const mock = t.mock.method(fs, 'rename', async (...[from, to]: Parameters<typeof fs.rename>) => { + if (to === runDir) { + probe = String(from); + if (++restoreAttempts === 1 || persistent) { + throw new Error('Transient sharing violation'); + } + } + return rename(from, to); + }); + try { + if (persistent) { + await assert.rejects(isRunDirInUse(runDir), error => { + assert.ok(error instanceof AggregateError); + assert.equal(error.errors.length, 3); + assert.ok(error.message.includes(probe!)); + return true; + }); + assert.equal(await fs.readFile(path.join(probe!, 'profile'), 'utf8'), 'preserve'); + } else { + assert.equal(await isRunDirInUse(runDir), false); + assert.equal(restoreAttempts, 2); + assert.equal(await fs.readFile(path.join(runDir, 'profile'), 'utf8'), 'preserve'); + } + } finally { + mock.mock.restore(); + await fs.rm(root, { recursive: true, force: true }); + } + }); +} diff --git a/scripts/code-oss-launcher/lib/runDirs.ts b/scripts/code-oss-launcher/lib/runDirs.ts new file mode 100644 index 00000000000000..eb82adcd0adc10 --- /dev/null +++ b/scripts/code-oss-launcher/lib/runDirs.ts @@ -0,0 +1,358 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Run directories hold the throwaway copies a launch uses. Fresh ones are named +// `<yyyyMMdd-HHmmss>-<random>` and removed once nothing uses them; reused ones are named +// `reuse-<key>` and synced on each launch. `launch-state.json` records which processes use one. + +import { spawnSync } from 'node:child_process'; +import { randomBytes } from 'node:crypto'; +import { promises as fs, realpathSync } from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { setTimeout as delay } from 'node:timers/promises'; + +const STATE_FILE = 'launch-state.json'; +const CLAIM_FILE = 'launch-claim.json'; +const REUSE_PREFIX = 'reuse-'; +const DELETING_MARKER = '.deleting-'; +// A launcher that has held a claim this long is assumed to be gone, whatever its PID says +const CLAIM_TIMEOUT_MS = 10 * 60 * 1000; +// Leaves a fresh run directory alone while the launch that created it may still write its state +const FRESH_GRACE_MS = 2 * 60 * 1000; +const UNUSED_REUSE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; +// Electron's main IPC socket, `<run-dir>/user-data/<version>-main.sock`, must fit the ~103-byte unix socket path limit +const UNIX_SOCKET_PATH_RESERVE = 30 + 'user-data/'.length; + +export interface IRunState { + readonly kind: 'fresh' | 'reuse'; + /** The launcher preparing the directory, until Code is up */ + readonly launcherPid?: number; + /** The Code main process */ + readonly codePid?: number; + readonly lastUsedAt: number; +} + +/** + * Where launches create run directories, in order of preference: + * `CODE_OSS_DEV_RUN_ROOT`; on Windows `<volume>\.code-oss-dev` when the repo is on a Dev Drive + * (ReFS, listed by the PowerShell wrapper in `CODE_OSS_DEV_REFS_VOLUMES`), whose performance-mode + * virus scanning makes copies several times faster; otherwise a folder in the temp directory. + */ +export function getRunRoot(repo: string): string { + if (process.env.CODE_OSS_DEV_RUN_ROOT) { + return path.resolve(process.env.CODE_OSS_DEV_RUN_ROOT); + } + if (process.platform === 'win32') { + const repoVolume = path.parse(path.resolve(repo)).root.toLowerCase(); + const refsVolumes = (process.env.CODE_OSS_DEV_REFS_VOLUMES ?? '').split(';').map(volume => volume.toLowerCase()); + if (refsVolumes.includes(repoVolume)) { + return path.join(path.parse(path.resolve(repo)).root, '.code-oss-dev'); + } + } + return getTempRunRoot(); +} + +/** + * The fallback run root in the temp directory. Long paths, so that run directories appear the same + * in process command lines as in comparisons. + */ +export function getTempRunRoot(): string { + const temp = realpathSync.native(os.tmpdir()); + if (process.platform === 'win32') { + return path.join(temp, 'code-oss-dev'); + } + // Per user, since the temp directory may be shared, as /tmp is on Linux. macOS's default TMPDIR + // is too long for Electron's unix socket below a run directory. + const name = `code-oss-dev-${os.userInfo().uid}`; + const root = path.join(temp, name); + return Buffer.byteLength(root) + '/20261020-120000-xxxxxx/'.length + UNIX_SOCKET_PATH_RESERVE <= 103 ? root : path.join('/tmp', name); +} + +/** + * Creates the run root, private to the current user on POSIX systems. An existing root must belong + * to the current user, since run directories hold copies of authenticated profiles. + */ +async function ensureRunRoot(root: string): Promise<void> { + await fs.mkdir(root, { recursive: true, mode: 0o700 }); + if (process.platform === 'win32') { + return; + } + const stat = await fs.lstat(root); + if (!stat.isDirectory() || stat.uid !== os.userInfo().uid) { + throw new Error(`The run root ${root} must be a directory owned by the current user.`); + } + if ((stat.mode & 0o077) !== 0) { + await fs.chmod(root, 0o700); + } +} + +/** + * All roots a run directory may be in, for validating cleanup requests. + */ +export function isInRunRoot(runDir: string): boolean { + const parent = path.dirname(path.resolve(runDir)); + if (process.env.CODE_OSS_DEV_RUN_ROOT) { + return isSamePath(process.env.CODE_OSS_DEV_RUN_ROOT, parent); + } + const roots = [getTempRunRoot()]; + const isVolumeRoot = process.platform === 'win32' && path.basename(parent) === '.code-oss-dev' && path.dirname(parent) === path.parse(parent).root; + return isVolumeRoot || roots.some(root => isSamePath(root, parent)); +} + +/** + * Creates a new run directory, private to the current user on POSIX systems. + */ +export async function createFreshRunDir(root: string): Promise<string> { + await ensureRunRoot(root); + const now = new Date(); + const pad = (value: number) => String(value).padStart(2, '0'); + const stamp = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}-${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; + const runDir = await fs.mkdtemp(path.join(root, `${stamp}-`)); + await writeState(runDir, { kind: 'fresh', launcherPid: process.pid, lastUsedAt: Date.now() }); + return runDir; +} + +/** + * Claims the reused run directory for `key`, or returns `undefined` when another launch or a + * running Code uses it. The claim must be released with {@link releaseClaim}. + */ +export async function claimReuseRunDir(root: string, key: string): Promise<string | undefined> { + const runDir = path.join(root, `${REUSE_PREFIX}${key}`); + await ensureRunRoot(root); + await fs.mkdir(runDir, { recursive: true, mode: 0o700 }); + const claimFile = path.join(runDir, CLAIM_FILE); + try { + await fs.writeFile(claimFile, JSON.stringify({ pid: process.pid, at: Date.now() }), { flag: 'wx' }); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'EEXIST' || await isClaimActive(runDir)) { + return undefined; + } + // A launch that ended without releasing its claim + await fs.rm(claimFile, { force: true }); + return claimReuseRunDir(root, key); + } + if (await isCodeRunningIn(runDir)) { + await releaseClaim(runDir); + return undefined; + } + return runDir; +} + +export async function releaseClaim(runDir: string): Promise<void> { + await fs.rm(path.join(runDir, CLAIM_FILE), { force: true }); +} + +export async function readState(runDir: string): Promise<IRunState | undefined> { + try { + return JSON.parse(await fs.readFile(path.join(runDir, STATE_FILE), 'utf8')); + } catch { + return undefined; + } +} + +export async function writeState(runDir: string, state: IRunState): Promise<void> { + await fs.writeFile(path.join(runDir, STATE_FILE), JSON.stringify(state)); +} + +/** + * Whether a launch is preparing the run directory or Code runs in it. + */ +export async function isRunDirInUse(runDir: string): Promise<boolean> { + if (await isClaimActive(runDir)) { + return true; + } + const state = await readState(runDir); + if (state?.launcherPid !== undefined && state.launcherPid !== process.pid && isProcessAlive(state.launcherPid) && Date.now() - state.lastUsedAt < CLAIM_TIMEOUT_MS) { + return true; + } + return isCodeRunningIn(runDir); +} + +async function isCodeRunningIn(runDir: string): Promise<boolean> { + if (process.platform === 'win32') { + // Running Code keeps files below the run directory open, which makes renaming it fail. + // Unlike a PID check, this is immune to PID reuse and also works without a state file. + return !(await canRename(runDir)); + } + const state = await readState(runDir); + return state?.codePid !== undefined && isCodeProcessOf(runDir, state.codePid); +} + +/** + * The `--user-data-dir` argument launches pass for a run directory, in each spelling the directory + * may have in a command line. + */ +function getUserDataArguments(runDir: string): string[] { + const spellings = new Set([path.resolve(runDir)]); + try { + spellings.add(realpathSync.native(runDir)); + } catch { + // Already gone + } + return [...spellings].map(spelling => `--user-data-dir=${path.join(spelling, 'user-data')}`); +} + +function matchesUserDataArgument(commandLine: string, runDir: string): boolean { + const flags = process.platform === 'win32' ? 'i' : ''; + return getUserDataArguments(runDir).some(argument => new RegExp(`(?:^|[\\s"])${escapeRegExp(argument)}(?=["\\s]|$)`, flags).test(commandLine)); +} + +/** + * Stops only the process tree whose command line names this run's exact profile directory. + */ +export function stopCodeProcesses(runDir: string, codePid: number | undefined): boolean { + if (process.platform === 'win32') { + const pids = findCodeProcesses(runDir); + for (const pid of pids) { + spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' }); + } + return pids.length > 0; + } + if (codePid === undefined || !isCodeProcessOf(runDir, codePid)) { + return false; + } + try { + // Both detached and managed POSIX launches have a private process group. + process.kill(-codePid, 'SIGTERM'); + return true; + } catch { + try { + process.kill(codePid, 'SIGTERM'); + return true; + } catch { + return false; + } + } +} + +function escapeRegExp(value: string): string { + return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Whether `pid` is a process of a launch in `runDir`, judged by its exact `--user-data-dir` + * argument. A recorded PID alone is not enough: once Code exits, the PID may be reused by an + * unrelated process. + */ +export function isCodeProcessOf(runDir: string, pid: number): boolean { + if (!isProcessAlive(pid)) { + return false; + } + if (process.platform === 'win32') { + return findCodeProcesses(runDir).includes(pid); + } + const result = spawnSync('ps', ['-o', 'args=', '-p', String(pid)], { encoding: 'utf8' }); + return result.status === 0 && matchesUserDataArgument(result.stdout, runDir); +} + +/** + * The processes started with the profile in `runDir` on Windows: Code and its helper processes. + */ +export function findCodeProcesses(runDir: string): number[] { + if (process.platform !== 'win32') { + throw new Error('findCodeProcesses is only implemented on Windows'); + } + const script = `Get-CimInstance Win32_Process -Filter "CommandLine like '%--user-data-dir=%'" | ForEach-Object { "$($_.ProcessId)\`t$($_.CommandLine)" }`; + const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `[Console]::OutputEncoding = [Text.Encoding]::UTF8; ${script}`], { encoding: 'utf8' }); + return (result.stdout ?? '').split(/\r?\n/).flatMap(line => { + const separator = line.indexOf('\t'); + const pid = Number(line.slice(0, separator)); + return separator > 0 && Number.isInteger(pid) && matchesUserDataArgument(line.slice(separator + 1), runDir) ? [pid] : []; + }); +} + +async function isClaimActive(runDir: string): Promise<boolean> { + try { + const claim: { pid: number; at: number } = JSON.parse(await fs.readFile(path.join(runDir, CLAIM_FILE), 'utf8')); + return claim.pid !== process.pid && isProcessAlive(claim.pid) && Date.now() - claim.at < CLAIM_TIMEOUT_MS; + } catch { + return false; + } +} + +async function canRename(runDir: string): Promise<boolean> { + const probe = `${runDir}.probe-${randomBytes(4).toString('hex')}`; + try { + await fs.rename(runDir, probe); + } catch { + return false; + } + const errors: unknown[] = []; + for (let attempt = 0; attempt < 3; attempt++) { + try { + await fs.rename(probe, runDir); + return true; + } catch (error) { + errors.push(error); + if (attempt < 2) { + await delay(100); + } + } + } + throw new AggregateError(errors, `Cannot restore run directory ${runDir} after checking its lock. Its contents remain at ${probe}; restore that path before retrying.`); +} + +export function isProcessAlive(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + // EPERM: the process exists but belongs to someone else + return (error as NodeJS.ErrnoException).code === 'EPERM'; + } +} + +/** + * Removes a run directory. It is renamed first, so that it disappears at once and a partial + * deletion never leaves a broken run directory behind. + */ +export async function removeRunDir(runDir: string): Promise<void> { + const deleting = `${runDir}${DELETING_MARKER}${randomBytes(4).toString('hex')}`; + await fs.rename(runDir, deleting); + await fs.rm(deleting, { recursive: true, force: true, maxRetries: 5 }); +} + +/** + * Removes abandoned run directories: fresh ones nothing uses any more, reused ones unused for a week, + * and leftovers of interrupted removals. + */ +export async function collectGarbage(root: string): Promise<string[]> { + const removed: string[] = []; + const entries = await fs.readdir(root, { withFileTypes: true }).catch(() => []); + for (const entry of entries) { + if (!entry.isDirectory()) { + continue; + } + const runDir = path.join(root, entry.name); + try { + if (entry.name.includes(DELETING_MARKER)) { + await fs.rm(runDir, { recursive: true, force: true, maxRetries: 5 }); + removed.push(runDir); + continue; + } + const state = await readState(runDir); + if (!state) { + continue; + } + const lastUsedAt = state?.lastUsedAt ?? (await fs.stat(runDir)).mtimeMs; + const maxAge = entry.name.startsWith(REUSE_PREFIX) ? UNUSED_REUSE_MAX_AGE_MS : FRESH_GRACE_MS; + // Without a state file only Windows can tell whether Code uses the directory + if (Date.now() - lastUsedAt < maxAge || await isRunDirInUse(runDir)) { + continue; + } + await removeRunDir(runDir); + removed.push(runDir); + } catch { + // Became busy, or is being removed by another collection + } + } + return removed; +} + +function isSamePath(a: string, b: string): boolean { + const normalize = (value: string) => process.platform === 'linux' ? path.resolve(value) : path.resolve(value).toLowerCase(); + return normalize(a) === normalize(b); +} diff --git a/scripts/code-oss-launcher/lib/settings.test.ts b/scripts/code-oss-launcher/lib/settings.test.ts new file mode 100644 index 00000000000000..a178196c22e62e --- /dev/null +++ b/scripts/code-oss-launcher/lib/settings.test.ts @@ -0,0 +1,47 @@ +/*--------------------------------------------------------------------------------------------- + * 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 'node:assert/strict'; +import { promises as fs } from 'node:fs'; +import * as path from 'node:path'; +import { test } from 'node:test'; +import { updateLaunchSettings } from './settings.ts'; + +test('prepares JSONC settings without changing the source profile', async () => { + const root = await fs.mkdtemp(path.join(import.meta.dirname, '.settings-test-')); + try { + const source = path.join(root, 'source.json'); + const destination = path.join(root, 'settings.json'); + const original = '{\n// retain this comment\n"files.simpleDialog.enable": false,\n"window.title": "old",\n"nested": { "window.title": "unchanged" },\n}\n'; + await fs.writeFile(source, original); + await fs.copyFile(source, destination); + updateLaunchSettings(destination, ' Test $ session\n title ', source); + assert.equal(await fs.readFile(source, 'utf8'), original); + assert.equal(await fs.readFile(destination, 'utf8'), '{\n// retain this comment\n"files.simpleDialog.enable": true,\n"window.title": "Test $ session title${separator}${rootName}${separator}${appName}",\n"nested": { "window.title": "unchanged" },\n}\n'); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +}); + +test('brackets and escaped quotes in string values do not affect root property matching', async () => { + const root = await fs.mkdtemp(path.join(import.meta.dirname, '.settings-test-')); + try { + const destination = path.join(root, 'settings.json'); + const original = { + text: '{ [ \\" nested-looking text', + nested: { 'window.title': 'unchanged } ]' }, + 'window.title': 'old', + }; + await fs.writeFile(destination, JSON.stringify(original)); + updateLaunchSettings(destination, 'New', destination); + assert.deepEqual(JSON.parse(await fs.readFile(destination, 'utf8')), { + ...original, + 'files.simpleDialog.enable': true, + 'window.title': 'New${separator}${rootName}${separator}${appName}', + }); + } finally { + await fs.rm(root, { recursive: true, force: true }); + } +}); diff --git a/scripts/code-oss-launcher/lib/settings.ts b/scripts/code-oss-launcher/lib/settings.ts new file mode 100644 index 00000000000000..e6eb3ee5d2b1dc --- /dev/null +++ b/scripts/code-oss-launcher/lib/settings.ts @@ -0,0 +1,192 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import * as fs from 'node:fs'; + +/** + * Prepares the launched profile's settings for automation: the simple file dialog, which unlike + * the native one can be driven over CDP, and optionally the session title in the window title. + * A settings file that is a link to the source profile's is replaced by a copy first. + */ +export function updateLaunchSettings(settingsFile: string, sessionTitle: string | undefined, sourceSettingsFile: string): void { + const title = sessionTitle?.replace(/\s+/g, ' ').trim().replaceAll('$', '\uFF04'); + + let settingsStat; + try { + settingsStat = fs.lstatSync(settingsFile); + } catch (error) { + if (!(error instanceof Error) || (error as NodeJS.ErrnoException).code !== 'ENOENT') { + throw error; + } + } + + let text; + if (settingsStat) { + if (settingsStat.isSymbolicLink()) { + text = fs.readFileSync(sourceSettingsFile, 'utf8'); + fs.unlinkSync(settingsFile); + } else { + text = fs.readFileSync(settingsFile, 'utf8'); + } + } else { + text = ''; + } + + if (!text.trim()) { + text = '{}\n'; + } + + text = setJsoncProperty(text, 'files.simpleDialog.enable', true, settingsFile); + if (title) { + text = setJsoncProperty( + text, + 'window.title', + `${title}\${separator}\${rootName}\${separator}\${appName}`, + settingsFile + ); + } + + fs.writeFileSync(settingsFile, text); +} + +function setJsoncProperty(text: string, key: string, value: boolean | string, settingsFile: string): string { + const maskedText = maskComments(text); + const properties = findRootProperties(maskedText, key, settingsFile); + const property = properties[properties.length - 1]; + const serializedValue = JSON.stringify(value); + + if (property) { + return text.slice(0, property.valueStart) + serializedValue + text.slice(property.valueEnd); + } + + const firstBrace = maskedText.indexOf('{'); + const lastBrace = maskedText.lastIndexOf('}'); + if (firstBrace === -1 || lastBrace === -1 || firstBrace >= lastBrace) { + throw new Error(`settings.json has no top-level object - refusing to clobber it: ${settingsFile}`); + } + + const lineEnding = text.includes('\r\n') ? '\r\n' : '\n'; + const contents = maskedText.slice(firstBrace + 1, lastBrace).trim(); + const separator = !contents || contents.endsWith(',') ? '' : ','; + const insertion = `${separator}${lineEnding} ${JSON.stringify(key)}: ${serializedValue}${lineEnding}`; + return text.slice(0, lastBrace) + insertion + text.slice(lastBrace); +} + +function findRootProperties(text: string, key: string, settingsFile: string): { valueStart: number; valueEnd: number }[] { + let depth = 0; + const properties: { valueStart: number; valueEnd: number }[] = []; + + for (let index = 0; index < text.length; index++) { + const current = text[index]; + if (current === '{' || current === '[') { + depth++; + continue; + } + if (current === '}' || current === ']') { + depth--; + continue; + } + if (current !== '"') { + continue; + } + + const stringEnd = findStringEnd(text, index, settingsFile); + if (depth === 1 && JSON.parse(text.slice(index, stringEnd)) === key) { + let valueStart = stringEnd; + while (/\s/.test(text[valueStart])) { + valueStart++; + } + if (text[valueStart] === ':') { + valueStart++; + while (/\s/.test(text[valueStart])) { + valueStart++; + } + const valueMatch = /^(?:"(?:\\.|[^"\\\r\n])*"|true|false|null|-?\d+(?:\.\d+)?)/.exec(text.slice(valueStart)); + if (!valueMatch) { + throw new Error(`Unsupported value for ${key} in ${settingsFile}`); + } + properties.push({ valueStart, valueEnd: valueStart + valueMatch[0].length }); + } + } + index = stringEnd - 1; + } + + return properties; +} + +function findStringEnd(text: string, start: number, settingsFile: string): number { + let escaped = false; + for (let index = start + 1; index < text.length; index++) { + if (escaped) { + escaped = false; + } else if (text[index] === '\\') { + escaped = true; + } else if (text[index] === '"') { + return index + 1; + } + } + throw new Error(`Unterminated string in ${settingsFile}`); +} + +function maskComments(text: string): string { + const characters = text.split(''); + let inString = false; + let escaped = false; + let inLineComment = false; + let inBlockComment = false; + + for (let index = 0; index < characters.length; index++) { + const current = characters[index]; + const next = characters[index + 1]; + + if (inLineComment) { + if (current === '\n') { + inLineComment = false; + } else if (current !== '\r') { + characters[index] = ' '; + } + continue; + } + + if (inBlockComment) { + if (current === '*' && next === '/') { + characters[index] = ' '; + characters[index + 1] = ' '; + index++; + inBlockComment = false; + } else if (current !== '\r' && current !== '\n') { + characters[index] = ' '; + } + continue; + } + + if (inString) { + if (escaped) { + escaped = false; + } else if (current === '\\') { + escaped = true; + } else if (current === '"') { + inString = false; + } + continue; + } + + if (current === '"') { + inString = true; + } else if (current === '/' && next === '/') { + characters[index] = ' '; + characters[index + 1] = ' '; + index++; + inLineComment = true; + } else if (current === '/' && next === '*') { + characters[index] = ' '; + characters[index + 1] = ' '; + index++; + inBlockComment = true; + } + } + + return characters.join(''); +} diff --git a/scripts/code-oss-launcher/managed.test.ts b/scripts/code-oss-launcher/managed.test.ts new file mode 100644 index 00000000000000..5ca297e32f726f --- /dev/null +++ b/scripts/code-oss-launcher/managed.test.ts @@ -0,0 +1,217 @@ +/*--------------------------------------------------------------------------------------------- + * 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 'node:assert/strict'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { once } from 'node:events'; +import { existsSync, promises as fs } from 'node:fs'; +import { stripTypeScriptTypes } from 'node:module'; +import * as path from 'node:path'; +import { test } from 'node:test'; + +const launcher = path.join(import.meta.dirname, 'launch.ts'); +const cleanup = path.join(import.meta.dirname, 'cleanup', 'cleanup.ts'); + +interface IReadiness { + readonly pid: number; + readonly runDir: string; + readonly userDataDir: string; + readonly sharedDataDir: string; + readonly extensionsDir: string; + readonly cdpPort: number; +} + +interface ILaunch { + readonly child: ChildProcess; + readonly exited: Promise<number | null>; + readonly ready: Promise<IReadiness>; + readonly startedFile: string; + readonly readyFile: string; + readonly exitFile: string; + readonly stdout: () => string; + readonly stderr: () => string; +} + +test('managed launcher readiness, lifetime, isolation, forwarding and exact-run cleanup', { timeout: 120_000 }, async t => { + const root = await fs.mkdtemp(path.join(import.meta.dirname, '.managed-test-')); + const repo = path.join(root, 'repo'); + const source = path.join(root, 'source'); + const shared = path.join(root, 'shared'); + const runRoot = path.join(root, 'runs'); + const env: NodeJS.ProcessEnv = { ...process.env, CODE_OSS_DEV_RUN_ROOT: runRoot, CODE_OSS_DEV_AUTHED_SHARED_DATA_DIR: shared, CODE_OSS_DEV_REUSE: '0' }; + delete env.CODE_OSS_DEV_SCRIPT_ARGS; + delete env.CODE_OSS_DEV_STDOUT_FILE; + delete env.CODE_OSS_DEV_STDERR_FILE; + const launches: ILaunch[] = []; + + async function start(name: string, extra: string[] = []): Promise<ILaunch> { + const startedFile = path.join(root, `${name}.started.json`); + const readyFile = path.join(root, `${name}.ready`); + const exitFile = path.join(root, `${name}.exit`); + const child = spawn(process.execPath, [launcher, '--repo', repo, '--wait', '--skip-prelaunch', '--session-title', 'Managed $ test', '--disable-workspace-trust', '--source-user-data-dir', source, '--', + `--fixture-started=${startedFile}`, `--fixture-ready=${readyFile}`, `--fixture-exit=${exitFile}`, ...extra, '--extensionDevelopmentPath=extension & 100% with spaces', 'workspace with spaces'], { env, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; + let stderr = ''; + child.stderr!.on('data', chunk => { stderr += chunk; }); + const exited = once(child, 'exit').then(([code]) => code as number | null); + const ready = new Promise<IReadiness>((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`Readiness timed out: ${stderr}`)), 30_000); + timer.unref(); + child.once('error', reject); + child.stdout!.on('data', chunk => { + stdout += chunk; + if (stdout.includes('\n')) { + clearTimeout(timer); + try { + resolve(JSON.parse(stdout.trim())); + } catch (error) { + reject(error); + } + } + }); + void exited.then(code => { + clearTimeout(timer); + if (!stdout.includes('\n')) { + reject(new Error(`Launcher exited ${code} before readiness: ${stderr}`)); + } + }); + }); + // Failures before readiness are asserted by the individual test below. + void ready.catch(() => { }); + const launch = { child, exited, ready, startedFile, readyFile, exitFile, stdout: () => stdout, stderr: () => stderr }; + launches.push(launch); + return launch; + } + + async function stop(runDir: string): Promise<{ removed: boolean }> { + const child = spawn(process.execPath, [cleanup, runDir], { env, stdio: ['ignore', 'pipe', 'pipe'] }); + let stdout = ''; + let stderr = ''; + child.stdout!.on('data', chunk => { stdout += chunk; }); + child.stderr!.on('data', chunk => { stderr += chunk; }); + const [code] = await once(child, 'exit'); + assert.equal(code, 0, stderr); + return JSON.parse(stdout); + } + + try { + await fs.mkdir(path.join(repo, 'scripts'), { recursive: true }); + await fs.writeFile(path.join(repo, 'product.json'), JSON.stringify({ nameShort: 'Code', sharedDataFolderName: '.unused' })); + await fs.writeFile(path.join(repo, 'index.js'), stripTypeScriptTypes( + await fs.readFile(path.join(import.meta.dirname, 'fixtures', 'fakeCode.ts'), 'utf8'), + )); + if (process.platform === 'win32') { + await fs.mkdir(path.join(repo, '.build', 'electron'), { recursive: true }); + await fs.writeFile(path.join(repo, 'scripts', 'code.bat'), ''); + await fs.copyFile(process.execPath, path.join(repo, '.build', 'electron', 'Code.exe')); + } else { + const quote = (value: string) => `'${value.replaceAll('\'', '\'\\\'\'')}'`; + await fs.writeFile(path.join(repo, 'scripts', 'code.sh'), `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(path.join(repo, 'index.js'))} "$@"\n`, { mode: 0o755 }); + } + for (const [relative, content] of Object.entries({ + 'User/settings.json': '{"editor.fontSize": 14}', + 'User/globalStorage/state.vscdb': 'synthetic auth state', + 'Local State': 'synthetic encryption state', + 'machineid': 'synthetic machine', + 'Network/Cookies': 'synthetic cookie', + 'logs/old.log': 'excluded', + })) { + await fs.mkdir(path.dirname(path.join(source, relative)), { recursive: true }); + await fs.writeFile(path.join(source, relative), content); + } + await fs.mkdir(shared, { recursive: true }); + await fs.writeFile(path.join(shared, 'seed'), 'synthetic shared state'); + + await t.test('emits one readiness record only after CDP and waits for the application exit code', async () => { + const launch = await start('lifetime'); + await waitUntil(() => existsSync(launch.startedFile)); + assert.equal(launch.stdout(), ''); + assert.equal(launch.child.exitCode, null); + await fs.writeFile(launch.readyFile, ''); + const record = await launch.ready; + assert.notEqual(record.userDataDir, source); + assert.equal(path.dirname(record.runDir), runRoot); + assert.equal(await fs.readFile(path.join(record.userDataDir, 'Network', 'Cookies'), 'utf8'), 'synthetic cookie'); + assert.equal(existsSync(path.join(record.userDataDir, 'logs', 'old.log')), false); + assert.equal(await fs.readFile(path.join(source, 'User', 'settings.json'), 'utf8'), '{"editor.fontSize": 14}'); + const settings = JSON.parse(await fs.readFile(path.join(record.userDataDir, 'User', 'settings.json'), 'utf8')); + assert.equal(settings['files.simpleDialog.enable'], true); + assert.equal(settings['window.title'], 'Managed $ test${separator}${rootName}${separator}${appName}'); + const args: string[] = JSON.parse(await fs.readFile(launch.startedFile, 'utf8')); + assert.ok(args.includes('--disable-workspace-trust')); + assert.ok(args.includes('--extensionDevelopmentPath=extension & 100% with spaces')); + assert.equal(args.at(-1), 'workspace with spaces'); + assert.equal(launch.child.exitCode, null); + assert.equal(launch.stdout().trim().split('\n').length, 1); + if (process.platform === 'win32') { + assert.equal(await fs.readFile(path.join(record.sharedDataDir, 'seed'), 'utf8'), 'synthetic shared state'); + } + await fs.writeFile(launch.exitFile, ''); + assert.equal(await launch.exited, 23, launch.stderr()); + assert.deepStrictEqual(await stop(record.runDir), { runDir: record.runDir, stopped: false, removed: true }); + assert.equal(existsSync(record.runDir), false); + }); + + await t.test('cleanup stops only the named run while another managed launch remains alive', async () => { + const first = await start('first'); + const second = await start('second'); + await fs.writeFile(first.readyFile, ''); + await fs.writeFile(second.readyFile, ''); + const [firstRecord, secondRecord] = await Promise.all([first.ready, second.ready]); + await stop(firstRecord.runDir); + await first.exited; + assert.equal(second.child.exitCode, null); + process.kill(secondRecord.pid, 0); + assert.equal(existsSync(secondRecord.userDataDir), true); + await stop(secondRecord.runDir); + await second.exited; + }); + + await t.test('early application exit fails without emitting readiness JSON', async () => { + const launch = await start('early', ['--fixture-exit-before-ready']); + await assert.rejects(launch.ready, /before readiness/); + assert.equal(await launch.exited, 1); + assert.equal(launch.stdout(), ''); + }); + + await t.test('does not permit forwarded arguments to override run isolation', async () => { + const launch = await start('override', ['--user-data-dir=somewhere-else']); + await assert.rejects(launch.ready, /launcher owns --user-data-dir/); + assert.equal(await launch.exited, 2); + assert.equal(existsSync(launch.startedFile), false); + }); + + await t.test('cleanup refuses an unrelated directory even inside the run root', async () => { + const unrelated = path.join(runRoot, 'unrelated'); + await fs.mkdir(unrelated, { recursive: true }); + await fs.writeFile(path.join(unrelated, 'keep'), 'not launcher-owned'); + const child = spawn(process.execPath, [cleanup, unrelated], { env, stdio: ['ignore', 'pipe', 'pipe'] }); + child.stdout!.resume(); + child.stderr!.resume(); + const [code] = await once(child, 'exit'); + assert.equal(code, 2); + assert.equal(await fs.readFile(path.join(unrelated, 'keep'), 'utf8'), 'not launcher-owned'); + }); + } finally { + for (const launch of launches) { + await fs.writeFile(launch.exitFile, ''); + } + for (const launch of launches) { + await Promise.race([launch.exited, new Promise(resolve => setTimeout(resolve, 3000))]); + if (launch.child.exitCode === null && launch.child.signalCode === null) { + launch.child.kill(); + } + } + await fs.rm(root, { recursive: true, force: true, maxRetries: 5 }); + } +}); + +async function waitUntil(predicate: () => boolean): Promise<void> { + const deadline = Date.now() + 20_000; + while (!predicate()) { + assert.ok(Date.now() < deadline, 'Timed out waiting for fake Code OSS to start'); + await new Promise(resolve => setTimeout(resolve, 25)); + } +} diff --git a/scripts/code-oss-launcher/package.json b/scripts/code-oss-launcher/package.json new file mode 100644 index 00000000000000..2e2f0188ae3954 --- /dev/null +++ b/scripts/code-oss-launcher/package.json @@ -0,0 +1,10 @@ +{ + "private": true, + "type": "module", + "engines": { + "node": ">=22.18.0" + }, + "scripts": { + "test": "node --test lib/profileCopy.test.ts lib/settings.test.ts lib/runDirs.test.ts waitForCdp.test.ts managed.test.ts" + } +} diff --git a/scripts/code-oss-launcher/waitForCdp.test.ts b/scripts/code-oss-launcher/waitForCdp.test.ts new file mode 100644 index 00000000000000..899c0addc04f16 --- /dev/null +++ b/scripts/code-oss-launcher/waitForCdp.test.ts @@ -0,0 +1,63 @@ +/*--------------------------------------------------------------------------------------------- + * 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 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { once } from 'node:events'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { test } from 'node:test'; +import { waitForCdp } from './waitForCdp.ts'; + +test('readiness requires a successful CDP version response, not just an HTTP listener', async () => { + let ready = false; + const server = http.createServer((request, response) => { + assert.equal(request.url, '/json/version'); + response.end(ready ? JSON.stringify({ webSocketDebuggerUrl: 'ws://127.0.0.1/devtools/browser/test' }) : '<html>not CDP</html>'); + }); + await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + const port = (server.address() as AddressInfo).port; + assert.deepStrictEqual(await waitForCdp(process.pid, port, 200), { status: 'timeout' }); + ready = true; + const result = await waitForCdp(process.pid, port, 2000); + assert.equal(result.status, 'ready'); + } finally { + await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } +}); + +test('an unresponsive endpoint respects the deadline', async () => { + const server = http.createServer(() => { }); + await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + assert.deepStrictEqual(await waitForCdp(process.pid, (server.address() as AddressInfo).port, 100), { status: 'timeout' }); + } finally { + server.closeAllConnections(); + await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } +}); + +test('reports when the launched process exits before readiness', async () => { + const child = spawn(process.execPath, ['-e', 'process.exit(0)'], { stdio: 'ignore' }); + await once(child, 'exit'); + assert.deepStrictEqual(await waitForCdp(child.pid!, 1, 2000), { status: 'exited' }); +}); + +test('oversized responses are disconnected before the server finishes sending', async () => { + let disconnected = 0; + const server = http.createServer((_request, response) => { + response.on('close', () => disconnected++); + response.write('x'.repeat(65 * 1024)); + }); + await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve)); + try { + assert.deepStrictEqual(await waitForCdp(process.pid, (server.address() as AddressInfo).port, 300), { status: 'timeout' }); + assert.ok(disconnected > 0); + } finally { + server.closeAllConnections(); + await new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } +}); diff --git a/scripts/code-oss-launcher/waitForCdp.ts b/scripts/code-oss-launcher/waitForCdp.ts new file mode 100644 index 00000000000000..9d5eb5a827027f --- /dev/null +++ b/scripts/code-oss-launcher/waitForCdp.ts @@ -0,0 +1,102 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +// Waits until Code OSS's CDP endpoint responds. Imported by the launcher; the standalone command +// `waitForCdp.ts <pid> <port> [timeout-ms]` prints the elapsed milliseconds and +// exits with 0 when ready, 1 on timeout, and 2 when the process exited first. + +import http from 'node:http'; +import process from 'node:process'; + +export type CdpWaitResult = { readonly status: 'ready'; readonly elapsedMs: number } | { readonly status: 'timeout' | 'exited' }; + +export async function waitForCdp(pid: number, port: number, timeoutMs: number): Promise<CdpWaitResult> { + const start = performance.now(); + while (performance.now() - start < timeoutMs) { + if (!isProcessRunning(pid)) { + return { status: 'exited' }; + } + + const remainingMs = timeoutMs - (performance.now() - start); + if (await probe(port, Math.min(200, remainingMs)) && performance.now() - start < timeoutMs && isProcessRunning(pid)) { + return { status: 'ready', elapsedMs: Math.round(performance.now() - start) }; + } + + await new Promise(resolve => setTimeout(resolve, Math.min(100, Math.max(0, timeoutMs - (performance.now() - start))))); + } + return { status: 'timeout' }; +} + +function isProcessRunning(pid: number): boolean { + try { + process.kill(pid, 0); + return true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === 'ESRCH') { + return false; + } + throw error; + } +} + +function probe(port: number, requestTimeoutMs: number): Promise<boolean> { + return new Promise<boolean>(resolve => { + let settled = false; + const finish = (ready: boolean) => { + if (!settled) { + settled = true; + clearTimeout(timer); + request.destroy(); + resolve(ready); + } + }; + const request = http.get({ host: '127.0.0.1', port, path: '/json/version' }, response => { + if (response.statusCode !== 200) { + response.resume(); + finish(false); + return; + } + let body = ''; + response.setEncoding('utf8'); + response.on('data', (chunk: string) => { + body += chunk; + if (body.length > 64 * 1024) { + response.destroy(); + finish(false); + } + }); + response.on('end', () => { + try { + const version: { webSocketDebuggerUrl?: string } = JSON.parse(body); + finish(typeof version?.webSocketDebuggerUrl === 'string' && /^wss?:\/\//.test(version.webSocketDebuggerUrl)); + } catch { + finish(false); + } + }); + response.on('error', () => finish(false)); + }); + const timer = setTimeout(() => finish(false), requestTimeoutMs); + request.on('error', () => finish(false)); + }); +} + +if (import.meta.main) { + const [pidArg, portArg, timeoutArg = '90000'] = process.argv.slice(2); + const pid = Number(pidArg); + const port = Number(portArg); + const timeoutMs = Number(timeoutArg); + + if (!Number.isInteger(pid) || pid <= 0 || !Number.isInteger(port) || port <= 0 || port > 65535 || !Number.isFinite(timeoutMs) || timeoutMs <= 0) { + console.error('Usage: waitForCdp.ts <pid> <port> [timeout-ms]'); + process.exit(3); + } + + const result = await waitForCdp(pid, port, timeoutMs); + if (result.status === 'ready') { + process.stdout.write(String(result.elapsedMs)); + process.exit(0); + } + process.exit(result.status === 'timeout' ? 1 : 2); +} diff --git a/src/vs/base/browser/ui/dialog/dialog.ts b/src/vs/base/browser/ui/dialog/dialog.ts index 31b8f6db77ffca..ca6524df4cfd51 100644 --- a/src/vs/base/browser/ui/dialog/dialog.ts +++ b/src/vs/base/browser/ui/dialog/dialog.ts @@ -477,6 +477,12 @@ export class Dialog extends Disposable { } } + if (focusableElements.length === 0) { + // Nothing to move focus to, so it stays inside the dialog + EventHelper.stop(e, true); + return; + } + // Focus next element (with wrapping) if (evt.equals(KeyCode.Tab) || evt.equals(KeyCode.RightArrow)) { const newFocusedIndex = (focusedIndex + 1) % focusableElements.length; diff --git a/src/vs/base/test/browser/ui/dialog/dialog.test.ts b/src/vs/base/test/browser/ui/dialog/dialog.test.ts index 5bd29321018bda..6e173327c90820 100644 --- a/src/vs/base/test/browser/ui/dialog/dialog.test.ts +++ b/src/vs/base/test/browser/ui/dialog/dialog.test.ts @@ -179,4 +179,33 @@ suite('Dialog', () => { dialog.dispose(); await result; }); + + test('keeps Tab inside a dialog with nothing to focus', async () => { + const container = append(document.body, $('.test-dialog-container')); + disposables.add(toDisposable(() => container.remove())); + const dialog = disposables.add(new Dialog(container, 'Message', [], { + disableDefaultAction: true, + buttonStyles: unthemedButtonStyles, + checkboxStyles: unthemedCheckboxStyles, + inputBoxStyles: unthemedInboxStyles, + dialogStyles: unthemedDialogStyles, + })); + const result = dialog.show(); + + const targetWindow = getWindow(container); + const focused = targetWindow.document.activeElement; + const event = new targetWindow.KeyboardEvent('keydown', { key: 'Tab', keyCode: 9, bubbles: true, cancelable: true }); + focused?.dispatchEvent(event); + + assert.deepStrictEqual({ + activeElement: targetWindow.document.activeElement, + defaultPrevented: event.defaultPrevented, + }, { + activeElement: focused, + defaultPrevented: true, + }); + + dialog.dispose(); + await result; + }); }); diff --git a/src/vs/platform/actionWidget/browser/tabbedActionListWidget.css b/src/vs/platform/actionWidget/browser/tabbedActionListWidget.css index aac3f4aa00738f..d1315e8181249e 100644 --- a/src/vs/platform/actionWidget/browser/tabbedActionListWidget.css +++ b/src/vs/platform/actionWidget/browser/tabbedActionListWidget.css @@ -97,12 +97,19 @@ margin-left: var(--vscode-spacing-size40); } -.action-widget .tabbed-action-list-tabbar .tabbed-action-list-tabbar-action:hover, +.action-widget .tabbed-action-list-tabbar .tabbed-action-list-tabbar-action:hover:not(.disabled), .action-widget .tabbed-action-list-tabbar .tabbed-action-list-tabbar-action.checked { background-color: var(--vscode-toolbar-hoverBackground); color: var(--vscode-foreground); } +/* Follows the checked rule at equal specificity, so a disabled action never looks pressed or interactive. */ +.action-widget .tabbed-action-list-tabbar .tabbed-action-list-tabbar-action.disabled { + background-color: transparent; + color: var(--vscode-disabledForeground); + cursor: default; +} + .action-widget .tabbed-action-list-tabbar .tabbed-action-list-tabbar-action:focus-visible { outline: 1px solid var(--vscode-focusBorder); outline-offset: -1px; diff --git a/src/vs/platform/actionWidget/browser/tabbedActionListWidget.ts b/src/vs/platform/actionWidget/browser/tabbedActionListWidget.ts index fea7a538bb1480..fcfc6a44a3d003 100644 --- a/src/vs/platform/actionWidget/browser/tabbedActionListWidget.ts +++ b/src/vs/platform/actionWidget/browser/tabbedActionListWidget.ts @@ -122,6 +122,8 @@ export interface ITabBarAction { readonly useManagedHover?: boolean; /** When true, the button renders in its pressed state. */ readonly checked?: boolean; + /** When set, the button is disabled and its hover explains why instead of showing {@link tooltip}. */ + readonly disabledReason?: string; run(): void; } @@ -407,10 +409,18 @@ export class TabbedActionListWidget extends Disposable { button.classList.toggle('checked', !!tabAction.checked); button.dataset.id = tabAction.id; button.ariaLabel = tabAction.tooltip; + // `aria-disabled` rather than `disabled`, so the button stays focusable and hoverable to explain why. + const disabledReason = tabAction.disabledReason; + button.classList.toggle('disabled', !!disabledReason); + if (disabledReason) { + button.setAttribute('aria-disabled', 'true'); + button.setAttribute('aria-description', disabledReason); + } + const hover = disabledReason ?? tabAction.tooltip; if (tabAction.useManagedHover) { - renderDisposables.add(this._hoverService.setupManagedHover(getDefaultHoverDelegate('element'), button, tabAction.tooltip)); + renderDisposables.add(this._hoverService.setupManagedHover(getDefaultHoverDelegate('element'), button, hover)); } else { - button.title = tabAction.tooltip; + button.title = hover; } // Only an action with a real on/off state announces as a toggle. A // momentary one would otherwise read as a toggle that is switched off. @@ -420,7 +430,9 @@ export class TabbedActionListWidget extends Disposable { dom.append(button, dom.$(`span${ThemeIcon.asCSSSelector(tabAction.icon)}`)); renderDisposables.add(dom.addDisposableListener(button, dom.EventType.CLICK, e => { dom.EventHelper.stop(e, true); - tabAction.run(); + if (!disabledReason) { + tabAction.run(); + } })); } diff --git a/src/vs/platform/actionWidget/test/browser/tabbedActionListWidget.test.ts b/src/vs/platform/actionWidget/test/browser/tabbedActionListWidget.test.ts index a8ba2fcaad8c0a..984ea206c07150 100644 --- a/src/vs/platform/actionWidget/test/browser/tabbedActionListWidget.test.ts +++ b/src/vs/platform/actionWidget/test/browser/tabbedActionListWidget.test.ts @@ -258,6 +258,48 @@ suite('TabbedActionListWidget', () => { }); }); + test('a disabled tab bar action explains why and does not run', () => { + const { widget } = createWidget(disposables); + const anchor = document.createElement('div'); + document.body.appendChild(anchor); + document.body.style.setProperty('--vscode-toolbar-hoverBackground', 'rgb(1, 2, 3)'); + disposables.add({ dispose: () => { anchor.remove(); document.body.style.removeProperty('--vscode-toolbar-hoverBackground'); } }); + let runs = 0; + widget.show<ITestItem>({ + user: 'test', + anchor, + tabs: [{ id: 'Models' }], + initialTab: 'Models', + tabBarActions: [ + { id: 'add', icon: Codicon.add, tooltip: 'Add Models...', checked: true, disabledReason: 'Not supported here', run: () => runs++ }, + { id: 'search', icon: Codicon.search, tooltip: 'Search Models', checked: true, run: () => { } }, + ], + createActionList: () => ({ items: [] }), + delegate: { onSelect: () => { }, onHide: () => { } }, + }); + const button = document.querySelector<HTMLElement>('[data-id="add"]')!; + button.click(); + assert.deepStrictEqual({ + label: button.getAttribute('aria-label'), + disabled: button.getAttribute('aria-disabled'), + description: button.getAttribute('aria-description'), + title: button.title, + disabledClass: button.classList.contains('disabled'), + checkedBackground: mainWindow.getComputedStyle(button).backgroundColor, + enabledCheckedBackground: mainWindow.getComputedStyle(document.querySelector<HTMLElement>('[data-id="search"]')!).backgroundColor, + runs, + }, { + label: 'Add Models...', + disabled: 'true', + description: 'Not supported here', + title: 'Not supported here', + disabledClass: true, + checkedBackground: 'rgba(0, 0, 0, 0)', + enabledCheckedBackground: 'rgb(1, 2, 3)', + runs: 0, + }); + }); + test('Escape from a Details radio dismisses the entire popup, including retained search', async () => { const { widget, input, selected } = createSearchableWidget(disposables, ['first match', 'second match']); let radio: Radio | undefined; diff --git a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts index 58640780f1cb61..2916f8dd48428c 100644 --- a/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts +++ b/src/vs/platform/agentHost/browser/agentHostProtocolClient.ts @@ -241,6 +241,8 @@ type ClientState = /** Optional configuration for an {@link AgentHostProtocolClient}. */ export interface IAgentHostProtocolClientOptions { + /** Seals relay credentials only after independently authenticating the requested recipient key. */ + readonly sealAuthenticationToken?: (request: IMissionControlCredentialSealingRequest) => Promise<string>; /** Estimator used to suppress watchdog closes while the local event loop is saturated. Defaults to the shared instance. */ readonly loadEstimator?: ILoadEstimator; /** Stable client identity. Generated when omitted. */ @@ -316,6 +318,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect private readonly _channelScheduler = this._register(new MutableDisposable<AgentHostChannelScheduler>()); private _mcpAuthenticationHandler: ((request: IAgentHostMcpAuthenticationRequest) => Promise<boolean>) | undefined; private _authenticationTokenSealer: ((request: IMissionControlCredentialSealingRequest) => Promise<string>) | undefined; + private readonly _trustedAuthenticationTokenSealer: IAgentHostProtocolClientOptions['sealAuthenticationToken']; declare readonly _serviceBrand: undefined; @@ -575,6 +578,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect this._prepareReconnect = options?.prepareReconnect; this._prepareAuthentication = options?.prepareAuthentication; this._resolveInitialAuthentication = options?.resolveInitialAuthentication; + this._trustedAuthenticationTokenSealer = options?.sealAuthenticationToken; this._resolveAdvertisedAuthentication = options?.resolveAdvertisedAuthentication; this._onDispose = options?.onDispose; @@ -2224,9 +2228,12 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect ? 'auth-token' : 'mcp-auth-token'; const encryption = readAgentHostAuthenticationEncryption(root, this._authenticationHandshake, purpose); if (!encryption) { + if (this._isWebPubSubRelay() && this._trustedAuthenticationTokenSealer) { + throw new Error('Mission Control host has no supported credential encryption key.'); + } return params; } - if (this._isWebPubSubRelay()) { + if (this._isWebPubSubRelay() && !this._trustedAuthenticationTokenSealer) { throw new Error('Relay credentials must be sealed using an independently trusted recipient key.'); } return this._sealAuthentication(params, encryption); @@ -2237,7 +2244,7 @@ export class AgentHostProtocolClient extends Disposable implements IAgentConnect private async _sealAuthentication(params: CommandMap['authenticate']['params'], encryption: IAgentHostAuthenticationEncryption): Promise<CommandMap['authenticate']['params']> { try { - const token = await (this._authenticationTokenSealer ?? sealAgentHostCredential)({ + const token = await (this._trustedAuthenticationTokenSealer ?? this._authenticationTokenSealer ?? sealAgentHostCredential)({ token: params.token, resource: params.resource, key: encryption.key, challenge: encryption.challenge, }); if (!/^copilot-sealed\.v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(token)) { diff --git a/src/vs/platform/agentHost/common/agentHostChatMove.ts b/src/vs/platform/agentHost/common/agentHostChatMove.ts index 52f698fbb10039..1d1ac142784513 100644 --- a/src/vs/platform/agentHost/common/agentHostChatMove.ts +++ b/src/vs/platform/agentHost/common/agentHostChatMove.ts @@ -49,8 +49,6 @@ export interface IChatMoveEligibility extends IChatMoveStructuralEligibility { readonly converting: boolean; /** It works in an additional worktree recorded for it that a chat staying in its session also uses ({@link AgentChatMoveRefusal.WorktreeFolder}). */ readonly worktreeFolder: boolean; - /** It or a descendant runs Agent Merge for a folder of its session ({@link AgentChatMoveRefusal.AgentMergeOwner}). */ - readonly agentMergeOwner: boolean; /** Its session's legacy chat catalog can't be converted for now: its conversion is parked ({@link AgentChatMoveRefusal.LegacyCatalog}). */ readonly legacyCatalog: boolean; } @@ -78,7 +76,6 @@ export function isChatMovable(eligibility: IChatMoveEligibility): boolean { && !eligibility.workspaceless && !eligibility.converting && !eligibility.worktreeFolder - && !eligibility.agentMergeOwner && !eligibility.legacyCatalog; } @@ -100,6 +97,7 @@ export const enum AgentChatMoveRefusal { ConversionInProgress = 'conversionInProgress', WorktreeFolder = 'worktreeFolder', Workspaceless = 'workspaceless', + /** Only older hosts: a chat that runs Agent Merge now moves with it. */ AgentMergeOwner = 'agentMergeOwner', DestinationSingleFolder = 'destinationSingleFolder', LegacyCatalog = 'legacyCatalog', diff --git a/src/vs/platform/agentHost/common/agentMerge.ts b/src/vs/platform/agentHost/common/agentMerge.ts index a24371096e1af5..f10d4e5576834c 100644 --- a/src/vs/platform/agentHost/common/agentMerge.ts +++ b/src/vs/platform/agentHost/common/agentMerge.ts @@ -515,6 +515,14 @@ export function agentMergeMergePullRequestDemotedNotice(): string { return localize('agentMerge.notice.mergeDemoted', "Agent Merge changed this pull request, so automatic merging was disabled for this session. Review the changes, then enable it again if you want it merged automatically."); } +/** + * The transcript notice shown when a chat that runs Agent Merge moves into a + * session where another chat already runs it for the same pull request. + */ +export function agentMergeMoveConflictNotice(): string { + return localize('agentMerge.notice.moveConflict', "Agent Merge was turned off for this chat: another chat in this session already runs it for this pull request."); +} + export function readAgentMergeSessionState(values: Record<string, unknown> | undefined, sessionFolderKey?: string): AgentMergeSessionState | undefined { if (sessionFolderKey !== undefined) { const folderState = readAgentMergeFolderState(values, sessionFolderKey, sessionFolderKey); diff --git a/src/vs/platform/agentHost/common/cloudSandboxAgentHost.ts b/src/vs/platform/agentHost/common/cloudSandboxAgentHost.ts index 46e3fc116a8fb6..9b01284891748e 100644 --- a/src/vs/platform/agentHost/common/cloudSandboxAgentHost.ts +++ b/src/vs/platform/agentHost/common/cloudSandboxAgentHost.ts @@ -15,7 +15,7 @@ import { Event } from '../../../base/common/event.js'; import { URI } from '../../../base/common/uri.js'; import { IConfigurationService } from '../../configuration/common/configuration.js'; import { createDecorator } from '../../instantiation/common/instantiation.js'; -import { AgentSession } from './agent.js'; +import { AgentSession, type AuthenticateParams } from './agent.js'; import { RemoteAgentHostsEnabledSettingId } from './remoteAgentHostService.js'; import { IReplayedTaskHistory } from './taskEventReplay.js'; import { SessionStatus } from './state/sessionState.js'; @@ -525,6 +525,8 @@ export interface ICloudSandboxConnectOptions { readonly name: string; /** Local identity that owns this staged user-local connection; never sent to MC. */ readonly accountKey?: string; + /** Recipient keys from this account's environment descriptor, fetched over authenticated HTTPS. */ + readonly trustedEncryptionKeys?: readonly IHostEncryptionKey[]; /** Caller provenance, not a claim about warm or cold compute. */ readonly connectionSource?: 'created' | 'existing'; /** Local task-creation start time for end-to-end provisioning telemetry; never persisted or sent to MC. */ @@ -564,6 +566,9 @@ export interface ICloudSandboxAgentHostService { */ getSealedGitHubToken(environmentId: string): string | undefined; + /** Resolves identity-only authentication for a user-local host; the protocol client seals it for each handshake. */ + resolveUserLocalAuthentication(environmentId: string, resource: string, forceRefresh?: boolean): Promise<AuthenticateParams>; + /** Renew a live connection's sealed credential, rejecting missing or reused envelopes while sharing its refresh and retry budget. */ refreshSealedGitHubToken(environmentId: string): Promise<string | undefined>; } diff --git a/src/vs/platform/agentHost/common/computerUse.ts b/src/vs/platform/agentHost/common/computerUse.ts index 025419c987087d..c74c0ec23c07e1 100644 --- a/src/vs/platform/agentHost/common/computerUse.ts +++ b/src/vs/platform/agentHost/common/computerUse.ts @@ -72,28 +72,30 @@ export type ComputerUsePermissionState = typeof computerUsePermissionStates[numb * - `needsPermissions`: the plugin waits for the user to choose an action. * - `working`: an action was sent and the plugin has not reported its outcome yet. * - `ready`: the plugin verified both permissions and resumed the operation that was waiting. - * - `ended`: the setup closed without readiness; see {@link IComputerUseSetupV1.error}. + * - `ended`: the setup closed without readiness, e.g. because the user declined or the waiting tool call or turn stopped. */ export const computerUseSetupStates = ['needsPermissions', 'working', 'ready', 'ended'] as const; export type ComputerUseSetupState = typeof computerUseSetupStates[number]; /** - * - `request`: show the native macOS permission prompt for a permission. - * - `openSettings`: open the permission's pane in System Settings. + * - `allow`: get a permission turned on. The first time the host asks for the permission in this Agent Host process, it + * shows the native macOS prompt, which macOS shows only once per app. After that it opens the permission's pane in + * System Settings. The plugin offers the pane only after a native request in its current loop, so in a new loop the + * host first sends a native request that macOS keeps silent, and opens the pane on the plugin's next prompt. * - `recheck`: restart Copilot Computer Use's helper, which some grants need to take effect, and verify again. */ -export const computerUseActions = ['request', 'openSettings', 'recheck'] as const; +export const computerUseActions = ['allow', 'recheck'] as const; export type ComputerUseAction = typeof computerUseActions[number]; /** Actions that must carry {@link IComputerUseRequest.permission}. */ -export const computerUsePermissionActions: readonly ComputerUseAction[] = ['request', 'openSettings']; +export const computerUsePermissionActions: readonly ComputerUseAction[] = ['allow']; export interface IComputerUsePermissionStatusV1 { readonly permission: ComputerUsePermission; readonly state: ComputerUsePermissionState; } -/** An action the plugin accepts for a setup now. */ +/** An action a setup accepts now. */ export interface IComputerUseSetupActionV1 { readonly action: ComputerUseAction; /** Present exactly for {@link computerUsePermissionActions}. */ @@ -114,12 +116,20 @@ export interface IComputerUseSetupV1 { readonly state: ComputerUseSetupState; /** Increments every time the plugin reports the permissions again; requests must name the current round. */ readonly round: number; - /** What the plugin accepts now. Empty unless {@link state} is `needsPermissions`. */ + /** `allow` for each permission the plugin found missing, and `recheck`. Empty unless {@link state} is `needsPermissions`. */ readonly actions: readonly IComputerUseSetupActionV1[]; + /** + * Only `stillNotGranted`: a check the user asked for changed nothing. Clients announce it to screen readers. Ended + * setups carry none. + */ readonly error?: IComputerUseErrorV1; } -/** The action in flight. At most one runs at a time across all setups, because they share one helper and one set of native prompts. */ +/** + * The action in flight: `allow` with its permission while the host has macOS ask for it or opens its System Settings + * pane, `recheck` while the helper verifies again. At most one runs at a time across all setups, because they share one + * helper and one set of native prompts. + */ export interface IComputerUseOperationV1 { readonly setupId: string; readonly action: ComputerUseAction; diff --git a/src/vs/platform/agentHost/node/agentHostChatMovability.ts b/src/vs/platform/agentHost/node/agentHostChatMovability.ts index 3ce0128689ab84..f977b30f52c2b6 100644 --- a/src/vs/platform/agentHost/node/agentHostChatMovability.ts +++ b/src/vs/platform/agentHost/node/agentHostChatMovability.ts @@ -11,7 +11,6 @@ import { URI } from '../../../base/common/uri.js'; import { ChatMoveConfigKey, chatMoveRootConfigSchema, isChatMovable, isChatStructurallyMovable, type IChatMoveStructuralEligibility } from '../common/agentHostChatMove.js'; import type { ISessionStateChange, ISessionStateSnapshot } from '../common/agentHostSessionStateStore.js'; import { getWorkingDirectoryKey } from '../common/agentHostWorkingDirectories.js'; -import { readAgentMergeFolderStates } from '../common/agentMerge.js'; import { readSessionMovable, withSessionMovable } from '../common/meta/agentHostSessionMoveMeta.js'; import { ActionType, type StateAction } from '../common/state/sessionActions.js'; import { ChatOriginKind, isSessionStatusArchived, readSessionWorkspaceless, type ChatSummary, type URI as ProtocolURI } from '../common/state/sessionState.js'; @@ -49,8 +48,6 @@ interface ISourceSessionContext { readonly folders: readonly string[]; /** The additional worktrees the session records, each with the chat it was created for. */ readonly additionalWorktrees: readonly ISessionAdditionalWorktree[]; - /** Chats that run Agent Merge for a folder of the session. */ - readonly agentMergeChats: ReadonlySet<string>; /** The session's chats by resource. */ readonly summaries: Map<ProtocolURI, ChatSummary>; /** The chats working in each scratch folder of the session (by working directory key), built on first use. */ @@ -84,7 +81,6 @@ function subtreeOf(children: ReadonlyMap<ProtocolURI, readonly ProtocolURI[]>, c /** Session actions after which a session's chats may become movable or not. */ const SESSION_INPUT_ACTIONS: ReadonlySet<StateAction['type']> = new Set([ ActionType.SessionIsArchivedChanged, - ActionType.SessionConfigChanged, ActionType.SessionMetaChanged, ActionType.SessionWorkingDirectorySet, ActionType.SessionWorkingDirectoryRemoved, @@ -313,7 +309,6 @@ export class AgentHostChatMovability extends Disposable { // Worktrees are shared by moves (Block 5): only a chat's own one that a staying chat also uses keeps it (D2). // Asked for another owner, this checks that owner's list, so it may miss D2; `planWorktreeMove` refuses it. worktreeFolder: this._worktreeUsers(context, currentContext).sharedOwnOf(subtree, folders) !== undefined, - agentMergeOwner: [...subtree].some(candidate => context.agentMergeChats.has(candidate)), legacyCatalog: context.legacyCatalog, }); } @@ -456,12 +451,6 @@ export class AgentHostChatMovability extends Disposable { siblings.push(chat.resource); } } - const agentMergeChats = new Set<string>(); - for (const folder of readAgentMergeFolderStates(state.config?.values, folders[0] === undefined ? undefined : getWorkingDirectoryKey(folders[0])).values()) { - if (folder.enabled && folder.chat !== undefined) { - agentMergeChats.add(folder.chat); - } - } return { archived: isSessionStatusArchived(state.status), workspaceless: readSessionWorkspaceless(state._meta), @@ -470,7 +459,6 @@ export class AgentHostChatMovability extends Disposable { legacyCatalog: this._sources.catalogs.isParked(session) && snapshot?.authority !== 2, folders, additionalWorktrees: parseSessionAdditionalWorktrees(snapshot?.values.get(ADDITIONAL_WORKTREES_METADATA_KEY)), - agentMergeChats, summaries: summaries ?? new Map(state.chats.map(chat => [chat.resource, chat])), scratchFolderUsers: undefined, children, diff --git a/src/vs/platform/agentHost/node/agentMergeController.ts b/src/vs/platform/agentHost/node/agentMergeController.ts index 9c8fde92bd7bf7..81db6f854a4da6 100644 --- a/src/vs/platform/agentHost/node/agentMergeController.ts +++ b/src/vs/platform/agentHost/node/agentMergeController.ts @@ -7,7 +7,7 @@ import { RunOnceScheduler, SequencerByKey } from '../../../base/common/async.js' import { CancellationTokenSource } from '../../../base/common/cancellation.js'; import { structuralEquals } from '../../../base/common/equals.js'; import { Emitter, Event } from '../../../base/common/event.js'; -import { Disposable, DisposableMap, DisposableStore, IReference, MutableDisposable, toDisposable } from '../../../base/common/lifecycle.js'; +import { Disposable, DisposableMap, DisposableStore, IDisposable, IReference, MutableDisposable, toDisposable } from '../../../base/common/lifecycle.js'; import { autorun } from '../../../base/common/observable.js'; import { isEqual } from '../../../base/common/resources.js'; import { URI } from '../../../base/common/uri.js'; @@ -20,7 +20,7 @@ import { PullRequestChecks, PullRequestRef, PullRequestSnapshot, PullRequestSubs import { GitHubRequestError, isSamlEnforcementError } from '../../github/common/githubTransport.js'; import { ILogService } from '../../log/common/log.js'; import { getWorkingDirectoryKey } from '../common/agentHostWorkingDirectories.js'; -import { AgentMergeConfiguration, AgentMergeConfigurationChangeScope, AgentMergeDisableReason, AgentMergeFolderState, AgentMergeSessionOverrides, AgentMergeTarget, AGENT_MERGE_UNKNOWN_COMMIT, agentMergeConfigurationChangedNotice, agentMergeDisableReasons, agentMergeDisabledNotice, agentMergeEnabledNotice, agentMergeGateFragments, agentMergeMergePullRequestDemotedNotice, classifyAgentMergeRequiredChecks, evaluateAgentMerge, isAnyAgentMergeEnabled, readAgentMergeFolderState, readAgentMergeFolderStates, readAgentMergeChatInjectedConfigurations, readAgentMergeInjectedConfiguration, resolveMergeMethod, shouldStopMergingAfterAgentChanges, withAgentMergeFolderControllerState, withAgentMergeChatInjectedConfiguration, withAgentMergeFolderState, withAgentMergeInjectedConfiguration, hasAgentMergeFolderControllerState, hasAgentMergeElevation, AgentMergeFolderControllerState, getAgentMergeCheckActivity, getAgentMergeRepairBlockers, hasAgentMergeRepairProgress } from '../common/agentMerge.js'; +import { AgentMergeConfiguration, AgentMergeConfigurationChangeScope, AgentMergeDisableReason, AgentMergeFolderState, AgentMergeSessionOverrides, AgentMergeTarget, AGENT_MERGE_UNKNOWN_COMMIT, agentMergeConfigurationChangedNotice, agentMergeDisableReasons, agentMergeDisabledNotice, agentMergeEnabledNotice, agentMergeGateFragments, agentMergeMergePullRequestDemotedNotice, agentMergeMoveConflictNotice, classifyAgentMergeRequiredChecks, evaluateAgentMerge, isAnyAgentMergeEnabled, readAgentMergeFolderState, readAgentMergeFolderStates, readAgentMergeChatInjectedConfigurations, readAgentMergeInjectedConfiguration, resolveMergeMethod, shouldStopMergingAfterAgentChanges, withAgentMergeFolderControllerState, withAgentMergeChatInjectedConfiguration, withAgentMergeFolderState, withAgentMergeInjectedConfiguration, hasAgentMergeFolderControllerState, hasAgentMergeElevation, AgentMergeFolderControllerState, getAgentMergeCheckActivity, getAgentMergeRepairBlockers, hasAgentMergeRepairProgress } from '../common/agentMerge.js'; import { buildAgentMergePrompt } from '../common/agentMergePrompt.js'; import { IAgentHostGitStateService } from '../common/agentHostGitStateService.js'; import { IAgentHostGitService } from '../common/agentHostGitService.js'; @@ -87,6 +87,9 @@ interface IDeferredWorkflowRerun { } interface IActiveAgentMergeTurnContext extends IAgentMergeTurnContext { + /** Where the repair runs now: a chat that moves takes its repair along (see {@link AgentMergeController.transferFolders}). */ + session: string; + folderKey: string; readonly reviewReplies: Promise<PullRequestReplyAndResolveResult>[]; completing: boolean; } @@ -129,9 +132,10 @@ class AgentMergeRuntime extends Disposable { return this.apiClientReference.value; } + /** Where the folder is monitored now: a chat that moves takes its monitoring along (see {@link AgentMergeController.transferFolders}). */ constructor( - readonly session: string, - readonly folderKey: string, + public session: string, + public folderKey: string, evaluate: () => void, ) { super(); @@ -165,6 +169,9 @@ export class AgentMergeController extends Disposable { private readonly _monitoredSessions = new Set<string>(); private readonly _announcedConfigurations = new Map<string, IAnnouncedAgentMergeConfiguration>(); + /** Folders whose monitoring a move is bringing into their new session, which announces nothing for them. */ + private readonly _arrivingFolders = new Set<string>(); + constructor( private readonly _options: IAgentMergeControllerOptions, @IAgentHostStateManager private readonly _stateManager: AgentHostStateManager, @@ -200,6 +207,10 @@ export class AgentMergeController extends Disposable { } for (const [folderKey, current] of currentStates) { const previous = previousStates.get(folderKey); + // A folder that moved with its chat keeps running as it did: nothing was turned on or chosen afresh. + if (this._arrivingFolders.delete(this._runtimeKey(session, folderKey))) { + continue; + } if (current.enabled && current.target && (!previous?.enabled || !previous.target)) { this._postEnabledNotice(session, folderKey, current); } else { @@ -216,7 +227,7 @@ export class AgentMergeController extends Disposable { if (isAhpChatChannel(envelope.channel) && (envelope.action.type === ActionType.ChatTurnComplete || envelope.action.type === ActionType.ChatTurnCancelled || envelope.action.type === ActionType.ChatError)) { void this._completeTurn(envelope.channel); } else if (envelope.action.type === ActionType.SessionChatRemoved && this._stateManager.chatRemovalReason(envelope.channel, envelope.action.chat) === ChatRemovalReason.Deleted) { - // A deleted chat's turn never reports its end. A moved chat's does; moves refuse Agent Merge owners anyway. + // A deleted chat's turn never reports its end. A moved chat's does, in the session it moved to. void this._completeTurn(envelope.action.chat); } })); @@ -403,6 +414,67 @@ export class AgentMergeController extends Disposable { this._syncSession(session); } + /** + * Moves the monitoring of `folders` from `source` to `target`, whose chats moved there with their Agent Merge: the + * runtime, a repair turn it is running and what it announced carry on in `target`, so the repair keeps running and + * nothing is announced again. An evaluation in progress in `source` finds its runtime moved and stops; the next one + * runs in `target` once it has. The folders in `conflicts` stay behind, as `target` already monitors their pull + * request: the chat that ran it is told, and their monitoring stops as `source` publishes them off, without the + * generic notice. Runs synchronously right before the sessions' new configuration is published; the returned + * disposable is disposed right after. + */ + transferFolders(source: string, target: string, folders: readonly string[], conflicts: readonly { readonly folderKey: string; readonly chat: string }[]): IDisposable { + for (const { folderKey, chat } of conflicts) { + const key = this._runtimeKey(source, folderKey); + this._logService.info(`[AgentMergeController] Turning Agent Merge off for a moved chat whose new session already runs it for the pull request: session=${source}, target=${target}, folder=${folderKey}`); + this._monitoredSessions.delete(key); + this._announcedConfigurations.delete(key); + try { + this._options.postNotice(chat, AgentSystemNotificationKind.AgentMergeDisabled, agentMergeMoveConflictNotice()); + } catch (error) { + this._logService.warn(`[AgentMergeController] Failed to post an Agent Merge notice: chat=${chat}`, error); + } + } + const arriving: string[] = []; + for (const folderKey of folders) { + const from = this._runtimeKey(source, folderKey); + const to = this._runtimeKey(target, folderKey); + if (this._runtimes.has(to)) { + this._logService.warn(`[AgentMergeController] Not moving monitoring into a folder that is already monitored: session=${source}, target=${target}, folder=${folderKey}`); + continue; + } + arriving.push(to); + this._arrivingFolders.add(to); + const runtime = this._runtimes.deleteAndLeak(from); + if (runtime) { + runtime.session = target; + this._runtimes.set(to, runtime); + // Its next evaluation waits for the one still running in `source`, which stops as its runtime moved. + void this._evaluations.queue(to, () => this._evaluations.queue(from, async () => { })); + } + const turn = this._activeTurns.get(from); + if (turn) { + this._activeTurns.delete(from); + turn.session = target; + this._activeTurns.set(to, turn); + } + if (this._monitoredSessions.delete(from)) { + this._monitoredSessions.add(to); + } + const announced = this._announcedConfigurations.get(from); + if (announced) { + this._announcedConfigurations.delete(from); + this._announcedConfigurations.set(to, announced); + } + this._logService.info(`[AgentMergeController] Moved folder monitoring with its chat: session=${source}, target=${target}, folder=${folderKey}, runtime=${runtime !== undefined}, repairTurn=${turn !== undefined}`); + } + return toDisposable(() => { + for (const key of arriving) { + this._arrivingFolders.delete(key); + } + }); + } + /** * The repair turn `chat` is running, if any. Only the chat running the * repair gets its authorization: other chats working in the same folder @@ -586,7 +658,7 @@ export class AgentMergeController extends Disposable { runtime.deferredWorkflowReruns.clear(); } if (!runtime) { - runtime = new AgentMergeRuntime(session, folderKey, () => this._queueEvaluation(key)); + const created: AgentMergeRuntime = runtime = new AgentMergeRuntime(session, folderKey, () => this._queueEvaluation(this._runtimeKey(created.session, created.folderKey))); this._runtimes.set(key, runtime); if (chat) { this._captureRuntimeCredentials(runtime, chat); @@ -1524,10 +1596,15 @@ export class AgentMergeController extends Disposable { const result = await runtime.client.mutations.merge(preparation, { method, authorization }, runtime.abortController.signal); this._logService.info(`[AgentMergeController] Pull request merged natively: session=${session}, method=${method}, outcome=${result.outcome}`); const mergedPullRequest = preparation.snapshot.core.value!; + // Where the folder is monitored now: its chat may have moved while the merge ran, taking its monitoring along. + if (!this._isCurrentRuntime(this._runtimeKey(runtime.session, runtime.folderKey), runtime)) { + return; + } + const mergedState = this._stateManager.getSessionState(runtime.session); this._disable( - session, + runtime.session, runtime.folderKey, - currentState, + readAgentMergeFolderState(mergedState?.config?.values, runtime.folderKey, this._sessionFolderKey(mergedState)) ?? currentState, agentMergeDisableReasons.pullRequestMerged(mergedPullRequest.number, mergedPullRequest.url), AgentSystemNotificationKind.AgentMergePullRequestMerged, ); @@ -1547,13 +1624,16 @@ export class AgentMergeController extends Disposable { } return; } - const [key, context] = entry; + const context = entry[1]; if (context.completing) { return; } context.completing = true; + // Read where the repair runs once its replies settled: the chat may have moved meanwhile, taking it along. + let key = entry[0]; try { const replies = await Promise.allSettled(context.reviewReplies); + key = this._runtimeKey(context.session, context.folderKey); const folder = { sessionUri: context.session, folderKey: context.folderKey }; const session = context.session; const state = this._stateManager.getSessionState(session); @@ -1600,8 +1680,9 @@ export class AgentMergeController extends Disposable { } this._schedule(key, 0); } finally { - if (this._activeTurns.get(key) === context) { - this._activeTurns.delete(key); + const current = this._findActiveTurnEntry(context.chat); + if (current?.[1] === context) { + this._activeTurns.delete(current[0]); } } } diff --git a/src/vs/platform/agentHost/node/agentService.ts b/src/vs/platform/agentHost/node/agentService.ts index 3685965663629f..a9d0fdf7a2f44a 100644 --- a/src/vs/platform/agentHost/node/agentService.ts +++ b/src/vs/platform/agentHost/node/agentService.ts @@ -86,7 +86,7 @@ import { IAgentHostSessionStateStore, type ISessionStateChatMove, type ISessionS import { getSessionStateValueKey } from './agentHostSessionStateMirror.js'; import { IAgentHostGitService, META_DIFF_BASE_BRANCH, resolveDefaultBaseBranchName, tryResolvePrimaryWorktreeRoot } from '../common/agentHostGitService.js'; import { getChatsInUse } from './agentHostChatsInUse.js'; -import { resolveBranchChangesetScopeForOwner, resolveBranchChangesetScopeForSource, resolveChangesetOwnerScope, resolveGitHubStateFolder } from './agentHostBranchChangesetScope.js'; +import { resolveAgentMergeOwningChat, resolveBranchChangesetScopeForOwner, resolveBranchChangesetScopeForSource, resolveChangesetOwnerScope, resolveGitHubStateFolder } from './agentHostBranchChangesetScope.js'; import { IAgentHostSubscriptionService, resolveAgentHostSession } from '../common/agentHostSubscriptionService.js'; import { deriveLegacyDefaultChat } from '../common/agentHostLegacyDefaultChat.js'; import { IAgentHostChatOwnershipService, usesStandardSessionUris, type IChatOwnerResolution } from './agentHostChatOwnershipService.js'; @@ -144,7 +144,7 @@ import { AgentHostLaunchKind, createUnknownAgentHostClientTelemetryContext, type import { IAgentHostGitHubEndpointService } from './agentHostGitHubEndpointService.js'; import { AgentMergeController, type IAgentMergeControllerOptions } from './agentMergeController.js'; import { AgentHostChatMovability, chatSubtree } from './agentHostChatMovability.js'; -import { getNonMergeSessionConfigValues, isAnyAgentMergeEnabled, mergeClientAgentMergeFolders, readAgentMergeChatInjectedConfigurations, readAgentMergeInjectedConfiguration, withoutAgentMergeElevation, readAgentMergeFolderStates } from '../common/agentMerge.js'; +import { getNonMergeSessionConfigValues, isAnyAgentMergeEnabled, mergeClientAgentMergeFolders, readAgentMergeChatInjectedConfigurations, readAgentMergeInjectedConfiguration, withoutAgentMergeElevation, readAgentMergeFolderStates, withAgentMergeChatInjectedConfiguration, withAgentMergeFolderState, readAgentMergeSessionState } from '../common/agentMerge.js'; import { isAgentMergeEnabled } from './agentMergeConfiguration.js'; import { readChatSandboxState, withChatSandboxState } from '../common/meta/agentSandboxStateMeta.js'; import { AgentChatMoveRefusal, AgentChatMoveRefusedError, ChatMoveConfigKey, chatMoveRootConfigSchema, type AgentChatMoveDestination } from '../common/agentHostChatMove.js'; @@ -469,13 +469,32 @@ function getPullRequestSessionGitHubState(session: URI, config: Record<string, u return { owner: pullRequest.owner, repo: pullRequest.repo, ...withMostRecentRelatedSessionPullRequest(undefined, pullRequestUrl, branchName) }; } -const HOST_OWNED_SESSION_CONFIG_KEYS = [ +/** Every session config value Agent Merge keeps: its settings, lifecycle state and elevation, current and of older builds. */ +const AGENT_MERGE_SESSION_CONFIG_KEYS = [ SessionConfigKey.AgentMerge, SessionConfigKey.AgentMergeController, SessionConfigKey.AgentMergeFolders, SessionConfigKey.AgentMergeControllerFolders, SessionConfigKey.AgentMergeInjectedConfiguration, SessionConfigKey.AgentMergeChatInjectedConfiguration, +] as const; + +/** `values` without any of Agent Merge's; see {@link AGENT_MERGE_SESSION_CONFIG_KEYS}. */ +function withoutAgentMergeSessionConfig(values: Readonly<Record<string, unknown>>): Record<string, unknown> { + const result = { ...values }; + for (const key of AGENT_MERGE_SESSION_CONFIG_KEYS) { + delete result[key]; + } + return result; +} + +/** The entries of a config patch that set a value, for a session that has none to remove. */ +function definedValues(patch: Readonly<Record<string, unknown>> | undefined): Record<string, unknown> { + return Object.fromEntries(Object.entries(patch ?? {}).filter(([, value]) => value !== undefined)); +} + +const HOST_OWNED_SESSION_CONFIG_KEYS = [ + ...AGENT_MERGE_SESSION_CONFIG_KEYS, SessionConfigKey.Isolation, SessionConfigKey.Branch, SessionConfigKey.WorktreeBranchPrefix, @@ -897,6 +916,23 @@ interface IMovedChatArtifacts { readonly target: readonly ISessionArtifact[]; } +/** + * The Agent Merge a move or promotion carries. Agent Merge belongs to the chat that turned it on: a folder's goes + * along when that chat moves, with its target, feedback watermark and settings, and nothing else of the source's does. + */ +interface IMovedAgentMerge { + /** The source's config patch: the moved folders are off there. `undefined` when the source ends or keeps all of it. */ + readonly source: Record<string, unknown> | undefined; + /** The destination's config patch: the moved folders' Agent Merge and the elevation of the chats that run it. */ + readonly target: Record<string, unknown>; + /** The folders whose Agent Merge runs on in the destination. */ + readonly folders: readonly string[]; + /** The folders whose Agent Merge stays off, as the destination already runs it for their pull request, and the chat that ran it. */ + readonly conflicts: readonly { readonly folderKey: string; readonly chat: string }[]; + /** The moved chats that keep Agent Merge's elevation: they run it on in the destination. */ + readonly elevated: ReadonlySet<string>; +} + /** * The agent service implementation that runs inside the agent-host utility * process. Dispatches to registered {@link IAgent} instances based @@ -3734,6 +3770,11 @@ export class AgentService extends Disposable implements IAgentService { } this._logService.info(`[AgentService] Restoring Agent-Merge-enabled session for monitoring: ${sessionStr}`); await this.restoreSession(session); + // Indexed with nothing on, as a session left when a chat moved its Agent Merge away and the host stopped before saying so. + const values = this._stateManager.getSessionState(sessionStr)?.config?.values; + if (values && !isAnyAgentMergeEnabled(values, this._sessionFolderKeyOf(sessionStr)) && readAgentMergeSessionState(values)?.enabled !== true) { + this._writeAgentMergeIndex(session, false); + } } catch (err) { this._logService.warn(`[AgentService] Failed to restore Agent-Merge-enabled session ${sessionStr}`, err); } @@ -7815,6 +7856,7 @@ export class AgentService extends Disposable implements IAgentService { const withholdings: IWorktreeWithholding[] = []; let handOver: IWorktreeHandOver | undefined; let movedArtifacts: IMovedChatArtifacts | undefined; + let indexedTarget = false; try { for (const folder of missingFolders) { const prepared = await this.prepareChatWorkingDirectory(target, URI.parse(folder), { isolation: 'folder' }); @@ -7849,14 +7891,8 @@ export class AgentService extends Disposable implements IAgentService { restoreScratchRow = recorded; } } - const config = this._movedChatConfig(sourceKey, targetKey, chatKey); - if (Object.keys(config).length > 0) { - // Persisted before the commit, in the chat's own database: its values in the source don't change by it, and - // a crash after the commit keeps them. A refused move restores the chat's previous values. - const previousConfig = this._stateManager.getChatConfig(chatKey)?.values ?? {}; - await this._sessionStateStore.chatRows.setChatConfig(session, chat, { ...previousConfig, ...config }); - restoreConfig = () => this._sessionStateStore.chatRows.setChatConfig(session, chat, previousConfig); - } + let config: Record<string, unknown> = {}; + let previousConfig: Record<string, unknown> | undefined; // Artifacts recorded meanwhile wait for the move, so the moved chats' artifacts are carried from their current lists. artifactsHold = await SessionArtifacts.hold(this._stateManager, [sourceKey, targetKey]); movedArtifacts = this._movedChatArtifacts(sourceKey, targetKey, chatKey, moved, sessionMove); @@ -7866,6 +7902,29 @@ export class AgentService extends Disposable implements IAgentService { }; // Read when committing, so a retry after importing older-build edits sees the chats and folders they added. const commit = async () => { + // The Agent Merge of the moved chats moves in the same transaction, so no restart finds it in both sessions or in neither. + const agentMerge = this._movedAgentMergeInto(sourceKey, targetKey, moved, sessionMove); + // The chat keeps Agent Merge's elevation only if it runs it on in the target, as this commit decides. + config = this._movedChatConfig(sourceKey, targetKey, chatKey, agentMerge?.elevated.has(chatKey)); + if (Object.keys(config).length > 0) { + // Persisted before the commit, in the chat's own database: its values in the source don't change by it, and + // a crash after the commit keeps them. A refused move restores the chat's previous values. + const previous = previousConfig ??= this._stateManager.getChatConfig(chatKey)?.values ?? {}; + await this._sessionStateStore.chatRows.setChatConfig(session, chat, { ...previous, ...config }); + restoreConfig = () => this._sessionStateStore.chatRows.setChatConfig(session, chat, previous); + } + // A session that ends keeps no copy of its Agent Merge for older builds: writing the target's values drops it. + const endsWithAgentMerge = sessionMove && AGENT_MERGE_SESSION_CONFIG_KEYS.some(key => this._stateManager.getSessionState(sourceKey)?.config?.values[key] !== undefined); + const agentMergeValues = agentMerge || endsWithAgentMerge ? { + source: agentMerge?.source ? { configValues: await this._persistedConfigValuesWith(sourceKey, agentMerge.source) } : {}, + target: (agentMerge && Object.keys(agentMerge.target).length > 0) || endsWithAgentMerge ? { configValues: await this._persistedConfigValuesWith(targetKey, agentMerge?.target ?? {}) } : {}, + } : undefined; + if (agentMerge?.folders.length) { + // Indexed first, so a restart right after the commit resumes monitoring it; a refused move drops it again. + indexedTarget = true; + this._writeAgentMergeIndex(target, true); + await this._agentMergeIndexWrites; + } const sourceFolders = this._stateManager.getSessionSummary(sourceKey)?.workingDirectories ?? []; const inheritedFolders = this._sessionFoldersOfChatWithoutOwn(sourceKey); const folders = { @@ -7887,7 +7946,10 @@ export class AgentService extends Disposable implements IAgentService { folders, coOwnedWorktrees: plan.coOwned, worktreeLists: this._movedWorktreeLists(chatKey, plan, handOver, sessionMove, targetPrimaryWorktree), - values: artifactValues, + values: artifactValues || agentMergeValues ? { + source: { ...artifactValues?.source, ...agentMergeValues?.source }, + target: { ...artifactValues?.target, ...agentMergeValues?.target }, + } : undefined, }; return sessionMove ? this._sessionStateStore.moveSession(move) : this._sessionStateStore.moveChat(move); }; @@ -7912,6 +7974,9 @@ export class AgentService extends Disposable implements IAgentService { // Committed: the co-owner rows keep the branches withheld from now on. withholdings.forEach(withholding => withholding.done()); } catch (error) { + if (indexedTarget) { + this._writeAgentMergeIndex(target, isAnyAgentMergeEnabled(this._stateManager.getSessionState(targetKey)?.config?.values, this._sessionFolderKeyOf(targetKey))); + } await restoreConfig?.().catch(restoreError => this._logService.warn(`[AgentService] Failed to restore the config of ${chatKey} after a refused move`, restoreError)); await restoreScratchRow?.().catch(restoreError => this._logService.warn(`[AgentService] Failed to undo the scratch folder record of ${chatKey} after a refused move`, restoreError)); await this._undoWorktreeMovePreparation(withholdings, handOver, chatKey); @@ -8011,6 +8076,17 @@ export class AgentService extends Disposable implements IAgentService { const preceding = committed.targetOrder.slice(0, Math.max(0, committed.targetOrder.indexOf(chat))); anchor = preceding.reverse().find(candidate => targetChats.has(candidate)); } + const agentMerge = this._beginAgentMergeTransfer(source, target, committed.moved, sessionMove); + try { + this._transferMovedChatsAndState(source, target, chat, committed, anchor, inMemory, sourceMeta, chatFolders, inheritedFolders, sessionMove, artifacts); + agentMerge.publish(); + } finally { + agentMerge.dispose(); + } + } + + /** Moves the committed chats and the state that goes with them in memory; see {@link _transferMovedChats}. */ + private _transferMovedChatsAndState(source: string, target: string, chat: string, committed: IMovedChats, anchor: string | undefined, inMemory: readonly string[], sourceMeta: SessionSummaryMeta | undefined, chatFolders: readonly string[], inheritedFolders: readonly string[] | undefined, sessionMove: boolean, artifacts: IMovedChatArtifacts | undefined): void { if (sessionMove) { // The session ends with the move: its applied sandbox states are read first. const sandboxStates = inMemory.map(candidate => [candidate, readChatSandboxState(this._stateManager.getSessionState(source), candidate)] as const); @@ -8076,12 +8152,141 @@ export class AgentService extends Disposable implements IAgentService { /** * The values a moved chat takes along: its effective value in the source for every property it may set for - * itself in the target. Host-owned (read-only) values are recomputed by the target. + * itself in the target. Host-owned (read-only) values are recomputed by the target. The elevation Agent Merge + * applied stays behind, session-wide and the chat's own, unless the chat runs Agent Merge on in the target + * (`keepsElevation`), which takes its own elevation along. */ - private _movedChatConfig(source: string, target: string, chat: string): Record<string, unknown> { + private _movedChatConfig(source: string, target: string, chat: string, keepsElevation = false): Record<string, unknown> { const schema = this._stateManager.getSessionState(target)?.config?.schema; - const effective = this._configurationService.getChatConfigValues({ session: source, chat }) ?? {}; - return Object.fromEntries(Object.entries(filterChatConfigValues(schema, effective)).filter(([key]) => schema?.properties[key]?.readOnly !== true)); + const sourceValues = this._configurationService.getSessionConfigValues(source) ?? {}; + const sessionValues = withoutAgentMergeElevation(sourceValues, readAgentMergeInjectedConfiguration(sourceValues)); + const values = { ...withoutAgentMergeElevation(this._configurationService.getChatConfigValues({ session: source, chat }) ?? {}, readAgentMergeInjectedConfiguration(sourceValues)) }; + const elevation = keepsElevation ? undefined : readAgentMergeChatInjectedConfigurations(sourceValues).get(chat); + // The values are applied over the chat's own: one it had none of before elevation is removed explicitly. + const removed: Record<string, undefined> = {}; + for (const [key, applied] of Object.entries(elevation?.applied ?? {})) { + if (!equals(values[key], applied)) { + continue; + } + // What the chat used before: its own value, else the session's. + const previous = Object.hasOwn(elevation!.previous, key) ? elevation!.previous[key] : sessionValues[key]; + if (previous === undefined) { + delete values[key]; + removed[key] = undefined; + } else { + values[key] = previous; + } + } + return { ...Object.fromEntries(Object.entries(filterChatConfigValues(schema, values)).filter(([key]) => schema?.properties[key]?.readOnly !== true)), ...removed }; + } + + /** + * The Agent Merge that moves with `moved` from `source` into a session whose config values are `target.values` + * (a promotion's new session's, before it exists); see {@link IMovedAgentMerge}. A folder's Agent Merge moves when + * the chat that runs it moves. Where the destination already runs Agent Merge for the folder or its pull request, + * the destination's is kept and the moved one is off. `undefined` when nothing changes. + */ + private _movedAgentMerge(source: string, target: { readonly values: Readonly<Record<string, unknown>> | undefined; readonly sessionFolderKey: string | undefined }, moved: readonly string[], sessionMove: boolean): IMovedAgentMerge | undefined { + const sourceValues = this._stateManager.getSessionState(source)?.config?.values ?? {}; + const sourceFolderKey = this._sessionFolderKeyOf(source); + const targetStates = readAgentMergeFolderStates(target.values as Record<string, unknown> | undefined, target.sessionFolderKey); + const monitored = new Set([...targetStates.values()].filter(state => state.enabled).map(state => state.target?.pullRequestUrl?.toLowerCase())); + let sourcePatch: Record<string, unknown> = {}; + let targetPatch: Record<string, unknown> = {}; + const folders: string[] = []; + const conflicts: { folderKey: string; chat: string }[] = []; + const elevated = new Set<string>(); + for (const [folderKey, state] of readAgentMergeFolderStates(sourceValues, sourceFolderKey)) { + const owner = resolveAgentMergeOwningChat(this._stateManager, source, folderKey, state.chat); + if (owner === undefined || !moved.includes(owner)) { + continue; + } + if (!sessionMove) { + // Off, with nothing of the chat's: clients never forget a folder's settings, so they see it turned off. + sourcePatch = { ...sourcePatch, ...withAgentMergeFolderState({ ...sourceValues, ...sourcePatch }, folderKey, sourceFolderKey, { enabled: false }) }; + } + const existing = targetStates.get(folderKey); + const pullRequest = state.target?.pullRequestUrl?.toLowerCase(); + if (state.enabled && (existing?.enabled || (pullRequest !== undefined && monitored.has(pullRequest)))) { + conflicts.push({ folderKey, chat: owner }); + continue; + } + if (existing && !state.enabled) { + continue; + } + const { injectedConfiguration: _sessionWide, ...carried } = state; + targetPatch = { ...targetPatch, ...withAgentMergeFolderState({ ...target.values, ...targetPatch }, folderKey, target.sessionFolderKey, { ...carried, chat: owner }) }; + if (state.enabled) { + folders.push(folderKey); + elevated.add(owner); + } + } + const elevations = readAgentMergeChatInjectedConfigurations(sourceValues); + for (const chat of moved) { + const elevation = elevations.get(chat); + if (!elevation) { + continue; + } + if (!sessionMove) { + sourcePatch = { ...sourcePatch, ...withAgentMergeChatInjectedConfiguration({ ...sourceValues, ...sourcePatch }, chat, undefined) }; + } + if (elevated.has(chat)) { + targetPatch = { ...targetPatch, ...withAgentMergeChatInjectedConfiguration({ ...target.values, ...targetPatch }, chat, elevation) }; + } + } + if (Object.keys(sourcePatch).length === 0 && Object.keys(targetPatch).length === 0 && conflicts.length === 0) { + return undefined; + } + return { source: Object.keys(sourcePatch).length > 0 ? sourcePatch : undefined, target: targetPatch, folders, conflicts, elevated }; + } + + /** The Agent Merge that moves with `moved` from `source` into the existing session `target`; see {@link _movedAgentMerge}. */ + private _movedAgentMergeInto(source: string, target: string, moved: readonly string[], sessionMove: boolean): IMovedAgentMerge | undefined { + return this._movedAgentMerge(source, { values: this._stateManager.getSessionState(target)?.config?.values, sessionFolderKey: this._sessionFolderKeyOf(target) }, moved, sessionMove); + } + + /** The key of a session's own folder, which Agent Merge settings of earlier versions describe. */ + private _sessionFolderKeyOf(session: string): string | undefined { + const folder = this._stateManager.getSessionState(session)?.workingDirectories?.[0]; + return folder === undefined ? undefined : getWorkingDirectoryKey(folder); + } + + /** The config values of `session` with `patch` over them, as persisted; see {@link getPersistedSessionConfigValues}. */ + private async _persistedConfigValuesWith(session: string, patch: Record<string, unknown>): Promise<string> { + const persisted = (await this._sessionStateStore.readWithoutImport(URI.parse(session), ['configValues'])).get('configValues'); + return JSON.stringify(getPersistedSessionConfigValues({ ...this._stateManager.getSessionState(session)?.config?.values, ...patch }, this._configurationService.getSessionSandboxEnabled(session), persisted)); + } + + /** + * Moves the monitoring of the Agent Merge that moves with `moved` from `source` to `target` (see + * {@link _movedAgentMerge}), so a repair turn running carries on in `target`. Runs before the chats move in memory, + * which it is computed from; `publish` publishes the sessions' Agent Merge once the chats are in place. Disposed + * right after. + */ + private _beginAgentMergeTransfer(source: string, target: string, moved: readonly string[], sessionMove: boolean): IDisposable & { publish(): void } { + const agentMerge = this._movedAgentMergeInto(source, target, moved, sessionMove); + const transfer = agentMerge && this._agentMergeController.transferFolders(source, target, agentMerge.folders, agentMerge.conflicts); + return { + publish: () => { + if (agentMerge && Object.keys(agentMerge.target).length > 0) { + this._configurationService.updateSessionConfig(target, agentMerge.target); + } + if (agentMerge?.source) { + this._configurationService.updateSessionConfig(source, agentMerge.source); + } + }, + dispose: () => transfer?.dispose(), + }; + } + + /** + * The config values a promoted chat's new session starts with: its source's, with the chat's own values over them. + * Agent Merge belongs to the chat that turned it on, so none of the source's Agent Merge comes along, nor the + * elevation it applied session-wide. + */ + private _promotedSessionConfigValues(sourceValues: Readonly<Record<string, unknown>>, source: string, chat: string): Record<string, unknown> { + const elevation = readAgentMergeInjectedConfiguration(sourceValues as Record<string, unknown>); + return withoutAgentMergeSessionConfig({ ...withoutAgentMergeElevation(sourceValues, elevation), ...this._movedChatConfig(source, source, chat) }); } /** @@ -8219,9 +8424,11 @@ export class AgentService extends Disposable implements IAgentService { let worktreePlan: IWorktreeMoveDecisions; const withholdings: IWorktreeWithholding[] = []; let movedArtifacts: IMovedChatArtifacts | undefined; + let indexedTarget = false; const sourceConfig = this._stateManager.getSessionState(sourceKey)?.config; - // The chat's own values become the new session's: its future chats start from them. - const config: SessionConfigState | undefined = sourceConfig && { schema: sourceConfig.schema, values: { ...sourceConfig.values, ...this._movedChatConfig(sourceKey, sourceKey, chatKey), ...this._promotedIsolationConfig(sourceConfig, session, chatKey, promotedRepository) } }; + const promotedAgentMerge = () => this._movedAgentMerge(sourceKey, { values: undefined, sessionFolderKey: chatFolders[0] === undefined ? undefined : getWorkingDirectoryKey(chatFolders[0]) }, moved, false); + // The chat's own values become the new session's: its future chats start from them. So does the Agent Merge it runs. + const config: SessionConfigState | undefined = sourceConfig && { schema: sourceConfig.schema, values: { ...this._promotedSessionConfigValues(sourceConfig.values, sourceKey, chatKey), ...this._promotedIsolationConfig(sourceConfig, session, chatKey, promotedRepository), ...definedValues(promotedAgentMerge()?.target) } }; try { this._checkMovedChat(sourceKey, chatKey); const current = chatSubtree(this._stateManager, sourceKey, chatKey); @@ -8272,8 +8479,17 @@ export class AgentService extends Disposable implements IAgentService { if (movedArtifacts) { values[SESSION_ARTIFACTS_KEY] = stringifySessionArtifacts(movedArtifacts.target); } - const sourceValues = movedArtifacts && { [SESSION_ARTIFACTS_KEY]: movedArtifacts.source.length > 0 ? stringifySessionArtifacts(movedArtifacts.source) : null }; + const artifactSourceValues = movedArtifacts && { [SESSION_ARTIFACTS_KEY]: movedArtifacts.source.length > 0 ? stringifySessionArtifacts(movedArtifacts.source) : null }; + if (promotedAgentMerge()?.folders.length) { + // Indexed first, so a restart right after the commit resumes monitoring it; a refused promotion drops it again. + indexedTarget = true; + this._writeAgentMergeIndex(target, true); + await this._agentMergeIndexWrites; + } const commit = async () => { + // The Agent Merge of the promoted chats leaves the source in the same transaction. + const agentMergeSource = promotedAgentMerge()?.source; + const sourceValues = agentMergeSource ? { ...artifactSourceValues, configValues: await this._persistedConfigValuesWith(sourceKey, agentMergeSource) } : artifactSourceValues; const inheritedFolders = this._sessionFoldersOfChatWithoutOwn(sourceKey); return this._sessionStateStore.promoteChat({ source: session, @@ -8315,6 +8531,9 @@ export class AgentService extends Disposable implements IAgentService { committed = result.moved; withholdings.forEach(withholding => withholding.done()); } catch (error) { + if (indexedTarget) { + this._writeAgentMergeIndex(target, false); + } await this._undoWorktreeMovePreparation(withholdings, undefined, chatKey); if (error instanceof SessionStateDeletedError) { refuse(AgentChatMoveRefusal.SessionNotReady, error.message); @@ -8407,9 +8626,7 @@ export class AgentService extends Disposable implements IAgentService { throw new Error(`Promoted chat ${chat} is not loaded`); } this._providerService.associateSession(target, provider.id); - const chatSummary = this._stateManager.getSessionState(source)?.chats.find(candidate => candidate.resource === chat); const sourceSummary = this._stateManager.getSessionSummary(source); - const now = new Date().toISOString(); let meta = withSessionExternal(undefined, false); const initiator = readSessionInitiator(sourceSummary); if (initiator) { @@ -8424,6 +8641,37 @@ export class AgentService extends Disposable implements IAgentService { meta = withSessionArtifacts(meta, artifacts.target) ?? meta; this._stateManager.setSessionMeta(source, withSessionArtifacts(sourceMeta, artifacts.source)); } + // Read from memory now: what Agent Merge recorded while the promotion committed, such as its feedback watermark, comes along. + const agentMerge = this._movedAgentMerge(source, { values: undefined, sessionFolderKey: chatFolders[0] === undefined ? undefined : getWorkingDirectoryKey(chatFolders[0]) }, committed, false); + const created = config && agentMerge ? { ...config, values: { ...withoutAgentMergeSessionConfig(config.values), ...definedValues(agentMerge.target) } } : config; + const elevation = agentMerge?.elevated.has(chat) ? readAgentMergeChatInjectedConfigurations(this._stateManager.getSessionState(source)?.config?.values).get(chat) : undefined; + const ownConfig = this._stateManager.getChatConfig(chat)?.values ?? {}; + // The elevation stays the chat's own, so disabling Agent Merge restores it and the session's other chats never start elevated. + const elevated = Object.fromEntries(Object.entries(elevation?.applied ?? {}).filter(([key, value]) => equals(ownConfig[key], value)).map(([key]) => [key, ownConfig[key]])); + const transfer = agentMerge && this._agentMergeController.transferFolders(source, target, agentMerge.folders, agentMerge.conflicts); + try { + this._promoteMovedChatsAndState(provider, source, target, chat, inMemory, chatFolders, created, inheritedFolders, project, meta, elevated); + if (agentMerge) { + if (created) { + // Created with what Agent Merge recorded since the commit, which persisted the values before it. + this._persistConfigValues(URI.parse(target), created.values); + } + if (agentMerge.source) { + this._configurationService.updateSessionConfig(source, agentMerge.source); + } + this._syncAgentMergeIndex(URI.parse(target), undefined, created); + this._agentMergeController.onSessionAvailable(target); + } + } finally { + transfer?.dispose(); + } + } + + /** Creates the promoted session in memory and moves the chats into it; see {@link _promoteMovedChats}. */ + private _promoteMovedChatsAndState(provider: IAgent, source: string, target: string, chat: string, inMemory: readonly string[], chatFolders: readonly string[], config: SessionConfigState | undefined, inheritedFolders: boolean, project: ProjectInfo | undefined, meta: SessionSummaryMeta | undefined, ownConfig: Record<string, unknown>): void { + const chatSummary = this._stateManager.getSessionState(source)?.chats.find(candidate => candidate.resource === chat); + const sourceSummary = this._stateManager.getSessionSummary(source); + const now = new Date().toISOString(); this._stateManager.promoteChats(source, { resource: target, provider: provider.id, @@ -8447,7 +8695,7 @@ export class AgentService extends Disposable implements IAgentService { } if (this._stateManager.getChatConfig(chat) !== undefined) { // Its own values are the new session's now, so the session's later changes reach it. - this._stateManager.dispatchServerAction(chat, { type: ActionType.ChatConfigChanged, config: {}, replace: true }); + this._stateManager.dispatchServerAction(chat, { type: ActionType.ChatConfigChanged, config: ownConfig, replace: true }); } this._sessionResidency.touch(URI.parse(target)); this._changesetCoordinator.onSessionCreated(target); @@ -8727,14 +8975,6 @@ export class AgentService extends Disposable implements IAgentService { if (!sessionMove && this._chatMovability.sharesScratchFolder(chat, sourceKey, chatFolders)) { refuse(AgentChatMoveRefusal.Workspaceless, `Chat ${chat} works in a scratch folder that another chat of ${sourceKey} also uses.`); } - const sourceFolders = this._stateManager.getSessionSummary(sourceKey)?.workingDirectories ?? []; - const sessionFolderKey = sourceFolders[0] === undefined ? undefined : getWorkingDirectoryKey(sourceFolders[0]); - for (const folder of readAgentMergeFolderStates(sourceState.config?.values, sessionFolderKey).values()) { - // A session that moves takes its own Agent Merge along: it stays. - if (folder.enabled && ((folder.chat !== undefined && moved.includes(folder.chat)) || (sessionMove && folder.chat === undefined))) { - refuse(AgentChatMoveRefusal.AgentMergeOwner, `Chat ${chat} runs Agent Merge for a folder of ${sourceKey}.`); - } - } if (target === undefined) { // A new session takes the chat's folders. if (chatFolders.length > 1 && !this._providerService.getProviderForSession(source)?.getDescriptor().capabilities?.multipleWorkingDirectories) { diff --git a/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts b/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts index 5b0420eacd0552..9dcaf85b975062 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts @@ -3173,7 +3173,7 @@ export class CopilotAgentSession extends Disposable { const subagentMeta = toolKind === 'subagent' ? getSubagentMetadata(parameters) : undefined; const clientToolName = this._clientToolName(toolName); const networkRestrictions = this._clientToolNames.has(clientToolName) - ? getCopilotBrowserSandboxNetworkRestrictions(this._configurationService, { session: this.launchOwner.toString(), chat: this._chatChannelUri.toString() }, clientToolName) : undefined; + ? getCopilotBrowserSandboxNetworkRestrictions(this._configurationService, this._configTarget(), clientToolName) : undefined; return { ...(networkRestrictions ? { 'vscode.copilotSandboxNetworkRestrictions': networkRestrictions, @@ -7687,8 +7687,11 @@ export class CopilotAgentSession extends Disposable { } private _configTarget(): IAgentChatConfigurationTarget { - // The running process is configured for its launch owner until the relaunch. - return { session: this.launchOwner.toString(), chat: this._chatChannelUri.toString() }; + // The running process is configured for its launch owner until the relaunch. One that ended by moving under + // another session left its values to the chat, which its current owner has. + const launchOwner = this.launchOwner.toString(); + const session = this._configurationService.getSessionConfigValues(launchOwner) === undefined ? this._ownerSessionUri.toString() : launchOwner; + return { session, chat: this._chatChannelUri.toString() }; } /** @@ -7716,7 +7719,7 @@ export class CopilotAgentSession extends Disposable { && !this._sandbox.isCustomTerminalToolEnabled(); // Session-only by construction: root and parent-session values are // never consulted. - const own = enabled ? this._configurationService.getSessionConfigValues(this.launchOwner.toString())?.[SessionConfigKey.ShellInitScripts] : undefined; + const own = enabled ? this._configurationService.getSessionConfigValues(this._configTarget().session)?.[SessionConfigKey.ShellInitScripts] : undefined; if (own !== undefined && !isShellInitScriptList(own)) { // Keep the last valid registration rather than clearing it. this._logService.warn(`[Copilot:${this.sessionId}] Ignoring malformed shell init script config`); diff --git a/src/vs/platform/agentHost/node/copilot/copilotComputerUsePermissionSetup.ts b/src/vs/platform/agentHost/node/copilot/copilotComputerUsePermissionSetup.ts index 26066d58bcc6b7..2e09292fc7b158 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotComputerUsePermissionSetup.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotComputerUsePermissionSetup.ts @@ -11,7 +11,7 @@ import { hasKey } from '../../../../base/common/types.js'; import { generateUuid } from '../../../../base/common/uuid.js'; import { localize } from '../../../../nls.js'; import { ILogService } from '../../../log/common/log.js'; -import { COMPUTER_USE_REQUEST_KEY, COMPUTER_USE_STATUS_KEY, computerUsePermissions, isComputerUseRequest, type ComputerUseAction, type ComputerUsePermission, type ComputerUsePermissionState, type ComputerUseSetupState, type IComputerUseErrorV1, type IComputerUseSetupActionV1, type IComputerUseStatusV1 } from '../../common/computerUse.js'; +import { COMPUTER_USE_REQUEST_KEY, COMPUTER_USE_STATUS_KEY, computerUsePermissions, isComputerUseRequest, type ComputerUsePermission, type ComputerUsePermissionState, type ComputerUseSetupState, type IComputerUseErrorV1, type IComputerUseSetupActionV1, type IComputerUseStatusV1 } from '../../common/computerUse.js'; import { ChatInputRequestPurpose, withChatInputRequestPurpose } from '../../common/meta/agentChatInputRequestMeta.js'; import { withComputerUseSetupCard } from '../../common/meta/computerUse.js'; import { ChatInputAnswerState, ChatInputAnswerValueKind, ChatInputResponseKind, type ChatInputAnswer, type ChatInputRequest } from '../../common/state/sessionState.js'; @@ -23,7 +23,7 @@ import { IAgentHostMacAccessibilityTrustService } from '../agentHostMacAccessibi /* * While Accessibility or Screen Recording is missing, the plugin's readiness check asks the MCP client, in a loop, to * choose one value of a single required `choice` enum: `request_<slug>` for each missing permission (the native macOS - * prompt), `settings_<slug>` for each one whose native prompt did not grant it (its System Settings pane), and + * prompt), `settings_<slug>` for each one whose native prompt in this loop did not grant it (its System Settings pane), and * `try_again` (restart the helper and verify again). It re-asks after every choice until both are granted, which lets * the waiting tool call continue; declining stops the loop and fails the tool call. Every other prompt of the plugin * comes after this check. See `elicit_macos_permissions` in github/computer-use `src/mcp/src/server.rs`. @@ -44,22 +44,27 @@ export interface IComputerUsePermissionPrompt { readonly settings: ReadonlySet<ComputerUsePermission>; } -function choiceFor(action: ComputerUseAction, permission: ComputerUsePermission | undefined): string | undefined { - switch (action) { - case 'request': return permission && `request_${PERMISSION_SLUGS[permission]}`; - case 'openSettings': return permission && `settings_${PERMISSION_SLUGS[permission]}`; +/** One choice of the plugin's permission prompt: `request_<slug>`, `settings_<slug>` or `try_again`. */ +type PluginAction = + | { readonly kind: 'request' | 'openSettings'; readonly permission: ComputerUsePermission } + | { readonly kind: 'recheck' }; + +function choiceFor(action: PluginAction): string { + switch (action.kind) { + case 'request': return `request_${PERMISSION_SLUGS[action.permission]}`; + case 'openSettings': return `settings_${PERMISSION_SLUGS[action.permission]}`; case 'recheck': return TRY_AGAIN_CHOICE; } } -function actionForChoice(choice: string | undefined): IComputerUseSetupActionV1 | undefined { +function pluginActionForChoice(choice: string | undefined): PluginAction | undefined { if (choice === TRY_AGAIN_CHOICE) { - return { action: 'recheck' }; + return { kind: 'recheck' }; } for (const permission of computerUsePermissions) { - for (const action of ['request', 'openSettings'] as const) { - if (choice === choiceFor(action, permission)) { - return { action, permission }; + for (const kind of ['request', 'openSettings'] as const) { + if (choice === choiceFor({ kind, permission })) { + return { kind, permission }; } } } @@ -83,14 +88,14 @@ export function parseComputerUsePermissionPrompt(schema: ElicitationSchema | und const settings = new Set<ComputerUsePermission>(); let canRecheck = false; for (const choice of field.enum) { - const offered = actionForChoice(typeof choice === 'string' ? choice : undefined); + const offered = pluginActionForChoice(typeof choice === 'string' ? choice : undefined); if (!offered) { return undefined; } - if (offered.action === 'recheck') { + if (offered.kind === 'recheck') { canRecheck = true; - } else if (offered.permission) { - (offered.action === 'request' ? missing : settings).add(offered.permission); + } else { + (offered.kind === 'request' ? missing : settings).add(offered.permission); } } if (!canRecheck || missing.size === 0 || [...settings].some(permission => !missing.has(permission))) { @@ -148,28 +153,27 @@ export function classifyComputerUsePrompt(schema: ElicitationSchema | undefined) return fields.some(field => choiceValues(field).some(isPermissionChoice)) ? { kind: 'unrecognizedPermissions' } : { kind: 'other' }; } +/** What a setup accepts while `prompt` waits: `allow` for each missing permission, and `recheck`. */ function offeredActions(prompt: IComputerUsePermissionPrompt): IComputerUseSetupActionV1[] { - const actions: IComputerUseSetupActionV1[] = []; - for (const permission of computerUsePermissions) { - if (prompt.missing.has(permission)) { - actions.push({ action: 'request', permission }); - } - if (prompt.settings.has(permission)) { - actions.push({ action: 'openSettings', permission }); - } - } - actions.push({ action: 'recheck' }); - return actions; + return [ + ...computerUsePermissions.filter(permission => prompt.missing.has(permission)).map((permission): IComputerUseSetupActionV1 => ({ action: 'allow', permission })), + { action: 'recheck' }, + ]; } -function isOffered(prompt: IComputerUsePermissionPrompt, { action, permission }: IComputerUseSetupActionV1): boolean { - switch (action) { - case 'request': return !!permission && prompt.missing.has(permission); - case 'openSettings': return !!permission && prompt.settings.has(permission); +function isOffered(prompt: IComputerUsePermissionPrompt, action: PluginAction): boolean { + switch (action.kind) { + case 'request': return prompt.missing.has(action.permission); + case 'openSettings': return prompt.settings.has(action.permission); case 'recheck': return true; } } +/** How clients see a plugin action in flight: asking macOS and opening System Settings both carry out `allow`. */ +function operationAction(action: PluginAction): IComputerUseSetupActionV1 { + return action.kind === 'recheck' ? { action: 'recheck' } : { action: 'allow', permission: action.permission }; +} + function selectedChoice(answer: ChatInputAnswer | undefined): string | undefined { if (answer?.state !== ChatInputAnswerState.Submitted) { return undefined; @@ -199,18 +203,6 @@ function stillNotGrantedError(missing: ReadonlySet<ComputerUsePermission>): ICom }; } -function notWaitingError(): IComputerUseErrorV1 { - return { code: 'notWaiting', message: localize('computerUse.error.notWaiting', "Copilot is no longer waiting for this setup. Ask Copilot to try again when you're ready.") }; -} - -function unconfirmedError(): IComputerUseErrorV1 { - return { code: 'unconfirmed', message: localize('computerUse.error.unconfirmed', "Copilot Computer Use stopped before confirming the permissions. If Copilot still can't use apps, ask it to try again.") }; -} - -function unsupportedPromptError(): IComputerUseErrorV1 { - return { code: 'unsupportedPrompt', message: localize('computerUse.error.unsupportedPrompt', "Copilot Computer Use asked for permissions in a way this setup doesn't support. Answer its request in the chat instead.") }; -} - // #endregion /** How a setup reaches the chat whose turn waits. Implemented by the Copilot chat session. */ @@ -246,20 +238,36 @@ interface ISetup { /** The open chat input request; `undefined` once a client or the host completed it. */ cardId: string | undefined; prompt: IPendingPrompt | undefined; - /** The action sent for the previous prompt. Its outcome is the next prompt, or the plugin moving past its check. */ - sent: IComputerUseSetupActionV1 | undefined; + /** The plugin action sent for the previous prompt. Its outcome is the next prompt, or the plugin moving past its check. */ + sent: PluginAction | undefined; /** Whether the host sent {@link sent} on its own, not for the user. */ sentAutomatically: boolean; + /** The permission whose System Settings pane opens on the next prompt: a new loop of the plugin offers the pane only after the native request that `allow` repeated, which macOS keeps silent. */ + openSettingsNext: ComputerUsePermission | undefined; error: IComputerUseErrorV1 | undefined; } -interface IQueuedAction extends IComputerUseSetupActionV1 { +/** What a queued action asks for: the setup UI's `allow`, which becomes a plugin action only when it is sent, or an exact plugin action. */ +type SetupAction = { readonly kind: 'allow'; readonly permission: ComputerUsePermission } | PluginAction; + +function setupActionForRequest({ action, permission }: IComputerUseSetupActionV1): SetupAction | undefined { + switch (action) { + case 'allow': return permission && { kind: 'allow', permission }; + case 'recheck': return { kind: 'recheck' }; + } +} + +interface IQueuedAction { readonly setupId: string; readonly round: number; + readonly action: SetupAction; /** Sent by the host on its own, so an outcome that changed nothing is no error. */ readonly automatic?: boolean; } +/** Why a setup ended without becoming ready. Only logged: ended setups carry no error. */ +type SetupEndReason = 'decline' | 'cancel' | 'notWaiting' | 'unconfirmed' | 'unsupportedPrompt'; + const MAX_REMEMBERED_NONCES = 128; const MAX_QUEUED_ACTIONS = 16; const MAX_FINISHED_SETUPS = 8; @@ -278,7 +286,8 @@ const ACCESSIBILITY_PROMPT_SETTLE_MS = 2000; * run one at a time across all setups, so native prompts never overlap; a request for an older round is dropped. * * When macOS reports an Accessibility change, every setup that waits for Accessibility checks again on its own, so a - * grant in System Settings shows up without the user asking. + * grant in System Settings shows up without the user asking. Likewise, once one setup is ready, every other setup that + * waits checks again on its own. */ export class CopilotComputerUsePermissionSetup extends Disposable { @@ -287,6 +296,8 @@ export class CopilotComputerUsePermissionSetup extends Disposable { private readonly _seenNonces = new Set<string>(); /** Chats whose user declined setup in their current turn. */ private readonly _declinedChats = new Set<ICopilotComputerUseSetupChat>(); + /** Permissions the plugin asked macOS for natively in this process. macOS shows each prompt only once per app. */ + private readonly _askedNatively = new Set<ComputerUsePermission>(); private readonly _permissions: Record<ComputerUsePermission, ComputerUsePermissionState> = { accessibility: 'unknown', screenRecording: 'unknown' }; private _verifiedAt: number | undefined; /** The setup whose action is in flight. */ @@ -343,21 +354,23 @@ export class CopilotComputerUsePermissionSetup extends Disposable { // still open in the chat was abandoned; the new prompt replaces it in the same setup. let setup = this._working?.chat === chat ? this._working : this._activeSetups(chat)[0]; if (!setup) { - setup = { id: generateUuid(), chat, state: 'needsPermissions', round: 0, cardId: undefined, prompt: undefined, sent: undefined, sentAutomatically: false, error: undefined }; + setup = { id: generateUuid(), chat, state: 'needsPermissions', round: 0, cardId: undefined, prompt: undefined, sent: undefined, sentAutomatically: false, openSettingsNext: undefined, error: undefined }; this._setups.set(setup.id, setup); } setup.prompt?.result.complete({ action: 'cancel' }); - if (setup.sent?.action === 'request' && setup.sent.permission === 'accessibility') { + if (setup.sent?.kind === 'request' && setup.sent.permission === 'accessibility') { this._accessibilityRequestedAt = Date.now(); } // The plugin installed its helper app before it could find permissions missing. this._readHelperAppIcon(); this._recordVerified(offered.missing); // Only a check the user asked for reports that it changed nothing. - setup.error = setup.sent?.action === 'recheck' && !setup.sentAutomatically ? stillNotGrantedError(offered.missing) : undefined; + setup.error = setup.sent?.kind === 'recheck' && !setup.sentAutomatically ? stillNotGrantedError(offered.missing) : undefined; + const openSettings = setup.openSettingsNext; setup.round++; setup.sent = undefined; setup.sentAutomatically = false; + setup.openSettingsNext = undefined; setup.state = 'needsPermissions'; setup.prompt = { offered, input, result: new DeferredPromise<ElicitationResult>() }; if (this._working === setup) { @@ -365,16 +378,22 @@ export class CopilotComputerUsePermissionSetup extends Disposable { } this._logService.info(`[ComputerUse] Setup ${setup.id} round ${setup.round}: missing ${[...offered.missing].join(', ')}`); this._showInput(setup); - this._publish(); const result = setup.prompt.result.p; - this._drain(); + if (openSettings && isOffered(offered, { kind: 'openSettings', permission: openSettings })) { + // Finishes the user's `allow` before anything else runs. + this._queue.unshift({ setupId: setup.id, round: setup.round, action: { kind: 'openSettings', permission: openSettings } }); + } + // Sending publishes, so clients don't see the setup wait between two steps of one action. + if (!this._drain()) { + this._publish(); + } return result; } /** * Handles a client's answer to a setup's chat input request; `false` when `requestId` is not one. Declining or - * cancelling ends the setup. Accepting submits the chosen action like a request, which clients without the setup UI - * do by answering the request's ordinary questions; like the plugin, an answer without a choice checks again. + * cancelling ends the setup. Accepting sends the plugin's choice that the user picked in the request's ordinary + * questions, which clients without the setup UI answer; like the plugin, an answer without a choice checks again. */ respondToInput(chat: ICopilotComputerUseSetupChat, requestId: string, response: ChatInputResponseKind, answers: Record<string, ChatInputAnswer> | undefined): boolean { const setup = [...this._setups.values()].find(candidate => candidate.chat === chat && candidate.cardId === requestId); @@ -386,16 +405,16 @@ export class CopilotComputerUsePermissionSetup extends Disposable { if (response === ChatInputResponseKind.Decline) { this._declinedChats.add(chat); } - this._end(setup, undefined, response === ChatInputResponseKind.Decline ? 'decline' : 'cancel'); + this._end(setup, response === ChatInputResponseKind.Decline ? 'decline' : 'cancel'); return true; } const choice = selectedChoice(answers?.[CHOICE_FIELD]); - const action = choice === undefined ? { action: 'recheck' as const } : actionForChoice(choice); + const action: PluginAction | undefined = choice === undefined ? { kind: 'recheck' } : pluginActionForChoice(choice); if (action) { - this._enqueue({ ...action, setupId: setup.id, round: setup.round }); + this._enqueue({ setupId: setup.id, round: setup.round, action }); } else { // The plugin stops asking when it gets a choice it doesn't know. - this._end(setup, undefined, 'cancel'); + this._end(setup, 'cancel'); } return true; } @@ -411,7 +430,7 @@ export class CopilotComputerUsePermissionSetup extends Disposable { if (setup.state === 'working' && success) { this._ready(setup); } else { - this._end(setup, setup.state === 'working' ? unconfirmedError() : notWaitingError(), 'cancel'); + this._end(setup, setup.state === 'working' ? 'unconfirmed' : 'notWaiting'); } } } @@ -431,7 +450,7 @@ export class CopilotComputerUsePermissionSetup extends Disposable { */ onUnrecognizedPrompt(chat: ICopilotComputerUseSetupChat): void { for (const setup of this._activeSetups(chat)) { - this._end(setup, unsupportedPromptError(), 'cancel'); + this._end(setup, 'unsupportedPrompt'); } } @@ -441,7 +460,7 @@ export class CopilotComputerUsePermissionSetup extends Disposable { for (const setup of this._activeSetups(chat)) { // The chat's turn is over, so its request is left as the turn left it. setup.cardId = undefined; - this._end(setup, notWaitingError(), 'cancel'); + this._end(setup, 'notWaiting'); } } @@ -457,19 +476,20 @@ export class CopilotComputerUsePermissionSetup extends Disposable { for (const setup of this._setups.values()) { if (setup.state === 'needsPermissions' && setup.prompt?.offered.missing.has('accessibility')) { this._logService.info(`[ComputerUse] Setup ${setup.id} round ${setup.round}: macOS changed Accessibility, checking again`); - this._enqueue({ setupId: setup.id, round: setup.round, action: 'recheck', automatic: true }); + this._enqueue({ setupId: setup.id, round: setup.round, action: { kind: 'recheck' }, automatic: true }); } } } /** - * Whether macOS may be asking for Accessibility. Asking adds the app to macOS's list, a change of its own, and shows - * a prompt that the helper holds open; an automatic check restarts the helper, which would close that prompt. + * Whether macOS may be asking for Accessibility, including through a waiting `allow`. Asking adds the app to macOS's + * list, a change of its own, and shows a prompt that the helper holds open; an automatic check restarts the helper, + * which would close that prompt. */ private _isAskingForAccessibility(): boolean { - const asks = (action: IComputerUseSetupActionV1 | undefined) => action?.action === 'request' && action.permission === 'accessibility'; + const asks = (action: SetupAction | undefined) => (action?.kind === 'request' || action?.kind === 'allow') && action.permission === 'accessibility'; return asks(this._working?.sent) - || this._queue.some(asks) + || this._queue.some(queued => asks(queued.action)) || (this._accessibilityRequestedAt !== undefined && Date.now() - this._accessibilityRequestedAt < ACCESSIBILITY_PROMPT_SETTLE_MS); } @@ -515,22 +535,32 @@ export class CopilotComputerUsePermissionSetup extends Disposable { this._recordVerified(new Set()); setup.state = 'ready'; setup.sent = undefined; + setup.openSettingsNext = undefined; setup.error = undefined; this._finish(setup, ChatInputResponseKind.Accept); + // The permissions are machine-wide, so the setups that still wait can continue too. + for (const other of this._setups.values()) { + if (other.state === 'needsPermissions') { + this._logService.info(`[ComputerUse] Setup ${other.id} round ${other.round}: another setup is ready, checking again`); + this._enqueue({ setupId: other.id, round: other.round, action: { kind: 'recheck' }, automatic: true }); + } + } } - private _end(setup: ISetup, error: IComputerUseErrorV1 | undefined, elicitation: 'decline' | 'cancel'): void { + private _end(setup: ISetup, reason: SetupEndReason): void { if (setup.state === 'ready' || setup.state === 'ended') { return; } - this._logService.info(`[ComputerUse] Setup ${setup.id} ended (${error?.code ?? elicitation})`); + this._logService.info(`[ComputerUse] Setup ${setup.id} ended (${reason})`); const prompt = setup.prompt; + const declined = reason === 'decline'; setup.state = 'ended'; setup.prompt = undefined; setup.sent = undefined; - setup.error = error; - this._finish(setup, elicitation === 'decline' ? ChatInputResponseKind.Decline : ChatInputResponseKind.Cancel); - prompt?.result.complete({ action: elicitation }); + setup.openSettingsNext = undefined; + setup.error = undefined; + this._finish(setup, declined ? ChatInputResponseKind.Decline : ChatInputResponseKind.Cancel); + prompt?.result.complete({ action: declined ? 'decline' : 'cancel' }); } private _finish(setup: ISetup, response: ChatInputResponseKind): void { @@ -550,6 +580,10 @@ export class CopilotComputerUsePermissionSetup extends Disposable { for (const permission of computerUsePermissions) { this._permissions[permission] = missing.has(permission) ? 'notGranted' : 'granted'; } + if (!missing.has('accessibility')) { + // macOS asks for nothing the helper has, so automatic checks needn't wait for a prompt to settle. + this._accessibilityRequestedAt = undefined; + } this._verifiedAt = Date.now(); } @@ -585,42 +619,48 @@ export class CopilotComputerUsePermissionSetup extends Disposable { return; } if (isNew) { - this._enqueue({ setupId: request.setupId, round: request.round, action: request.action, ...(request.permission ? { permission: request.permission } : {}) }); + const action = setupActionForRequest(request); + if (action) { + this._enqueue({ setupId: request.setupId, round: request.round, action }); + } } } - private _enqueue(action: IQueuedAction): void { + private _enqueue(entry: IQueuedAction): void { // Every action makes the plugin verify again, so an automatic check adds nothing to a setup with an action // waiting, and running one first would make the user's action stale. - if (action.automatic && this._queue.some(queued => queued.setupId === action.setupId)) { + if (entry.automatic && this._queue.some(queued => queued.setupId === entry.setupId)) { return; } - if (!action.automatic) { - const waiting = this._queue.findIndex(queued => queued.setupId === action.setupId && queued.automatic); + if (!entry.automatic) { + const waiting = this._queue.findIndex(queued => queued.setupId === entry.setupId && queued.automatic); if (waiting !== -1) { this._queue.splice(waiting, 1); } } if (this._queue.length >= MAX_QUEUED_ACTIONS) { - this._logService.warn(`[ComputerUse] Dropping a '${action.action}' request: too many requests are waiting`); + this._logService.warn(`[ComputerUse] Dropping a '${entry.action.kind}' request: too many requests are waiting`); return; } - this._queue.push(action); + this._queue.push(entry); this._drain(); } - /** Sends queued actions while none is in flight; one that no longer matches its setup's prompt is dropped. */ - private _drain(): void { + /** + * Sends the next queued action unless one is in flight, dropping those that no longer match their setup's prompt. + * Returns whether it sent one, which it publishes. + */ + private _drain(): boolean { while (!this._working && !this._store.isDisposed) { const next = this._queue.shift(); if (!next) { - return; + return false; } const setup = this._setups.get(next.setupId); const prompt = setup?.state === 'needsPermissions' && setup.round === next.round ? setup.prompt : undefined; - const choice = prompt && isOffered(prompt.offered, next) ? choiceFor(next.action, next.permission) : undefined; - if (!setup || !prompt || !choice) { - this._logService.info(`[ComputerUse] Dropping a '${next.action}' request for an older or unavailable step`); + const step = prompt && this._resolve(next.action, prompt.offered); + if (!setup || !prompt || !step || !isOffered(prompt.offered, step.action)) { + this._logService.info(`[ComputerUse] Dropping a '${next.action.kind}' request for an older or unavailable step`); // A client may have completed the request to send it; keep the prompt answerable. if (setup && !setup.cardId) { this._showInput(setup); @@ -631,16 +671,42 @@ export class CopilotComputerUsePermissionSetup extends Disposable { this._logService.info(`[ComputerUse] Setup ${setup.id}: not checking again on its own while macOS asks for Accessibility`); continue; } + const choice = choiceFor(step.action); this._logService.info(`[ComputerUse] Setup ${setup.id} round ${setup.round}: sending '${choice}'${next.automatic ? ' on its own' : ''}`); + if (step.action.kind === 'request') { + this._askedNatively.add(step.action.permission); + } setup.prompt = undefined; setup.state = 'working'; - setup.sent = next.permission ? { action: next.action, permission: next.permission } : { action: next.action }; + setup.sent = step.action; setup.sentAutomatically = !!next.automatic; + setup.openSettingsNext = step.openSettingsNext; setup.error = undefined; this._working = setup; this._publish(); prompt.result.complete({ action: 'accept', content: { [CHOICE_FIELD]: choice } }); + return true; + } + return false; + } + + /** + * The plugin action that carries out `action` for `prompt`. `allow` has macOS ask natively the first time, and opens + * System Settings after that. The plugin offers the pane only once a native request in its current loop didn't + * grant the permission, so a new loop gets the silent request first and opens the pane on its next prompt. + */ + private _resolve(action: SetupAction, prompt: IComputerUsePermissionPrompt): { readonly action: PluginAction; readonly openSettingsNext?: ComputerUsePermission } { + if (action.kind !== 'allow') { + return { action }; + } + const permission = action.permission; + if (!this._askedNatively.has(permission)) { + return { action: { kind: 'request', permission } }; + } + if (prompt.settings.has(permission)) { + return { action: { kind: 'openSettings', permission } }; } + return { action: { kind: 'request', permission }, openSettingsNext: permission }; } // #endregion @@ -654,7 +720,7 @@ export class CopilotComputerUsePermissionSetup extends Disposable { schemaVersion: 1, permissions: computerUsePermissions.map(permission => ({ permission, state: this._permissions[permission] })), ...(this._verifiedAt !== undefined ? { verifiedAt: this._verifiedAt } : {}), - ...(working?.sent ? { operation: { setupId: working.id, ...working.sent } } : {}), + ...(working?.sent ? { operation: { setupId: working.id, ...operationAction(working.sent) } } : {}), setups: [...this._setups.values()].map(setup => ({ id: setup.id, chat: setup.chat.chatUri, diff --git a/src/vs/platform/agentHost/test/common/computerUse.test.ts b/src/vs/platform/agentHost/test/common/computerUse.test.ts index 18b9b3037d5dc2..f0de7b303ff177 100644 --- a/src/vs/platform/agentHost/test/common/computerUse.test.ts +++ b/src/vs/platform/agentHost/test/common/computerUse.test.ts @@ -16,20 +16,21 @@ suite('Computer Use setup contract', () => { test('accepts only well-formed requests, with the permission each action needs', () => { const base = { nonce: 'n', setupId: 's', round: 1 }; assert.deepStrictEqual([ - { ...base, action: 'request', permission: 'accessibility' }, - { ...base, action: 'openSettings', permission: 'screenRecording' }, + { ...base, action: 'allow', permission: 'accessibility' }, + { ...base, action: 'allow', permission: 'screenRecording' }, { ...base, action: 'recheck' }, - { ...base, action: 'request' }, + { ...base, action: 'allow' }, { ...base, action: 'recheck', permission: 'accessibility' }, - { ...base, action: 'request', permission: 'camera' }, - { ...base, action: 'reset' }, + { ...base, action: 'allow', permission: 'camera' }, + { ...base, action: 'request', permission: 'accessibility' }, + { ...base, action: 'openSettings', permission: 'screenRecording' }, { ...base, action: 'recheck', round: -1 }, { ...base, action: 'recheck', round: 1.5 }, { ...base, action: 'recheck', nonce: '' }, { ...base, action: 'recheck', setupId: 'x'.repeat(257) }, ['recheck'], undefined, - ].map(isComputerUseRequest), [true, true, true, false, false, false, false, false, false, false, false, false, false]); + ].map(isComputerUseRequest), [true, true, true, false, false, false, false, false, false, false, false, false, false, false]); }); test('reads published status defensively and only from schema version 1', () => { @@ -37,9 +38,9 @@ suite('Computer Use setup contract', () => { schemaVersion: 1, permissions: [{ permission: 'screenRecording', state: 'granted' }, { permission: 'accessibility', state: 'bogus' }, { permission: 'camera', state: 'granted' }], verifiedAt: 5, - operation: { setupId: 'a', action: 'request' }, + operation: { setupId: 'a', action: 'allow', permission: 'accessibility' }, setups: [ - { id: 'a', chat: 'chat:a', state: 'needsPermissions', round: 2, actions: [{ action: 'request', permission: 'accessibility' }, { action: 'openSettings' }, { action: 'recheck', permission: 'accessibility' }, { action: 'recheck' }], error: { code: 'stillNotGranted', message: 'Still off' }, extra: true }, + { id: 'a', chat: 'chat:a', state: 'needsPermissions', round: 2, actions: [{ action: 'allow', permission: 'accessibility' }, { action: 'allow' }, { action: 'request', permission: 'screenRecording' }, { action: 'recheck', permission: 'accessibility' }, { action: 'recheck' }], error: { code: 'stillNotGranted', message: 'Still off' }, extra: true }, { id: 'a', chat: 'chat:a', state: 'ready', round: 3, actions: [] }, { id: 'b', chat: 'chat:b', state: 'ready', round: 1, actions: [{ action: 'recheck' }], error: { code: '', message: 'dropped' } }, { id: 'c', chat: 'chat:c', state: 'unknown', round: 1, actions: [] }, @@ -48,6 +49,11 @@ suite('Computer Use setup contract', () => { }); assert.deepStrictEqual({ status, + operations: [ + { setupId: 'a', action: 'recheck' }, + { setupId: 'a', action: 'allow' }, + { setupId: 'a', action: 'openSettings', permission: 'accessibility' }, + ].map(operation => readComputerUseStatus({ schemaVersion: 1, permissions: [], setups: [], operation })?.operation), otherVersion: readComputerUseStatus({ schemaVersion: 2, permissions: [], setups: [] }), notAnObject: readComputerUseStatus('status'), helperApps: [ @@ -64,11 +70,13 @@ suite('Computer Use setup contract', () => { schemaVersion: 1, permissions: [{ permission: 'accessibility', state: 'unknown' }, { permission: 'screenRecording', state: 'granted' }], verifiedAt: 5, + operation: { setupId: 'a', action: 'allow', permission: 'accessibility' }, setups: [ - { id: 'a', chat: 'chat:a', state: 'needsPermissions', round: 2, actions: [{ action: 'request', permission: 'accessibility' }, { action: 'recheck' }], error: { code: 'stillNotGranted', message: 'Still off' } }, + { id: 'a', chat: 'chat:a', state: 'needsPermissions', round: 2, actions: [{ action: 'allow', permission: 'accessibility' }, { action: 'recheck' }], error: { code: 'stillNotGranted', message: 'Still off' } }, { id: 'b', chat: 'chat:b', state: 'ready', round: 1, actions: [] }, ], }, + operations: [{ setupId: 'a', action: 'recheck' }, undefined, undefined], otherVersion: undefined, notAnObject: undefined, helperApps: [ diff --git a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts index 21d20401a37e14..b254fbb21c948a 100644 --- a/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts +++ b/src/vs/platform/agentHost/test/electron-browser/agentHostProtocolClient.test.ts @@ -4945,7 +4945,7 @@ suite('AgentHostProtocolClient', () => { * client plus a `transports` array recording each transport handed * out, so tests can drive handshake/reconnect interactions. */ - function createFactoryClient(permissionService = createPermissionService(), clientInfo?: Implementation, telemetryService: ITelemetryService = NullTelemetryService, reconnectPolicy?: IRemoteAgentHostReconnectPolicy, loadEstimator?: { hasHighLoad(): boolean }, prepareReconnect?: () => Promise<void>, authentication?: Pick<IAgentHostProtocolClientOptions, 'prepareAuthentication' | 'resolveInitialAuthentication' | 'resolveAdvertisedAuthentication'>, power?: { onDidSuspend: Event<void>; onDidResume: Event<void> }, connectionKind?: AgentHostClientConnectionKind): { client: AgentHostProtocolClient; transports: TestClientProtocolTransport[]; configurationService: TestConfigurationService } { + function createFactoryClient(permissionService = createPermissionService(), clientInfo?: Implementation, telemetryService: ITelemetryService = NullTelemetryService, reconnectPolicy?: IRemoteAgentHostReconnectPolicy, loadEstimator?: { hasHighLoad(): boolean }, prepareReconnect?: () => Promise<void>, authentication?: Pick<IAgentHostProtocolClientOptions, 'prepareAuthentication' | 'resolveInitialAuthentication' | 'resolveAdvertisedAuthentication' | 'sealAuthenticationToken'>, power?: { onDidSuspend: Event<void>; onDidResume: Event<void> }, connectionKind?: AgentHostClientConnectionKind): { client: AgentHostProtocolClient; transports: TestClientProtocolTransport[]; configurationService: TestConfigurationService } { const transports: TestClientProtocolTransport[] = []; const factory = () => { const t = disposables.add(new TestClientProtocolTransport(connectionKind)); @@ -4995,6 +4995,43 @@ suite('AgentHostProtocolClient', () => { }); } + for (const encryption of ['mcp-key', 'missing-key', 'provider-key-only'] as const) { + test(`untargeted non-GitHub MCP credentials require trusted relay encryption: ${encryption}`, async () => { + const sealed: IMissionControlCredentialSealingRequest[] = []; + const { client, transports } = createFactoryClient(undefined, undefined, undefined, undefined, undefined, undefined, { + sealAuthenticationToken: async request => { + sealed.push(request); + return 'copilot-sealed.v1.key.ciphertext'; + }, + }, undefined, AgentHostClientConnectionKind.MissionControl); + const key = { keyId: 'key', publicKey: 'public-key', algorithm: 'x25519-sealedbox', use: encryption === 'mcp-key' ? 'mcp-auth-token' : 'auth-token' }; + const connecting = client.connect(); + await initializeAdvertised(transports[0], { 'copilot.encryptionKeys': encryption === 'missing-key' ? [] : [key] }); + await connecting; + const resource = 'https://mcp.example.test'; + const authenticating = client.authenticate({ resource, scopes: ['read'], token: 'mcp-token' }); + if (encryption === 'mcp-key') { + const request = await waitForRequestAtWithin(transports[0], 'authenticate', 0); + transports[0].fireMessage({ jsonrpc: '2.0', id: request.id, result: {} }); + const subscription = await waitForRequestAtWithin(transports[0], 'subscribe', 0); + transports[0].fireMessage({ jsonrpc: '2.0', id: subscription.id, result: { snapshot: { resource: ROOT_STATE_URI, fromSeq: 0, state: client.rootState.value } } }); + await authenticating; + assert.deepStrictEqual({ + sealed: sealed.map(request => [request.token, request.resource, request.key.use]), + params: request.params, + }, { + sealed: [['mcp-token', resource, 'mcp-auth-token']], + params: { channel: ROOT_STATE_URI, resource, scopes: ['read'], token: 'copilot-sealed.v1.key.ciphertext' }, + }); + } else { + await assert.rejects(authenticating, /no supported credential encryption key/); + assert.deepStrictEqual({ + sealed, authenticationSent: transports[0].sentMessages.some(message => hasKey(message, { method: true }) && message.method === 'authenticate'), + }, { sealed: [], authenticationSent: false }); + } + }); + } + test('initial encryption failures do not publish a ready connection or release protected requests', async () => { const { client, transports } = createFactoryClient(undefined, undefined, undefined, undefined, undefined, undefined, { resolveAdvertisedAuthentication: async () => [{ resource: advertisedAgent.protectedResources[0].resource, token: 'must-not-leak' }], @@ -5093,6 +5130,75 @@ suite('AgentHostProtocolClient', () => { }); } + for (const recovery of ['replay', 'snapshot', 'fresh initialize'] as const) { + test(`Mission Control ${recovery} reseals provider and targeted MCP credentials with the current challenge`, async function () { + this.timeout(20_000); + const resource = advertisedAgent.protectedResources[0].resource; + const sealed: IMissionControlCredentialSealingRequest[] = []; + const { client, transports } = createFactoryClient(undefined, undefined, undefined, immediateReconnectPolicy, undefined, undefined, { + resolveInitialAuthentication: async () => ({ resource, token: 'identity-token' }), + sealAuthenticationToken: async request => { + sealed.push(request); + return `copilot-sealed.v1.${request.key.key_id}.ciphertext`; + }, + }, undefined, AgentHostClientConnectionKind.MissionControl); + const firstChallenge = '0123456789abcdef0123456789abcdef'; + const nextChallenge = 'abcdef0123456789abcdef0123456789'; + const metadata = (challenge: string) => ({ 'copilot.encryptionRequired': ['auth-token', 'mcp-auth-token'], 'copilot.authChallenge': { challenge, required: true } }); + const rootMeta = { 'copilot.encryptionKeys': ['auth-token', 'mcp-auth-token'].map(use => ({ keyId: use, publicKey: 'public-key', use, algorithm: 'x25519-sealedbox' })) }; + const root = { agents: [advertisedAgent], activeSessions: 0, _meta: rootMeta }; + const acknowledgeRoot = async (transport: TestClientProtocolTransport, index: number) => { + const subscription = await waitForRequestAtWithin(transport, 'subscribe', index); + transport.fireMessage({ jsonrpc: '2.0', id: subscription.id, result: { snapshot: { resource: ROOT_STATE_URI, fromSeq: 0, state: root } } }); + }; + const connecting = client.connect(); + await initializeAdvertised(transports[0], rootMeta, metadata(firstChallenge)); + const first = await waitForRequestAtWithin(transports[0], 'authenticate', 0); + transports[0].fireMessage({ jsonrpc: '2.0', id: first.id, result: {} }); + await acknowledgeRoot(transports[0], 0); + await connecting; + const target = { kind: AuthenticateTargetKind.McpServer, session: 'opaque-session://tenant/id', customizationId: 'mcp/server' }; + const authenticatingMcp = client.authenticate({ resource, target, token: 'mcp-token' }); + const mcp = await waitForRequestAtWithin(transports[0], 'authenticate', 1); + transports[0].fireMessage({ jsonrpc: '2.0', id: mcp.id, result: {} }); + await acknowledgeRoot(transports[0], 1); + await authenticatingMcp; + transports[0].fireClose(); + const replacement = await waitForTransport(transports, 1); + replacement.connectDeferred.complete(); + const reconnect = await waitForRequestAtWithin(replacement, 'reconnect', 0); + if (recovery === 'fresh initialize') { + replacement.fireMessage({ jsonrpc: '2.0', id: reconnect.id, error: { code: AhpErrorCodes.NotFound, message: 'Host restarted' } }); + const initialize = await waitForRequestAtWithin(replacement, 'initialize', 0); + replacement.fireMessage({ jsonrpc: '2.0', id: initialize.id, result: { protocolVersion: PROTOCOL_VERSION, serverSeq: 0, _meta: metadata(nextChallenge), snapshots: [{ resource: ROOT_STATE_URI, fromSeq: 0, state: root }] } }); + } else { + replacement.fireMessage({ + jsonrpc: '2.0', id: reconnect.id, + result: recovery === 'replay' + ? { type: ReconnectResultType.Replay, actions: [], missing: [], _meta: metadata(nextChallenge) } + : { type: ReconnectResultType.Snapshot, snapshots: [{ resource: ROOT_STATE_URI, fromSeq: 0, state: root }], _meta: metadata(nextChallenge) }, + }); + } + const provider = await waitForRequestAtWithin(replacement, 'authenticate', 0); + assert.strictEqual(replacement.sentMessages.filter(message => hasKey(message, { method: true }) && message.method === 'authenticate').length, 1); + replacement.fireMessage({ jsonrpc: '2.0', id: provider.id, result: {} }); + const restoredMcp = await waitForRequestAtWithin(replacement, 'authenticate', 1); + replacement.fireMessage({ jsonrpc: '2.0', id: restoredMcp.id, result: {} }); + await acknowledgeRoot(replacement, 0); + await waitForConnectedWithin(client); + assert.deepStrictEqual({ + sealed: sealed.map(request => [request.token, request.key.use, request.challenge]), + target: (restoredMcp.params as AuthenticateParams).target, + }, { + sealed: [ + ['identity-token', 'auth-token', firstChallenge], ['mcp-token', 'mcp-auth-token', firstChallenge], + ['identity-token', 'auth-token', nextChallenge], ['mcp-token', 'mcp-auth-token', nextChallenge], + ], + target, + }); + }); + } + test('transport closure during reconnect sealing retries without waiting for encryption', async function () { this.timeout(20_000); const resource = advertisedAgent.protectedResources[0].resource; diff --git a/src/vs/platform/agentHost/test/node/agentHostChatMovability.test.ts b/src/vs/platform/agentHost/test/node/agentHostChatMovability.test.ts index 24211534eae11f..04264edcd7a0c0 100644 --- a/src/vs/platform/agentHost/test/node/agentHostChatMovability.test.ts +++ b/src/vs/platform/agentHost/test/node/agentHostChatMovability.test.ts @@ -474,14 +474,19 @@ suite('AgentHostChatMovability', () => { assert.deepStrictEqual(results, { off: [off, off], onWithWorktree: [onWithWorktree, onWithWorktree] }); }); - test('a chat that runs Agent Merge for a folder of its session is not movable until it stops', async () => { + test('a chat that runs Agent Merge for a folder of its session stays movable: its Agent Merge moves with it', async () => { const { stateManager, peer, flip } = await setupStrict(); stateManager.setSessionConfig(session, { schema: { type: 'object', properties: {} }, values: {} }); const agentMerge = (enabled: boolean) => stateManager.dispatchServerAction(session, { type: ActionType.SessionConfigChanged, config: { [SessionConfigKey.AgentMergeFolders]: { [getWorkingDirectoryKey(folder)]: { enabled, chat: peer } } }, }); - assert.deepStrictEqual(await flip(() => agentMerge(true), () => agentMerge(false)), flipped); + assert.deepStrictEqual(await flip(() => agentMerge(true), () => agentMerge(false)), { + before: { summary: true, state: true }, + refused: { summary: true, state: true }, + allowed: { summary: true, state: true }, + announced: [], + }); }); test('a restored chat, which registers once its session lists it, is published at once and follows its session\'s inputs', async () => { diff --git a/src/vs/platform/agentHost/test/node/agentMergeController.test.ts b/src/vs/platform/agentHost/test/node/agentMergeController.test.ts index 20b2a7d40d080b..37b2be5ec3b76f 100644 --- a/src/vs/platform/agentHost/test/node/agentMergeController.test.ts +++ b/src/vs/platform/agentHost/test/node/agentMergeController.test.ts @@ -1938,7 +1938,7 @@ suite('AgentMergeController', () => { * for that folder and owned by `owningChat` (the peer chat by default). The * pull request has a failing check, so the controller starts a repair turn. */ - function createPeerRepairHarness(disposables: ReturnType<typeof ensureNoDisposablesAreLeakedInTestSuite>, owningChat?: (stateManager: AgentHostStateManager) => string, initialSnapshot = repairSnapshot(), mutations?: PullRequestMutationApi) { + function createPeerRepairHarness(disposables: ReturnType<typeof ensureNoDisposablesAreLeakedInTestSuite>, owningChat?: (stateManager: AgentHostStateManager) => string, initialSnapshot = repairSnapshot(), mutations?: PullRequestMutationApi, beforeCredential?: () => Promise<void>) { const logService = new NullLogService(); const stateManager = disposables.add(new AgentHostStateManager(logService)); const configurationService = disposables.add(new AgentConfigurationService(stateManager, logService)); @@ -1987,6 +1987,7 @@ suite('AgentMergeController', () => { override readonly mutations = mutations ?? new class extends mock<PullRequestMutationApi>() { }(); override readonly credentials = new class extends mock<IGitHubCredentials>() { override async getCredential(signal: AbortSignal): Promise<GitHubCredential> { + await beforeCredential?.(); return { account: snapshot.get().ref, token: 'test-token', generation: 1, signal }; } }(); @@ -2019,6 +2020,146 @@ suite('AgentMergeController', () => { return { stateManager, configurationService, gitService, gitStateService, controller, session, peerChat, otherKey, startTurns, turnStart, cancelledTurns, notices, snapshot, refreshes, start }; } + suite('moving the chat that runs Agent Merge', () => { + /** + * Moves the harness's peer chat into a new session as the host publishes a move: its folder's monitoring moves + * first, then the chat, then each session's Agent Merge. With `conflict`, the new session already runs Agent + * Merge for the pull request, so the peer's stays off. + */ + function movePeer(h: ReturnType<typeof createPeerRepairHarness>, conflict = false): string { + const target = `copilot:/agent-merge-controller-${++sessionCounter}`; + h.stateManager.createSession(summary(target)); + h.stateManager.setSessionConfig(target, { schema: platformSessionSchema.toProtocol(), values: {} }); + h.stateManager.setSessionMeta(target, withFolderGitHubState(undefined, h.otherKey, { pullRequestUrls: ['https://github.com/octo/repo/pull/1'], pullRequestBranchName: 'feature-tools' })); + h.stateManager.dispatchServerAction(target, { type: ActionType.SessionReady }); + const values = h.configurationService.getSessionConfigValues(h.session) ?? {}; + const transfer = h.controller.transferFolders(h.session, target, conflict ? [] : [h.otherKey], conflict ? [{ folderKey: h.otherKey, chat: h.peerChat }] : []); + h.stateManager.transferChats(h.session, target, [h.peerChat], undefined); + if (!conflict) { + h.configurationService.updateSessionConfig(target, { + [SessionConfigKey.AgentMergeFolders]: values[SessionConfigKey.AgentMergeFolders], + [SessionConfigKey.AgentMergeControllerFolders]: values[SessionConfigKey.AgentMergeControllerFolders], + }); + } + h.configurationService.updateSessionConfig(h.session, { + [SessionConfigKey.AgentMergeFolders]: { [h.otherKey]: { enabled: false } }, + [SessionConfigKey.AgentMergeControllerFolders]: {}, + }); + transfer.dispose(); + return target; + } + + test('a repair turn keeps running in the session its chat moved to and ends there, without another one starting', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createPeerRepairHarness(disposables); + await h.start(); + const noticesBefore = h.notices.length; + const target = movePeer(h); + await timeout(0); + const moved = { session: h.controller.getTurnContext(h.peerChat)?.session === target, cancelled: [...h.cancelledTurns], notices: h.notices.slice(noticesBefore) }; + + const turnId = h.stateManager.getChatState(h.peerChat)!.activeTurn!.id; + const refreshesBefore = h.refreshes.count; + h.stateManager.dispatchServerAction(h.peerChat, { type: ActionType.ChatTurnComplete, turnId, duration: 1 }); + await timeout(1000); + + assert.deepStrictEqual({ + moved, + ended: h.controller.getTurnContext(h.peerChat), + // Its end is handled where it runs now, which looks at the pull request again. + refreshedAfterTurn: h.refreshes.count > refreshesBefore, + starts: h.startTurns, + target: readAgentMergeFolderState(h.configurationService.getSessionConfigValues(target), h.otherKey, getWorkingDirectoryKey(REPOSITORY))?.lastPromptFingerprint !== undefined, + source: readAgentMergeFolderState(h.configurationService.getSessionConfigValues(h.session), h.otherKey, getWorkingDirectoryKey(REPOSITORY)), + }, { + moved: { session: true, cancelled: [], notices: [] }, + ended: undefined, + refreshedAfterTurn: true, + starts: [h.peerChat], + target: true, + source: { enabled: false }, + }); + })); + + test('a repair turn whose end is being handled when its chat moves is handled in the session the chat moved to', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const h = createPeerRepairHarness(disposables); + await h.start(); + const turnId = h.stateManager.getChatState(h.peerChat)!.activeTurn!.id; + const refreshesBefore = h.refreshes.count; + h.stateManager.dispatchServerAction(h.peerChat, { type: ActionType.ChatTurnComplete, turnId, duration: 1 }); + const target = movePeer(h); + await timeout(1000); + const refreshedAfterTurn = h.refreshes.count > refreshesBefore; + // The pull request now conflicts: the next repair runs, in the session the chat moved to. + const conflicting = repairSnapshot(); + h.snapshot.set({ ...conflicting, mergeability: { ...conflicting.mergeability, value: { ...conflicting.mergeability.value!, mergeable: 'CONFLICTING', mergeStateStatus: 'DIRTY' } } }, undefined); + // Past the debounce of pull request changes. + await timeout(60_000); + + assert.deepStrictEqual({ + refreshedAfterTurn, + starts: h.startTurns, + nextRepairIn: h.controller.getTurnContext(h.peerChat)?.session === target, + cancelled: h.cancelledTurns, + }, { + refreshedAfterTurn: true, + starts: [h.peerChat, h.peerChat], + nextRepairIn: true, + cancelled: [], + }); + })); + + test('an evaluation running when its chat moves stops, and the next one runs in the session the chat moved to', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const gate = new DeferredPromise<void>(); + const requested = new DeferredPromise<void>(); + const credentialRequests = { count: 0 }; + const h = createPeerRepairHarness(disposables, undefined, undefined, undefined, () => { + if (++credentialRequests.count > 1) { + return Promise.resolve(); + } + requested.complete(); + return gate.p; + }); + const started = h.start(); + await requested.p; + const target = movePeer(h); + await timeout(60_000); + // The next evaluation waits for the one still running for the source. + const requestsWhileRunning = credentialRequests.count; + gate.complete(); + await started; + + assert.deepStrictEqual({ + requestsWhileRunning, + starts: h.startTurns, + session: h.controller.getTurnContext(h.peerChat)?.session === target, + cancelled: h.cancelledTurns, + }, { + requestsWhileRunning: 1, + starts: [h.peerChat], + session: true, + cancelled: [], + }); + })); + + test('a moved chat whose new session already runs Agent Merge for its pull request stops its repair and is told why', async () => { + const h = createPeerRepairHarness(disposables); + await h.start(); + const noticesBefore = h.notices.length; + movePeer(h, true); + await timeout(0); + + assert.deepStrictEqual({ + cancelled: h.cancelledTurns, + context: h.controller.getTurnContext(h.peerChat), + notices: h.notices.slice(noticesBefore), + }, { + cancelled: [h.peerChat], + context: undefined, + notices: [{ chat: h.peerChat, kind: AgentSystemNotificationKind.AgentMergeDisabled, content: 'Agent Merge was turned off for this chat: another chat in this session already runs it for this pull request.' }], + }); + }); + }); + for (const state of ['merged', 'closed'] as const) { test(`announces a ${state} pull request when monitoring stops`, async () => { diff --git a/src/vs/platform/agentHost/test/node/agentService.test.ts b/src/vs/platform/agentHost/test/node/agentService.test.ts index 2ef0b8ff8ad5c8..7af0ef28d981b8 100644 --- a/src/vs/platform/agentHost/test/node/agentService.test.ts +++ b/src/vs/platform/agentHost/test/node/agentService.test.ts @@ -35381,6 +35381,11 @@ suite('AgentService (node dispatcher)', () => { stateManager.dispatchServerAction(chat.toString(), { type: ActionType.ChatTurnComplete, turnId: 'first-turn', duration: 1 }); } + /** Starts a turn in `chat` that is still running when it moves: Agent Merge's elevation never changes under it. */ + function startTurn(service: AgentService, chat: URI): void { + getStateManager(service).dispatchServerAction(chat.toString(), { type: ActionType.ChatTurnStarted, turnId: 'running-turn', startedAt: new Date(0).toISOString(), message: { text: 'Fix it', origin: { kind: MessageKind.User } } }); + } + /** Records pull request `number` as an artifact of `chat`, as the artifact tools do. */ async function recordPullRequest(service: AgentService, session: URI, chat: string, number: number): Promise<void> { const accessor = (service as unknown as { _createArtifactServerToolAccessor(): { persist: ConstructorParameters<typeof SessionArtifacts>[3] } })._createArtifactServerToolAccessor(); @@ -35402,6 +35407,56 @@ suite('AgentService (node dispatcher)', () => { }; } + /** The config values of Agent Merge on `folder`, turned on by `chat` and bound to pull request `number`. */ + function agentMergeConfigValues(chat: string, folder: URI, number: number): Record<string, unknown> { + const folderKey = getWorkingDirectoryKey(folder.toString()); + return { + [SessionConfigKey.AgentMergeFolders]: { [folderKey]: { enabled: true, overrides: { mergePullRequest: 'never' }, chat } }, + [SessionConfigKey.AgentMergeControllerFolders]: { [folderKey]: { target: { branchName: `pr-${number}`, pullRequestUrl: `https://github.com/microsoft/vscode/pull/${number}`, enabledAt: `enabled-${number}`, commentWatermark: `watermark-${number}` } } }, + }; + } + + /** The Agent Merge config values among `values`. */ + function agentMergeConfigValuesOf(values: Readonly<Record<string, unknown>> | undefined): Record<string, unknown> { + return Object.fromEntries(Object.entries(values ?? {}).filter(([key, value]) => key.startsWith(SessionConfigKey.AgentMerge) && value !== undefined)); + } + + /** The config values of `session` as persisted, which a restart restores. */ + async function persistedConfigValues(service: AgentService, session: URI): Promise<Record<string, unknown> | undefined> { + const persisted = (await getTestSessionStateStore(service).readWithoutImport(session, ['configValues'])).get('configValues'); + return persisted === undefined ? undefined : JSON.parse(persisted); + } + + /** A session config schema with an approval level each chat may set for itself, which Agent Merge elevates. */ + const approvalSchema = { + type: 'object' as const, properties: { + autoApprove: { type: 'string' as const, title: 'Approvals', enum: ['default', 'assisted', 'autoApprove'], sessionMutable: true, chatMutable: true }, + }, + }; + + /** + * Turns Agent Merge on, with its provider elevating approvals, for `folder` of `session`, owned by `chat` and + * bound to pull request `number`; `sessions` start with default approvals. + */ + async function enableAgentMerge(service: AgentService, agent: IAgent, sessions: readonly URI[], session: URI, chat: string, folder: URI, number: number, sessionValues: Record<string, unknown> = { autoApprove: 'default' }): Promise<Record<string, unknown>> { + agent.getAutonomousSessionConfig = () => ({ autoApprove: 'autoApprove' }); + getConfigurationService(service).updateRootConfig({ [AgentMergeConfigKey.Enabled]: true }); + for (const candidate of sessions) { + getStateManager(service).setSessionConfig(candidate.toString(), { schema: approvalSchema, values: sessionValues }); + } + const values = agentMergeConfigValues(chat, folder, number); + getConfigurationService(service).updateSessionConfig(session.toString(), values); + await timeout(0); + return values; + } + + /** The sessions the Agent Merge index resumes monitoring after a restart, by name. */ + async function agentMergeIndexOf(service: AgentService, names: Record<string, URI>): Promise<string[]> { + const internals = service as unknown as { _agentMergeIndexWrites: Promise<void>; _sessionRegistry: { listAgentMergeEnabled(): Promise<readonly URI[]> } }; + await internals._agentMergeIndexWrites; + return (await internals._sessionRegistry.listAgentMergeEnabled()).map(session => Object.entries(names).find(([, candidate]) => candidate.toString() === session.toString())?.[0] ?? session.toString()).sort(); + } + class MovingAgent extends MockAgent { readonly materialized: { readonly chat: string; readonly providerData: string | undefined }[] = []; readonly metadataStorage: string[] = []; @@ -35946,14 +36001,6 @@ suite('AgentService (node dispatcher)', () => { const stateManager = getStateManager(service); stateManager.setSessionMeta(source.toString(), withSessionWorkspaceless(stateManager.getSessionState(source.toString())?._meta, true)); }, - agentMergeOwner: async ({ service, source, peer, folder }) => { - const stateManager = getStateManager(service); - const config = stateManager.getSessionState(source.toString())?.config; - stateManager.setSessionConfig(source.toString(), { - schema: config?.schema ?? { type: 'object', properties: {} }, - values: { ...config?.values, [SessionConfigKey.AgentMergeFolders]: { [getWorkingDirectoryKey(folder.toString())]: { enabled: true, chat: peer.toString() } } }, - }); - }, legacyCatalog: async ({ internals, source }) => { // Its reconciliation is parked: its provider can't vouch for its chats. (internals as unknown as { _catalogReconciliationService: { isParked(session: string): boolean } })._catalogReconciliationService.isParked = session => session === source.toString(); @@ -36757,14 +36804,6 @@ suite('AgentService (node dispatcher)', () => { const changes: Record<string, (env: Awaited<ReturnType<typeof setupMove>>) => void> = { archived: ({ service, target }) => getStateManager(service).dispatchServerAction(target.toString(), { type: ActionType.SessionIsArchivedChanged, isArchived: true }), deleted: ({ service, source, peer }) => getStateManager(service).removeChat(source.toString(), peer.toString()), - agentMergeOwner: ({ service, source, peer, folder }) => { - const stateManager = getStateManager(service); - const config = stateManager.getSessionState(source.toString())?.config; - stateManager.setSessionConfig(source.toString(), { - schema: config?.schema ?? { type: 'object', properties: {} }, - values: { ...config?.values, [SessionConfigKey.AgentMergeFolders]: { [getWorkingDirectoryKey(folder.toString())]: { enabled: true, chat: peer.toString() } } }, - }); - }, }; const outcomes: Record<string, unknown> = {}; for (const [name, change] of Object.entries(changes)) { @@ -36784,7 +36823,6 @@ suite('AgentService (node dispatcher)', () => { assert.deepStrictEqual(outcomes, { archived: { reason: AgentChatMoveRefusal.SessionArchived, targetFolders: [other.toString()] }, deleted: { reason: AgentChatMoveRefusal.NotMovable, targetFolders: [other.toString()] }, - agentMergeOwner: { reason: AgentChatMoveRefusal.AgentMergeOwner, targetFolders: [other.toString()] }, }); }); @@ -36831,6 +36869,187 @@ suite('AgentService (node dispatcher)', () => { }); }); + test('a promoted chat\'s new session inherits neither the Agent Merge of its source nor its elevation', async () => { + const { service, source, peer, folder } = await setupMove(); + const stateManager = getStateManager(service); + const schema = { + type: 'object' as const, properties: { + autoApprove: { type: 'string' as const, title: 'Approvals', enum: ['default', 'assisted', 'autoApprove'], sessionMutable: true, chatMutable: true }, + autonomy: { type: 'string' as const, title: 'Autonomy', enum: ['low', 'high'], sessionMutable: true }, + }, + }; + const agentMerge = agentMergeConfigValues(buildDefaultChatUri(source), folder, 1); + // Elevated session-wide, as for a folder without a chat of the session: the peer uses it. + const elevation = { previous: { autoApprove: 'assisted', autonomy: 'low' }, applied: { autoApprove: 'autoApprove', autonomy: 'high' } }; + stateManager.setSessionConfig(source.toString(), { + schema, values: { + autoApprove: 'autoApprove', autonomy: 'high', ...agentMerge, + [SessionConfigKey.AgentMergeInjectedConfiguration]: elevation, + }, + }); + + completeTurn(service, peer); + const target = await service.moveChat(source, peer, { kind: 'newSession' }); + await timeout(0); + + assert.deepStrictEqual({ + memory: stateManager.getSessionState(target.toString())?.config?.values, + persisted: await persistedConfigValues(service, target), + sourceAgentMerge: agentMergeConfigValuesOf(stateManager.getSessionState(source.toString())?.config?.values), + }, { + memory: { autoApprove: 'assisted', autonomy: 'low' }, + persisted: { autoApprove: 'assisted', autonomy: 'low' }, + sourceAgentMerge: { ...agentMerge, [SessionConfigKey.AgentMergeInjectedConfiguration]: elevation }, + }); + }); + + test('a chat that runs Agent Merge takes it along when it moves to another session: the same pull request, target and feedback watermark, in memory, on disk and in the index', async () => { + const { service, agent, source, target, peer, folder } = await setupMove(true, URI.file('/other'), true); + const stateManager = getStateManager(service); + const agentMerge = await enableAgentMerge(service, agent, [source, target], source, peer.toString(), folder, 1); + const elevated = { [SessionConfigKey.AgentMergeChatInjectedConfiguration]: { [peer.toString()]: { previous: {}, applied: { autoApprove: 'autoApprove' } } } }; + const before = agentMergeConfigValuesOf(stateManager.getSessionState(source.toString())?.config?.values); + startTurn(service, peer); + + await service.moveChat(source, peer, { kind: 'session', session: target, after: undefined }); + await timeout(0); + await getTestSessionStateStore(service).whenIdle(undefined); + const off = { [SessionConfigKey.AgentMergeFolders]: { [getWorkingDirectoryKey(folder.toString())]: { enabled: false } }, [SessionConfigKey.AgentMergeControllerFolders]: {} }; + + assert.deepStrictEqual({ + before, + target: agentMergeConfigValuesOf(stateManager.getSessionState(target.toString())?.config?.values), + source: agentMergeConfigValuesOf(stateManager.getSessionState(source.toString())?.config?.values), + persisted: { target: agentMergeConfigValuesOf(await persistedConfigValues(service, target)), source: agentMergeConfigValuesOf(await persistedConfigValues(service, source)) }, + approvals: getConfigurationService(service).getChatConfigValues({ session: target.toString(), chat: peer.toString() })?.autoApprove, + indexed: await agentMergeIndexOf(service, { source, target }), + }, { + before: { ...agentMerge, ...elevated }, + target: { ...agentMerge, ...elevated }, + // Off, and none of the chat's: clients keep a folder's last settings, so they show it off. + source: off, + persisted: { target: { ...agentMerge, ...elevated }, source: off }, + approvals: 'autoApprove', + indexed: ['target'], + }); + }); + + test('a chat that runs Agent Merge moving into a session that already runs it for the folder keeps the destination\'s, and its own turns off with a notice and without its elevation', async () => { + const outcomes: Record<string, unknown> = {}; + const expected: Record<string, unknown> = {}; + // With approvals the sessions choose, and without: then the chat had none before Agent Merge elevated it. + for (const [name, sessionValues] of Object.entries({ sessionApprovals: { autoApprove: 'default' }, noApprovals: {} })) { + const { service, agent, source, target, peer, folder } = await setupMove(); + const stateManager = getStateManager(service); + const theirs = agentMergeConfigValues(buildDefaultChatUri(target), folder, 2); + await enableAgentMerge(service, agent, [source, target], source, peer.toString(), folder, 1, sessionValues); + getConfigurationService(service).updateSessionConfig(target.toString(), theirs); + await timeout(0); + + await service.moveChat(source, peer, { kind: 'session', session: target, after: undefined }); + await timeout(0); + const folders = (values: Readonly<Record<string, unknown>> | undefined) => ({ folders: values?.[SessionConfigKey.AgentMergeFolders], controller: values?.[SessionConfigKey.AgentMergeControllerFolders] }); + const notices = stateManager.getChatState(peer.toString())?.turns.flatMap(turn => turn.responseParts).filter(part => part.kind === ResponsePartKind.SystemNotification).map(part => part.kind === ResponsePartKind.SystemNotification ? part.content : undefined); + outcomes[name] = { + target: folders(stateManager.getSessionState(target.toString())?.config?.values), + source: folders(stateManager.getSessionState(source.toString())?.config?.values), + approvals: getConfigurationService(service).getChatConfigValues({ session: target.toString(), chat: peer.toString() })?.autoApprove, + notice: notices?.at(-1), + }; + expected[name] = { + target: folders(theirs), + source: { folders: { [getWorkingDirectoryKey(folder.toString())]: { enabled: false } }, controller: {} }, + approvals: sessionValues.autoApprove, + notice: 'Agent Merge was turned off for this chat: another chat in this session already runs it for this pull request.', + }; + } + + assert.deepStrictEqual(outcomes, expected); + }); + + test('a chat that runs Agent Merge promoted to its own session takes it along, keeping its elevation its own', async () => { + const { service, agent, source, peer, folder } = await setupMove(); + const stateManager = getStateManager(service); + const agentMerge = await enableAgentMerge(service, agent, [source], source, peer.toString(), folder, 1); + + completeTurn(service, peer); + startTurn(service, peer); + const promoted = await service.moveChat(source, peer, { kind: 'newSession' }); + await timeout(0); + await getTestSessionStateStore(service).whenIdle(undefined); + const elevated = { [SessionConfigKey.AgentMergeChatInjectedConfiguration]: { [peer.toString()]: { previous: {}, applied: { autoApprove: 'autoApprove' } } } }; + const off = { [SessionConfigKey.AgentMergeFolders]: { [getWorkingDirectoryKey(folder.toString())]: { enabled: false } }, [SessionConfigKey.AgentMergeControllerFolders]: {} }; + + assert.deepStrictEqual({ + promoted: agentMergeConfigValuesOf(stateManager.getSessionState(promoted.toString())?.config?.values), + source: agentMergeConfigValuesOf(stateManager.getSessionState(source.toString())?.config?.values), + persisted: { promoted: agentMergeConfigValuesOf(await persistedConfigValues(service, promoted)), source: agentMergeConfigValuesOf(await persistedConfigValues(service, source)) }, + approvals: { session: stateManager.getSessionState(promoted.toString())?.config?.values.autoApprove, chat: stateManager.getChatConfig(peer.toString())?.values }, + indexed: await agentMergeIndexOf(service, { source, promoted }), + }, { + promoted: { ...agentMerge, ...elevated }, + source: off, + persisted: { promoted: { ...agentMerge, ...elevated }, source: off }, + // Its future chats start without Agent Merge's elevation, which turning it off restores for the chat. + approvals: { session: 'default', chat: { autoApprove: 'autoApprove' } }, + indexed: ['promoted'], + }); + }); + + test('a chat that runs Agent Merge moved by a host that stops right after committing has it in its new session only, after a restart', async () => { + const outcomes: Record<string, unknown> = {}; + const expected: Record<string, unknown> = {}; + const off = { [SessionConfigKey.AgentMergeFolders]: { [getWorkingDirectoryKey(URI.file('/repo').toString())]: { enabled: false } }, [SessionConfigKey.AgentMergeControllerFolders]: {} }; + for (const kind of ['move', 'promotion'] as const) { + const { service, agent, source, target, peer, folder } = await setupMove(true, URI.file('/other'), true); + const agentMerge = await enableAgentMerge(service, agent, [source, target], source, peer.toString(), folder, 1); + const internals = service as unknown as { _transferMovedChatsAndState(): void; _promoteMovedChatsAndState(): void; _reloadAfterFailedMove(): Promise<void> }; + // The host goes away between the commit and memory: what is on disk is what a restart finds. + internals._transferMovedChatsAndState = internals._promoteMovedChatsAndState = () => { throw new Error('host stopped'); }; + internals._reloadAfterFailedMove = async () => { }; + completeTurn(service, peer); + const destination = await service.moveChat(source, peer, kind === 'move' ? { kind: 'session', session: target, after: undefined } : { kind: 'newSession' }); + await getTestSessionStateStore(service).whenIdle(undefined); + const bound = (values: Record<string, unknown> | undefined) => ({ [SessionConfigKey.AgentMergeFolders]: values?.[SessionConfigKey.AgentMergeFolders], [SessionConfigKey.AgentMergeControllerFolders]: values?.[SessionConfigKey.AgentMergeControllerFolders] }); + outcomes[kind] = { + destination: bound(await persistedConfigValues(service, destination)), + source: bound(await persistedConfigValues(service, source)), + indexed: await agentMergeIndexOf(service, { source, target, destination }), + }; + // Indexed before the commit; the source's flag clears on the restore that finds nothing on. + expected[kind] = { destination: bound(agentMerge), source: off, indexed: kind === 'move' ? ['source', 'target'] : ['destination', 'source'] }; + } + + assert.deepStrictEqual(outcomes, expected); + }); + + test('a promoted chat\'s Agent Merge keeps the feedback watermark it advanced while the promotion committed', async () => { + const { service, agent, source, peer, folder } = await setupMove(); + await enableAgentMerge(service, agent, [source], source, peer.toString(), folder, 1); + const advanced = { [getWorkingDirectoryKey(folder.toString())]: { target: { branchName: 'pr-1', pullRequestUrl: 'https://github.com/microsoft/vscode/pull/1', enabledAt: 'enabled-1', commentWatermark: 'watermark-advanced' } } }; + const store = getTestSessionStateStore(service); + const promoteChat = store.promoteChat.bind(store); + store.promoteChat = async promotion => { + const result = await promoteChat(promotion); + // A repair turn ended meanwhile and moved the watermark past the comments it addressed. + getConfigurationService(service).updateSessionConfig(source.toString(), { [SessionConfigKey.AgentMergeControllerFolders]: advanced }); + return result; + }; + + completeTurn(service, peer); + const promoted = await service.moveChat(source, peer, { kind: 'newSession' }); + await timeout(0); + await getTestSessionStateStore(service).whenIdle(undefined); + + assert.deepStrictEqual({ + memory: getStateManager(service).getSessionState(promoted.toString())?.config?.values[SessionConfigKey.AgentMergeControllerFolders], + persisted: (await persistedConfigValues(service, promoted))?.[SessionConfigKey.AgentMergeControllerFolders], + }, { + memory: advanced, + persisted: advanced, + }); + }); + test('a promoted worktree chat\'s session is a worktree session with its branch, base branch and isolation, its worktree recorded centrally only (Block 5)', async () => { const { service, source, peer, folder } = await setupMove(true, undefined, true, undefined, true); const stateManager = getStateManager(service); @@ -37597,6 +37816,124 @@ suite('AgentService (node dispatcher)', () => { }, { draft: 'After the move', strayDirectory: false }); }); + test('a session that runs Agent Merge nested under another keeps it in its chat there, across restarts, with no copy left behind; undoing the nest takes it along again', async () => { + const { createService, orchestratorDatabase, agent, service, source, target, chat } = await setupSessionMove(); + const folder = URI.file('/repo'); + const agentMerge = await enableAgentMerge(service, agent, [source, target], source, chat.toString(), folder, 1); + const elevated = { [SessionConfigKey.AgentMergeChatInjectedConfiguration]: { [chat.toString()]: { previous: {}, applied: { autoApprove: 'autoApprove' } } } }; + /** A host started over the same storage once `previous` is idle, resuming the monitoring the index records. */ + const restart = async (previous: AgentService) => { + await previous.whenCatalogReconciliationIdle(); + await getTestSessionStateStore(previous).whenIdle(undefined); + const restarted = createService(); + await restarted.listSessions(); + getConfigurationService(restarted).updateRootConfig({ [AgentMergeConfigKey.Enabled]: true }); + await restarted.whenAgentMergeSessionsRestored(); + return restarted; + }; + const agentMergeIn = (host: AgentService, session: URI) => agentMergeConfigValuesOf(getStateManager(host).getSessionState(session.toString())?.config?.values); + // A restarted host elevates by its provider's schema, where approvals are session-wide: the folders' settings and targets carry over. + const boundIn = (host: AgentService, session: URI) => { + const values = getStateManager(host).getSessionState(session.toString())?.config?.values; + return { [SessionConfigKey.AgentMergeFolders]: values?.[SessionConfigKey.AgentMergeFolders], [SessionConfigKey.AgentMergeControllerFolders]: values?.[SessionConfigKey.AgentMergeControllerFolders] }; + }; + const bound = { [SessionConfigKey.AgentMergeFolders]: agentMerge[SessionConfigKey.AgentMergeFolders], [SessionConfigKey.AgentMergeControllerFolders]: agentMerge[SessionConfigKey.AgentMergeControllerFolders] }; + + await service.moveSession(source, target, undefined); + await timeout(0); + await getTestSessionStateStore(service).whenIdle(undefined); + const sourceDatabase = (service as unknown as { _sessionDataService: ISessionDataService })._sessionDataService.openDatabase(source); + const nested = { + target: agentMergeIn(service, target), + approvals: getConfigurationService(service).getChatConfigValues({ session: target.toString(), chat: chat.toString() })?.autoApprove, + // An older build never finds it enabled where it no longer is. + endedSessionCopy: await sourceDatabase.object.getMetadata('configValues'), + indexed: await agentMergeIndexOf(service, { source, target }), + }; + sourceDatabase.dispose(); + const restarted = await restart(service); + const nestedAfterRestart = boundIn(restarted, target); + + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Write the stored row, as the host does. + const raw = await orchestratorDatabase['_ensureDatabase'](); + await new Promise<void>((resolve, reject) => raw.run('UPDATE chats_v2 SET provider_data = ? WHERE chat_uri = ?', ['session-backing', chat.toString()], error => error ? reject(error) : resolve())); + await getStateManager(restarted).resolveChatState(chat.toString()); + completeTurn(restarted, chat); + const promoted = await restarted.moveChat(target, chat, { kind: 'newSession' }); + await timeout(0); + const undone = { promoted: boundIn(restarted, promoted), target: boundIn(restarted, target), indexed: await agentMergeIndexOf(restarted, { source, target, promoted }) }; + const undoneAfterRestart = await restart(restarted); + const persisted = await persistedConfigValues(undoneAfterRestart, promoted); + + assert.deepStrictEqual({ + nested, nestedAfterRestart, undone, undoneAfterRestart: { + promoted: { [SessionConfigKey.AgentMergeFolders]: persisted?.[SessionConfigKey.AgentMergeFolders], [SessionConfigKey.AgentMergeControllerFolders]: persisted?.[SessionConfigKey.AgentMergeControllerFolders] }, + indexed: await agentMergeIndexOf(undoneAfterRestart, { source, target, promoted }), + targetLoaded: getStateManager(undoneAfterRestart).getSessionState(target.toString()) !== undefined, + }, + }, { + nested: { target: { ...agentMerge, ...elevated }, approvals: 'autoApprove', endedSessionCopy: undefined, indexed: ['target'] }, + nestedAfterRestart: bound, + // Off for the destination's chats, with nothing of the chat's. + undone: { promoted: bound, target: { [SessionConfigKey.AgentMergeFolders]: { [getWorkingDirectoryKey(folder.toString())]: { enabled: false } }, [SessionConfigKey.AgentMergeControllerFolders]: undefined }, indexed: ['promoted'] }, + // The destination isn't monitored any more, so nothing restores it. + undoneAfterRestart: { promoted: bound, indexed: ['promoted'], targetLoaded: false }, + }); + }); + + test('a session that runs Agent Merge nested under one that already runs it for its pull request keeps no copy of it for older builds', async () => { + const { agent, service, source, target, chat } = await setupSessionMove(); + const folder = URI.file('/repo'); + await enableAgentMerge(service, agent, [source, target], source, chat.toString(), folder, 1); + const theirs = agentMergeConfigValues(getStateManager(service).getSessionState(target.toString())!.defaultChat!, folder, 1); + getConfigurationService(service).updateSessionConfig(target.toString(), theirs); + await timeout(0); + await getTestSessionStateStore(service).whenIdle(undefined); + const sourceDatabase = (service as unknown as { _sessionDataService: ISessionDataService })._sessionDataService.openDatabase(source); + const before = await sourceDatabase.object.getMetadata('configValues') !== undefined; + + await service.moveSession(source, target, undefined); + await timeout(0); + await getTestSessionStateStore(service).whenIdle(undefined); + const endedSessionCopy = await sourceDatabase.object.getMetadata('configValues'); + sourceDatabase.dispose(); + const values = getStateManager(service).getSessionState(target.toString())?.config?.values; + + assert.deepStrictEqual({ before, endedSessionCopy, target: { [SessionConfigKey.AgentMergeFolders]: values?.[SessionConfigKey.AgentMergeFolders], [SessionConfigKey.AgentMergeControllerFolders]: values?.[SessionConfigKey.AgentMergeControllerFolders] } }, { + before: true, + endedSessionCopy: undefined, + target: theirs, + }); + }); + + test('a moved session\'s chat promoted out again inherits none of the destination\'s Agent Merge, in memory or on disk', async () => { + const { orchestratorDatabase, service, source, target, chat } = await setupSessionMove(); + const stateManager = getStateManager(service); + const targetChat = stateManager.getSessionState(target.toString())!.defaultChat!; + const agentMerge = agentMergeConfigValues(targetChat, URI.file('/repo'), 2); + const targetConfig = stateManager.getSessionState(target.toString())?.config; + stateManager.setSessionConfig(target.toString(), { schema: targetConfig?.schema ?? { type: 'object', properties: {} }, values: { ...targetConfig?.values, ...agentMerge } }); + + await service.moveSession(source, target, undefined); + // eslint-disable-next-line local/code-no-bracket-notation-for-identifiers -- Write the stored row, as the host does. + const raw = await orchestratorDatabase['_ensureDatabase'](); + await new Promise<void>((resolve, reject) => raw.run('UPDATE chats_v2 SET provider_data = ? WHERE chat_uri = ?', ['session-backing', chat.toString()], error => error ? reject(error) : resolve())); + completeTurn(service, chat); + const promoted = await service.moveChat(target, chat, { kind: 'newSession' }); + await service.whenCatalogReconciliationIdle(); + await getTestSessionStateStore(service).whenIdle(undefined); + + assert.deepStrictEqual({ + memory: agentMergeConfigValuesOf(stateManager.getSessionState(promoted.toString())?.config?.values), + persisted: agentMergeConfigValuesOf(await persistedConfigValues(service, promoted) as Record<string, unknown>), + target: agentMergeConfigValuesOf(stateManager.getSessionState(target.toString())?.config?.values), + }, { + memory: {}, + persisted: {}, + target: agentMerge, + }); + }); + test('the session\'s recorded pull request moves with its chat, and comes back with it when the move is undone by promoting the chat, across a restart', async () => { const { createService, orchestratorDatabase, service, source, target, chat } = await setupSessionMove(); const targetChat = getStateManager(service).getSessionState(target.toString())!.defaultChat!; @@ -44023,6 +44360,22 @@ suite('AgentService (node dispatcher)', () => { }); }); + test('a session indexed with nothing on, as a host that stopped right after moving its Agent Merge away leaves it, leaves the index on its next restore', async () => { + const orchestratorDb = new TestAgentHostOrchestratorDatabase(); + const sessionDb = new TestSessionDatabase(); + const { localAgent, localService, sessionResource } = await createEnabledSession(sessionDb, orchestratorDb); + await getTestSessionStateStore(localService).update(sessionResource, 'configValues', () => JSON.stringify({ [SessionConfigKey.AgentMerge]: { enabled: false } }), SessionStateMirrorFlush.Immediate); + localService.dispose(); + await orchestratorDb.setSessionAgentMergeEnabled(sessionResource.toString(), true); + + const restarted = createAgentMergeService(sessionDb, orchestratorDb); + registerTestAgentProvider(restarted, localAgent); + await restarted.whenAgentMergeSessionsRestored(); + await restarted.whenAgentMergeSessionsRestored(); + + assert.deepStrictEqual(await orchestratorDb.listAgentMergeEnabledSessions(), []); + }); + test('enabling records the session in the host index rather than in each session database', async () => { const orchestratorDb = new TestAgentHostOrchestratorDatabase(); const { sessionResource } = await createEnabledSession(new TestSessionDatabase(), orchestratorDb); diff --git a/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts b/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts index 2faf4e9705212c..afb499a4215546 100644 --- a/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts +++ b/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts @@ -2373,6 +2373,29 @@ suite('CopilotAgentSession', () => { }); }); + test('configures the running process for its current owner once its launch owner ended by moving it under another session', async () => { + const ended = AgentSession.uri('copilot', 'owner-ended'); + const current = AgentSession.uri('copilot', 'owner-current'); + const owner = disposables.add(new TestChatOwnerRef(ended)); + const logService = new CapturingLogService(); + // Only the current owner has config: the launch owner ended with the move, leaving its values to the chat. + const { session, mockSession } = await createAgentSession(disposables, { + sessionUri: current, owner, logService, + configValues: { [SessionConfigKey.AutoApprove]: 'default' }, + chatConfigValues: { [SessionConfigKey.AutoApprove]: 'assisted', [SessionConfigKey.Mode]: 'autopilot' }, + }); + owner.set(current); + await session.syncPermissionMode('config-change'); + + assert.deepStrictEqual({ + permissionModes: mockSession.permissionModeSetCalls, + logs: logService.infos.map(entry => entry.message).filter(message => message.includes('Syncing permission mode')), + }, { + permissionModes: ['assisted'], + logs: ['[Copilot:test-session-1] Syncing permission mode: source=config-change, agentMode=autopilot, configuredLevel=assisted, sdkMode=assisted, previousSdkMode=unknown, globalAutoApprove=false'], + }); + }); + test('shows a synchronous command once the runtime moves it to the background', async () => { const { mockSession, signals, waitForSignal } = await createAgentSession(disposables); mockSession.backgroundTasks = [{ ...shell('timed-out'), executionMode: 'sync' }]; @@ -23811,7 +23834,7 @@ Use the attached image as context. mockSession.fire('tool.execution_start', { toolCallId: 'tc-window', toolName: 'get_window_state', mcpServerName: 'computer-use' }); const first = permissionPrompt(runtime); const setupId = configuration.status?.setups[0]?.id ?? ''; - configuration.send({ setupId, round: 1, action: 'request', permission: 'accessibility' }); + configuration.send({ setupId, round: 1, action: 'allow', permission: 'accessibility' }); const firstResult = await first; const second = permissionPrompt(runtime, ['screenRecording']); configuration.send({ setupId, round: 2, action: 'recheck' }); @@ -23900,7 +23923,7 @@ Use the attached image as context. permissions: configuration.status?.permissions.map(permission => permission.state), actions: inputActions(signals).map(action => action.type === 'requested' ? action.setup : action.response), }, { - setup: [{ state: 'ended', error: 'unsupportedPrompt' }], + setup: [{ state: 'ended', error: undefined }], permissions: ['granted', 'notGranted'], actions: [true, ChatInputResponseKind.Cancel, false], }); @@ -23913,7 +23936,7 @@ Use the attached image as context. await session[cancellation](); assert.deepStrictEqual({ result: await result, setup: configuration.status?.setups.map(candidate => ({ state: candidate.state, error: candidate.error?.code })) }, { result: { action: 'cancel' }, - setup: [{ state: 'ended', error: 'notWaiting' }], + setup: [{ state: 'ended', error: undefined }], }); }); } @@ -31685,6 +31708,19 @@ Use the attached image as context. ); }); + test('applies the session script of the chat\'s current owner once its launch owner ended by moving it under another session', async () => { + const ended = AgentSession.uri('copilot', 'owner-ended'); + const current = AgentSession.uri('copilot', 'owner-current'); + const owner = disposables.add(new TestChatOwnerRef(ended)); + // Only the current owner has config: the launch owner ended with the move. + const { session, mockSession } = await createEnabledSession({ sessionUri: current, owner, configValues: { [SessionConfigKey.ShellInitScripts]: [initScript] } }); + owner.set(current); + + await session.send('go', undefined, 'turn-1', 'interactive'); + + assert.deepStrictEqual(mockSession.shellInitScriptUpdates.map(update => (update as unknown[]).length), [1]); + }); + test('does not apply a session script while the host flag is off', async () => { const { session, mockSession, storedFileContents, setConfigValue } = await createAgentSession(disposables); setConfigValue(SessionConfigKey.ShellInitScripts, [initScript]); diff --git a/src/vs/platform/agentHost/test/node/copilotComputerUsePermissionSetup.test.ts b/src/vs/platform/agentHost/test/node/copilotComputerUsePermissionSetup.test.ts index 246dc49899f00e..92a6f0e4f92158 100644 --- a/src/vs/platform/agentHost/test/node/copilotComputerUsePermissionSetup.test.ts +++ b/src/vs/platform/agentHost/test/node/copilotComputerUsePermissionSetup.test.ts @@ -141,8 +141,8 @@ suite('CopilotComputerUsePermissionSetup', () => { }; }; assert.deepStrictEqual({ working: await run(true), waiting: await run(false) }, { - working: { result: { action: 'accept', content: { choice: 'try_again' } }, setup: [{ state: 'ended', error: 'unsupportedPrompt' }], permissions: ['notGranted', 'notGranted'], cardCompletions: [ChatInputResponseKind.Cancel] }, - waiting: { result: { action: 'cancel' }, setup: [{ state: 'ended', error: 'unsupportedPrompt' }], permissions: ['notGranted', 'notGranted'], cardCompletions: [ChatInputResponseKind.Cancel] }, + working: { result: { action: 'accept', content: { choice: 'try_again' } }, setup: [{ state: 'ended', error: undefined }], permissions: ['notGranted', 'notGranted'], cardCompletions: [ChatInputResponseKind.Cancel] }, + waiting: { result: { action: 'cancel' }, setup: [{ state: 'ended', error: undefined }], permissions: ['notGranted', 'notGranted'], cardCompletions: [ChatInputResponseKind.Cancel] }, }); }); @@ -154,7 +154,7 @@ suite('CopilotComputerUsePermissionSetup', () => { const first = prompt(setup, chat, ['accessibility', 'screenRecording']); const needsBoth = configuration.status; const setupId = needsBoth?.setups[0]?.id ?? ''; - configuration.send({ setupId, round: 1, action: 'request', permission: 'accessibility' }); + configuration.send({ setupId, round: 1, action: 'allow', permission: 'accessibility' }); const working = configuration.status; await first.done; @@ -175,10 +175,10 @@ suite('CopilotComputerUsePermissionSetup', () => { permissions: [{ permission: 'accessibility', state: 'notGranted' }, { permission: 'screenRecording', state: 'notGranted' }], setups: [{ chat: 'chat:a', state: 'needsPermissions', round: 1, - actions: [{ action: 'request', permission: 'accessibility' }, { action: 'request', permission: 'screenRecording' }, { action: 'recheck' }], + actions: [{ action: 'allow', permission: 'accessibility' }, { action: 'allow', permission: 'screenRecording' }, { action: 'recheck' }], }], }, - working: { operation: { setupId, action: 'request', permission: 'accessibility' }, state: 'working', actions: [] }, + working: { operation: { setupId, action: 'allow', permission: 'accessibility' }, state: 'working', actions: [] }, firstAnswer: [{ action: 'accept', content: { choice: 'request_accessibility' } }], card: { purpose: ChatInputRequestPurpose.Elicitation, setup: { setupId }, message: 'Copilot Computer Use needs macOS permissions', questions: ['choice'] }, sameCard: true, @@ -186,13 +186,74 @@ suite('CopilotComputerUsePermissionSetup', () => { permissions: [{ permission: 'accessibility', state: 'granted' }, { permission: 'screenRecording', state: 'notGranted' }], setups: [{ chat: 'chat:a', state: 'needsPermissions', round: 2, - actions: [{ action: 'request', permission: 'screenRecording' }, { action: 'openSettings', permission: 'screenRecording' }, { action: 'recheck' }], + actions: [{ action: 'allow', permission: 'screenRecording' }, { action: 'recheck' }], }], pending: [], }, }); }); + test('asks macOS natively the first time Allow is chosen, and opens System Settings on a later Allow in the same loop', async () => { + const { configuration, setup } = createSetup(); + const chat = new TestSetupChat('chat:a'); + const first = prompt(setup, chat, ['accessibility', 'screenRecording']); + const setupId = configuration.status?.setups[0]?.id ?? ''; + configuration.send({ setupId, round: 1, action: 'allow', permission: 'accessibility' }); + await first.done; + const second = prompt(setup, chat, ['accessibility', 'screenRecording'], ['accessibility']); + configuration.send({ setupId, round: 2, action: 'allow', permission: 'accessibility' }); + const openingSettings = configuration.status?.operation; + await second.done; + const third = prompt(setup, chat, ['accessibility', 'screenRecording'], ['accessibility']); + configuration.send({ setupId, round: 3, action: 'allow', permission: 'screenRecording' }); + await third.done; + + assert.deepStrictEqual({ answers: [...first.results, ...second.results, ...third.results], openingSettings }, { + answers: [ + { action: 'accept', content: { choice: 'request_accessibility' } }, + { action: 'accept', content: { choice: 'settings_accessibility' } }, + { action: 'accept', content: { choice: 'request_screen_recording' } }, + ], + openingSettings: { setupId, action: 'allow', permission: 'accessibility' }, + }); + }); + + test('in a new loop, asks macOS again for a permission it already asked for, then opens System Settings on its own', async () => { + const { configuration, setup } = createSetup(); + const chat = new TestSetupChat('chat:a'); + const firstLoop = prompt(setup, chat, ['accessibility']); + configuration.send({ setupId: configuration.status?.setups[0]?.id ?? '', round: 1, action: 'allow', permission: 'accessibility' }); + await firstLoop.done; + // The waiting tool call timed out, and the next one starts a new loop, which offers no System Settings pane yet. + setup.onToolCallCompleted(chat, false); + const newLoop = prompt(setup, chat, ['accessibility']); + const setupId = configuration.status?.setups[1]?.id ?? ''; + const publishedBefore = configuration.published.length; + configuration.send({ setupId, round: 1, action: 'allow', permission: 'accessibility' }); + await newLoop.done; + const next = prompt(setup, chat, ['accessibility'], ['accessibility']); + await next.done; + + assert.deepStrictEqual({ + answers: [...firstLoop.results, ...newLoop.results, ...next.results], + published: configuration.published.slice(publishedBefore).map(status => { + const candidate = status?.setups.find(entry => entry.id === setupId); + return { state: candidate?.state, round: candidate?.round, operation: status?.operation }; + }), + }, { + answers: [ + { action: 'accept', content: { choice: 'request_accessibility' } }, + { action: 'accept', content: { choice: 'request_accessibility' } }, + { action: 'accept', content: { choice: 'settings_accessibility' } }, + ], + // The setup goes from one step of the user's Allow to the next without waiting in between. + published: [ + { state: 'working', round: 1, operation: { setupId, action: 'allow', permission: 'accessibility' } }, + { state: 'working', round: 2, operation: { setupId, action: 'allow', permission: 'accessibility' } }, + ], + }); + }); + test('drops duplicate, stale, unoffered and malformed requests', async () => { const { configuration, setup } = createSetup(); const chat = new TestSetupChat('chat:a'); @@ -200,13 +261,14 @@ suite('CopilotComputerUsePermissionSetup', () => { const setupId = configuration.status?.setups[0]?.id ?? ''; const nonce = configuration.send({ setupId, round: 1, action: 'recheck' }); await first.done; - const second = prompt(setup, chat, ['accessibility', 'screenRecording']); + const second = prompt(setup, chat, ['accessibility']); configuration.send({ setupId, round: 2, action: 'recheck', nonce }); - configuration.send({ setupId, round: 1, action: 'request', permission: 'accessibility' }); - configuration.send({ setupId, round: 2, action: 'openSettings', permission: 'accessibility' }); + configuration.send({ setupId, round: 1, action: 'allow', permission: 'accessibility' }); + configuration.send({ setupId, round: 2, action: 'allow', permission: 'screenRecording' }); configuration.send({ setupId: 'unknown', round: 2, action: 'recheck' }); - configuration.updateRootConfig({ [COMPUTER_USE_REQUEST_KEY]: { nonce: 'n', setupId, round: 2, action: 'request' } }); + configuration.updateRootConfig({ [COMPUTER_USE_REQUEST_KEY]: { nonce: 'n', setupId, round: 2, action: 'allow' } }); + configuration.updateRootConfig({ [COMPUTER_USE_REQUEST_KEY]: { nonce: 'm', setupId, round: 2, action: 'request', permission: 'accessibility' } }); await timeout(0); assert.deepStrictEqual({ @@ -244,7 +306,82 @@ suite('CopilotComputerUsePermissionSetup', () => { }; assert.deepStrictEqual({ succeeded: await run(true), failed: await run(false) }, { succeeded: { stillOff: 'stillNotGranted', state: 'ready', error: undefined, permissions: ['granted', 'granted'], cardCompletions: [ChatInputResponseKind.Accept] }, - failed: { stillOff: 'stillNotGranted', state: 'ended', error: 'unconfirmed', permissions: ['notGranted', 'notGranted'], cardCompletions: [ChatInputResponseKind.Cancel] }, + failed: { stillOff: 'stillNotGranted', state: 'ended', error: undefined, permissions: ['notGranted', 'notGranted'], cardCompletions: [ChatInputResponseKind.Cancel] }, + }); + }); + + test('publishes no error for a setup that ended, however it ended', async () => { + const end = async (stop: (setup: CopilotComputerUsePermissionSetup, chat: TestSetupChat) => void, whileWorking = false) => { + const { configuration, setup } = createSetup(); + const chat = new TestSetupChat('chat:a'); + const pending = prompt(setup, chat, ['accessibility']); + if (whileWorking) { + configuration.send({ setupId: configuration.status?.setups[0]?.id ?? '', round: 1, action: 'recheck' }); + } + stop(setup, chat); + await pending.done; + return configuration.status?.setups.map(({ id, ...rest }) => rest); + }; + const ended = [{ chat: 'chat:a', state: 'ended', round: 1, actions: [] }]; + assert.deepStrictEqual({ + timedOutWhileWaiting: await end((setup, chat) => setup.onToolCallCompleted(chat, false)), + timedOutWhileWorking: await end((setup, chat) => setup.onToolCallCompleted(chat, false), true), + chatStopped: await end((setup, chat) => setup.cancelChat(chat)), + declined: await end((setup, chat) => setup.respondToInput(chat, chat.requests[0].id, ChatInputResponseKind.Decline, undefined)), + unrecognizedPrompt: await end((setup, chat) => setup.onUnrecognizedPrompt(chat)), + }, { + timedOutWhileWaiting: ended, + timedOutWhileWorking: ended, + chatStopped: ended, + declined: ended, + unrecognizedPrompt: ended, + }); + }); + + test('lets the other waiting setups check again on their own once one is ready, even right after macOS asked for Accessibility', () => runWithFakedTimers({}, async () => { + const { configuration, setup } = createSetup(); + const [chatA, chatB] = [new TestSetupChat('chat:a'), new TestSetupChat('chat:b')]; + const a = prompt(setup, chatA, ['accessibility']); + const b = prompt(setup, chatB, ['accessibility']); + const setupA = configuration.status?.setups[0]?.id ?? ''; + configuration.send({ setupId: setupA, round: 1, action: 'allow', permission: 'accessibility' }); + await a.done; + // macOS asked for Accessibility, and the user turned it on before checking again. + const again = prompt(setup, chatA, ['accessibility'], ['accessibility']); + configuration.send({ setupId: setupA, round: 2, action: 'recheck' }); + await again.done; + setup.onToolCallCompleted(chatA, true); + await timeout(0); + const checkedOnItsOwn = [...b.results]; + setup.onToolCallCompleted(chatB, true); + + assert.deepStrictEqual({ checkedOnItsOwn, setups: configuration.status?.setups.map(candidate => candidate.state) }, { + checkedOnItsOwn: [{ action: 'accept', content: { choice: 'try_again' } }], + setups: ['ready', 'ready'], + }); + })); + + test('sends exactly the choice a client without the setup UI picked, and remembers its native requests', async () => { + const { configuration, setup } = createSetup(); + const chat = new TestSetupChat('chat:a'); + const answer = async (choice: string) => { + const pending = prompt(setup, chat, ['accessibility'], ['accessibility']); + setup.respondToInput(chat, chat.requests.at(-1)?.id ?? '', ChatInputResponseKind.Accept, { choice: { state: ChatInputAnswerState.Submitted, value: { kind: ChatInputAnswerValueKind.Selected, value: choice } } }); + return pending.done; + }; + // Nothing asked macOS natively yet, so Allow would ask first. + const openSettings = await answer('settings_accessibility'); + const request = await answer('request_accessibility'); + // macOS asked already, so Allow would open System Settings. + const requestAgain = await answer('request_accessibility'); + const allow = prompt(setup, chat, ['accessibility'], ['accessibility']); + configuration.send({ setupId: configuration.status?.setups[0]?.id ?? '', round: 4, action: 'allow', permission: 'accessibility' }); + + assert.deepStrictEqual({ openSettings, request, requestAgain, allow: await allow.done }, { + openSettings: { action: 'accept', content: { choice: 'settings_accessibility' } }, + request: { action: 'accept', content: { choice: 'request_accessibility' } }, + requestAgain: { action: 'accept', content: { choice: 'request_accessibility' } }, + allow: { action: 'accept', content: { choice: 'settings_accessibility' } }, }); }); @@ -301,7 +438,7 @@ suite('CopilotComputerUsePermissionSetup', () => { const unchanged = { state: configuration.status?.setups[0]?.state, error: configuration.status?.setups[0]?.error }; // Asking for Accessibility adds the app to macOS's list while macOS shows its prompt, which the helper holds. - configuration.send({ setupId, round: 2, action: 'request', permission: 'accessibility' }); + configuration.send({ setupId, round: 2, action: 'allow', permission: 'accessibility' }); accessibilityTrust.reportChange(); await timeout(1000); const third = prompt(setup, chat, ['accessibility', 'screenRecording'], ['accessibility']); @@ -330,9 +467,9 @@ suite('CopilotComputerUsePermissionSetup', () => { const c = prompt(setup, chatC, ['accessibility']); const [setupA, setupB] = configuration.status?.setups.map(candidate => candidate.id) ?? []; - // A's request runs while B's waits; a check queued now would run as macOS shows B's prompt. - configuration.send({ setupId: setupA, round: 1, action: 'request', permission: 'screenRecording' }); - configuration.send({ setupId: setupB, round: 1, action: 'request', permission: 'accessibility' }); + // A's request runs while B's Allow waits; a check queued now would run as macOS shows B's prompt. + configuration.send({ setupId: setupA, round: 1, action: 'allow', permission: 'screenRecording' }); + configuration.send({ setupId: setupB, round: 1, action: 'allow', permission: 'accessibility' }); accessibilityTrust.reportChange(); await timeout(1000); prompt(setup, chatA, ['screenRecording'], ['screenRecording']); @@ -346,17 +483,17 @@ suite('CopilotComputerUsePermissionSetup', () => { const { configuration, setup, accessibilityTrust } = createSetup(); const [chatA, chatB] = [new TestSetupChat('chat:a'), new TestSetupChat('chat:b')]; prompt(setup, chatA, ['accessibility']); - const b = prompt(setup, chatB, ['accessibility'], ['accessibility']); + const b = prompt(setup, chatB, ['accessibility']); const setupB = configuration.status?.setups[1]?.id ?? ''; - // A's automatic check runs while B's waits, and B's user asks for System Settings meanwhile. + // A's automatic check runs while B's waits, and B's user chooses Allow meanwhile. accessibilityTrust.reportChange(); await timeout(1000); - configuration.send({ setupId: setupB, round: 1, action: 'openSettings', permission: 'accessibility' }); + configuration.send({ setupId: setupB, round: 1, action: 'allow', permission: 'accessibility' }); prompt(setup, chatA, ['accessibility']); await timeout(0); - assert.deepStrictEqual(b.results, [{ action: 'accept', content: { choice: 'settings_accessibility' } }]); + assert.deepStrictEqual(b.results, [{ action: 'accept', content: { choice: 'request_accessibility' } }]); })); test('runs one action at a time across chats so native prompts never overlap', async () => { @@ -366,8 +503,8 @@ suite('CopilotComputerUsePermissionSetup', () => { const a = prompt(setup, chatA, ['accessibility']); const b = prompt(setup, chatB, ['accessibility']); const [setupA, setupB] = configuration.status?.setups.map(candidate => candidate.id) ?? []; - configuration.send({ setupId: setupA, round: 1, action: 'request', permission: 'accessibility' }); - configuration.send({ setupId: setupB, round: 1, action: 'request', permission: 'accessibility' }); + configuration.send({ setupId: setupA, round: 1, action: 'allow', permission: 'accessibility' }); + configuration.send({ setupId: setupB, round: 1, action: 'allow', permission: 'accessibility' }); await timeout(0); const whileAWorks = { a: a.results.length, b: b.results.length, operation: configuration.status?.operation?.setupId === setupA }; prompt(setup, chatA, ['accessibility'], ['accessibility']); @@ -445,7 +582,7 @@ suite('CopilotComputerUsePermissionSetup', () => { }, { cancelled: [{ action: 'cancel' }], stopped: [{ action: 'cancel' }], - setups: [{ own: true, state: 'ended', error: 'notWaiting' }, { own: true, state: 'ended', error: 'notWaiting' }], + setups: [{ own: true, state: 'ended', error: undefined }, { own: true, state: 'ended', error: undefined }], cardCompletions: { cancelled: [], stopped: [ChatInputResponseKind.Cancel] }, }); }); diff --git a/src/vs/platform/git/node/localGitService.ts b/src/vs/platform/git/node/localGitService.ts index 3bcb7608dd87d5..f05e11a7093915 100644 --- a/src/vs/platform/git/node/localGitService.ts +++ b/src/vs/platform/git/node/localGitService.ts @@ -125,17 +125,19 @@ export class LocalGitService implements ILocalGitService { } async clone(operationId: string, cloneUrl: string, targetPath: string, ref?: string, options?: IGitNetworkOptions): Promise<void> { - const args = ['clone']; + const args = ['clone', '--depth', '1']; const normalizedRef = ref?.trim().toLowerCase(); const pinnedCommit = normalizedRef && FULL_COMMIT_SHA_PATTERN.test(normalizedRef) ? normalizedRef : undefined; - if (ref && !pinnedCommit) { + if (pinnedCommit) { + args.push('--no-checkout'); + } else if (ref) { args.push('--branch', ref); } args.push('--', cloneUrl, targetPath); await this._exec(operationId, args, undefined, options); if (pinnedCommit) { try { - await this._exec(operationId, ['fetch', 'origin', pinnedCommit], targetPath, options); + await this._exec(operationId, ['fetch', '--depth', '1', 'origin', pinnedCommit], targetPath, options); await this.checkoutCommit(operationId, targetPath, pinnedCommit); } catch (error) { try { diff --git a/src/vs/platform/git/test/node/localGitService.test.ts b/src/vs/platform/git/test/node/localGitService.test.ts index f6d8ddb95d33e4..302e6c3a7ac482 100644 --- a/src/vs/platform/git/test/node/localGitService.test.ts +++ b/src/vs/platform/git/test/node/localGitService.test.ts @@ -7,6 +7,7 @@ import assert from 'assert'; import * as cp from 'child_process'; import { promises as fs } from 'fs'; import { tmpdir } from 'os'; +import { pathToFileURL } from 'url'; import { promisify } from 'util'; import { CancellationError, isCancellationError } from '../../../../base/common/errors.js'; import { join } from '../../../../base/common/path.js'; @@ -82,7 +83,7 @@ suite('LocalGitService', () => { } } const expectations: IExecFileExpectation[] = [{ args: ['--version'], stdout: 'git version 2.31.0\n' }, { - args: ['clone', '--', 'https://github.com/test/private.git', '/tmp/private'], + args: ['clone', '--depth', '1', '--', 'https://github.com/test/private.git', '/tmp/private'], environment: { GIT_TRACE2: '0', GIT_TRACE2_EVENT: '0', @@ -107,12 +108,25 @@ suite('LocalGitService', () => { assert.strictEqual(expectations.length, 0); }); - test('clone fetches and checks out a full commit SHA', async () => { + for (const ref of [undefined, 'main', 'v1.0.0']) { + test(`clone limits history for ${ref ?? 'the default branch'}`, async () => { + const expectations: IExecFileExpectation[] = [{ + args: ['clone', '--depth', '1', ...(ref ? ['--branch', ref] : []), '--', 'https://github.com/test/repo.git', '/tmp/repo'], + }]; + const service = new LocalGitService(new NullLogService(), createExecFile(expectations)); + + await service.clone('test-op', 'https://github.com/test/repo.git', '/tmp/repo', ref); + + assert.strictEqual(expectations.length, 0); + }); + } + + test('clone shallowly fetches and checks out a full commit SHA', async () => { const commit = 'AABBCCDDEEFF00112233445566778899AABBCCDD'; const normalizedCommit = commit.toLowerCase(); const expectations: IExecFileExpectation[] = [ - { args: ['clone', '--', 'https://github.com/test/repo.git', '/tmp/repo'] }, - { args: ['fetch', 'origin', normalizedCommit] }, + { args: ['clone', '--depth', '1', '--no-checkout', '--', 'https://github.com/test/repo.git', '/tmp/repo'] }, + { args: ['fetch', '--depth', '1', 'origin', normalizedCommit] }, { args: ['rev-parse', `${normalizedCommit}^{commit}`], stdout: `${normalizedCommit}\n` }, { args: ['checkout', '--detach', normalizedCommit] }, { args: ['rev-parse', 'HEAD'], stdout: `${normalizedCommit}\n` }, @@ -132,8 +146,8 @@ suite('LocalGitService', () => { await fs.mkdir(targetPath); const checkoutError = new Error('Commit is unavailable'); const expectations: IExecFileExpectation[] = [ - { args: ['clone', '--', 'https://github.com/test/repo.git', targetPath] }, - { args: ['fetch', 'origin', commit] }, + { args: ['clone', '--depth', '1', '--no-checkout', '--', 'https://github.com/test/repo.git', targetPath] }, + { args: ['fetch', '--depth', '1', 'origin', commit] }, { args: ['rev-parse', `${commit}^{commit}`], error: checkoutError }, ]; const service = new LocalGitService(new NullLogService(), createExecFile(expectations)); @@ -150,8 +164,8 @@ suite('LocalGitService', () => { const targetPath = join(parentPath, 'repo'); await fs.mkdir(targetPath); const expectations: IExecFileExpectation[] = [ - { args: ['clone', '--', 'https://github.com/test/repo.git', targetPath] }, - { args: ['fetch', 'origin', commit], error: new CancellationError() }, + { args: ['clone', '--depth', '1', '--no-checkout', '--', 'https://github.com/test/repo.git', targetPath] }, + { args: ['fetch', '--depth', '1', 'origin', commit], error: new CancellationError() }, ]; const service = new LocalGitService(new NullLogService(), createExecFile(expectations)); @@ -160,6 +174,81 @@ suite('LocalGitService', () => { assert.strictEqual(expectations.length, 0); }); + suite('shallow repositories', () => { + let remotePath: string; + let repoPath: string; + let pinnedCommit: string; + let latestCommit: string; + const service = new LocalGitService(new NullLogService()); + + async function runGit(cwd: string, ...args: string[]): Promise<string> { + const { stdout } = await execFile('git', ['-C', cwd, ...args], { encoding: 'utf8' }); + return stdout.trim(); + } + + async function commit(content: string): Promise<string> { + await fs.writeFile(join(remotePath, 'payload.txt'), content); + await runGit(remotePath, 'add', 'payload.txt'); + await runGit(remotePath, '-c', 'user.name=VS Code Test', '-c', 'user.email=vscode-test@example.com', 'commit', '-m', content); + return runGit(remotePath, 'rev-parse', 'HEAD'); + } + + setup(async () => { + const root = await fs.mkdtemp(join(tmpdir(), 'vscode-plugin-git-shallow-')); + temporaryDirectories.push(root); + remotePath = join(root, 'remote'); + repoPath = join(root, 'clone'); + await fs.mkdir(remotePath); + await runGit(remotePath, 'init', '--initial-branch=main'); + pinnedCommit = await commit('pinned content'); + await runGit(remotePath, '-c', 'user.name=VS Code Test', '-c', 'user.email=vscode-test@example.com', 'tag', '-a', 'v1.0.0', '-m', 'release'); + await commit('intermediate content'); + latestCommit = await commit('latest content'); + }); + + for (const ref of [undefined, 'main', 'v1.0.0']) { + test(`clones ${ref ?? 'the default branch'} without its history`, async () => { + await service.clone('clone-op', pathToFileURL(remotePath).toString(), repoPath, ref); + + assert.deepStrictEqual({ + head: await service.revParse(repoPath, 'HEAD'), + count: await runGit(repoPath, 'rev-list', '--all', '--count'), + shallow: await runGit(repoPath, 'rev-parse', '--is-shallow-repository'), + }, { + head: ref === 'v1.0.0' ? pinnedCommit : latestCommit, + count: '1', + shallow: 'true', + }); + + if (ref === 'v1.0.0') { + assert.strictEqual(await service.pull('pull-op', repoPath, { skipDetachedHead: true }), false); + } else { + const nextCommit = await commit('updated content'); + await service.fetch('fetch-op', repoPath); + assert.strictEqual(await service.revListCount(repoPath, 'HEAD', '@{u}'), 1); + const changed = await service.pull('pull-op', repoPath, { skipDetachedHead: true }); + assert.deepStrictEqual({ + changed, + head: await service.revParse(repoPath, 'HEAD'), + content: await fs.readFile(join(repoPath, 'payload.txt'), 'utf8'), + }, { changed: true, head: nextCommit, content: 'updated content' }); + } + }).timeout(20_000); + } + + test('fetches an older pinned commit outside the shallow history', async () => { + await service.clone('clone-op', pathToFileURL(remotePath).toString(), repoPath, pinnedCommit.toUpperCase()); + + assert.deepStrictEqual({ + head: await service.revParse(repoPath, 'HEAD'), + count: await runGit(repoPath, 'rev-list', 'HEAD', '--count'), + shallow: await runGit(repoPath, 'rev-parse', '--is-shallow-repository'), + branch: await runGit(repoPath, 'rev-parse', '--abbrev-ref', 'HEAD'), + content: await fs.readFile(join(repoPath, 'payload.txt'), 'utf8'), + }, { head: pinnedCommit, count: '1', shallow: 'true', branch: 'HEAD', content: 'pinned content' }); + }).timeout(20_000); + }); + test('authenticated Git removes tracing variables case-insensitively', async () => { const inherited = { git_trace_curl: '1', @@ -170,7 +259,7 @@ suite('LocalGitService', () => { Object.assign(process.env, inherited); try { const expectations: IExecFileExpectation[] = [{ args: ['--version'], stdout: 'git version 2.31.0\n' }, { - args: ['clone', '--', 'https://github.com/test/private.git', '/tmp/private'], + args: ['clone', '--depth', '1', '--', 'https://github.com/test/private.git', '/tmp/private'], absentEnvironment: Object.keys(inherited), }]; const service = new LocalGitService(new NullLogService(), createExecFile(expectations)); @@ -212,7 +301,7 @@ suite('LocalGitService', () => { }); try { const expectations: IExecFileExpectation[] = [{ args: ['--version'], stdout: 'git version 2.31.0\n' }, { - args: ['clone', '--', 'https://github.com/test/private.git', '/tmp/private'], + args: ['clone', '--depth', '1', '--', 'https://github.com/test/private.git', '/tmp/private'], environment: { GIT_CONFIG_COUNT: '3', GIT_CONFIG_KEY_0: 'http.proxy', diff --git a/src/vs/platform/github/common/client/localMissionControlRequestProvider.ts b/src/vs/platform/github/common/client/localMissionControlRequestProvider.ts index 0560af4c80fc10..6de8fdf122fa74 100644 --- a/src/vs/platform/github/common/client/localMissionControlRequestProvider.ts +++ b/src/vs/platform/github/common/client/localMissionControlRequestProvider.ts @@ -48,10 +48,15 @@ export class LocalMissionControlRequestProvider extends BufferedApiRequestProvid throw new GitHubRequestError('Invalid Mission Control operation', 'validation'); } const feed = metadata.path === '/feed/connect'; + const identity = metadata.path === '/environments/tokens'; if (feed && (!this.endpoint.feedApiBaseUri || metadata.method !== 'GET' || bodyText !== undefined)) { throw new GitHubRequestError('No approved Mission Control feed endpoint is configured for this operation', 'validation'); } - const endpoint = feed ? { ...this.endpoint, apiBaseUri: this.endpoint.feedApiBaseUri! } : this.endpoint; + if (identity && (!this.endpoint.identityApiBaseUri || metadata.method !== 'POST' || bodyText !== '{}')) { + throw new GitHubRequestError('No approved Mission Control identity endpoint is configured for this operation', 'validation'); + } + const endpoint = feed ? { ...this.endpoint, apiBaseUri: this.endpoint.feedApiBaseUri! } + : identity ? { ...this.endpoint, apiBaseUri: this.endpoint.identityApiBaseUri! } : this.endpoint; const { url } = resolveReadApiUrl(endpoint.apiBaseUri, metadata.path); const { mutation, sensitive, retry } = missionControlRequestPolicy(metadata); let credential = await withGitHubCredentialDeadline(signal, signal => this.credentials.getCredential(signal), undefined, metadata.options?.deadline); diff --git a/src/vs/platform/github/common/missionControl/environments.ts b/src/vs/platform/github/common/missionControl/environments.ts index 8386453d767b4f..0af2e87a5d38cd 100644 --- a/src/vs/platform/github/common/missionControl/environments.ts +++ b/src/vs/platform/github/common/missionControl/environments.ts @@ -203,6 +203,9 @@ export type EnvironmentConnectResult = /** Operations for listing environments and requesting connection credentials. */ export interface IEnvironmentsClient { + /** POST /agents/environments/tokens: mint a short-lived identity credential for host authentication. */ + mintIdentityToken(signal: AbortSignal, options?: ApiRequestOptions): Promise<EnvironmentIdentityToken>; + /** GET /agents/environments: list the authenticated account's environments with optional filters. */ list(signal: AbortSignal, options?: ListEnvironmentsOptions): Promise<readonly Environment[]>; @@ -215,3 +218,10 @@ export interface IEnvironmentsClient { /** GET /agents/environments/{environment_id}/reconnect: refresh an existing client's credentials, or report that the environment is waking. */ reconnect(environmentId: string, clientId: string, signal: AbortSignal, options?: EnvironmentConnectionOptions): Promise<EnvironmentConnectResult>; } + +/** An identity credential that must be sealed before transmission to an environment host. */ +export interface EnvironmentIdentityToken { + readonly token: string; + readonly expires_at?: string; + readonly expires_in?: number; +} diff --git a/src/vs/platform/github/common/missionControl/environmentsClient.ts b/src/vs/platform/github/common/missionControl/environmentsClient.ts index bc2d53dcaaf1cc..df1a975496e06f 100644 --- a/src/vs/platform/github/common/missionControl/environmentsClient.ts +++ b/src/vs/platform/github/common/missionControl/environmentsClient.ts @@ -6,12 +6,23 @@ import { ApiRequestOptions, ApiResponse } from '../client/request.js'; import { pathSegment, withQuery } from '../client/routing.js'; import { parse, SchemaError } from '../client/schema.js'; -import { AdvertisedEncryptionKey, ClientTokenResponse, ConnectEnvironmentOptions, Environment, EnvironmentConnectionOptions, EnvironmentConnectResult, IEnvironmentsClient, ListEnvironmentsOptions, WakingResponse } from './environments.js'; +import { AdvertisedEncryptionKey, ClientTokenResponse, ConnectEnvironmentOptions, Environment, EnvironmentConnectionOptions, EnvironmentConnectResult, EnvironmentIdentityToken, IEnvironmentsClient, ListEnvironmentsOptions, WakingResponse } from './environments.js'; import { MissionControlClient, parseActivationContext, parseEnvironmentKind } from './missionControlClient.js'; export class EnvironmentsClient implements IEnvironmentsClient { constructor(private readonly _client: MissionControlClient) { } + mintIdentityToken(signal: AbortSignal, options?: ApiRequestOptions): Promise<EnvironmentIdentityToken> { + return this._client.request({ + domain: 'environments', method: 'POST', path: '/environments/tokens', body: {}, expectedStatus: 200, + policy: { credential: true }, options, + }, signal, response => parse.object<EnvironmentIdentityToken>({ + token: parse.nonEmptyString, + expires_at: parse.optional(parse.dateTime), + expires_in: parse.optional(parse.nonNegativeInteger), + })(response.data)); + } + list(signal: AbortSignal, options?: ListEnvironmentsOptions): Promise<readonly Environment[]> { const { query, ...requestOptions } = options ?? {}; return this._client.request({ diff --git a/src/vs/platform/github/common/missionControl/missionControlClient.ts b/src/vs/platform/github/common/missionControl/missionControlClient.ts index 6dacca04d336e9..4aace02adefa71 100644 --- a/src/vs/platform/github/common/missionControl/missionControlClient.ts +++ b/src/vs/platform/github/common/missionControl/missionControlClient.ts @@ -20,6 +20,8 @@ export interface ApiEndpoint { readonly apiBaseUri: string; /** Approved feed gateway; the Copilot-hosted task proxy does not serve feed negotiation. */ readonly feedApiBaseUri?: string; + /** Approved credential gateway; the task proxy does not serve identity-token exchanges. */ + readonly identityApiBaseUri?: string; /** The integration identity supplied by the hosting application. */ readonly integrationId: string; /** The optional GitHub API version; omitted unless explicitly configured. */ @@ -131,7 +133,7 @@ export class MissionControlClient { export const parseMissionControlOptions = parse.object<MissionControlClientOptions>({ endpoint: parse.object<ApiEndpoint>({ - apiBaseUri: parse.nonEmptyString, feedApiBaseUri: parse.optional(parse.nonEmptyString), integrationId: parse.nonEmptyString, apiVersion: parse.optional(parse.string), + apiBaseUri: parse.nonEmptyString, feedApiBaseUri: parse.optional(parse.nonEmptyString), identityApiBaseUri: parse.optional(parse.nonEmptyString), integrationId: parse.nonEmptyString, apiVersion: parse.optional(parse.string), }), }); @@ -201,6 +203,7 @@ function normalizeEndpoint(endpoint: ApiEndpoint): ApiEndpoint { return Object.freeze({ apiBaseUri, integrationId: endpoint.integrationId, apiVersion: endpoint.apiVersion, ...(endpoint.feedApiBaseUri ? { feedApiBaseUri: normalizeReadApiBaseUri(endpoint.feedApiBaseUri) } : {}), + ...(endpoint.identityApiBaseUri ? { identityApiBaseUri: normalizeReadApiBaseUri(endpoint.identityApiBaseUri) } : {}), }); } diff --git a/src/vs/platform/github/test/node/missionControlClient.test.ts b/src/vs/platform/github/test/node/missionControlClient.test.ts index c3f2ea521e148d..9ecd9894efc9d1 100644 --- a/src/vs/platform/github/test/node/missionControlClient.test.ts +++ b/src/vs/platform/github/test/node/missionControlClient.test.ts @@ -675,6 +675,36 @@ suite('Mission Control client', () => { }, { connections: [{ status: 200, data: connection }, { status: 200, data: connection }], attempts: 5, validators: Array(5).fill(null) }); }); + test('mints identity credentials only on the approved gateway without sharing or caching', async () => { + const options = clientOptions(); + const identity = { token: 'identity-secret', expires_in: 3600, expires_at: date }; + const { client, requests } = setup(() => Response.json(identity, { headers: { etag: '"private"' } }), { + ...options, + missionControl: { endpoint: { ...options.missionControl!.endpoint, identityApiBaseUri: 'https://api.github.com/cmc_internal/api/agents' } }, + }); + const credentials = await Promise.all([client.environments.mintIdentityToken(signal()), client.environments.mintIdentityToken(signal())]); + assert.deepStrictEqual({ + credentials, + requests: requests.map(request => ({ + url: request.url.href, method: request.init.method, body: request.init.body, + integration: new Headers(request.init.headers).get('Copilot-Integration-Id'), + validator: new Headers(request.init.headers).get('If-None-Match'), + })), + }, { + credentials: [identity, identity], + requests: Array.from({ length: 2 }, () => ({ + url: 'https://api.github.com/cmc_internal/api/agents/environments/tokens', + method: 'POST', body: '{}', integration: 'test-integration', validator: null, + })), + }); + }); + + test('does not guess an identity endpoint when its gateway is not configured', async () => { + const { client, requests } = setup(() => Response.json({ token: 'must-not-be-requested' })); + await assert.rejects(client.environments.mintIdentityToken(signal()), { kind: 'validation' }); + assert.deepStrictEqual(requests, []); + }); + test('negotiates task feed credentials on the approved gateway without caching or coalescing', async () => { const feed = { url: 'wss://relay.example.test/?access_token=feed-secret', diff --git a/src/vs/platform/mcp/common/allowedMcpServers.ts b/src/vs/platform/mcp/common/allowedMcpServers.ts index 640d0b2782cd9e..cbd3bc01495502 100644 --- a/src/vs/platform/mcp/common/allowedMcpServers.ts +++ b/src/vs/platform/mcp/common/allowedMcpServers.ts @@ -20,6 +20,36 @@ export interface IMcpServerMatcher { readonly serverCommand?: readonly string[]; } +/** + * Maps strings in the allow/deny lists to those same strings with environment variables filled in by the host that runs or connects to the server. + * Before starting a server or sending a request, use these values in place of the original policy strings and check the actual command or URL against the lists: a matching deny blocks it, a configured allowlist must admit it, and a missing required value blocks it. + * + * @example + * ```ts + * // Policy: allow ["${NODE}", "${SCRIPT_DIR}/approved.js"] + * // deny ["${NODE}", "${SCRIPT_DIR}/blocked.js"] + * // Each command/argument string containing variables gets its own entry, not the array + * const policyValues = { + * '${NODE}': '/usr/bin/node', + * '${SCRIPT_DIR}/approved.js': '/opt/scripts/approved.js', + * '${SCRIPT_DIR}/blocked.js': '/opt/scripts/blocked.js', + * }; + * + * // Replace each policy array element using its entry, leaving literal elements unchanged + * // Then compare the resulting array with the actual [command, ...args], in order + * // ["/usr/bin/node", "/opt/scripts/approved.js"] -> allowed + * // ["/usr/bin/node", "/opt/scripts/blocked.js"] -> denied + * // ["/usr/bin/node", "/opt/scripts/other.js"] -> not allowed + * // Missing policyValues["${NODE}"] -> blocked before execution + * + * // A URL policy works the same way + * // Policy: allow "https://${HOST}/mcp", with HOST=trusted.example + * // policyValues: { "https://${HOST}/mcp": "https://trusted.example/mcp" } + * // A request to https://other.example/mcp is still blocked, including redirects + * ``` + */ +export type McpServerPolicyValues = Readonly<Record<string, string>>; + /** * Normalized identity of an MCP server used for allowlist matching. Both the install-time and the * runtime enforcement paths reduce their server representation to this shape: `url` is set for @@ -30,6 +60,8 @@ export interface IMcpServerIdentity { readonly name: string; readonly url?: string; readonly command?: readonly string[]; + /** Values to substitute into the allow/deny lists, not into this server's command or URL. Providing them does not mean the server is allowed; the allowed-servers service must check it before execution. */ + readonly policyValues?: McpServerPolicyValues; } /** @@ -75,32 +107,35 @@ function isValidMatcher(entry: unknown): entry is IMcpServerMatcher { * matcher list matches nothing. */ export function isMcpServerMatched(matchers: readonly IMcpServerMatcher[] | undefined, identity: IMcpServerIdentity): boolean { - return !!matchers && matchers.some(matcher => matchesMatcher(matcher, identity)); + return !!matchers && matchers.some(matcher => matchesMatcher(matcher, identity, value => identity.policyValues?.[value] ?? value)); } /** - * Evaluates an MCP server against the allow and deny lists. Deny always takes precedence; an unset - * (`undefined`) allowlist imposes no restriction, while a configured allowlist requires a match. + * Evaluates one allowlist layer using the runtime's transport-specific name fallback; deny entries + * remain additive. An unset allowlist imposes no restriction, while an empty allowlist admits none. */ export function checkMcpServerAllowed(allowlist: readonly IMcpServerMatcher[] | undefined, denylist: readonly IMcpServerMatcher[] | undefined, identity: IMcpServerIdentity): McpServerAllowResult { if (isMcpServerMatched(denylist, identity)) { return McpServerAllowResult.Denied; } - if (allowlist !== undefined && !isMcpServerMatched(allowlist, identity)) { + const transportMatchers = identity.url !== undefined + ? allowlist?.filter(matcher => isString(matcher.serverUrl)) + : identity.command !== undefined ? allowlist?.filter(matcher => Array.isArray(matcher.serverCommand)) : undefined; + if (allowlist !== undefined && !isMcpServerMatched(transportMatchers?.length ? transportMatchers : allowlist, identity)) { return McpServerAllowResult.NotAllowed; } return McpServerAllowResult.Allowed; } -function matchesMatcher(matcher: IMcpServerMatcher, identity: IMcpServerIdentity): boolean { +function matchesMatcher(matcher: IMcpServerMatcher, identity: IMcpServerIdentity, resolve: (value: string) => string): boolean { if (isString(matcher.serverName)) { return matcher.serverName === identity.name; } if (isString(matcher.serverUrl)) { - return identity.url !== undefined && matchesUrlPattern(matcher.serverUrl, identity.url); + return identity.url !== undefined && matchesUrlPattern(resolve(matcher.serverUrl), identity.url); } if (Array.isArray(matcher.serverCommand)) { - return identity.command !== undefined && equals(matcher.serverCommand, identity.command); + return identity.command !== undefined && equals(matcher.serverCommand.map(resolve), identity.command); } return false; } @@ -114,16 +149,18 @@ function matchesUrlPattern(pattern: string, url: string): boolean { if (destination === undefined) { return false; } - if (!pattern.includes('*')) { + const schemeSeparator = pattern.indexOf('://'); + const originOnly = schemeSeparator >= 0 && findAuthorityEnd(pattern, schemeSeparator + 3) === pattern.length; + if (!pattern.includes('*') && !originOnly) { const expected = toNetworkDestinationUrl(pattern); - return expected !== undefined && expected.toLowerCase() === destination.toLowerCase(); + return expected !== undefined && expected === destination; } - const normalizedPattern = toNetworkDestinationPattern(pattern); + const normalizedPattern = toNetworkDestinationPattern(originOnly ? `${pattern}/*` : pattern); if (normalizedPattern === undefined) { return false; } try { - return new RegExp(buildUrlPatternRegexSource(normalizedPattern), 'i').test(destination); + return new RegExp(buildUrlPatternRegexSource(normalizedPattern)).test(destination); } catch { return false; } @@ -138,7 +175,7 @@ function toNetworkDestinationUrl(url: string): string | undefined { if (parsed.protocol === 'http:' || parsed.protocol === 'https:') { return parsed.origin + parsed.pathname + parsed.search; } - return url; + return toNetworkDestinationPattern(url); } catch { return undefined; } @@ -150,12 +187,12 @@ function toNetworkDestinationPattern(pattern: string): string | undefined { return pattern; } const scheme = pattern.slice(0, schemeSeparator).toLowerCase(); + const rest = pattern.slice(schemeSeparator + 3); + const authorityEnd = findAuthorityEnd(rest, 0); if (scheme !== 'http' && scheme !== 'https') { - return pattern; + return `${scheme}://${rest.slice(0, authorityEnd).toLowerCase()}${rest.slice(authorityEnd)}`; } - const rest = pattern.slice(schemeSeparator + 3); - const authorityEnd = findAuthorityEnd(rest, 0); let authority = rest.slice(0, authorityEnd); const userinfoEnd = authority.lastIndexOf('@'); if (userinfoEnd >= 0) { @@ -180,7 +217,7 @@ function toNetworkDestinationPattern(pattern: string): string | undefined { afterAuthority = `/${afterAuthority}`; } - return `${scheme}://${hostAndPort.host}${port !== undefined ? `:${port}` : ''}${afterAuthority}`; + return `${scheme}://${hostAndPort.host.toLowerCase()}${port !== undefined ? `:${port}` : ''}${afterAuthority}`; } function splitHostAndPort(authority: string): { host: string; port: string | undefined } | undefined { diff --git a/src/vs/platform/mcp/common/allowedMcpServersService.ts b/src/vs/platform/mcp/common/allowedMcpServersService.ts index 7733f56523d80d..acfa0dec959661 100644 --- a/src/vs/platform/mcp/common/allowedMcpServersService.ts +++ b/src/vs/platform/mcp/common/allowedMcpServersService.ts @@ -4,6 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import { Disposable } from '../../../base/common/lifecycle.js'; +import { toErrorMessage } from '../../../base/common/errorMessage.js'; import * as nls from '../../../nls.js'; import { createCommandUri, IMarkdownString, MarkdownString } from '../../../base/common/htmlContent.js'; import { IConfigurationService } from '../../configuration/common/configuration.js'; @@ -11,9 +12,11 @@ import { hasConfigurationVariable } from '../../configuration/common/configurati import { Emitter } from '../../../base/common/event.js'; import { hasKey, isString } from '../../../base/common/types.js'; import { checkMcpServerAllowed, getMcpServerMatchers, IMcpServerIdentity, IMcpServerMatcher, McpServerAllowResult } from './allowedMcpServers.js'; -import { IAllowedMcpServersService, IGalleryMcpServer, IInstallableMcpServer, ILocalMcpServer, mcpAccessConfig, mcpAllowedServersConfig, mcpDeniedServersConfig, McpAccessValue, replaceMcpServerVariableReferences } from './mcpManagement.js'; +import { IAllowedMcpServersService, IGalleryMcpServer, IInstallableMcpServer, ILocalMcpServer, mcpAccessConfig, mcpAllowedServersConfig, mcpDeniedServersConfig, McpAccessValue, McpServerConfigurationParseResult, RegistryType } from './mcpManagement.js'; import { McpServerType } from './mcpPlatformTypes.js'; import { COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG } from '../../policy/common/copilotManagedSettings.js'; +import { McpServerManifestParser } from './mcpManagementService.js'; +import { hasEnvVarReferences } from './envVarResolution.js'; export class AllowedMcpServersService extends Disposable implements IAllowedMcpServersService { @@ -34,7 +37,34 @@ export class AllowedMcpServersService extends Disposable implements IAllowedMcpS } isAllowed(mcpServer: IGalleryMcpServer | ILocalMcpServer | IInstallableMcpServer): true | IMarkdownString { - return this.isServerAllowedBeforeResolution(this.toIdentity(mcpServer)); + if (hasKey(mcpServer, { config: true })) { + const config = mcpServer.config; + return this.isServerAllowedBeforeResolution(config.type === McpServerType.REMOTE + ? { name: mcpServer.name, url: config.url } + : { name: mcpServer.name, command: [config.command, ...(config.args ?? [])] }); + } + + const parser = new McpServerManifestParser(); + let candidates: McpServerConfigurationParseResult[]; + try { + candidates = [ + ...(mcpServer.configuration.remotes ?? []).map(remote => parser.getMcpServerConfigurationFromManifest({ remotes: [remote] }, RegistryType.REMOTE)), + ...(mcpServer.configuration.packages ?? []) + .filter(p => [RegistryType.NODE, RegistryType.PYTHON, RegistryType.DOCKER, RegistryType.NUGET].includes(p.registryType)) + .map(p => parser.getMcpServerConfigurationFromManifest({ packages: [p] }, p.registryType)), + ]; + } catch (error) { + return new MarkdownString().appendText(nls.localize('mcp gallery configuration invalid', "This Model Context Protocol server cannot be installed because its gallery configuration is invalid: {0}", toErrorMessage(error))); + } + let result = this.isServerAllowedBeforeResolution({ name: mcpServer.name }); + for (const candidate of candidates) { + const allowed = this.isAllowed({ name: mcpServer.name, config: candidate.mcpServerConfiguration.config }); + if (allowed === true) { + return true; + } + result = allowed; + } + return result; } isServerAllowedBeforeResolution(identity: IMcpServerIdentity): true | IMarkdownString { @@ -45,35 +75,62 @@ export class AllowedMcpServersService extends Disposable implements IAllowedMcpS return this.checkServerAllowed(identity, 'resolved'); } + getServerPolicyVariableValues(): readonly string[] { + const { allowlist, denylist } = this.getPolicyLists(); + return [...new Set([...(allowlist ?? []), ...(denylist ?? [])].flatMap(matcher => + [...(matcher.serverCommand ?? []), ...(matcher.serverUrl !== undefined ? [matcher.serverUrl] : [])] + .filter(value => hasEnvVarReferences(value))))]; + } + + private getPolicyLists(): { allowlist: readonly IMcpServerMatcher[] | undefined; denylist: readonly IMcpServerMatcher[] | undefined } { + const managedOnly = this.configurationService.getValue<boolean>(COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG) === true; + return { + allowlist: managedOnly + ? getMcpServerMatchers(this.configurationService.inspect<readonly IMcpServerMatcher[]>(mcpAllowedServersConfig).policyValue) ?? [] + : getMcpServerMatchers(this.configurationService.getValue(mcpAllowedServersConfig)), + denylist: managedOnly + ? this.getAllConfiguredMatchers(mcpDeniedServersConfig) + : getMcpServerMatchers(this.configurationService.getValue(mcpDeniedServersConfig)), + }; + } + private checkServerAllowed(identity: IMcpServerIdentity, phase: 'definition' | 'resolved'): true | IMarkdownString { if (this.configurationService.getValue(mcpAccessConfig) === McpAccessValue.None) { const settingsCommandLink = createCommandUri('workbench.action.openSettings', { query: `@id:${mcpAccessConfig}` }).toString(); return new MarkdownString(nls.localize('mcp servers are not allowed', "Model Context Protocol servers are disabled in the Editor. Please check your [settings]({0}).", settingsCommandLink)); } - const managedOnly = this.configurationService.getValue<boolean>(COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG) === true; - const allowlist = managedOnly - ? getMcpServerMatchers(this.configurationService.inspect<readonly IMcpServerMatcher[]>(mcpAllowedServersConfig).policyValue) ?? [] - : getMcpServerMatchers(this.configurationService.getValue(mcpAllowedServersConfig)); - const denylist = managedOnly - ? this.getAllConfiguredMatchers(mcpDeniedServersConfig) - : getMcpServerMatchers(this.configurationService.getValue(mcpDeniedServersConfig)); + const { allowlist, denylist } = this.getPolicyLists(); + const unresolvedPolicy = [...(allowlist ?? []), ...(denylist ?? [])].some(matcher => + [...(matcher.serverCommand ?? []), ...(matcher.serverUrl !== undefined ? [matcher.serverUrl] : [])] + .some(value => hasEnvVarReferences(value) && identity.policyValues?.[value] === undefined)); + if (phase === 'resolved' && unresolvedPolicy) { + return new MarkdownString(nls.localize('mcp policy environment unresolved', "This Model Context Protocol server cannot run because its policy environment variables have not been resolved on the server host. Restart the server to try again.")); + } const result = phase === 'definition' - ? this.checkServerAllowedBeforeResolution(allowlist, denylist, identity) + ? this.checkServerAllowedBeforeResolution(allowlist, denylist, identity, unresolvedPolicy) : checkMcpServerAllowed(allowlist, denylist, identity); switch (result) { case McpServerAllowResult.Denied: return new MarkdownString(nls.localize('mcp server is denied', "This Model Context Protocol server is blocked by your organization's policy. Please contact your administrator for more information.")); case McpServerAllowResult.NotAllowed: + if (allowlist?.some(matcher => matcher.serverName === identity.name)) { + if (identity.url !== undefined) { + return new MarkdownString(nls.localize('mcp server name overridden by url', "This Model Context Protocol server is not in the list of servers allowed by your organization. A name entry matches, but this allowlist contains URL entries, so the server must match an allowed URL. Please contact your administrator for more information.")); + } + if (identity.command !== undefined) { + return new MarkdownString(nls.localize('mcp server name overridden by command', "This Model Context Protocol server is not in the list of servers allowed by your organization. A name entry matches, but this allowlist contains command entries, so the server must match an allowed command and arguments. Please contact your administrator for more information.")); + } + } return new MarkdownString(nls.localize('mcp server not in allowlist', "This Model Context Protocol server is not in the list of servers allowed by your organization. Please contact your administrator for more information.")); } return true; } - private checkServerAllowedBeforeResolution(allowlist: readonly IMcpServerMatcher[] | undefined, denylist: readonly IMcpServerMatcher[] | undefined, identity: IMcpServerIdentity): McpServerAllowResult { - const unresolvedUrl = identity.url !== undefined && hasConfigurationVariable(identity.url); - const unresolvedCommand = identity.command?.some(hasConfigurationVariable) ?? false; + private checkServerAllowedBeforeResolution(allowlist: readonly IMcpServerMatcher[] | undefined, denylist: readonly IMcpServerMatcher[] | undefined, identity: IMcpServerIdentity, unresolvedPolicy: boolean): McpServerAllowResult { + const unresolvedUrl = identity.url !== undefined && (hasConfigurationVariable(identity.url) || unresolvedPolicy); + const unresolvedCommand = identity.command !== undefined && (identity.command.some(hasConfigurationVariable) || unresolvedPolicy); if (!unresolvedUrl && !unresolvedCommand) { return checkMcpServerAllowed(allowlist, denylist, identity); } @@ -82,18 +139,16 @@ export class AllowedMcpServersService extends Disposable implements IAllowedMcpS name: identity.name, url: unresolvedUrl ? undefined : identity.url, command: unresolvedCommand ? undefined : identity.command, + policyValues: identity.policyValues, }; if (checkMcpServerAllowed(undefined, denylist, knownIdentity) === McpServerAllowResult.Denied) { return McpServerAllowResult.Denied; } - if (allowlist === undefined || checkMcpServerAllowed(allowlist, undefined, knownIdentity) === McpServerAllowResult.Allowed) { + if (allowlist?.some(matcher => + (unresolvedUrl && isString(matcher.serverUrl)) || (unresolvedCommand && Array.isArray(matcher.serverCommand)))) { return McpServerAllowResult.Allowed; } - - return allowlist.some(matcher => - (unresolvedUrl && isString(matcher.serverUrl)) || (unresolvedCommand && Array.isArray(matcher.serverCommand))) - ? McpServerAllowResult.Allowed - : McpServerAllowResult.NotAllowed; + return checkMcpServerAllowed(allowlist, undefined, knownIdentity); } private getAllConfiguredMatchers(key: string): IMcpServerMatcher[] { @@ -110,18 +165,4 @@ export class AllowedMcpServersService extends Disposable implements IAllowedMcpS ].flatMap(value => getMcpServerMatchers(value) ?? []); } - private toIdentity(mcpServer: IGalleryMcpServer | ILocalMcpServer | IInstallableMcpServer): IMcpServerIdentity { - if (hasKey(mcpServer, { config: true })) { - const config = mcpServer.config; - if (config.type === McpServerType.REMOTE) { - return { name: mcpServer.name, url: config.url }; - } - return { name: mcpServer.name, command: [config.command, ...(config.args ?? [])] }; - } - - // Gallery server: match by name or a remote URL; the local command invocation is only - // known once the server is installed with a resolved configuration. - const remote = mcpServer.configuration.remotes?.[0]; - return { name: mcpServer.name, url: remote ? replaceMcpServerVariableReferences(remote.url, remote.variables) : undefined }; - } } diff --git a/src/vs/platform/mcp/common/mcpManagement.ts b/src/vs/platform/mcp/common/mcpManagement.ts index 8a9ee4c3539fc0..826512c6e1ddb6 100644 --- a/src/vs/platform/mcp/common/mcpManagement.ts +++ b/src/vs/platform/mcp/common/mcpManagement.ts @@ -297,6 +297,8 @@ export interface IAllowedMcpServersService { readonly _serviceBrand: undefined; readonly onDidChangeAllowedMcpServers: Event<void>; + /** Original allow/deny URL and command strings containing environment references, to be resolved into {@link IMcpServerIdentity.policyValues} by the executing host. */ + getServerPolicyVariableValues(): readonly string[]; /** Checks a server definition before resolution, deferring rules for variable-dependent URL/command fields. */ isAllowed(mcpServer: IGalleryMcpServer | ILocalMcpServer | IInstallableMcpServer): true | IMarkdownString; @@ -304,8 +306,8 @@ export interface IAllowedMcpServersService { isServerAllowedBeforeResolution(identity: IMcpServerIdentity): true | IMarkdownString; /** - * Checks access and allow/deny rules against a resolved runtime identity without deferring URL rules. - * Runtime callers must use this after resolving a server definition. + * Checks the resolved command or destination against access and allow/deny rules, substituting `identity.policyValues` into the policy matchers. + * Call before execution and for every request destination; missing host expansions fail closed, while preliminary checks only defer the decision. */ isServerAllowed(identity: IMcpServerIdentity): true | IMarkdownString; } diff --git a/src/vs/platform/mcp/common/mcpManagementService.ts b/src/vs/platform/mcp/common/mcpManagementService.ts index e7e88edc94b372..4ae8f9ed4ca7e0 100644 --- a/src/vs/platform/mcp/common/mcpManagementService.ts +++ b/src/vs/platform/mcp/common/mcpManagementService.ts @@ -70,6 +70,13 @@ export abstract class AbstractCommonMcpManagementService extends Disposable impl super(); } + getMcpServerConfigurationFromManifest(manifest: IGalleryMcpServerConfiguration, packageType: RegistryType): McpServerConfigurationParseResult { + return new McpServerManifestParser().getMcpServerConfigurationFromManifest(manifest, packageType); + } +} + +export class McpServerManifestParser { + getMcpServerConfigurationFromManifest(manifest: IGalleryMcpServerConfiguration, packageType: RegistryType): McpServerConfigurationParseResult { // remote diff --git a/src/vs/platform/mcp/test/common/allowedMcpServers.test.ts b/src/vs/platform/mcp/test/common/allowedMcpServers.test.ts index 96bef468eee1b7..faa730340cf897 100644 --- a/src/vs/platform/mcp/test/common/allowedMcpServers.test.ts +++ b/src/vs/platform/mcp/test/common/allowedMcpServers.test.ts @@ -59,7 +59,7 @@ suite('AllowedMcpServers', () => { assert.strictEqual(isMcpServerMatched(matchers, { name: 'gitlab' }), false); }); - test('matches by remote URL with wildcards, case-insensitively', () => { + test('matches remote URL authorities case-insensitively with bounded wildcards', () => { const matchers: IMcpServerMatcher[] = [{ serverUrl: 'https://*.example.com/*' }]; assert.strictEqual(isMcpServerMatched(matchers, { name: 's', url: 'https://mcp.example.com/api' }), true); assert.strictEqual(isMcpServerMatched(matchers, { name: 's', url: 'https://MCP.EXAMPLE.COM/api' }), true); @@ -95,7 +95,7 @@ suite('AllowedMcpServers', () => { ], [ true, true, - false, + true, true, true, true, @@ -134,10 +134,78 @@ suite('AllowedMcpServers', () => { assert.strictEqual(isMcpServerMatched(matchers, { name: 's', command: ['npx', '-y', 'server', '--flag'] }), false); assert.strictEqual(isMcpServerMatched(matchers, { name: 's', url: 'https://mcp.example.com' }), false); }); + + test('URL paths and query values are case-sensitive for exact and wildcard patterns', () => { + assert.deepStrictEqual( + ['https://MCP.EXAMPLE.COM/API?key=Value', 'HTTPS://*.EXAMPLE.COM/API?key=*'].map(serverUrl => + ['https://mcp.example.com/API?key=Value', 'https://mcp.example.com/api?key=Value', 'https://mcp.example.com/API?key=value'].map(url => + isMcpServerMatched([{ serverUrl }], { name: 's', url }))), + [[true, false, false], [true, false, true]] + ); + }); + + test('preserves non-HTTP scheme and authority casing without folding paths or socket fragments', () => { + assert.deepStrictEqual( + ['UNIX://HOST/tmp/Socket#API', 'UNIX://HOST/tmp/S*#API'].map(serverUrl => + ['unix://host/tmp/Socket#API', 'unix://HOST/tmp/socket#API', 'unix://host/tmp/Socket#api'].map(url => + isMcpServerMatched([{ serverUrl }], { name: 's', url }))), + [[true, false, false], [true, false, false]] + ); + }); + + test('matches policy commands and URLs using host-resolved strings but leaves names literal', () => { + const policyValues = { + '${EXECUTABLE}': 'node', + '${MISSING:-approved.js}': 'approved.js', + '${SCRIPT:-approved.js}': '', + '${MISSING}': '${MISSING}', + '${PATH}/node': '/host/node', + 'https://${HOST}/API': 'https://mcp.example.com/API', + '${HOST}': 'mcp.example.com', + }; + assert.deepStrictEqual([ + isMcpServerMatched([{ serverCommand: ['${EXECUTABLE}', '${MISSING:-approved.js}'] }], { name: 's', command: ['node', 'approved.js'], policyValues }), + isMcpServerMatched([{ serverCommand: ['node', '${SCRIPT:-approved.js}'] }], { name: 's', command: ['node', ''], policyValues }), + isMcpServerMatched([{ serverCommand: ['node', '${MISSING}'] }], { name: 's', command: ['node', '${MISSING}'], policyValues }), + isMcpServerMatched([{ serverCommand: ['node', '${MISSING}'] }], { name: 's', command: ['node', ''], policyValues }), + isMcpServerMatched([{ serverCommand: ['${PATH}/node'] }], { name: 's', command: ['/host/node'], policyValues }), + isMcpServerMatched([{ serverCommand: ['${PATH}/node'] }], { name: 's', command: ['/host/node'] }), + isMcpServerMatched([{ serverUrl: 'https://${HOST}/API' }], { name: 's', url: 'https://mcp.example.com/API', policyValues }), + isMcpServerMatched([{ serverUrl: 'https://${HOST}/API' }], { name: 's', url: 'https://other.example.com/API', policyValues }), + isMcpServerMatched([{ serverName: '${HOST}' }], { name: 'mcp.example.com', policyValues }), + isMcpServerMatched([{ serverName: '${HOST}' }], { name: '${HOST}', policyValues }), + ], [true, true, true, false, true, false, true, false, false, true]); + }); }); suite('checkMcpServerAllowed', () => { + test('transport-specific allow entries take precedence over names, but not over deny entries', () => { + const allow: IMcpServerMatcher[] = [ + { serverName: 'approved' }, + { serverCommand: ['node', 'approved.js', '--flag'] }, + { serverUrl: 'https://approved.example/API' }, + ]; + const stdio = { name: 'approved', command: ['node', 'other.js'] }; + const remote = { name: 'approved', url: 'https://other.example/API' }; + assert.deepStrictEqual([ + checkMcpServerAllowed(allow, undefined, stdio), + checkMcpServerAllowed(allow, undefined, remote), + checkMcpServerAllowed(allow, undefined, { name: 'other', command: ['node', 'approved.js', '--flag'] }), + checkMcpServerAllowed(allow, undefined, { name: 'other', command: ['node', '--flag', 'approved.js'] }), + checkMcpServerAllowed(allow, undefined, { name: 'other', url: 'https://approved.example/API' }), + checkMcpServerAllowed(allow.filter(m => !m.serverCommand), undefined, stdio), + checkMcpServerAllowed(allow.filter(m => !m.serverUrl), undefined, remote), + checkMcpServerAllowed(allow, [{ serverName: 'approved' }, { serverCommand: ['node', 'different.js'] }], stdio), + checkMcpServerAllowed(allow, [{ serverName: 'approved' }, { serverUrl: 'https://different.example' }], remote), + ], [ + McpServerAllowResult.NotAllowed, McpServerAllowResult.NotAllowed, + McpServerAllowResult.Allowed, McpServerAllowResult.NotAllowed, + McpServerAllowResult.Allowed, McpServerAllowResult.Allowed, McpServerAllowResult.Allowed, + McpServerAllowResult.Denied, McpServerAllowResult.Denied, + ]); + }); + test('no lists configured allows everything', () => { assert.strictEqual(checkMcpServerAllowed(undefined, undefined, { name: 'x' }), McpServerAllowResult.Allowed); }); diff --git a/src/vs/platform/mcp/test/common/allowedMcpServersService.test.ts b/src/vs/platform/mcp/test/common/allowedMcpServersService.test.ts index 9483e2ee51cb8b..fef4f98f28d3db 100644 --- a/src/vs/platform/mcp/test/common/allowedMcpServersService.test.ts +++ b/src/vs/platform/mcp/test/common/allowedMcpServersService.test.ts @@ -7,10 +7,11 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js'; import { TestConfigurationService } from '../../../configuration/test/common/testConfigurationService.js'; import { AllowedMcpServersService } from '../../common/allowedMcpServersService.js'; -import { GalleryMcpServerStatus, IGalleryMcpServer, IInstallableMcpServer, mcpAccessConfig, mcpAllowedServersConfig, mcpDeniedServersConfig, McpAccessValue, TransportType } from '../../common/mcpManagement.js'; +import { GalleryMcpServerStatus, IGalleryMcpServer, IGalleryMcpServerConfiguration, IInstallableMcpServer, mcpAccessConfig, mcpAllowedServersConfig, mcpDeniedServersConfig, McpAccessValue, RegistryType, TransportType } from '../../common/mcpManagement.js'; import { McpServerType } from '../../common/mcpPlatformTypes.js'; import { COPILOT_ALLOW_MANAGED_MCP_SERVERS_ONLY_CONFIG } from '../../../policy/common/copilotManagedSettings.js'; import { IConfigurationValue } from '../../../configuration/common/configuration.js'; +import { createEnvVarResolver } from '../../common/envVarResolution.js'; suite('AllowedMcpServersService', () => { @@ -31,6 +32,166 @@ suite('AllowedMcpServersService', () => { assert.strictEqual(service.isServerAllowed({ name: 'github' }), true); }); + suite('gallery command admission', () => { + function gallery(configuration: IGalleryMcpServerConfiguration): IGalleryMcpServer { + return { + name: 'microsoft/playwright-mcp', displayName: 'Playwright', description: '', publisher: 'microsoft', + version: '1.0.0', isLatest: true, status: GalleryMcpServerStatus.Active, configuration, + }; + } + + for (const [registryType, command] of [ + [RegistryType.NODE, ['npx', '--registry', 'https://registry.example', 'server@1.2.3']], + [RegistryType.PYTHON, ['uvx', '--index-url', 'https://registry.example', 'server@1.2.3']], + [RegistryType.DOCKER, ['docker', 'run', '-i', '--rm', 'https://registry.example/server:1.2.3']], + [RegistryType.NUGET, ['dnx', 'server@1.2.3', '--yes', '--source', 'https://registry.example']], + ] as const) { + test(`uses installation's ${registryType} command, arguments, version and registry`, () => { + const server = gallery({ + packages: [{ + registryType, identifier: 'server', version: '1.2.3', registryBaseUrl: 'https://registry.example', transport: { type: TransportType.STDIO }, + }] + }); + const approved = createService({ [mcpAllowedServersConfig]: [{ serverCommand: command }] }); + const wrongVersion = createService({ [mcpAllowedServersConfig]: [{ serverCommand: command.map(part => part.replace('1.2.3', '2.0.0')) }] }); + const denied = createService({ [mcpAllowedServersConfig]: [{ serverCommand: command }], [mcpDeniedServersConfig]: [{ serverCommand: command }] }); + assert.deepStrictEqual([approved, wrongVersion, denied].map(service => service.isAllowed(server) === true), [true, false, false]); + }); + } + + test('evaluates every package and remote candidate without authorizing a different final configuration', () => { + const service = createService({ [mcpAllowedServersConfig]: [{ serverName: 'microsoft/playwright-mcp' }, { serverCommand: ['npx', '@playwright/mcp@latest'] }, { serverUrl: 'https://approved.example/mcp' }] }); + const configuration: IGalleryMcpServerConfiguration = { + packages: [ + { registryType: RegistryType.NODE, identifier: 'unapproved', transport: { type: TransportType.STDIO } }, + { registryType: RegistryType.NODE, identifier: '@playwright/mcp', version: 'latest', transport: { type: TransportType.STDIO } }, + ], + remotes: [ + { type: TransportType.STREAMABLE_HTTP, url: 'https://unapproved.example/mcp' }, + { type: TransportType.STREAMABLE_HTTP, url: 'https://approved.example/mcp' }, + ], + }; + assert.deepStrictEqual([ + service.isAllowed(gallery(configuration)) === true, + service.isAllowed(gallery({ packages: configuration.packages })) === true, + service.isAllowed(gallery({ remotes: configuration.remotes })) === true, + service.isAllowed(gallery({ packages: configuration.packages?.slice(0, 1), remotes: configuration.remotes?.slice(0, 1) })) === true, + service.isServerAllowed({ name: 'microsoft/playwright-mcp', command: ['npx', 'unapproved'] }) === true, + service.isServerAllowed({ name: 'microsoft/playwright-mcp', url: 'https://unapproved.example/mcp' }) === true, + ], [true, true, true, false, false, false]); + }); + + test('uses runtime and package arguments and defers only unresolved inputs', () => { + const service = createService({ [mcpAllowedServersConfig]: [{ serverCommand: ['npx', '-y', 'server', '--mode', 'approved'] }] }); + const server = (value?: string) => gallery({ + packages: [{ + registryType: RegistryType.NODE, identifier: 'server', transport: { type: TransportType.STDIO }, + runtimeArguments: [{ type: 'positional', value: '-y' }], + packageArguments: [{ type: 'named', name: '--mode', value, description: 'Mode' }], + }] + }); + assert.deepStrictEqual([ + service.isAllowed(server('approved')) === true, + service.isAllowed(server('other')) === true, + service.isAllowed(server()) === true, + service.isServerAllowed({ name: 'server', command: ['npx', '-y', 'server', '--mode', 'other'] }) === true, + service.isServerAllowed({ name: 'server', command: ['npx', '-y', 'server', '--mode', 'approved'] }) === true, + ], [true, false, true, false, true]); + }); + + test('reports invalid gallery configurations without admitting another candidate', () => { + const service = createService({ [mcpAllowedServersConfig]: [{ serverCommand: ['npx', 'approved'] }] }); + const server = gallery({ + remotes: [{ + type: TransportType.STREAMABLE_HTTP, + url: 'https://{host}/mcp', + variables: { host: { description: 'URL host' } }, + headers: [{ name: 'X-Host', value: '{host}', variables: { host: { description: 'Header host' } } }], + }], + packages: [{ registryType: RegistryType.NODE, identifier: 'approved', transport: { type: TransportType.STDIO } }], + }); + const result = service.isAllowed(server); + assert.deepStrictEqual({ + allowed: result === true, + invalidManifest: result !== true && result.value.includes('gallery configuration is invalid'), + conflict: result !== true && result.value.includes('conflicting definitions'), + }, { allowed: false, invalidManifest: true, conflict: true }); + }); + + test('does not normalize executable wrappers or add npm arguments to satisfy a policy', () => { + const server = gallery({ + packages: [{ + registryType: RegistryType.NODE, identifier: '@playwright/mcp', version: 'latest', transport: { type: TransportType.STDIO }, + }] + }); + assert.deepStrictEqual([ + ['npx', '@playwright/mcp@latest'], + ['npx', '-y', '@playwright/mcp@latest'], + ['cmd', '/c', 'npx', '@playwright/mcp@latest'], + ].map(serverCommand => createService({ [mcpAllowedServersConfig]: [{ serverCommand }] }).isAllowed(server) === true), [true, false, false]); + }); + }); + + test('expands policy values on the executing host and fails closed without the resolved values', () => { + const service = createService({ + [mcpAllowedServersConfig]: [{ serverName: 'server' }, { serverCommand: ['${RUNTIME}', '${SCRIPT:-approved.js}'] }], + [mcpDeniedServersConfig]: [{ serverCommand: ['${RUNTIME}', 'blocked.js'] }], + }); + const values = service.getServerPolicyVariableValues(); + const resolve = createEnvVarResolver({ RUNTIME: '/remote/node' }, false); + const policyValues = Object.fromEntries(values.map(value => [value, resolve(value)])); + const identity = { name: 'server', command: ['/remote/node', 'approved.js'], policyValues }; + assert.deepStrictEqual({ + values, + preliminary: service.isServerAllowedBeforeResolution({ name: 'server', command: ['${input:runtime}', '${input:script}'] }) === true, + unresolved: service.isServerAllowed({ ...identity, policyValues: undefined }) === true, + approved: service.isServerAllowed(identity) === true, + otherHost: service.isServerAllowed({ ...identity, command: ['/local/node', 'approved.js'] }) === true, + denied: service.isServerAllowed({ ...identity, command: ['/remote/node', 'blocked.js'] }) === true, + }, { + values: ['${RUNTIME}', '${SCRIPT:-approved.js}'], + preliminary: true, unresolved: false, approved: true, otherHost: false, denied: false, + }); + }); + + test('explains why a matching name does not admit a nonmatching command or URL', () => { + const service = createService({ + [mcpAllowedServersConfig]: [ + { serverName: 'approved' }, + { serverCommand: ['node', 'approved.js'] }, + { serverUrl: 'https://approved.example/mcp' }, + ], + }); + const commandResult = service.isServerAllowed({ name: 'approved', command: ['node', 'other.js'] }); + const urlResult = service.isServerAllowed({ name: 'approved', url: 'https://other.example/mcp' }); + assert.deepStrictEqual({ + command: commandResult !== true && commandResult.value.includes('this allowlist contains command entries'), + url: urlResult !== true && urlResult.value.includes('this allowlist contains URL entries'), + }, { command: true, url: true }); + }); + + test('defers unknown transport details without bypassing known name denials or final rules', () => { + const allowlist = [ + { serverName: 'approved' }, + { serverCommand: ['node', 'approved.js'] }, + { serverUrl: 'https://approved.example/mcp' }, + ]; + const service = createService({ [mcpAllowedServersConfig]: allowlist }); + const denied = createService({ [mcpAllowedServersConfig]: allowlist, [mcpDeniedServersConfig]: [{ serverName: 'approved' }] }); + const unresolved = [ + { name: 'approved', command: ['node', '${input:script}'] }, + { name: 'approved', url: 'https://${input:host}/mcp' }, + ]; + assert.deepStrictEqual({ + preliminary: unresolved.map(identity => service.isServerAllowedBeforeResolution(identity) === true), + denied: unresolved.map(identity => denied.isServerAllowedBeforeResolution(identity) === true), + resolved: [ + { name: 'approved', command: ['node', 'other.js'] }, + { name: 'approved', url: 'https://other.example/mcp' }, + ].map(identity => service.isServerAllowed(identity) === true), + }, { preliminary: [true, true], denied: [false, false], resolved: [false, false] }); + }); + test('blocks all servers when access is None', () => { const service = createService({ [mcpAccessConfig]: McpAccessValue.None }); const result = service.isServerAllowed({ name: 'github' }); diff --git a/src/vs/platform/mcp/test/common/mcpManagementService.test.ts b/src/vs/platform/mcp/test/common/mcpManagementService.test.ts index 5f1d1cb0c87a5d..ed70d460f28503 100644 --- a/src/vs/platform/mcp/test/common/mcpManagementService.test.ts +++ b/src/vs/platform/mcp/test/common/mcpManagementService.test.ts @@ -62,7 +62,7 @@ class TestMcpManagementService extends AbstractCommonMcpManagementService { } class TestMcpResourceManagementService extends AbstractMcpResourceManagementService { - constructor(mcpResource: URI, fileService: FileService, uriIdentityService: UriIdentityService, mcpResourceScannerService: McpResourceScannerService, allowedMcpServersService: IAllowedMcpServersService = { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }) { + constructor(mcpResource: URI, fileService: FileService, uriIdentityService: UriIdentityService, mcpResourceScannerService: McpResourceScannerService, allowedMcpServersService: IAllowedMcpServersService = { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }) { super( mcpResource, ConfigurationTarget.USER, @@ -1529,7 +1529,7 @@ suite('McpResourceManagementService', () => { uriIdentityService, new NullLogService(), scannerService, - { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }, + { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }, upcastPartial<IEnvironmentService>({ userRoamingDataHome: URI.from({ scheme: Schemas.inMemory, path: '/user' }) }), )); const [local] = await galleryService.getInstalled(); @@ -1549,7 +1549,7 @@ suite('McpResourceManagementService', () => { uriIdentityService, new NullLogService(), scannerService, - { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }, + { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }, upcastPartial<IEnvironmentService>({ userRoamingDataHome: URI.from({ scheme: Schemas.inMemory, path: '/user' }) }), )); @@ -1567,7 +1567,7 @@ suite('McpResourceManagementService', () => { uriIdentityService, new NullLogService(), scannerService, - { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }, + { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }, upcastPartial<IEnvironmentService>({ userRoamingDataHome: URI.from({ scheme: Schemas.inMemory, path: '/user' }) }), )); const gallery = { @@ -1610,7 +1610,7 @@ suite('McpResourceManagementService', () => { uriIdentityService, logService, scannerService, - { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }, + { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }, upcastPartial<IEnvironmentService>({ userRoamingDataHome: URI.from({ scheme: Schemas.inMemory, path: '/user' }) }), )); @@ -1636,7 +1636,7 @@ suite('McpResourceManagementService - install policy enforcement', () => { const server: IInstallableMcpServer = { name: 'my-server', config: { type: McpServerType.LOCAL, command: 'node', args: [] } }; function createService(isAllowed: IAllowedMcpServersService['isAllowed']): TestMcpResourceManagementService { - const allowedMcpServersService: IAllowedMcpServersService = { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }; + const allowedMcpServersService: IAllowedMcpServersService = { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }; return disposables.add(new TestMcpResourceManagementService(mcpResource, fileService, uriIdentityService, scannerService, allowedMcpServersService)); } diff --git a/src/vs/sessions/DESKTOP.md b/src/vs/sessions/DESKTOP.md index 2ec5a8cad05309..aa53ceb4c0e27c 100644 --- a/src/vs/sessions/DESKTOP.md +++ b/src/vs/sessions/DESKTOP.md @@ -137,7 +137,7 @@ In `chat`, workspace-backed drafts and created chats use owner-scoped current an ### Quick chats / no workspace Workspace selection in a draft changes content, not layout. Switching between a workspace and No workspace preserves Editor and Auxiliary Bar visibility and their sizes, including explicit opens or closes made between selections. A visible Auxiliary Bar shows the Files empty view for No workspace. The draft strategy does not save or restore a separate composition for these transitions, and normal Editor minimum-width constraints remain unchanged. -Quick Chats with saved editors share overall side-pane visibility with Existing Sessions, mapping a visible profile to Editor-only and keeping a hidden profile hidden. Opening a first editor and visibility changes made in an editor-bearing Quick Chat update the shared profile before the chat's first switch. An editorless Quick Chat hides the side pane after its working-set restore settles, including on reload, without overwriting the shared profile. This transient side-pane behavior remains unchanged by the experiment; Quick Chats do not route through durable owner-composition or last-open catalogs. +Quick Chats with saved editors share overall side-pane visibility with Existing Sessions, mapping a visible profile to Editor-only and keeping a hidden profile hidden. In `chat`, a Quick Chat instead remembers its own last side-pane visibility for the window session, mapped to Editor-only or hidden, and restores it when revisited, revealing a side pane that another session left closed; until it has remembered visibility (for example after reload), it uses the shared behavior. Opening a first editor and visibility changes made in an editor-bearing Quick Chat update the shared profile before the chat's first switch. An editorless Quick Chat hides the side pane after its working-set restore settles, including on reload, without overwriting the shared profile. This transient side-pane behavior remains unchanged by the experiment; Quick Chats do not route through durable owner-composition or last-open catalogs. ### Multiple visible sessions Visibility restoration is reveal-only while multiple sessions are visible. Focusing a workspace session reveals the parts enabled by its matching profile, while focusing a quick chat or another session without side-pane content does not hide Editor. Collapsing back to one Quick Chat keeps Editor visible; collapsing to a workspace session restores that session type's complete shared profile. Reveal-only preservation applies only to panel synchronization: active Changes/Files editors still publish their docked-details capability so **Toggle Details** remains available. diff --git a/src/vs/sessions/LAYOUT_CONTROLLER.md b/src/vs/sessions/LAYOUT_CONTROLLER.md index 6496f9142c6806..5df098c4299062 100644 --- a/src/vs/sessions/LAYOUT_CONTROLLER.md +++ b/src/vs/sessions/LAYOUT_CONTROLLER.md @@ -35,7 +35,7 @@ With the experiment disabled, each session owns its editor working set and panel | Existing Session Editor/Details profile | `sessions.singlePane.sidePaneVisibility` | Shared across Existing Sessions | | Side-pane and panel visibility | Workbench part visibility | Window | -Draft Sessions do not persist a separate legacy visibility profile. Quick Chats reuse the Existing Session profile when they have editor content and hide the side pane when their editor working set is empty. +Draft Sessions do not persist a separate legacy visibility profile. Quick Chats reuse the Existing Session profile when they have editor content and hide the side pane when their editor working set is empty. In `chat`, a Quick Chat with editor content instead restores its own last side-pane visibility recorded in this window. In both enabled desktop modes, the focused `(sessionResource, chatResource)` owns the singleton Editor's ordinary working set and active editor and selected bottom-panel view. Focus changes within one session and between sessions use the same layout owner boundary, including with multiple visible sessions or chat groups. Resource identities are provider-neutral and opaque. The main chat uses its session resource as its layout key; peers use a composite session/chat key. diff --git a/src/vs/sessions/SESSIONS_LIST.md b/src/vs/sessions/SESSIONS_LIST.md index af350c9a26b913..c0a9d45fefd7bc 100644 --- a/src/vs/sessions/SESSIONS_LIST.md +++ b/src/vs/sessions/SESSIONS_LIST.md @@ -131,6 +131,10 @@ A session drop resolves to a destination placement: Pinned, a custom group, an u Archived sections and comparison groups keep a fixed order, and comparison group membership cannot change by dragging. Multi-selection preserves relative order. +## Agent tools + +The `readSessionsList` and `organizeSessionsList` client tools let an agent read and change the list as the user can. Reading reports the view options and the composed tree, including rows and sections that capping hides, using stable header ids (section ids, and `group:<id>` for custom groups) and session ids. Changes go through `SessionsList` and `SessionsView` rather than directly through the owning services, so they follow the same placement precedence, validity rules, and undo affordances as drag and drop and the list's actions. The tools exist only in the Agents window, form the `vscodeSessionsList` client tool set, and are deferred behind tool search on agent hosts. + ## Reactive presentation Rows derive title, status, workspace, changes, capabilities, and quick-chat identity from session observables. Renderers must support tree virtualization: reusing a row template for another session must not retain stale state, animations, hovers, or disposables. diff --git a/src/vs/sessions/browser/menus.ts b/src/vs/sessions/browser/menus.ts index 852f0c6c8a5ee7..5858044181b903 100644 --- a/src/vs/sessions/browser/menus.ts +++ b/src/vs/sessions/browser/menus.ts @@ -95,6 +95,9 @@ export const Menus = { SessionsEditorTabsBarAddTab: new MenuId('SessionsEditorTabsBarAddTab'), SessionsEditorTabsBarAddTabCanvas: new MenuId('SessionsEditorTabsBarAddTabCanvas'), EmptyFileEditorActions: new MenuId('SessionsEmptyFileEditorActions'), + EmptySearchEditorActions: new MenuId('SessionsEmptySearchEditorActions'), + EmptyBrowserEditorActions: new MenuId('SessionsEmptyBrowserEditorActions'), + EmptyChangesActions: new MenuId('SessionsEmptyChangesActions'), /** * The Add Tab actions listed in place of the watermark in an empty editor * group. A subset of {@link SessionsEditorTabsBarAddTab}, which still backs @@ -139,4 +142,6 @@ export const SessionActivityBarGroup = { SidePanel: '1_sidePanel', /** The terminal, followed by the panel toggle. */ Panel: '2_panel', + /** Links to the active chat's pull requests and issues. */ + GitHub: '3_github', } as const; diff --git a/src/vs/sessions/browser/parts/chatGroupView.ts b/src/vs/sessions/browser/parts/chatGroupView.ts index 251c6f7fee737e..2c0a6ea67b036c 100644 --- a/src/vs/sessions/browser/parts/chatGroupView.ts +++ b/src/vs/sessions/browser/parts/chatGroupView.ts @@ -257,6 +257,7 @@ export class ChatGroupView extends Disposable implements ISerializableView { this._connection.setSession(context?.session); if (!context) { + this._sessionActivityBar.setChatActions(undefined); this._draftChatResource = undefined; this._activeChatIsClosableKey.reset(); this._activeChatCanArchiveKey.reset(); @@ -409,6 +410,7 @@ export class ChatGroupView extends Disposable implements ISerializableView { this._contentContainer.replaceChildren(view.element, this._remoteHostUnavailableEmptyState.domNode); this._currentView.value = view; currentView.set(view, undefined); + this._sessionActivityBar.setChatActions(view.activityBarActions); view.setPrimary(this._primary, this._split); view.setActive(this._sessionActive && this._groupActive); view.setVisible(this._sessionVisible); diff --git a/src/vs/sessions/browser/parts/chatView.ts b/src/vs/sessions/browser/parts/chatView.ts index a24103f29e670b..622d983bb467a9 100644 --- a/src/vs/sessions/browser/parts/chatView.ts +++ b/src/vs/sessions/browser/parts/chatView.ts @@ -8,6 +8,7 @@ import { ISerializableView, IViewSize } from '../../../base/browser/ui/grid/grid import { ProgressBar } from '../../../base/browser/ui/progressbar/progressbar.js'; import { Emitter, Event } from '../../../base/common/event.js'; import { Disposable } from '../../../base/common/lifecycle.js'; +import { IAction } from '../../../base/common/actions.js'; import { constObservable, IObservable } from '../../../base/common/observable.js'; import { URI } from '../../../base/common/uri.js'; import { CancellationToken } from '../../../base/common/cancellation.js'; @@ -87,6 +88,10 @@ export abstract class AbstractChatView extends Disposable implements ISerializab readonly pickerVisibility: IObservable<ISessionPickerVisibility> = constObservable(noSessionPickerVisibility); + get activityBarActions(): IObservable<readonly IAction[]> { + return constObservable([]); + } + get scrollDownButtonDomNode(): HTMLElement | undefined { return undefined; } diff --git a/src/vs/sessions/browser/parts/emptyEditorGroupAddTab.ts b/src/vs/sessions/browser/parts/emptyEditorGroupAddTab.ts index 1a14bdf83dfa80..3a996db56ac671 100644 --- a/src/vs/sessions/browser/parts/emptyEditorGroupAddTab.ts +++ b/src/vs/sessions/browser/parts/emptyEditorGroupAddTab.ts @@ -3,6 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import './media/sessionsEmptyState.css'; import { $, addDisposableListener, append, EventHelper, EventLike, EventType } from '../../../base/browser/dom.js'; import { ActionBar, ActionsOrientation } from '../../../base/browser/ui/actionbar/actionbar.js'; import { BaseActionViewItem } from '../../../base/browser/ui/actionbar/actionViewItems.js'; @@ -21,6 +22,7 @@ import { localize } from '../../../nls.js'; import { getFlatActionBarActions } from '../../../platform/actions/browser/menuEntryActionViewItem.js'; import { IMenuService, MenuId, MenuItemAction, SubmenuItemAction } from '../../../platform/actions/common/actions.js'; import { IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; +import { IHoverService } from '../../../platform/hover/browser/hover.js'; import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; import { IKeybindingService } from '../../../platform/keybinding/common/keybinding.js'; import { INotificationService } from '../../../platform/notification/common/notification.js'; @@ -28,6 +30,7 @@ import { ITelemetryService } from '../../../platform/telemetry/common/telemetry. import { defaultKeybindingLabelStyles } from '../../../platform/theme/browser/defaultStyles.js'; import { EditorAddTabControl } from '../../../workbench/browser/parts/editor/editorAddTabControl.js'; import { SubmenuFlyout } from './submenuFlyout.js'; +import { SessionsEmptyStateLayout } from './sessionsEmptyStateLayout.js'; /** The parts of an editor group that the empty-group Add Tab UI depends on. */ export interface IEmptyEditorGroup { @@ -99,12 +102,14 @@ export class EmptyEditorGroupAddTab extends Disposable { })); const lookupKeybinding = (commandId: string) => this.keybindingService.lookupKeybinding(commandId, contextKeyService); - const actionBar = store.add(new ActionBar(append(watermarkContainer, $('.sessions-add-tab-watermark-list')), { + const listContainer = append(watermarkContainer, $('.sessions-add-tab-watermark-list.sessions-watermark-actions')); + const actionBar = store.add(new ActionBar(listContainer, { orientation: ActionsOrientation.VERTICAL, ariaLabel: localize('addTabWatermark', "Add Tab"), actionRunner, - actionViewItemProvider: action => this.instantiationService.createInstance(AddTabWatermarkActionViewItem, action, lookupKeybinding), + actionViewItemProvider: action => this.instantiationService.createInstance(SessionsWatermarkActionViewItem, action, lookupKeybinding), })); + const layout = store.add(new SessionsEmptyStateLayout(watermarkContainer, [listContainer])); // Submenu entries such as Canvas render their items, so changes inside them must refresh the list too. const menu = store.add(this.menuService.createMenu(this.listMenuId, contextKeyService, { emitEventsForSubmenuChanges: true })); @@ -123,6 +128,7 @@ export class EmptyEditorGroupAddTab extends Disposable { actionBar.clear(); actionBar.push(actions); groupElement.classList.toggle(HAS_ADD_TAB_WATERMARK_CLASS, actions.length > 0); + layout.layout(); }; update(true); store.add(menu.onDidChange(() => update(false))); @@ -143,7 +149,7 @@ function getActionsSignature(actions: readonly IAction[]): string { ])); } -class AddTabWatermarkActionViewItem extends BaseActionViewItem { +export class SessionsWatermarkActionViewItem extends BaseActionViewItem { private submenuFlyout: SubmenuFlyout | undefined; @@ -151,6 +157,8 @@ class AddTabWatermarkActionViewItem extends BaseActionViewItem { action: IAction, private readonly lookupKeybinding: (commandId: string) => ResolvedKeybinding | undefined, @IInstantiationService private readonly instantiationService: IInstantiationService, + @IKeybindingService private readonly keybindingService: IKeybindingService, + @IHoverService private readonly hoverService: IHoverService, ) { super(undefined, action); } @@ -160,7 +168,7 @@ class AddTabWatermarkActionViewItem extends BaseActionViewItem { super.render(row); row.setAttribute('role', 'button'); - const icon = append(row, $('span.sessions-add-tab-watermark-icon')); + const icon = append(row, $('span.sessions-add-tab-watermark-icon', { 'aria-hidden': 'true' })); const item = this._action instanceof MenuItemAction || this._action instanceof SubmenuItemAction ? this._action.item : undefined; if (item?.icon && ThemeIcon.isThemeIcon(item.icon)) { icon.classList.add(...ThemeIcon.asClassNameArray(item.icon)); @@ -168,16 +176,26 @@ class AddTabWatermarkActionViewItem extends BaseActionViewItem { append(row, $('span.sessions-add-tab-watermark-label')).textContent = this._action.label; - const keybinding = this._action instanceof MenuItemAction ? this.lookupKeybinding(this._action.id) : undefined; - // Rows end with their keybinding or submenu chevron, so both line up at the row's trailing edge. - if (keybinding) { - this._register(new KeybindingLabel(append(row, $('span.sessions-add-tab-watermark-keybinding')), OS, defaultKeybindingLabelStyles)).set(keybinding); - } - - const keybindingAriaLabel = keybinding?.getAriaLabel(); - row.setAttribute('aria-label', keybindingAriaLabel - ? localize('addTabWatermarkEntryAriaLabel', "{0} ({1})", this._action.label, keybindingAriaLabel) - : this._action.label); + const keybindingContainer = $('span.sessions-add-tab-watermark-keybinding', { 'aria-hidden': 'true' }); + const keybindingLabel = this._register(new KeybindingLabel(keybindingContainer, OS, defaultKeybindingLabelStyles)); + const updateKeybinding = () => { + const keybinding = this._action instanceof MenuItemAction ? this.lookupKeybinding(this._action.id) : undefined; + keybindingLabel.set(keybinding); + if (keybinding) { + if (keybindingContainer.parentElement !== row) { + append(row, keybindingContainer); + } + } else { + keybindingContainer.remove(); + } + const keybindingAriaLabel = keybinding?.getAriaLabel(); + row.setAttribute('aria-label', keybindingAriaLabel + ? localize('addTabWatermarkEntryAriaLabel', "{0} ({1})", this._action.label, keybindingAriaLabel) + : this._action.label); + }; + updateKeybinding(); + this._register(this.keybindingService.onDidUpdateKeybindings(updateKeybinding)); + this._register(this.hoverService.setupDelayedHover(row, () => ({ content: this._action.label }))); const action = this._action; if (action instanceof SubmenuItemAction) { diff --git a/src/vs/sessions/browser/parts/media/editorPart.css b/src/vs/sessions/browser/parts/media/editorPart.css index 02f76231ede8b9..0486e7772f4e00 100644 --- a/src/vs/sessions/browser/parts/media/editorPart.css +++ b/src/vs/sessions/browser/parts/media/editorPart.css @@ -25,12 +25,16 @@ --modern-ui-editor-tabs-border: color-mix(in srgb, var(--vscode-activeSessionView-foreground, var(--vscode-agentsPanel-foreground)) 12%, transparent); } -/* Detail-pane view tabs need a leading icon inset without widening the RTL file-icon gutter. */ +/* Detail-pane view tabs need a leading icon inset. */ .agent-sessions-workbench.dock-detail-panel .part.editor:not(.modal-editor-part) > .content .editor-group-container > .title.tabs .tabs-container > .tab:not(.sticky-compact):not(.tab-actions-left) { --modern-ui-editor-tab-left-inset: var(--vscode-spacing-size80); } -.agent-sessions-workbench.dock-detail-panel.file-icons-enabled:dir(rtl) .part.editor:not(.modal-editor-part) > .content .editor-group-container > .title.tabs.show-file-icons .tabs-container > .tab:not(.sticky-compact):not(.tab-actions-left) { +/* When a file icon renders, its own built-in box (width + trailing gap) already carries most of that + * leading inset. Keeping the full inset on top of the icon's box double-counts the space, so reduce it + * to match core editor tabs (https://github.com/microsoft/vscode/issues/331234). + * Apply in both directions to avoid widening the file-icon gutter in either one. */ +.agent-sessions-workbench.dock-detail-panel.file-icons-enabled .part.editor:not(.modal-editor-part) > .content .editor-group-container > .title.tabs.show-file-icons .tabs-container > .tab:not(.sticky-compact):not(.tab-actions-left) { --modern-ui-editor-tab-left-inset: var(--vscode-spacing-size60); } @@ -271,73 +275,6 @@ width: calc(100% - 2 * var(--vscode-spacing-size240)); max-width: 320px; pointer-events: auto; - container-type: inline-size; -} - -/* Labels matter more than shortcuts: drop the keybinding column when the list is too narrow for both. */ -@container (max-width: 240px) { - .agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-keybinding { - display: none; - } -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .monaco-action-bar.vertical .actions-container { - display: block; -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-entry { - display: flex; - align-items: center; - gap: var(--vscode-spacing-size80); - height: var(--vscode-spacing-size280); - padding: 0 var(--vscode-spacing-size80); - border-radius: var(--vscode-cornerRadius-small); - color: var(--vscode-foreground); - font-size: var(--vscode-fontSize-body1); - cursor: pointer; -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-entry:hover, -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-entry.submenu-open { - background-color: var(--vscode-toolbar-hoverBackground); - outline: var(--vscode-strokeThickness) dashed var(--vscode-toolbar-hoverOutline); - outline-offset: calc(-1 * var(--vscode-strokeThickness)); -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-entry:focus-visible { - outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); - outline-offset: calc(-1 * var(--vscode-strokeThickness)); -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-entry.disabled { - opacity: 0.5; - cursor: default; -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-icon { - flex: 0 0 auto; - width: var(--vscode-codiconFontSize); - color: var(--vscode-descriptionForeground); -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-label { - flex: 1 1 auto; - min-width: 0; - overflow: hidden; - text-overflow: ellipsis; - white-space: nowrap; -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-keybinding { - flex: 0 0 auto; - color: var(--vscode-descriptionForeground); -} - -.agent-sessions-workbench .sessions-empty-group-add-tab-watermark .sessions-add-tab-watermark-submenu-indicator { - flex: 0 0 auto; - /* The chevron glyph sits inset in its icon box; offset that so it visually ends with the keycaps above. */ - margin-inline-end: calc(-1 * var(--vscode-spacing-size40)); - color: var(--vscode-descriptionForeground); } .agent-sessions-workbench .part.editor > .content .editor-group-container > .title > .tabs-and-actions-container.tabs-border-bottom > .monaco-scrollable-element { diff --git a/src/vs/sessions/browser/parts/media/sessionsEmptyState.css b/src/vs/sessions/browser/parts/media/sessionsEmptyState.css index ebff580e9daf5c..6dbae9e4e91701 100644 --- a/src/vs/sessions/browser/parts/media/sessionsEmptyState.css +++ b/src/vs/sessions/browser/parts/media/sessionsEmptyState.css @@ -29,3 +29,89 @@ color: var(--vscode-descriptionForeground); font-weight: var(--vscode-fontWeight-regular); } + +.sessions-empty-state-content { + display: flex; + flex-direction: column; + gap: var(--vscode-spacing-size160); + width: min(320px, calc(100% - 2 * var(--vscode-spacing-size240))); +} + +.sessions-empty-state-content > .sessions-empty-state-description { + margin: 0; + text-align: center; +} + +.sessions-watermark-actions { + width: 100%; + container-type: inline-size; +} + +@container (max-width: 240px) { + .sessions-watermark-actions .sessions-add-tab-watermark-keybinding { + display: none; + } +} + +.sessions-watermark-actions .monaco-action-bar.vertical { + height: auto; +} + +.sessions-watermark-actions .monaco-action-bar.vertical .actions-container { + display: block; + height: auto; +} + +.sessions-watermark-actions .monaco-action-bar .sessions-add-tab-watermark-entry { + display: flex; + align-items: center; + gap: var(--vscode-spacing-size80); + height: var(--vscode-spacing-size280); + padding: 0 var(--vscode-spacing-size80); + border-radius: var(--vscode-cornerRadius-small); + color: var(--vscode-foreground); + font-size: var(--vscode-fontSize-body1); + cursor: pointer; +} + +.sessions-watermark-actions .sessions-add-tab-watermark-entry:hover, +.sessions-watermark-actions .sessions-add-tab-watermark-entry.submenu-open { + background-color: var(--vscode-toolbar-hoverBackground); + outline: var(--vscode-strokeThickness) dashed var(--vscode-toolbar-hoverOutline); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.sessions-watermark-actions .sessions-add-tab-watermark-entry:focus-visible { + outline: var(--vscode-strokeThickness) solid var(--vscode-focusBorder); + outline-offset: calc(-1 * var(--vscode-strokeThickness)); +} + +.sessions-watermark-actions .sessions-add-tab-watermark-entry.disabled { + opacity: 0.5; + cursor: default; +} + +.sessions-watermark-actions .sessions-add-tab-watermark-icon { + flex: 0 0 auto; + width: var(--vscode-codiconFontSize); + color: var(--vscode-descriptionForeground); +} + +.sessions-watermark-actions .sessions-add-tab-watermark-label { + flex: 1 1 auto; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.sessions-watermark-actions .sessions-add-tab-watermark-keybinding { + flex: 0 0 auto; + color: var(--vscode-descriptionForeground); +} + +.sessions-watermark-actions .sessions-add-tab-watermark-submenu-indicator { + flex: 0 0 auto; + margin-inline-end: calc(-1 * var(--vscode-spacing-size40)); + color: var(--vscode-descriptionForeground); +} diff --git a/src/vs/sessions/browser/parts/sessionActivityBar.ts b/src/vs/sessions/browser/parts/sessionActivityBar.ts index 8d69f94d086f16..d2e78009816239 100644 --- a/src/vs/sessions/browser/parts/sessionActivityBar.ts +++ b/src/vs/sessions/browser/parts/sessionActivityBar.ts @@ -13,11 +13,11 @@ import { AnchorAlignment } from '../../../base/browser/ui/contextview/contextvie import { HoverPosition } from '../../../base/browser/ui/hover/hoverWidget.js'; import { Codicon } from '../../../base/common/codicons.js'; import { KeyCode } from '../../../base/common/keyCodes.js'; -import { Disposable, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../base/common/lifecycle.js'; +import { Disposable, DisposableMap, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../base/common/lifecycle.js'; import { clamp } from '../../../base/common/numbers.js'; import { autorun, constObservable, derived, IObservable, observableFromEvent, observableValue, transaction } from '../../../base/common/observable.js'; import { ThemeIcon } from '../../../base/common/themables.js'; -import { IAction, toAction } from '../../../base/common/actions.js'; +import { Action, IAction, toAction } from '../../../base/common/actions.js'; import { localize } from '../../../nls.js'; import { HiddenItemStrategy, MenuWorkbenchToolBar } from '../../../platform/actions/browser/toolbar.js'; import { IMenuEntryActionViewItemOptions, MenuEntryActionViewItem } from '../../../platform/actions/browser/menuEntryActionViewItem.js'; @@ -30,16 +30,18 @@ import { TogglePanelAction } from '../../../workbench/browser/parts/panel/panelA import { ISessionActivityBarActivityService } from '../../services/activity/common/sessionActivityBarActivityService.js'; import { ICommandService } from '../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../platform/configuration/common/configuration.js'; -import { IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; +import { IContextKey, IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; import { IContextMenuService } from '../../../platform/contextview/browser/contextView.js'; import { IHoverService, WorkbenchHoverDelegate } from '../../../platform/hover/browser/hover.js'; import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; +import { ServiceCollection } from '../../../platform/instantiation/common/serviceCollection.js'; import { IKeybindingService } from '../../../platform/keybinding/common/keybinding.js'; import { Menus, SessionActivityBarGroup } from '../menus.js'; import { AgentWorkbenchLayout, IAgentWorkbenchLayoutService } from '../workbench.js'; import { AGENTS_CONTENT_HORIZONTAL_PADDING } from '../../common/layoutConstants.js'; import { SESSION_ACTIVITY_BAR_SETTING } from '../../common/sessionConfig.js'; import { TOGGLE_SIDE_PANEL_COMMAND_ID } from '../../common/sessionCommands.js'; +import { sessionActivityBarChatActionContext } from '../../common/contextkeys.js'; import { isPhoneLayout } from './mobile/mobileLayout.js'; import { SubmenuFlyout } from './submenuFlyout.js'; @@ -61,6 +63,8 @@ export class SessionActivityBar extends Disposable { /** The number of entries, which determines the strip's height. */ readonly itemCount: IObservable<number> = this._itemCount; + private readonly chatActions = observableValue<IObservable<readonly IAction[]> | undefined>(this, undefined); + constructor( container: HTMLElement, @IConfigurationService private readonly configurationService: IConfigurationService, @@ -71,10 +75,14 @@ export class SessionActivityBar extends Disposable { super(); this.element = append(container, $('.session-activity-bar')); + const scopedContextKeyService = this._register(contextKeyService.createScoped(this.element)); + const scopedInstantiationService = this._register(instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]))); + let actionsById = new Map<string, IAction>(); + const renderedChatActions = this._register(new DisposableMap<string, Action>()); // Like the workbench activity bar, once an entry's hover has shown, moving to another entry shows its hover instantly. const hoverDelegate = this._register(instantiationService.createInstance(WorkbenchHoverDelegate, 'element', { instantHover: true }, { position: { hoverPosition: HoverPosition.LEFT } })); - const toolbar = this._register(instantiationService.createInstance(MenuWorkbenchToolBar, this.element, Menus.SessionActivityBar, { + const toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, this.element, Menus.SessionActivityBar, { orientation: ActionsOrientation.VERTICAL, ariaLabel: localize('sessionActivityBar', "Session Activity Bar"), telemetrySource: 'sessionActivityBar', @@ -86,8 +94,12 @@ export class SessionActivityBar extends Disposable { // Every group shows in the strip: the side panel toggle and tab entries, then the terminal and panel toggle. toolbarOptions: { primaryGroup: () => true, useSeparatorsInPrimaryActions: true }, actionViewItemProvider: (action, options) => { + const chatAction = renderedChatActions.get(action.id); + if (chatAction) { + return new ActionViewItem(undefined, chatAction, { ...options, icon: true, label: false }); + } if (action instanceof SubmenuItemAction) { - return instantiationService.createInstance(SessionActivityBarSubmenuViewItem, action, { ...options, icon: true, label: false }); + return scopedInstantiationService.createInstance(SessionActivityBarSubmenuViewItem, action, { ...options, icon: true, label: false }); } if (action instanceof MenuItemAction) { return instantiationService.createInstance(SessionActivityBarActionViewItem, action, options); @@ -107,6 +119,50 @@ export class SessionActivityBar extends Disposable { }; update(); this._register(toolbar.onDidChangeMenuItems(update)); + const keys = new Map<string, IContextKey<boolean>>(); + const enabled = observableFromEvent(this, this.configurationService.onDidChangeConfiguration, () => !!this.configurationService.getValue<boolean>(SESSION_ACTIVITY_BAR_SETTING)); + this._register(autorun(reader => { + const actions = enabled.read(reader) ? this.chatActions.read(reader)?.read(reader) ?? [] : []; + actionsById = new Map(actions.map(action => [action.id, action])); + const changed = actions.length !== renderedChatActions.size || actions.some(action => !renderedChatActions.has(action.id)); + for (const [id] of renderedChatActions) { + if (!actionsById.has(id)) { + renderedChatActions.deleteAndDispose(id); + } + } + for (const action of actions) { + let rendered = renderedChatActions.get(action.id); + if (!rendered) { + const id = action.id; + rendered = new Action(id, action.label, action.class, action.enabled, context => actionsById.get(id)?.run(context)); + renderedChatActions.set(action.id, rendered); + } + rendered.label = action.label; + rendered.class = action.class ?? ''; + rendered.enabled = action.enabled; + rendered.tooltip = action.tooltip; + } + scopedContextKeyService.bufferChangeEvents(() => { + for (const [id, key] of keys) { + if (!actionsById.has(id)) { + key.reset(); + keys.delete(id); + } + } + for (const action of actions) { + if (!keys.has(action.id)) { + keys.set(action.id, sessionActivityBarChatActionContext(action.id).bindTo(scopedContextKeyService)); + } + } + for (const [id, key] of keys) { + key.set(actionsById.has(id)); + } + }); + if (changed) { + toolbar.refresh(); + } + update(); + })); // Entries show the toolbar's own context menu, which appends these actions; this covers the rest of the strip. this._register(addDisposableListener(this.element, EventType.CONTEXT_MENU, (e: MouseEvent) => { EventHelper.stop(e, true); @@ -122,6 +178,10 @@ export class SessionActivityBar extends Disposable { } })); } + + setChatActions(actions: IObservable<readonly IAction[]> | undefined): void { + this.chatActions.set(actions, undefined); + } } /** Default distance from the top of the chat area to the strip. */ @@ -265,6 +325,10 @@ export class ChatViewSessionActivityBar extends Disposable { this.applyPosition(); } + setChatActions(actions: IObservable<readonly IAction[]> | undefined): void { + this.activityBar?.setChatActions(actions); + } + /** Positions the strip within the chat area at `top` with the given `height` in the host. */ layout(top: number, height: number): void { this.area = { top, height }; diff --git a/src/vs/sessions/browser/parts/sessionView.ts b/src/vs/sessions/browser/parts/sessionView.ts index c764a0b7b38223..66c5f126f1a5bf 100644 --- a/src/vs/sessions/browser/parts/sessionView.ts +++ b/src/vs/sessions/browser/parts/sessionView.ts @@ -533,6 +533,7 @@ export class SessionView extends Disposable implements ISerializableView, ISessi })); this._lastContentLayout = undefined; } + this._standaloneSessionActivityBar?.setChatActions(standaloneView?.activityBarActions); this._standaloneSessionActivityBar?.setActive(this._isActive && this._isVisible && !!standaloneView); } diff --git a/src/vs/sessions/browser/parts/sessionsEmptyStateActions.ts b/src/vs/sessions/browser/parts/sessionsEmptyStateActions.ts new file mode 100644 index 00000000000000..c4255decd71550 --- /dev/null +++ b/src/vs/sessions/browser/parts/sessionsEmptyStateActions.ts @@ -0,0 +1,44 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/sessionsEmptyState.css'; +import { ActionsOrientation } from '../../../base/browser/ui/actionbar/actionbar.js'; +import { Disposable } from '../../../base/common/lifecycle.js'; +import { HiddenItemStrategy, IMenuWorkbenchToolBarOptions, MenuWorkbenchToolBar } from '../../../platform/actions/browser/toolbar.js'; +import { MenuId } from '../../../platform/actions/common/actions.js'; +import { IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; +import { IInstantiationService } from '../../../platform/instantiation/common/instantiation.js'; +import { ServiceCollection } from '../../../platform/instantiation/common/serviceCollection.js'; +import { IKeybindingService } from '../../../platform/keybinding/common/keybinding.js'; +import { SessionsWatermarkActionViewItem } from './emptyEditorGroupAddTab.js'; + +export class SessionsEmptyStateActions extends Disposable { + private readonly toolbar: MenuWorkbenchToolBar; + + constructor( + container: HTMLElement, + menuId: MenuId, + options: IMenuWorkbenchToolBarOptions, + @IContextKeyService contextKeyService: IContextKeyService, + @IInstantiationService instantiationService: IInstantiationService, + @IKeybindingService keybindingService: IKeybindingService, + ) { + super(); + container.classList.add('sessions-watermark-actions'); + const scopedContextKeyService = this._register(contextKeyService.createScoped(container)); + const scopedInstantiationService = this._register(instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]))); + this.toolbar = this._register(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, container, menuId, { + ...options, + orientation: ActionsOrientation.VERTICAL, + hiddenItemStrategy: HiddenItemStrategy.NoHide, + toolbarOptions: { primaryGroup: group => group === 'navigation' }, + actionViewItemProvider: action => scopedInstantiationService.createInstance(SessionsWatermarkActionViewItem, action, commandId => keybindingService.lookupKeybinding(commandId, scopedContextKeyService)), + })); + } + + focus(): void { + this.toolbar.focus(); + } +} diff --git a/src/vs/sessions/browser/parts/sessionsEmptyStateLayout.ts b/src/vs/sessions/browser/parts/sessionsEmptyStateLayout.ts new file mode 100644 index 00000000000000..f54f1c48bfdebb --- /dev/null +++ b/src/vs/sessions/browser/parts/sessionsEmptyStateLayout.ts @@ -0,0 +1,76 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { getWindow, isHTMLElement } from '../../../base/browser/dom.js'; +import { Disposable, toDisposable } from '../../../base/common/lifecycle.js'; + +const DEFAULT_WATERMARK_HEIGHT = 3 * 28; + +/** Aligns the first action to the default three-action panel watermark, keeping search fields and status text above it. */ +export class SessionsEmptyStateLayout extends Disposable { + private readonly reference: HTMLElement; + private offset = 0; + + constructor( + private readonly container: HTMLElement, + private readonly elements: readonly HTMLElement[], + private readonly anchor: HTMLElement = elements[0], + ResizeObserverCtor: typeof ResizeObserver = getWindow(container).ResizeObserver, + ) { + super(); + this.reference = container.closest<HTMLElement>('.editor-group-container') ?? container; + for (const element of elements) { + element.classList.add('sessions-empty-state-aligned'); + } + const observer = new ResizeObserverCtor(() => this.layout()); + this._register(toDisposable(() => observer.disconnect())); + const observed = new Set<HTMLElement>([container, this.reference, this.anchor, ...elements]); + // Only preceding toolbars can change the space available above the aligned content. + for (let sibling = elements[0].previousElementSibling; sibling; sibling = sibling.previousElementSibling) { + if (isHTMLElement(sibling)) { + observed.add(sibling); + } + } + for (const element of observed) { + observer.observe(element); + } + this._register(toDisposable(() => { + for (const element of elements) { + element.classList.remove('sessions-empty-state-aligned'); + element.style.removeProperty('translate'); + } + })); + this.layout(); + } + + layout(): void { + const bounds = this.elements.map(element => element.getBoundingClientRect()); + if (!bounds.length || bounds.some(bounds => bounds.height === 0)) { + return; + } + const available = this.container.getBoundingClientRect(); + const reference = this.reference.getBoundingClientRect(); + let availableTop = available.top; + for (let sibling = this.elements[0].previousElementSibling; sibling; sibling = sibling.previousElementSibling) { + const bounds = sibling.getBoundingClientRect(); + if (bounds.height > 0) { + availableTop = Math.max(availableTop, bounds.bottom); + } + } + const top = Math.min(...bounds.map(bounds => bounds.top)); + const bottom = Math.max(...bounds.map(bounds => bounds.bottom)); + const desired = this.offset + (reference.top + reference.bottom - DEFAULT_WATERMARK_HEIGHT) / 2 - this.anchor.getBoundingClientRect().top; + const minimum = this.offset + availableTop - top; + const maximum = this.offset + available.bottom - bottom; + const offset = Math.max(minimum, Math.min(maximum, desired)); + if (Math.abs(offset - this.offset) < 0.25) { + return; + } + this.offset = offset; + for (const element of this.elements) { + element.style.translate = `0 ${offset}px`; + } + } +} diff --git a/src/vs/sessions/common/contextkeys.ts b/src/vs/sessions/common/contextkeys.ts index 58f3d6243cbbae..164b7fa611c101 100644 --- a/src/vs/sessions/common/contextkeys.ts +++ b/src/vs/sessions/common/contextkeys.ts @@ -8,6 +8,10 @@ import { ContextKeyExpr, RawContextKey } from '../../platform/contextkey/common/ import { AuxiliaryBarFocusContext, EditorAreaFocusContext } from '../../workbench/common/contextkeys.js'; import { SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from './sessionConfig.js'; +export function sessionActivityBarChatActionContext(commandId: string): RawContextKey<boolean> { + return new RawContextKey<boolean>(`sessionActivityBar.chatAction.${commandId}`, false); +} + //#region < --- Active Session --- > export const IsNewChatSessionContext = new RawContextKey<boolean>('isNewChatSession', true); diff --git a/src/vs/sessions/common/sessionConfig.ts b/src/vs/sessions/common/sessionConfig.ts index 3d3cce95d49ac2..5c9b832553db6b 100644 --- a/src/vs/sessions/common/sessionConfig.ts +++ b/src/vs/sessions/common/sessionConfig.ts @@ -17,11 +17,16 @@ export const SESSION_ACTIVITY_BAR_SETTING = 'sessions.showSessionActivityBar'; /** Whether the Session Activity Bar hosts the side panel and panel toggles in place of the title bar. */ export const SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING = 'sessions.sessionActivityBar.showLayoutActions'; +export const SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING = 'sessions.sessionActivityBar.showGitHubActions'; + /** The setting {@link SESSION_ACTIVITY_BAR_SETTING} was named before the Session Toolbar became the Session Activity Bar. */ export const LEGACY_SESSION_TOOLBAR_SETTING = 'sessions.showSessionToolbar'; export const SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING = 'sessions.list.groupExternalSessions'; +/** Whether agents get tools to read and organize the Agents window Sessions list. */ +export const SESSIONS_LIST_AGENT_TOOLS_SETTING = 'sessions.list.agentTools.enabled'; + export const SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING = 'sessions.list.externalApplicationBadge'; export const SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SHOW_FROM_SETTING = 'sessions.list.externalApplicationBadge.showFrom'; diff --git a/src/vs/sessions/contrib/canvases/browser/sessionCanvasesControl.ts b/src/vs/sessions/contrib/canvases/browser/sessionCanvasesControl.ts index 08ae92edc999f7..46ba2837dcdd85 100644 --- a/src/vs/sessions/contrib/canvases/browser/sessionCanvasesControl.ts +++ b/src/vs/sessions/contrib/canvases/browser/sessionCanvasesControl.ts @@ -38,6 +38,7 @@ export class SessionCanvasesControl extends Disposable { closeCanvas: canvas => sessionsManagementService.closeCanvas(currentSession, currentChat, canvas), }; }); - this.sections = this._register(instantiationService.createInstance(CanvasesPillControl, context)).sections; + const control = this._register(instantiationService.createInstance(CanvasesPillControl, context)); + this.sections = control.sections; } } diff --git a/src/vs/sessions/contrib/changes/browser/changesEmptyState.ts b/src/vs/sessions/contrib/changes/browser/changesEmptyState.ts new file mode 100644 index 00000000000000..c513b9ef84cbad --- /dev/null +++ b/src/vs/sessions/contrib/changes/browser/changesEmptyState.ts @@ -0,0 +1,53 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { $, append } from '../../../../base/browser/dom.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { MenuRegistry } from '../../../../platform/actions/common/actions.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { searchViewIcon } from '../../../../workbench/contrib/search/browser/searchIcons.js'; +import { OpenEditorCommandId } from '../../../../workbench/contrib/searchEditor/browser/constants.js'; +import { Menus } from '../../../browser/menus.js'; +import { SessionsEmptyStateActions } from '../../../browser/parts/sessionsEmptyStateActions.js'; +import { SessionsEmptyStateLayout } from '../../../browser/parts/sessionsEmptyStateLayout.js'; +import { NEW_FILE_TAB_COMMAND_ID } from '../../../common/sessionCommands.js'; +import { EmptyFileEditorInput } from '../../editor/browser/emptyFileEditorInput.js'; + +export class ChangesEmptyState extends Disposable { + constructor( + container: HTMLElement, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(); + const content = append(container, $('.sessions-empty-state-content')); + append(content, $('.sessions-empty-state-description')).textContent = localize('changes.empty', "No changed files"); + const actions = append(content, $('.changes-empty-state-actions')); + this._register(instantiationService.createInstance(SessionsEmptyStateActions, actions, Menus.EmptyChangesActions, { + ariaLabel: localize('changes.emptyActions', "Changes actions"), + telemetrySource: 'changes.emptyState', + })); + this._register(new SessionsEmptyStateLayout(container, [content], actions)); + } +} + +MenuRegistry.appendMenuItems([ + { + id: Menus.EmptyChangesActions, + item: { + command: { id: NEW_FILE_TAB_COMMAND_ID, title: localize2('changes.openFiles', "Open Files"), icon: EmptyFileEditorInput.ICON }, + group: 'navigation', + order: 1, + }, + }, + { + id: Menus.EmptyChangesActions, + item: { + command: { id: OpenEditorCommandId, title: localize2('changes.searchFiles', "Search in Files"), icon: searchViewIcon }, + group: 'navigation', + order: 2, + }, + }, +]); diff --git a/src/vs/sessions/contrib/changes/browser/changesView.ts b/src/vs/sessions/contrib/changes/browser/changesView.ts index 7aca5f7afa2637..adb42edb64c4cb 100644 --- a/src/vs/sessions/contrib/changes/browser/changesView.ts +++ b/src/vs/sessions/contrib/changes/browser/changesView.ts @@ -80,7 +80,7 @@ import { Color } from '../../../../base/common/color.js'; import { PANEL_SECTION_BORDER } from '../../../../workbench/common/theme.js'; import { EditorResourceAccessor, SideBySideEditor } from '../../../../workbench/common/editor.js'; import { logChangesViewFileSelect, logChangesViewVersionModeChange, logChangesViewViewModeChange } from '../../../common/sessionsTelemetry.js'; -import { renderSessionsEmptyState } from '../../../browser/parts/sessionsEmptyState.js'; +import { ChangesEmptyState } from './changesEmptyState.js'; import { ChecksViewModel } from './checksViewModel.js'; import { REVEAL_CI_CHECKS_COMMAND_ID } from './checksActions.js'; // eslint-disable-next-line local/code-import-patterns -- TODO: move skill button constants out of providers @@ -916,11 +916,7 @@ export class ChangesViewPane extends ViewPane { this.welcomeContainer = dom.append(this.contentContainer, $('.changes-welcome')); this.welcomeContainer.style.display = 'none'; - renderSessionsEmptyState( - this.welcomeContainer, - localize('changesView.emptyTitle', "Changes"), - localize('changesView.noChanges', "No changed files"), - ); + this._register(this.scopedInstantiationService.createInstance(ChangesEmptyState, this.welcomeContainer)); // CI Status widget — bottom pane this.ciStatusWidget = this._register(this.scopedInstantiationService.createInstance(CIStatusWidget, this.splitViewContainer)); diff --git a/src/vs/sessions/contrib/changes/browser/media/changesView.css b/src/vs/sessions/contrib/changes/browser/media/changesView.css index a04b4c498baf99..53b3450da8ec93 100644 --- a/src/vs/sessions/contrib/changes/browser/media/changesView.css +++ b/src/vs/sessions/contrib/changes/browser/media/changesView.css @@ -38,7 +38,7 @@ align-items: center; justify-content: center; flex: 1; - padding: 32px; + padding: 0; } /* Main container */ diff --git a/src/vs/sessions/contrib/changes/browser/media/sessionChangesEditor.css b/src/vs/sessions/contrib/changes/browser/media/sessionChangesEditor.css index 7eed0148f96413..3433793c0564d5 100644 --- a/src/vs/sessions/contrib/changes/browser/media/sessionChangesEditor.css +++ b/src/vs/sessions/contrib/changes/browser/media/sessionChangesEditor.css @@ -11,6 +11,25 @@ color: var(--vscode-agentsPanel-foreground); } +.session-changes-editor-body { + position: relative; +} + +.session-changes-editor-empty-state { + position: absolute; + inset: 0; + align-items: center; + justify-content: center; +} + +.session-changes-editor-empty-state:not([hidden]) { + display: flex; +} + +.session-changes-editor-body.has-empty-state .multiDiffEditor .placeholder { + display: none; +} + .session-changes-file-stats { display: inline-flex; flex: 0 0 auto; diff --git a/src/vs/sessions/contrib/changes/browser/sessionChangesEditor.ts b/src/vs/sessions/contrib/changes/browser/sessionChangesEditor.ts index 6d430e1682e492..43f3485ae4b5e4 100644 --- a/src/vs/sessions/contrib/changes/browser/sessionChangesEditor.ts +++ b/src/vs/sessions/contrib/changes/browser/sessionChangesEditor.ts @@ -61,6 +61,7 @@ import { getChangesEditorFileStats } from './changesEditorLabels.js'; import { IDiffEditorOptionsService } from '../../editor/common/diffEditorOptionsService.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; import { observableWorkbenchMultiDiffEditorVariant } from '../../../../workbench/contrib/multiDiffEditor/common/multiDiffEditor.js'; +import { ChangesEmptyState } from './changesEmptyState.js'; const HEADER_HEIGHT = 35; @@ -290,6 +291,14 @@ export class SessionChangesEditor extends AbstractEditorWithViewState<IMultiDiff this._register(autorun(reader => this.widget?.setVariant(variant.read(reader)))); this._register(this.widget.onDidChangeActiveControl(() => this._onDidChangeControl.fire())); this.widget.setPaddingBottom(CHANGES_LIST_BOTTOM_PADDING_PX); + const emptyState = append(this.bodyContainer, $('.session-changes-editor-empty-state')); + this._register(scopedInstantiationService.createInstance(ChangesEmptyState, emptyState)); + this._register(autorun(reader => { + const model = this.widget?.viewModel.read(reader); + const empty = !!model && !model.isLoading.read(reader) && model.items.read(reader).length === 0; + emptyState.hidden = !empty; + this.bodyContainer?.classList.toggle('has-empty-state', empty); + })); this._register(autorun(reader => { this.widget?.setDiffLayoutOptions( this.diffEditorOptionsService.viewMode.read(reader), diff --git a/src/vs/sessions/contrib/changes/browser/sessionsChangesAccessibilityHelp.ts b/src/vs/sessions/contrib/changes/browser/sessionsChangesAccessibilityHelp.ts index 43621800c853b6..29d16603a24c4c 100644 --- a/src/vs/sessions/contrib/changes/browser/sessionsChangesAccessibilityHelp.ts +++ b/src/vs/sessions/contrib/changes/browser/sessionsChangesAccessibilityHelp.ts @@ -11,9 +11,10 @@ import { AccessibleContentProvider, AccessibleViewProviderId, AccessibleViewType import { IAccessibleViewImplementation } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; import { IViewsService } from '../../../../workbench/services/views/common/viewsService.js'; import { AccessibilityVerbositySettingId } from '../../../../workbench/contrib/accessibility/browser/accessibilityConfiguration.js'; -import { FocusedViewContext } from '../../../../workbench/common/contextkeys.js'; +import { ActiveEditorContext, EditorAreaFocusContext, FocusedViewContext } from '../../../../workbench/common/contextkeys.js'; import { CHANGES_VIEW_ID, CreatePullRequestFocusedContext } from '../common/changes.js'; import { ChangesViewPane } from './changesView.js'; +import { SessionChangesEditorInput } from './sessionChangesEditorInput.js'; /** * Accessibility help dialog for the Changes view. Documents the file tree and @@ -24,7 +25,11 @@ export class SessionsChangesAccessibilityHelp implements IAccessibleViewImplemen readonly priority = 115; readonly name = 'sessionsChanges'; readonly type = AccessibleViewType.Help; - readonly when = ContextKeyExpr.or(FocusedViewContext.isEqualTo(CHANGES_VIEW_ID), CreatePullRequestFocusedContext); + readonly when = ContextKeyExpr.or( + FocusedViewContext.isEqualTo(CHANGES_VIEW_ID), + CreatePullRequestFocusedContext, + ContextKeyExpr.and(EditorAreaFocusContext, ActiveEditorContext.isEqualTo(SessionChangesEditorInput.EDITOR_ID)), + ); getProvider(accessor: ServicesAccessor) { const focusedElement = getActiveElement(); @@ -47,11 +52,17 @@ export class SessionsChangesAccessibilityHelp implements IAccessibleViewImplemen ); } const viewsService = accessor.get(IViewsService); + const inEditor = isHTMLElement(focusedElement) && !!focusedElement.closest('.session-changes-editor'); const content: string[] = []; - content.push(localize('sessionsChanges.overview', "You are in the Changes view. It shows the files changed by the current session as a tree, followed by a collapsible Checks section.")); - content.push(localize('sessionsChanges.tree', "Use the up and down arrow keys to move between changed files, and the left and right arrow keys to collapse or expand folders. Press Enter to open the selected file's diff.")); - content.push(localize('sessionsChanges.checks', "The Checks section lists the continuous integration checks for the session's pull request. Its header is a button: press Enter or Space to collapse or expand it{0}.", '<keybinding:sessions.action.revealCIChecks>')); + content.push(inEditor + ? localize('sessionsChanges.editorOverview', "You are in the Changes editor. It shows the changed files and their diffs for the current session.") + : localize('sessionsChanges.overview', "You are in the Changes view. It shows the files changed by the current session as a tree, followed by a collapsible Checks section.")); + content.push(localize('sessionsChanges.empty', "When there are no changed files, use Tab to reach Open Files and Search in Files. Use Up Arrow and Down Arrow to move between those actions, and Enter or Space to run one.")); + if (!inEditor) { + content.push(localize('sessionsChanges.tree', "Use the up and down arrow keys to move between changed files, and the left and right arrow keys to collapse or expand folders. Press Enter to open the selected file's diff.")); + content.push(localize('sessionsChanges.checks', "The Checks section lists the continuous integration checks for the session's pull request. Its header is a button: press Enter or Space to collapse or expand it{0}.", '<keybinding:sessions.action.revealCIChecks>')); + } content.push(localize('sessionsChanges.viewMode', "The Changes view can show files as a tree or a flat list. Use Files View in the editor title area's More Actions menu, or the view's toolbar actions, to switch between View as List and View as Tree. Files View shows both options and marks the active one as selected.")); content.push(localize('sessionsChanges.editorActions', "Changes actions, including Run Code Review and Commit when available, are in the toolbar beside the editor tabs, before the separator and layout actions. Use its More Actions menu for diff actions and the Files View submenu in the final group.")); content.push(localize('sessionsChanges.operations', "When available, a changed file's toolbar provides actions such as Discard Changes. Destructive actions ask for confirmation and are disabled while the agent is working. The Changes toolbar or editor title bar also provides actions to commit, merge, sync, or create a pull request. When Agent Merge is the primary action, activate it to toggle Agent Merge and use its dropdown to configure it. Use Tab and Shift+Tab to move between the file list and toolbar actions.")); @@ -64,6 +75,10 @@ export class SessionsChangesAccessibilityHelp implements IAccessibleViewImplemen { type: AccessibleViewType.Help }, () => content.join('\n'), () => { + if (inEditor && isHTMLElement(focusedElement) && focusedElement.isConnected) { + focusedElement.focus(); + return; + } const view = viewsService.getViewWithId<ChangesViewPane>(CHANGES_VIEW_ID); view?.focus(); }, diff --git a/src/vs/sessions/contrib/changes/test/browser/changesEmptyState.test.ts b/src/vs/sessions/contrib/changes/test/browser/changesEmptyState.test.ts new file mode 100644 index 00000000000000..ab22278204bec1 --- /dev/null +++ b/src/vs/sessions/contrib/changes/test/browser/changesEmptyState.test.ts @@ -0,0 +1,113 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import assert from 'assert'; +import { $, append } from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IMenuService } from '../../../../../platform/actions/common/actions.js'; +import { MenuService } from '../../../../../platform/actions/common/menuService.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { ChangesEmptyState } from '../../browser/changesEmptyState.js'; +import { NEW_FILE_TAB_COMMAND_ID } from '../../../../common/sessionCommands.js'; +import { OpenEditorCommandId } from '../../../../../workbench/contrib/searchEditor/browser/constants.js'; +import { IViewsService } from '../../../../../workbench/services/views/common/viewsService.js'; +import { SessionsChangesAccessibilityHelp } from '../../browser/sessionsChangesAccessibilityHelp.js'; + +suite('Sessions - Changes empty state', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('retains the status and offers keyboard-accessible workspace actions', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + const commands: string[] = []; + instantiationService.stub(ICommandService, new class extends mock<ICommandService>() { + override async executeCommand<T>(id: string): Promise<T | undefined> { + commands.push(id); + return undefined; + } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + const container = append(mainWindow.document.body, $('div')); + store.add(toDisposable(() => container.remove())); + store.add(instantiationService.createInstance(ChangesEmptyState, container)); + const rows = [...container.querySelectorAll<HTMLElement>('.sessions-add-tab-watermark-entry')]; + rows.forEach(row => row.click()); + assert.deepStrictEqual({ + heading: container.querySelector('h2')?.textContent, + status: container.querySelector('.sessions-empty-state-description')?.textContent, + actions: rows.map(row => ({ label: row.textContent, role: row.getAttribute('role') })), + commands, + }, { + heading: undefined, + status: 'No changed files', + actions: [{ label: 'Open Files', role: 'button' }, { label: 'Search in Files', role: 'button' }], + commands: [NEW_FILE_TAB_COMMAND_ID, OpenEditorCommandId], + }); + }); + + test('aligns the first Changes action to the main panel action with status text above it', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + const group = append(mainWindow.document.body, $('.editor-group-container')); + group.style.cssText = 'height: 400px; width: 400px; display: flex; flex-direction: column; --vscode-spacing-size160: 16px; --vscode-spacing-size280: 28px;'; + store.add(toDisposable(() => group.remove())); + const header = append(group, $('div')); + header.style.flex = '0 0 35px'; + const container = append(group, $('div')); + container.style.cssText = 'flex: 1; display: flex; align-items: center; justify-content: center;'; + store.add(instantiationService.createInstance(ChangesEmptyState, container)); + const content = container.firstElementChild; + assert.ok(content); + const actions = content.querySelector<HTMLElement>('.changes-empty-state-actions'); + const status = content.querySelector<HTMLElement>('.sessions-empty-state-description'); + assert.ok(actions && status); + const panelBounds = group.getBoundingClientRect(); + const firstActionTop = actions.getBoundingClientRect().top; + assert.deepStrictEqual({ + firstActionAligned: Math.abs(firstActionTop - (panelBounds.top + panelBounds.bottom) / 2 + 42) < 1, + statusAboveActions: status.getBoundingClientRect().bottom < firstActionTop, + headerUnmoved: header.getBoundingClientRect().top === panelBounds.top, + }, { + firstActionAligned: true, + statusAboveActions: true, + headerUnmoved: true, + }); + }); + + test('documents empty-editor actions and restores focus after accessibility help', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IViewsService, new class extends mock<IViewsService>() { }()); + const container = append(mainWindow.document.body, $('.session-changes-editor')); + store.add(toDisposable(() => container.remove())); + const action = append(container, $('button', undefined, 'Open Files')); + action.focus(); + const provider = store.add(new SessionsChangesAccessibilityHelp().getProvider(instantiationService)); + const content = provider.provideContent(); + append(container, $('button', undefined, 'Other')).focus(); + provider.onClose(); + assert.deepStrictEqual({ + editorOverview: content.includes('You are in the Changes editor.'), + emptyActions: content.includes('Open Files and Search in Files'), + treeInstructions: content.includes('collapse or expand folders'), + focusRestored: mainWindow.document.activeElement === action, + }, { + editorOverview: true, + emptyActions: true, + treeInstructions: false, + focusRestored: true, + }); + }); +}); diff --git a/src/vs/sessions/contrib/chat/browser/chatView.ts b/src/vs/sessions/contrib/chat/browser/chatView.ts index 9bb3299e47f260..1acef522305ed4 100644 --- a/src/vs/sessions/contrib/chat/browser/chatView.ts +++ b/src/vs/sessions/contrib/chat/browser/chatView.ts @@ -287,6 +287,10 @@ export class ChatView extends AbstractChatView { override readonly kind: ChatViewKind = 'chat'; + override get activityBarActions() { + return this._chatPills.activityBarActions; + } + override get scrollDownButtonDomNode(): HTMLElement { return this._widget.scrollDownButtonDomNode; } diff --git a/src/vs/sessions/contrib/chat/browser/newChatWidget.ts b/src/vs/sessions/contrib/chat/browser/newChatWidget.ts index 53ef4247eea4c4..a62bd776f537b5 100644 --- a/src/vs/sessions/contrib/chat/browser/newChatWidget.ts +++ b/src/vs/sessions/contrib/chat/browser/newChatWidget.ts @@ -2255,7 +2255,10 @@ export class NewChatWidget extends Disposable { if (!workspace || !this.uriIdentityService.extUri.isEqual(workspace.workspace.folders[0]?.root, folderUri) || (environment.kind === 'container') !== preferDevContainer) { const selected = getDefaultSessionCreationEnvironment(this._environments.get(), folderUri, this._workspacePicker.selectedResolved?.providerId, preferDevContainer); - this._pickedEnvironment.set(selected, undefined); + // Keep automatic defaults reactive while refreshing explicit selections. + if (this._pickedEnvironment.get() || selected?.id !== environment.id) { + this._pickedEnvironment.set(selected, undefined); + } } } if (!this._isCurrentWorkspaceSelection(folderUri)) { diff --git a/src/vs/sessions/contrib/chat/browser/sessionChatInputToolbar.ts b/src/vs/sessions/contrib/chat/browser/sessionChatInputToolbar.ts index 318616f0483c16..d77502bce97160 100644 --- a/src/vs/sessions/contrib/chat/browser/sessionChatInputToolbar.ts +++ b/src/vs/sessions/contrib/chat/browser/sessionChatInputToolbar.ts @@ -12,9 +12,10 @@ import { Event } from '../../../../base/common/event.js'; import { structuralEquals } from '../../../../base/common/equals.js'; import { toErrorMessage } from '../../../../base/common/errorMessage.js'; import { status } from '../../../../base/browser/ui/aria/aria.js'; -import { Disposable, MutableDisposable } from '../../../../base/common/lifecycle.js'; +import { Disposable, DisposableStore, MutableDisposable, toDisposable } from '../../../../base/common/lifecycle.js'; +import { CancellationTokenSource } from '../../../../base/common/cancellation.js'; import { Schemas } from '../../../../base/common/network.js'; -import { autorun, constObservable, derived, derivedOpts, IObservable, IReader, observableFromEvent, observableValue } from '../../../../base/common/observable.js'; +import { autorun, constObservable, derived, derivedOpts, IObservable, IReader, observableFromEvent, observableSignalFromEvent, observableValue } from '../../../../base/common/observable.js'; import { isEqual } from '../../../../base/common/resources.js'; import { ThemeIcon } from '../../../../base/common/themables.js'; import { URI } from '../../../../base/common/uri.js'; @@ -23,6 +24,14 @@ import { ICommandService } from '../../../../platform/commands/common/commands.j import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { INotificationService } from '../../../../platform/notification/common/notification.js'; +import { IQuickInputService } from '../../../../platform/quickinput/common/quickInput.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { ILogService } from '../../../../platform/log/common/log.js'; +import { IExtensionService } from '../../../../workbench/services/extensions/common/extensions.js'; +import { IExternalUriOpenerService } from '../../../../workbench/contrib/externalUriOpener/common/externalUriOpenerService.js'; +import { externalUriOpenersSettingId } from '../../../../workbench/contrib/externalUriOpener/common/configuration.js'; +import { observableConfigValue } from '../../../../platform/observable/common/platformObservableUtils.js'; +import { SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING } from '../../../common/sessionConfig.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; import { AgentHostAutoAttachPullRequestsConfigKey } from '../../../../platform/agentHost/common/agentHostSchema.js'; import { ChatInputPills, StandardChatInputPillSources, createChatInputPillSource, IChatInputPillSource } from '../../../../workbench/contrib/chat/browser/chatInputPills.js'; @@ -31,7 +40,7 @@ import { diffStatsEqual, EMPTY_DIFF_STATS, IDiffStats } from '../../../../workbe import { SessionArtifacts, sessionArtifactLocation } from './sessionArtifacts.js'; import { SessionCustomizations } from '../../../../workbench/contrib/chat/browser/sessionCustomizations.js'; import { localize } from '../../../../nls.js'; -import { CHAT_INPUT_PILLS_ROW_HEIGHT, chatPillCopyUrlHoverLabel, chatPillRemoveArtifactHoverLabel, getChatPillResourceLocation, getChatReferencePillPresentation, type ChatPillsCompactMode, type IChatPillEntry, type IChatPillSection, withChatPillHoverLabel } from '../../../../workbench/browser/chatPills.js'; +import { CHAT_INPUT_PILLS_ROW_HEIGHT, chatPillCopyUrlHoverLabel, chatPillRemoveArtifactHoverLabel, getChatPillEntries, getChatPillResourceLocation, getChatReferencePillPresentation, type ChatPillsCompactMode, type IChatPillEntry, type IChatPillSection, withChatPillHoverLabel } from '../../../../workbench/browser/chatPills.js'; import { computeAggregateIssueIcon, computeIssueIcon, getPullRequestStatusFromIcon, GitHubCIOverallStatus, GitHubIssueState, OPEN_ISSUE_ACTION_ID, OPEN_PULL_REQUEST_ACTION_ID, OPEN_PULL_REQUEST_CHANGES_ACTION_ID, type IGitHubIssue } from '../../github/common/types.js'; import { getSessionGitHubReferences } from '../../github/common/sessionGitHubReferences.js'; import { IGitHubService } from '../../github/browser/githubService.js'; @@ -65,10 +74,22 @@ const openChangesHoverLabel = localize('sessionChatPills.openChanges', "Open Cha const copyFeedbackDuration = 1200; /** Fake artifacts for the pill debug overlay. */ -function buildDebugArtifactSections(debugData: ISessionChatPillsDebugData): readonly IChatPillSection[] { +function buildDebugArtifactSections(debugData: ISessionChatPillsDebugData, copy: (value: string) => void): readonly IChatPillSection[] { const entries = debugData.markdownFiles.map(name => { const resource = URI.from({ scheme: 'session-chat-pills-debug', path: `/${name}` }); - return { id: name, label: name, resource, ...sessionArtifactLocation(resource.path, name), open: () => { } }; + return { + id: name, + label: name, + resource, + toolbarActions: [toAction({ + id: `sessions.debug.chatPills.copyArtifactPath.${name}`, + label: localize('sessions.debug.chatPills.copyArtifactPath', "Copy Path"), + class: ThemeIcon.asClassName(Codicon.copy), + run: () => copy(resource.path), + })], + ...sessionArtifactLocation(resource.path, name), + open: () => { }, + }; }); return entries.length ? [{ title: localize('sessionArtifacts.files', "Files"), entries }] : []; } @@ -388,6 +409,7 @@ export class SessionChatInputToolbar extends Disposable { readonly element: HTMLElement; readonly onDidChangeChatPetPlatform: Event<void>; readonly onDidChangeVisibility: Event<boolean>; + readonly activityBarActions: IObservable<readonly IAction[]>; private readonly _inputPills: ChatInputPills; private _inputElement: HTMLElement | undefined; @@ -403,6 +425,8 @@ export class SessionChatInputToolbar extends Disposable { private readonly _issueHoverCache = this._register(new ChatPillHoverCache()); private readonly _pullRequestCopyActions = this._register(new CopyFeedbackActionCache()); private readonly _issueCopyActions = this._register(new CopyFeedbackActionCache()); + private readonly _activityBarPicker = this._register(new MutableDisposable<DisposableStore>()); + private readonly _activityBarOpenerCheck = this._register(new MutableDisposable()); /** The session that owns the reflected chat, from an explicit override or resolved from the chat. */ private readonly _session: IObservable<IActiveSession | undefined> = derived(reader => { @@ -451,6 +475,11 @@ export class SessionChatInputToolbar extends Disposable { @IInstantiationService instantiationService: IInstantiationService, @IChatEntitlementService entitlementService: IChatEntitlementService, @ITelemetryService telemetryService: ITelemetryService, + @IQuickInputService quickInputService: IQuickInputService, + @IExternalUriOpenerService externalUriOpenerService: IExternalUriOpenerService, + @IExtensionService extensionService: IExtensionService, + @IConfigurationService configurationService: IConfigurationService, + @ILogService logService: ILogService, ) { super(); @@ -483,7 +512,7 @@ export class SessionChatInputToolbar extends Disposable { const sessionArtifacts = this._register(instantiationService.createInstance(SessionArtifacts, this._session, this._chat, this._browsers.urls, gitHubReferences, detailsHost)); this._artifactSections = derived(this, reader => { const debugData = this._debugData.read(reader); - return debugData ? buildDebugArtifactSections(debugData) : sessionArtifacts.sections.read(reader); + return debugData ? buildDebugArtifactSections(debugData, value => clipboardService.writeText(value)) : sessionArtifacts.sections.read(reader); }); this._referenceSections = sessionArtifacts.referenceSections; const sessionCustomizations = this._register(instantiationService.createInstance(SessionCustomizations, @@ -568,6 +597,113 @@ export class SessionChatInputToolbar extends Disposable { .map(section => ({ ...section, entries: section.entries.filter(entry => !sessionArtifacts.hasIntegration(entry.id, reader)) }))); const plainIssueSections = derived(this, reader => issueSections.read(reader) .map(section => ({ ...section, entries: section.entries.filter(entry => !sessionArtifacts.hasIntegration(entry.id, reader)) }))); + const pullRequestData = createSessionPullRequestPillData(plainPullRequestSections, visibility.pullRequests, pullRequestPresentation.icon); + const activityBarPullRequests = createSessionPullRequestPillData(pullRequestSections, visibility.pullRequests, pullRequestPresentation.icon); + const gitHubActionsEnabled = observableConfigValue(SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, false, configurationService); + const openerChanges = observableSignalFromEvent(this, Event.any<unknown>( + extensionService.onDidChangeExtensions, + Event.filter(configurationService.onDidChangeConfiguration, event => event.affectsConfiguration(externalUriOpenersSettingId)), + )); + const activityBarOpeners = derived(this, reader => { + openerChanges.read(reader); + const supported = observableValue<ReadonlySet<string>>(this, new Set()); + if (!gitHubActionsEnabled.read(reader) || !pillsVisible.read(reader) || this._debugData.read(reader) || entitlementService.sentimentObs.read(reader).hidden) { + return supported; + } + const refs = [...pullRequestRefs.read(reader), ...issueRefs.read(reader)]; + const cancellation = new CancellationTokenSource(); + const check = toDisposable(() => cancellation.dispose(true)); + this._activityBarOpenerCheck.value = check; + reader.store.add(toDisposable(() => { + if (this._activityBarOpenerCheck.value === check) { + this._activityBarOpenerCheck.clear(); + } + })); + void Promise.all(refs.map(async ref => { + try { + const opener = await externalUriOpenerService.getOpener(ref.uri, { sourceUri: ref.uri }, cancellation.token); + return opener ? ref.recordedReferenceId ?? ref.uri.toString() : undefined; + } catch (error) { + if (!cancellation.token.isCancellationRequested) { + logService.error('[SessionChatInputToolbar] Could not resolve GitHub activity bar opener', error); + } + return undefined; + } + })).then(ids => { + if (!cancellation.token.isCancellationRequested) { + supported.set(new Set(coalesce(ids)), undefined); + } + }); + return supported; + }); + this.activityBarActions = derived(this, reader => { + if (!gitHubActionsEnabled.read(reader) || !pillsVisible.read(reader) || this._debugData.read(reader) || entitlementService.sentimentObs.read(reader).hidden) { + return []; + } + const chat = this._chat.read(reader); + const session = this._session.read(reader); + const createAction = (id: string, title: string, sections: IObservable<readonly IChatPillSection[]>, icon: ThemeIcon): IAction[] => { + const supported = activityBarOpeners.read(reader).read(reader); + const entries = getChatPillEntries(sections.read(reader)).filter(entry => supported.has(entry.id)); + if (!entries.length) { + return []; + } + const label = entries.length === 1 + ? entries[0].ariaLabel ?? entries[0].label + : localize('sessionChatPills.activityBar.openEntries', "{0} ({1})", title, entries.length); + return [toAction({ + id, label, class: ThemeIcon.asClassName(icon), + run: async () => { + if (this._store.isDisposed || !gitHubActionsEnabled.read(undefined) || !pillsVisible.read(undefined) || entitlementService.sentimentObs.read(undefined).hidden || this._chat.read(undefined) !== chat || this._session.read(undefined) !== session) { + return; + } + this._activityBarPicker.clear(); + const currentEntries = getChatPillEntries(sections.read(undefined)).filter(entry => activityBarOpeners.read(undefined).read(undefined).has(entry.id)); + if (currentEntries.length <= 1) { + currentEntries[0]?.open(); + return; + } + const store = new DisposableStore(); + this._activityBarPicker.value = store; + const cancellation = new CancellationTokenSource(); + store.add(toDisposable(() => cancellation.dispose(true))); + try { + store.add(autorun(reader => { + if (!gitHubActionsEnabled.read(reader) || !pillsVisible.read(reader) || this._debugData.read(reader) || entitlementService.sentimentObs.read(reader).hidden || this._chat.read(reader) !== chat || this._session.read(reader) !== session) { + cancellation.cancel(); + return; + } + const supported = activityBarOpeners.read(reader).read(reader); + const entries = getChatPillEntries(sections.read(reader)).filter(entry => supported.has(entry.id)); + if (entries.length !== currentEntries.length || entries.some((entry, index) => entry.id !== currentEntries[index].id)) { + cancellation.cancel(); + } + })); + const selected = await quickInputService.pick(currentEntries.map(entry => ({ + label: `${entry.icon ? `$(${entry.icon.id}) ` : ''}${entry.badge ? `${entry.badge} ` : ''}${entry.label}`, + description: entry.ariaDescription, + entry, + })), { title, matchOnDescription: true }, cancellation.token); + if (selected && !cancellation.token.isCancellationRequested) { + getChatPillEntries(sections.read(undefined)).find(entry => entry.id === selected.entry.id && activityBarOpeners.read(undefined).read(undefined).has(entry.id))?.open(); + } + } catch (error) { + if (!cancellation.token.isCancellationRequested) { + notificationService.error(error); + } + } finally { + if (this._activityBarPicker.value === store) { + this._activityBarPicker.clear(); + } + } + }, + })]; + }; + return [ + ...createAction(OPEN_PULL_REQUEST_ACTION_ID, localize('sessionChatPills.activityBar.openPullRequest', "Open Pull Request"), activityBarPullRequests.sections, activityBarPullRequests.icon.read(reader)), + ...createAction(OPEN_ISSUE_ACTION_ID, localize('sessionChatPills.activityBar.openIssue', "Open Issue"), issueSections, issueIcon.read(reader)), + ]; + }); const integratedSources = derived(this, reader => { if (this._debugData.read(reader) || entitlementService.sentimentObs.read(reader).hidden) { return []; @@ -623,7 +759,7 @@ export class SessionChatInputToolbar extends Disposable { }); }, }, - pullRequests: createSessionPullRequestPillData(plainPullRequestSections, visibility.pullRequests, pullRequestPresentation.icon), + pullRequests: pullRequestData, issues: { sections: plainIssueSections, icon: issueIcon, @@ -636,7 +772,11 @@ export class SessionChatInputToolbar extends Disposable { browsers: { sections: this._browsers.sections }, subagents: this._backgroundActivities, backgroundShells, - }, SESSION_CHAT_PILL_KINDS)); + }, SESSION_CHAT_PILL_KINDS, derived(this, reader => { + const session = this._session.read(reader); + const chat = this._chat.read(reader); + return session && chat ? JSON.stringify([session.providerId, session.resource.toString(), chat.resource.toString()]) : undefined; + }))); const actionRunner = this._register(new SessionActivatingActionRunner(() => this._session.get(), this._sessionsService)); this._inputPills = this._register(instantiationService.createInstance(ChatInputPills, undefined, { debugName: 'SessionChatInputToolbar.content', diff --git a/src/vs/sessions/contrib/chat/browser/sessionWorkspacePicker.ts b/src/vs/sessions/contrib/chat/browser/sessionWorkspacePicker.ts index 27889b157a9ce0..89758fa5596829 100644 --- a/src/vs/sessions/contrib/chat/browser/sessionWorkspacePicker.ts +++ b/src/vs/sessions/contrib/chat/browser/sessionWorkspacePicker.ts @@ -24,7 +24,6 @@ import { ActionListItemKind, IActionListDelegate, IActionListItem, IActionListOp import { ITabDescriptor, TabbedActionListWidget } from '../../../../platform/actionWidget/browser/tabbedActionListWidget.js'; import { IMenuService, MenuItemAction } from '../../../../platform/actions/common/actions.js'; import { IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostsEnabledSettingId } from '../../../../platform/agentHost/common/remoteAgentHostService.js'; -import { TUNNEL_ADDRESS_PREFIX } from '../../../../platform/agentHost/common/tunnelAgentHost.js'; import { DevContainerSample, devContainerSamples, devContainerSampleUri, findDevContainerSample, getDevContainerSampleUrl } from '../../../../platform/agentHost/common/devContainerSamples.js'; import { ICommandService } from '../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; @@ -1981,7 +1980,6 @@ export class WorkspacePicker extends Disposable { if (includeRemoteProviders) { for (const provider of remoteProviders) { const status = provider.connectionStatus!.get(); - const isTunnel = provider.remoteAddress?.startsWith(TUNNEL_ADDRESS_PREFIX) === true; const statusDescription = getRemoteHostStatusDescription(provider, status); const action = toAction({ id: `workspacePicker.remote.${provider.id}`, @@ -1997,7 +1995,7 @@ export class WorkspacePicker extends Disposable { extended.ariaLabel = localize('workspacePicker.remoteAriaLabel', "{0}, {1}", provider.label, statusDescription); extended.icon = RemoteAgentHostConnectionStatus.isIncompatible(status) ? Codicon.warning - : (isTunnel ? Codicon.cloud : Codicon.remote); + : Codicon.remote; extended.hoverContent = getStatusHover(status, provider.remoteAddress); if (provider.remoteAddress && provider.canRemove !== false) { extended.onRemove = async () => { diff --git a/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts b/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts index 67afce44cb2186..08bbc04851963f 100644 --- a/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts +++ b/src/vs/sessions/contrib/chat/browser/sessionsChatAccessibilityHelp.ts @@ -247,8 +247,8 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.contextReferences', "Type # in the chat input to attach context. Use #file to reference a file or folder, or #session to reference another agent session. Referencing a session together with the /troubleshoot command analyzes that session's logs instead of the current one. Accept a suggestion with Tab or Enter. Openable references appear as buttons above the input; activate one to open it, or use its Remove button to detach it.")); content.push(localize('sessionsChat.pastedText', "Long pasted text is stored as an attached text item and replaced in the input with a numbered inline reference.")); content.push(localize('sessionsChat.pasteAsText', "To paste the clipboard as plain text, without converting it to Markdown or storing it as an attachment, invoke Paste as Text{0}.", '<keybinding:editor.action.pasteAsText>')); - content.push(localize('sessionsChat.backgroundActivities', "Press Shift+Tab from the chat input to reach metadata and status pills above it, use the left and right arrows to move between pills, and press Enter or Space to activate one. Live browsers appear in their own pill, and the chat's subagents appear in another. A pill with more than one entry opens a picker. Subagents are grouped under Subagents: In Progress and Subagents: Completed. In Progress includes subagents waiting for input; Completed includes failed subagents. Use the up and down arrows to move between entries. When an entry has details, Tab moves through its row actions and detail links; Shift+Tab returns to the row action, and the up and down arrows continue moving between entries. Press Enter to open an entry, or Escape to dismiss the picker and return focus to the pill.")); - content.push(localize('sessionsChat.canvases', "Available canvases appear in their own pill. A single canvas shows its title and opens directly; multiple canvases show a count and open a picker. Activating a canvas focuses its open tab or reopens it if it was closed. To close a canvas rather than only its tab, use Close Canvas: the X on the pill of a single canvas or on a picker row, or the pill's context menu. Closing ends the canvas and notifies the extension that provides it.")); + content.push(localize('sessionsChat.backgroundActivities', "Press Shift+Tab from the chat input to reach metadata and status pills above it, use the left and right arrows to move between pills, and press Enter or Space to activate one. Live browsers appear in their own pill, and the chat's subagents appear in another. An aggregated pill opens a picker. Use Pin on a picker row to keep that entry as its own pill; it is removed from the picker, and a sole remaining entry is shown directly unless it requires a details picker. A pinned pill shows a trailing Unpin button that pointer users can activate to unpin it. Keyboard and screen reader users can open the pinned pill's context menu and choose Unpin. Pin choices are remembered for each chat. Subagents are grouped under Subagents: In Progress and Subagents: Completed. In Progress includes subagents waiting for input; Completed includes failed subagents. Use the up and down arrows to move between entries. When an entry has details, Tab moves through its row actions and detail links; Shift+Tab returns to the row action, and the up and down arrows continue moving between entries. Press Enter to open an entry, or Escape to dismiss the picker and return focus to the pill.")); + content.push(localize('sessionsChat.canvases', "Available canvases appear in their own pill. A single canvas shows its title and opens directly; multiple canvases show a count and open a picker. Activating a canvas focuses its open tab or reopens it if it was closed. To close a canvas rather than only its tab, use Close Canvas: the X on a canvas pill or picker row, or the pill's context menu. Closing ends the canvas and notifies the extension that provides it.")); content.push(getBackgroundShellsPillAccessibilityHelp()); const chatTabsMode = configurationService.getValue<SessionsChatTabsMode>(SESSIONS_CHAT_TABS_SETTING) ?? SESSIONS_CHAT_TABS_DEFAULT; content.push(chatTabsMode === SessionsChatTabsMode.Single @@ -306,7 +306,7 @@ export class SessionsChatAccessibilityHelp implements IAccessibleViewImplementat content.push(localize('sessionsChat.sessionsView', "Focus the Chat Sessions view{0}.", '<keybinding:workbench.action.chat.focusAgentSessionsViewer>')); const agentLayoutService = accessor.get(IAgentWorkbenchLayoutService); if (agentLayoutService.agentWorkbenchLayout === AgentWorkbenchLayout.Desktop && !isPhoneLayout(agentLayoutService) && configurationService.getValue<boolean>(SESSION_ACTIVITY_BAR_SETTING)) { - content.push(localize('sessionsChat.sessionActivityBar', "The Session Activity Bar beside the active chat opens the Changes, Files, Browser, and Canvas tabs. Its layout actions, Toggle Side Panel above the tabs and Toggle Panel below them, replace the title bar buttons; turn them off with Show Layout Actions in its context menu. Press Tab past the chat input's controls to reach it, use the Up and Down Arrow keys to move between its entries, and press Enter or Space to open one. The Changes entry's label includes the active chat's number of changed files and lines added and removed, and New changes when it has changes you have not yet seen in the Changes tab. Only canvases belonging to the active chat are shown. A single canvas opens directly and is labeled with its title. With multiple canvases, Canvas opens a submenu: press Enter, Space, or Left Arrow to open it, and Right Arrow or Escape to close it. Open the context menu{1} on an entry to hide that entry or the whole activity bar. Toggle the activity bar from the chat background's context menu, View > Appearance > Session Activity Bar, or the {0} setting.", SESSION_ACTIVITY_BAR_SETTING, '<keybinding:editor.action.showContextMenu>')); + content.push(localize('sessionsChat.sessionActivityBar', "The Session Activity Bar beside the active chat opens the Changes, Files, Browser, and Canvas tabs. Pull request and issue actions are off by default. Enable Show Pull Request and Issue Actions in the activity bar's context menu to show them. Open Pull Request and Open Issue are also available for the active chat's pull requests and issues when a contributed opener is available for their links. A single supported reference opens directly; multiple supported references open a picker. Use the Up and Down Arrow keys and Enter to choose a reference, or Escape to cancel. Its layout actions, Toggle Side Panel above the tabs and Toggle Panel below them, replace the title bar buttons; turn them off with Show Layout Actions in its context menu. Press Tab past the chat input's controls to reach it, use the Up and Down Arrow keys to move between its entries, and press Enter or Space to open one. The Changes entry's label includes the active chat's number of changed files and lines added and removed, and New changes when it has changes you have not yet seen in the Changes tab. Only canvases belonging to the active chat are shown. A single canvas opens directly and is labeled with its title. With multiple canvases, Canvas opens a submenu: press Enter, Space, or Left Arrow to open it, and Right Arrow or Escape to close it. Open the context menu{1} on an entry to hide that entry or the whole activity bar. Toggle the activity bar from the chat background's context menu, View > Appearance > Session Activity Bar, or the {0} setting.", SESSION_ACTIVITY_BAR_SETTING, '<keybinding:editor.action.showContextMenu>')); } if (!isPhoneLayout(accessor.get(IWorkbenchLayoutService))) { content.push(localize('sessionsChat.emptyEditorAddTab', "When the side panel's editor has no open tabs, it shows Add Tab at the top and lists the Add Tab actions, such as Changes, Files, Browser, and Search, with their keybindings. Press Tab to reach the list, use the Up and Down arrow keys to move between actions, and press Enter or Space to open one. For an action with a submenu, such as Canvas, press Enter, Space, or the Right arrow key to open the submenu, the Up and Down arrow keys to choose an item, and the Left arrow key or Escape to return to the list.")); diff --git a/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts b/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts index ef8d3a1eee416d..46374a36e61055 100644 --- a/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts +++ b/src/vs/sessions/contrib/chat/browser/voiceBridge.contribution.ts @@ -20,6 +20,7 @@ import { SessionStatus } from '../../../services/sessions/common/session.js'; import { IActiveSession, inheritableSessionTarget, ISendRequestOptions, ISessionsManagementService } from '../../../services/sessions/common/sessionsManagement.js'; import { INewChatVoiceComposer, INewChatVoiceTargetService, NEW_CHAT_VOICE_SENTINEL } from './newChatVoice.js'; import { INewSessionComposerService } from './newSessionComposerService.js'; +import { ChatRequestQueueKind } from '../../../../workbench/contrib/chat/common/chatService/chatService.js'; export async function prepareNewVoiceSession( text: string, @@ -133,17 +134,21 @@ export class SessionsVoiceBridgeContribution extends Disposable implements IWork const widget = expectedSessionId ? this.chatWidgetService.getWidgetBySessionResource(URI.parse(expectedSessionId)) : this._activeSessionWidget() ?? this.chatWidgetService.lastFocusedWidget; - if (expectedSessionId && widget?.viewModel?.sessionResource.toString() !== expectedSessionId) { + const viewModel = widget?.viewModel; + if (expectedSessionId && viewModel?.sessionResource.toString() !== expectedSessionId) { return false; } - if (widget?.viewModel) { - if (widget.viewModel.editing) { + if (widget && viewModel) { + if (viewModel.editing) { // Let the user review edited input before submitting. widget.input.setValue(text, false); return false; } else { // Preserve any text the user already typed in the input. - return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { preserveFocus: true }); + return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { + preserveFocus: true, + ...(viewModel.model?.requestInProgress?.get() === true ? { queue: ChatRequestQueueKind.Steering } : {}), + }); } } return false; diff --git a/src/vs/sessions/contrib/chat/test/browser/newChatWidget.test.ts b/src/vs/sessions/contrib/chat/test/browser/newChatWidget.test.ts index 327ceecd73fe4e..c0d3136ee9ecc8 100644 --- a/src/vs/sessions/contrib/chat/test/browser/newChatWidget.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/newChatWidget.test.ts @@ -55,7 +55,7 @@ import { SessionComparisonModelSelection } from '../../browser/sessionComparison import { ILanguageModelChatMetadata, ILanguageModelChatMetadataAndIdentifier } from '../../../../../workbench/contrib/chat/common/languageModels.js'; import { SessionView } from '../../../../browser/parts/sessionView.js'; import { createSessionViewTestServices, createTestActiveSession } from '../../../../test/browser/sessionViewTestUtils.js'; -import { ISessionCreationEnvironment } from '../../browser/sessionEnvironmentPicker.js'; +import { getDefaultSessionCreationEnvironment, ISessionCreationEnvironment } from '../../browser/sessionEnvironmentPicker.js'; import { IChatService } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; /** The part of the active session `_recreateOnProviderChange` actually reads. */ @@ -568,6 +568,62 @@ suite('NewChatWidget', () => { const container: ISessionCreationEnvironment = { ...local, id: 'container:local', kind: 'container' }; const folder = URI.file('/project'); + test('automatic workspace restoration does not pin Cloud before This Computer registers', async () => { + const environments = observableValue<readonly ISessionCreationEnvironment[]>('environments', [cloud]); + const picked = observableValue<ISessionCreationEnvironment | undefined>('pickedEnvironment', undefined); + const environment = derived(reader => picked.read(reader) + ?? getDefaultSessionCreationEnvironment(environments.read(reader), folder, 'cloud')); + const widget = Object.assign(Object.create(NewChatWidget.prototype), { + _environment: environment, + _environments: environments, + _pickedEnvironment: picked, + _environmentPickerBeforeWorkspace: constObservable(false), + _workspaceOptOutEnabled: constObservable(false), + uriIdentityService: { extUri }, + _workspacePicker: { + selectedResolved: { providerId: 'cloud' }, + getEnvironmentWorkspace: () => undefined, + }, + _isCurrentWorkspaceSelection: () => false, + _onWorkspaceSelected: async () => { }, + _newChatInput: { focus: () => { } }, + }); + const initialEnvironment = environment.get()?.id; + + await handleWorkspaceSelection.call(widget, folder); + environments.set([cloud, local], undefined); + + assert.deepStrictEqual({ initialEnvironment, selected: environment.get()?.id, picked: picked.get()?.id }, { + initialEnvironment: 'cloud', + selected: 'local', + picked: undefined, + }); + }); + + test('refreshes an explicit environment selection when its metadata changes without changing its id', async () => { + const updatedCloud: ISessionCreationEnvironment = { ...cloud, label: 'Updated Cloud', providerIds: ['new-cloud-provider'] }; + const picked = observableValue<ISessionCreationEnvironment | undefined>('pickedEnvironment', cloud); + const widget = Object.assign(Object.create(NewChatWidget.prototype), { + _environment: constObservable(cloud), + _environments: constObservable([updatedCloud]), + _pickedEnvironment: picked, + _environmentPickerBeforeWorkspace: constObservable(false), + _workspaceOptOutEnabled: constObservable(false), + uriIdentityService: { extUri }, + _workspacePicker: { + selectedResolved: { providerId: 'new-cloud-provider' }, + getEnvironmentWorkspace: () => undefined, + }, + _isCurrentWorkspaceSelection: () => false, + _onWorkspaceSelected: async () => { }, + _newChatInput: { focus: () => { } }, + }); + + await handleWorkspaceSelection.call(widget, folder); + + assert.strictEqual(picked.get(), updatedCloud); + }); + function createHarness(compatible: boolean, onSelect: () => Promise<void> = async () => { }) { const calls: string[] = []; let selectedFolder: URI | undefined = folder; diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionActivityBar.fixture.ts b/src/vs/sessions/contrib/chat/test/browser/sessionActivityBar.fixture.ts index e550bd06d2fabf..5a74bda13e4b7b 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionActivityBar.fixture.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionActivityBar.fixture.ts @@ -5,6 +5,8 @@ import { $, append } from '../../../../../base/browser/dom.js'; import { Event } from '../../../../../base/common/event.js'; +import { toAction } from '../../../../../base/common/actions.js'; +import { ThemeIcon } from '../../../../../base/common/themables.js'; import { autorun, constObservable } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; import { mock } from '../../../../../base/test/common/mock.js'; @@ -29,6 +31,7 @@ import { IconBadge } from '../../../../../workbench/services/activity/common/act import { Codicon } from '../../../../../base/common/codicons.js'; import { FixtureContextViewService, FixtureKeybindingService, FixtureMenuService, fixtureBrowser, fixtureCanvas, fixtureChanges, fixtureFiles, fixtureTerminal, fixtureTogglePanel, fixtureToggleSidePanel, IFixtureEntry } from '../../../../test/browser/addTabFixtureUtils.js'; import { SessionActivityBarGroup } from '../../../../browser/menus.js'; +import { OPEN_ISSUE_ACTION_ID, OPEN_PULL_REQUEST_ACTION_ID } from '../../../github/common/types.js'; import { ExternalSessionBanner } from '../../browser/externalSessionBanner.js'; import '../../browser/media/chatView.css'; import '../../../../browser/parts/media/chatCompositeBar.css'; @@ -53,6 +56,7 @@ interface IFixtureOptions { readonly dragBy?: number; /** Badges the Changes entry, as new changes do. */ readonly newChanges?: boolean; + readonly githubReferenceCount?: number; } // The tab entries share the side panel toggle's group; the terminal shares the panel toggle's. @@ -90,6 +94,8 @@ export default defineThemedFixtureGroup({ path: 'sessions/sessionActivityBar/' } AtBottom: activityBarFixture({ dragBy: 2000 }), SubmenuOpen: activityBarFixture({ openSubmenu: true }, highContrastThemes), NewChanges: activityBarFixture({ newChanges: true }, highContrastThemes), + GitHubReferences: activityBarFixture({ githubReferenceCount: 1 }, highContrastThemes), + MultipleGitHubReferences: activityBarFixture({ githubReferenceCount: 2 }, highContrastThemes), }); const HEIGHT = 500; @@ -126,7 +132,11 @@ async function renderActivityBar(context: ComponentFixtureContext, options: IFix const { container, disposableStore, theme } = context; const { renderChatWidget } = await import('../../../../../workbench/test/browser/componentFixtures/chat/chatWidget.fixture.js'); const width = options.width ?? 640; - const entries = options.entries ?? workspaceChatEntries; + const githubEntries: readonly IFixtureEntry[] = options.githubReferenceCount ? [ + { id: OPEN_PULL_REQUEST_ACTION_ID, title: 'Open Pull Request', icon: Codicon.gitPullRequest, group: SessionActivityBarGroup.GitHub }, + { id: OPEN_ISSUE_ACTION_ID, title: 'Open Issue', icon: Codicon.issues, group: SessionActivityBarGroup.GitHub }, + ] : []; + const entries = [...(options.entries ?? workspaceChatEntries), ...githubEntries]; container.style.width = `${width}px`; container.style.height = `${HEIGHT}px`; container.classList.add('agent-sessions-workbench'); @@ -180,6 +190,12 @@ async function renderActivityBar(context: ComponentFixtureContext, options: IFix const areaHeight = HEIGHT - HEADER_HEIGHT; const activityBar = disposableStore.add(instantiationService.createInstance(ChatViewSessionActivityBar, chatGroup)); + activityBar.setChatActions(constObservable(githubEntries.map(entry => toAction({ + id: entry.id, + label: options.githubReferenceCount === 1 ? `${entry.title} #42: Improve the activity bar` : `${entry.title} (${options.githubReferenceCount})`, + class: ThemeIcon.asClassName(entry.icon), + run: () => { }, + })))); activityBar.layout(HEADER_HEIGHT, areaHeight); const reservedWidth = activityBar.reservedWidth.get(); diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionChatInputToolbar.test.ts b/src/vs/sessions/contrib/chat/test/browser/sessionChatInputToolbar.test.ts index fea9223e2eba1f..75db7891bf5707 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionChatInputToolbar.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionChatInputToolbar.test.ts @@ -11,7 +11,7 @@ import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Codicon } from '../../../../../base/common/codicons.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { ImmortalReference, toDisposable } from '../../../../../base/common/lifecycle.js'; -import { constObservable, derived, observableValue } from '../../../../../base/common/observable.js'; +import { autorun, constObservable, derived, observableValue } from '../../../../../base/common/observable.js'; import { SubmenuAction, type IAction } from '../../../../../base/common/actions.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { URI } from '../../../../../base/common/uri.js'; @@ -26,8 +26,11 @@ import { ICommandService } from '../../../../../platform/commands/common/command import { IConfigurationChangeEvent, IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; +import { ILogService } from '../../../../../platform/log/common/log.js'; import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; import { INotificationService } from '../../../../../platform/notification/common/notification.js'; +import { IQuickInputService, IQuickPickItem } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IChatEntitlementService } from '../../../../../workbench/services/chat/common/chatEntitlementService.js'; import { ArtifactIntegrationsSettingId, ArtifactSnapshot, IArtifactModel } from '../../../../../platform/artifactIntegrations/common/artifactIntegration.js'; import type { IChatPillEntry } from '../../../../../workbench/browser/chatPills.js'; import { IBrowserViewWorkbenchService } from '../../../../../workbench/contrib/browserView/common/browserView.js'; @@ -39,6 +42,10 @@ import { workbenchInstantiationService } from '../../../../../workbench/test/bro import { ChatPillHoverCache } from '../../../../../workbench/browser/chatPillHover.js'; import { ChatDropdownPillActionViewItem } from '../../../../../workbench/browser/chatDropdownPill.js'; import { IWorkbenchGitHubService } from '../../../../../workbench/services/github/common/githubService.js'; +import { IExternalUriOpener, IExternalUriOpenerService } from '../../../../../workbench/contrib/externalUriOpener/common/externalUriOpenerService.js'; +import { IExtensionService } from '../../../../../workbench/services/extensions/common/extensions.js'; +import { externalUriOpenersSettingId } from '../../../../../workbench/contrib/externalUriOpener/common/configuration.js'; +import { SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING } from '../../../../common/sessionConfig.js'; import { IAgentWorkbenchLayoutService } from '../../../../browser/workbench.js'; import { IAgentHostSessionsProvider, LOCAL_AGENT_HOST_PROVIDER_ID, REMOTE_AGENT_HOST_PROVIDER_PREFIX } from '../../../../common/agentHostSessionsProvider.js'; import { ISessionsProvidersService } from '../../../../services/sessions/browser/sessionsProvidersService.js'; @@ -61,9 +68,9 @@ import { buildSessionArtifactSections, type ISessionArtifactActions } from '../. suite('SessionChatInputToolbar', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - function createServices(artifactIntegrationsEnabled = false) { + function createServices(artifactIntegrationsEnabled = false, gitHubActionsEnabled = true) { const instantiationService = workbenchInstantiationService(undefined, store); - const configuration = new TestConfigurationService({ [ArtifactIntegrationsSettingId]: artifactIntegrationsEnabled }); + const configuration = new TestConfigurationService({ [ArtifactIntegrationsSettingId]: artifactIntegrationsEnabled, [SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING]: gitHubActionsEnabled }); store.add(configuration.onDidChangeConfigurationEmitter); instantiationService.stub(IConfigurationService, configuration); instantiationService.stub(IChatService, upcastPartial<IChatService>({ @@ -82,6 +89,9 @@ suite('SessionChatInputToolbar', () => { instantiationService.stub(ISessionChangesStatsCache, upcastPartial<ISessionChangesStatsCache>({ get: () => undefined })); instantiationService.stub(ISessionsProvidersService, upcastPartial<ISessionsProvidersService>({ getProvider: () => undefined })); instantiationService.stub(ISessionsManagementService, upcastPartial<ISessionsManagementService>({})); + instantiationService.stub(IExternalUriOpenerService, upcastPartial<IExternalUriOpenerService>({ + getOpener: async () => upcastPartial<IExternalUriOpener>({ id: 'test-opener' }), + })); instantiationService.stub(ISessionsService, upcastPartial<ISessionsService>({ visibleSessions: constObservable([]), activeSession: constObservable(undefined), @@ -89,6 +99,313 @@ suite('SessionChatInputToolbar', () => { return { instantiationService, visibility, configuration }; } + async function createGitHubActivityBar(kind: SessionArtifactKind.PullRequest | SessionArtifactKind.Issue, providerId: string, getOpener?: IExternalUriOpenerService['getOpener'], gitHubActionsEnabled = true) { + const services = createServices(false, gitHubActionsEnabled); + const { instantiationService } = services; + const extensionsChanged = store.add(new Emitter<{ added: []; removed: [] }>()); + instantiationService.stub(IExtensionService, 'onDidChangeExtensions', extensionsChanged.event); + if (getOpener) { + instantiationService.stub(IExternalUriOpenerService, 'getOpener', getOpener); + } + const sentiment = observableValue('sentiment', { hidden: false }); + instantiationService.stub(IChatEntitlementService, { + sentimentObs: sentiment, + get sentiment() { return sentiment.get(); }, + }); + const main = upcastPartial<IChat>({ resource: URI.parse('chat:main'), title: constObservable('Main'), status: constObservable(SessionStatus.Completed) }); + const peer = upcastPartial<IChat>({ resource: URI.parse('chat:peer'), title: constObservable('Peer'), status: constObservable(SessionStatus.Completed) }); + const artifact = (number: number, chat: IChat, isArtifact = true): ISessionArtifact => ({ + id: `artifact-${number}`, kind, label: `Item ${number}`, isArtifact, isGitHub: true, chat: chat.resource, + link: URI.parse(`https://github.com/owner/repo/${kind === SessionArtifactKind.PullRequest ? 'pull' : 'issues'}/${number}`), + }); + const artifacts = observableValue<readonly ISessionArtifact[]>('artifacts', [artifact(1, main), artifact(2, peer), artifact(3, main, false)]); + const session = upcastPartial<IActiveSession>({ + providerId, sessionId: 'session', resource: URI.parse('session:1'), artifacts, + loading: constObservable(false), capabilities: constObservable({ supportsMultipleChats: true }), + chats: constObservable([main, peer]), mainChat: constObservable(main), workspace: constObservable(undefined), + }); + const pullRequest = observableValue<IGitHubPullRequest | undefined>('pull request', undefined); + instantiationService.stub(IGitHubService, upcastPartial<IGitHubService>({ + createPullRequestModelReference: () => new ImmortalReference(upcastPartial<GitHubPullRequestModel>({ pullRequest })), + createIssueModelReference: () => new ImmortalReference(upcastPartial<GitHubIssueModel>({ + issue: constObservable(undefined), refresh: async () => { }, startPolling: () => toDisposable(() => { }), + })), + })); + const opened: { command: string; number: number | undefined }[] = []; + instantiationService.stub(ISessionsService, 'setActive', (target: IActiveSession) => assert.strictEqual(target, session)); + instantiationService.stub(ICommandService, upcastPartial<ICommandService>({ + executeCommand: async (command, context: { pullRequest?: IGitHubPullRequestRef; issue?: IGitHubIssueRef }) => { + opened.push({ command, number: (context.pullRequest ?? context.issue)?.number }); + return undefined; + }, + })); + const toolbar = store.add(instantiationService.createInstance(SessionChatInputToolbar, false, undefined)); + toolbar.setSession(session, main); + store.add(autorun(reader => toolbar.activityBarActions.read(reader))); + await timeout(0); + return { ...services, toolbar, session, main, peer, artifacts, artifact, opened, sentiment, pullRequest, extensionsChanged }; + } + + for (const kind of [SessionArtifactKind.PullRequest, SessionArtifactKind.Issue] as const) { + test(`activity bar opts ${kind} actions in without changing composer pills`, async () => { + let lookups = 0; + const { toolbar, configuration, opened } = await createGitHubActivityBar(kind, LOCAL_AGENT_HOST_PROVIDER_ID, + async () => { + lookups++; + return upcastPartial<IExternalUriOpener>({ id: 'supported' }); + }, false); + const setEnabled = async (enabled: boolean | undefined) => { + await configuration.setUserConfiguration(SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, enabled); + configuration.onDidChangeConfigurationEmitter.fire(upcastPartial<IConfigurationChangeEvent>({ + affectsConfiguration: key => key === SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, + })); + await timeout(0); + }; + await setEnabled(undefined); + const before = { actions: toolbar.activityBarActions.get().length, lookups, pill: toolbar.element.querySelector('.chat-dropdown-pill-button')?.getAttribute('aria-label') }; + await setEnabled(true); + const enabled = toolbar.activityBarActions.get().length; + const stale = toolbar.activityBarActions.get()[0]; + await setEnabled(false); + await stale.run(); + assert.deepStrictEqual({ + before, enabled, disabled: toolbar.activityBarActions.get().length, + composerUnchanged: toolbar.element.querySelector('.chat-dropdown-pill-button')?.getAttribute('aria-label') === before.pill, opened, + }, { + before: { actions: 0, lookups: 0, pill: `Open ${kind === SessionArtifactKind.PullRequest ? 'Pull Request' : 'Issue'} #1: Item 1` }, + enabled: 1, disabled: 0, composerUnchanged: true, opened: [], + }); + }); + } + + for (const kind of [SessionArtifactKind.PullRequest, SessionArtifactKind.Issue] as const) { + test(`activity bar hides ${kind} without a contributed opener and preserves its composer pill`, async () => { + const { toolbar } = await createGitHubActivityBar(kind, LOCAL_AGENT_HOST_PROVIDER_ID, async () => undefined); + assert.deepStrictEqual({ + activityActions: toolbar.activityBarActions.get().length, + composerLabel: toolbar.element.querySelector('.chat-dropdown-pill-button')?.getAttribute('aria-label'), + }, { + activityActions: 0, + composerLabel: `Open ${kind === SessionArtifactKind.PullRequest ? 'Pull Request' : 'Issue'} #1: Item 1`, + }); + }); + + test(`activity bar filters ${kind} picker entries by opener support`, async () => { + const { instantiationService, toolbar, artifacts, artifact, main, opened } = await createGitHubActivityBar(kind, LOCAL_AGENT_HOST_PROVIDER_ID, + async uri => uri.path.endsWith('/5') ? undefined : upcastPartial<IExternalUriOpener>({ id: 'supported' })); + artifacts.set([...artifacts.get(), artifact(4, main), artifact(5, main)], undefined); + await timeout(0); + let labels: string[] = []; + instantiationService.stub(IQuickInputService, 'pick', async (picks: IQuickPickItem[]) => { + labels = picks.map(pick => pick.label); + return picks[1]; + }); + await toolbar.activityBarActions.get()[0].run(); + assert.deepStrictEqual({ + label: toolbar.activityBarActions.get()[0].label, + numbers: labels.map(label => label.match(/#\d+/)?.[0]), + opened: opened.map(entry => entry.number), + }, { label: `Open ${kind === SessionArtifactKind.PullRequest ? 'Pull Request' : 'Issue'} (2)`, numbers: ['#1', '#4'], opened: [4] }); + }); + } + + test('activity bar refreshes opener support after extension and opener-configuration changes', async () => { + let available = false; + const { toolbar, extensionsChanged, configuration, opened } = await createGitHubActivityBar(SessionArtifactKind.Issue, LOCAL_AGENT_HOST_PROVIDER_ID, + async () => available ? upcastPartial<IExternalUriOpener>({ id: 'supported' }) : undefined); + const absent = toolbar.activityBarActions.get().length; + available = true; + extensionsChanged.fire({ added: [], removed: [] }); + await timeout(0); + const added = toolbar.activityBarActions.get().length; + const stale = toolbar.activityBarActions.get()[0]; + available = false; + configuration.onDidChangeConfigurationEmitter.fire(upcastPartial<IConfigurationChangeEvent>({ + affectsConfiguration: key => key === externalUriOpenersSettingId, + })); + await stale.run(); + await timeout(0); + assert.deepStrictEqual({ absent, added, removed: toolbar.activityBarActions.get().length, opened }, { absent: 0, added: 1, removed: 0, opened: [] }); + }); + + test('activity bar logs opener lookup failures and hides unsupported actions', async () => { + const { toolbar, instantiationService, extensionsChanged } = await createGitHubActivityBar(SessionArtifactKind.Issue, LOCAL_AGENT_HOST_PROVIDER_ID); + const error = new Error('Opener lookup failed'); + const errors: Error[] = []; + instantiationService.stub(ILogService, 'error', (_message: string, reported: Error) => errors.push(reported)); + instantiationService.stub(IExternalUriOpenerService, 'getOpener', async () => { throw error; }); + extensionsChanged.fire({ added: [], removed: [] }); + await timeout(0); + assert.deepStrictEqual({ errors, actions: toolbar.activityBarActions.get().length }, { errors: [error], actions: 0 }); + }); + + test('activity bar cancels pending opener checks on chat switches and disposal', async () => { + const pending: { token: CancellationToken; resolve: (opener: IExternalUriOpener) => void }[] = []; + const { toolbar, session, peer } = await createGitHubActivityBar(SessionArtifactKind.Issue, LOCAL_AGENT_HOST_PROVIDER_ID, + (_uri, _context, token) => new Promise(resolve => pending.push({ token, resolve }))); + const before = toolbar.activityBarActions.get().length; + toolbar.setSession(session, peer); + const old = pending[0]; + old.resolve(upcastPartial<IExternalUriOpener>({ id: 'old-chat' })); + await timeout(0); + const afterSwitch = toolbar.activityBarActions.get().length; + toolbar.dispose(); + pending[1].resolve(upcastPartial<IExternalUriOpener>({ id: 'disposed' })); + await timeout(0); + assert.deepStrictEqual({ before, afterSwitch, cancelled: pending.map(check => check.token.isCancellationRequested) }, { + before: 0, afterSwitch: 0, cancelled: [true, true], + }); + }); + + test('disabling GitHub activity actions cancels pending checks and ignores late results', async () => { + const pending: { token: CancellationToken; resolve: (opener: IExternalUriOpener) => void }[] = []; + const { toolbar, configuration } = await createGitHubActivityBar(SessionArtifactKind.Issue, LOCAL_AGENT_HOST_PROVIDER_ID, + (_uri, _context, token) => new Promise(resolve => pending.push({ token, resolve }))); + await configuration.setUserConfiguration(SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, false); + configuration.onDidChangeConfigurationEmitter.fire(upcastPartial<IConfigurationChangeEvent>({ + affectsConfiguration: key => key === SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, + })); + pending[0].resolve(upcastPartial<IExternalUriOpener>({ id: 'late' })); + await timeout(0); + assert.deepStrictEqual({ + actions: toolbar.activityBarActions.get().length, checks: pending.length, cancelled: pending[0].token.isCancellationRequested, + }, { actions: 0, checks: 1, cancelled: true }); + }); + + test('activity bar follows PR state filtering without changing independent pill visibility', async () => { + const { toolbar, visibility, pullRequest } = await createGitHubActivityBar(SessionArtifactKind.PullRequest, LOCAL_AGENT_HOST_PROVIDER_ID); + const all = toolbar.activityBarActions.get().length; + pullRequest.set(upcastPartial<IGitHubPullRequest>({ state: GitHubPullRequestState.Closed, isDraft: false }), undefined); + visibility.pullRequests.setShowAll(false); + const filtered = toolbar.activityBarActions.get().length; + visibility.pullRequests.setShowAll(true); + const restored = toolbar.activityBarActions.get().length; + visibility.hide(SessionChatPillKind.PullRequests); + const independentlyVisible = toolbar.activityBarActions.get().length; + assert.deepStrictEqual({ all, filtered, restored, independentlyVisible }, { all: 1, filtered: 0, restored: 1, independentlyVisible: 1 }); + }); + + for (const cancelled of [false, true]) { + test(`activity bar reports picker failures only without cancellation (${cancelled})`, async () => { + const { instantiationService, toolbar, artifacts, artifact, main, opened } = await createGitHubActivityBar(SessionArtifactKind.Issue, LOCAL_AGENT_HOST_PROVIDER_ID); + artifacts.set([...artifacts.get(), artifact(4, main)], undefined); + await timeout(0); + const error = new Error('picker unavailable'); + const errors: Error[] = []; + instantiationService.stub(IQuickInputService, 'pick', async () => { + if (cancelled) { + toolbar.dispose(); + } + throw error; + }); + instantiationService.stub(INotificationService, 'error', (reported: Error) => errors.push(reported)); + await toolbar.activityBarActions.get()[0].run(); + assert.deepStrictEqual({ errors, opened }, { errors: cancelled ? [] : [error], opened: [] }); + }); + } + + test('activity bar removes AI-hidden actions and rejects stale invocations after hiding or disposal', async () => { + const { toolbar, sentiment, opened } = await createGitHubActivityBar(SessionArtifactKind.Issue, LOCAL_AGENT_HOST_PROVIDER_ID); + const action = toolbar.activityBarActions.get()[0]; + sentiment.set({ hidden: true }, undefined); + const hidden = toolbar.activityBarActions.get().length; + await action.run(); + sentiment.set({ hidden: false }, undefined); + await timeout(0); + const restored = toolbar.activityBarActions.get().length; + toolbar.dispose(); + await action.run(); + assert.deepStrictEqual({ hidden, restored, opened }, { hidden: 0, restored: 1, opened: [] }); + }); + + for (const providerId of [LOCAL_AGENT_HOST_PROVIDER_ID, `${REMOTE_AGENT_HOST_PROVIDER_PREFIX}test-host`]) { + for (const kind of [SessionArtifactKind.PullRequest, SessionArtifactKind.Issue] as const) { + test(`activity bar opens the single ${kind} of its own chat on ${providerId}`, async () => { + const { toolbar, session, main, peer, artifacts, opened } = await createGitHubActivityBar(kind, providerId); + const first = toolbar.activityBarActions.get()[0]; + await first.run(); + toolbar.setSession(session, peer); + await first.run(); + await timeout(0); + await toolbar.activityBarActions.get()[0].run(); + const peerLabel = toolbar.activityBarActions.get()[0].label; + toolbar.setSession(session, { ...peer, origin: { kind: ChatOriginKind.Tool, parentChat: main.resource } }); + const toolChat = toolbar.activityBarActions.get().length; + toolbar.setSession(session, main); + artifacts.set([], undefined); + + assert.deepStrictEqual({ + opened, peerLabel, toolChat, afterRemoval: toolbar.activityBarActions.get().length, + }, { + opened: [1, 2].map(number => ({ command: kind === SessionArtifactKind.PullRequest ? OPEN_PULL_REQUEST_ACTION_ID : OPEN_ISSUE_ACTION_ID, number })), + peerLabel: `Open ${kind === SessionArtifactKind.PullRequest ? 'Pull Request' : 'Issue'} #2: Item 2`, + toolChat: 0, afterRemoval: 0, + }); + }); + + test(`activity bar picks among current-chat ${kind} entries on ${providerId}`, async () => { + const { instantiationService, toolbar, artifacts, artifact, main, opened } = await createGitHubActivityBar(kind, providerId); + artifacts.set([...artifacts.get(), artifact(4, main)], undefined); + await timeout(0); + let labels: string[] = []; + instantiationService.stub(IQuickInputService, 'pick', async (picks: IQuickPickItem[]) => { + labels = picks.map(pick => pick.label); + return picks[1]; + }); + await toolbar.activityBarActions.get()[0].run(); + + assert.deepStrictEqual({ + label: toolbar.activityBarActions.get()[0].label, + picks: labels.map(label => label.replace(/^\$\([^)]+\) /, '')), + opened, + }, { + label: `Open ${kind === SessionArtifactKind.PullRequest ? 'Pull Request' : 'Issue'} (2)`, + picks: ['#1 Item 1', '#4 Item 4'], + opened: [{ command: kind === SessionArtifactKind.PullRequest ? OPEN_PULL_REQUEST_ACTION_ID : OPEN_ISSUE_ACTION_ID, number: 4 }], + }); + }); + } + } + + for (const transition of ['switch', 'dispose', 'cancel', 'remove', 'remove-one', 'hide', 'opener', 'disable'] as const) { + test(`activity bar does not open a stale issue after picker ${transition}`, async () => { + let openerAvailable = true; + const { instantiationService, toolbar, session, peer, artifacts, artifact, main, opened, configuration, sentiment, extensionsChanged } = await createGitHubActivityBar( + SessionArtifactKind.Issue, LOCAL_AGENT_HOST_PROVIDER_ID, + async () => openerAvailable ? upcastPartial<IExternalUriOpener>({ id: 'test-opener' }) : undefined, + ); + artifacts.set([...artifacts.get(), artifact(4, main)], undefined); + await timeout(0); + let cancelled = false; + instantiationService.stub(IQuickInputService, 'pick', async (picks: IQuickPickItem[], _options: object, token: CancellationToken) => { + if (transition === 'switch') { + toolbar.setSession(session, peer); + } else if (transition === 'dispose') { + toolbar.dispose(); + } else if (transition === 'remove') { + artifacts.set([], undefined); + } else if (transition === 'remove-one') { + artifacts.set(artifacts.get().filter(entry => entry.id !== 'artifact-4'), undefined); + } else if (transition === 'hide') { + sentiment.set({ hidden: true }, undefined); + } else if (transition === 'opener') { + openerAvailable = false; + extensionsChanged.fire({ added: [], removed: [] }); + await timeout(0); + } else if (transition === 'disable') { + await configuration.setUserConfiguration(SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, false); + configuration.onDidChangeConfigurationEmitter.fire(upcastPartial<IConfigurationChangeEvent>({ + affectsConfiguration: key => key === SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, + })); + } + cancelled = token.isCancellationRequested; + return transition === 'cancel' ? undefined : picks[1]; + }); + await toolbar.activityBarActions.get()[0].run(); + assert.deepStrictEqual({ opened, cancelled }, { opened: [], cancelled: transition !== 'cancel' }); + }); + } + test('keeps copied feedback stable across section refreshes', async () => { const { instantiationService } = createServices(); const toolbar = store.add(instantiationService.createInstance(SessionChatInputToolbar, false, undefined)); @@ -1492,10 +1809,10 @@ suite('SessionChatInputToolbar', () => { const dashboardEntry = entries.find(entry => entry.label === dashboard.title); assert.ok(dashboardEntry); dashboardEntry.select(); - const closeActionLabels = entries.flatMap(entry => entry.toolbarActions.map(action => action.label)); - await dashboardEntry.toolbarActions[0]?.run(); + const rowActionLabels = entries.flatMap(entry => entry.toolbarActions.map(action => action.label)); + await dashboardEntry.toolbarActions.find(action => action.label === 'Close Canvas Dashboard')?.run(); - assert.deepStrictEqual({ single, multiple, commandCalls, closeActionLabels, closeCalls }, { + assert.deepStrictEqual({ single, multiple, commandCalls, rowActionLabels, closeCalls }, { single: { label: 'Preview', ariaLabel: 'Open canvas Preview', closeLabel: 'Close Canvas Preview' }, multiple: { label: '2 Canvases', ariaLabel: 'Show 2 canvases', closeLabel: undefined }, commandCalls: [ @@ -1518,7 +1835,7 @@ suite('SessionChatInputToolbar', () => { }, }, ], - closeActionLabels: ['Close Canvas Preview', 'Close Canvas Dashboard'], + rowActionLabels: ['Pin Preview', 'Close Canvas Preview', 'Pin Dashboard', 'Close Canvas Dashboard'], closeCalls: [ { session: session.sessionId, chat: chat.resource.toString(), canvas: preview.resource.toString() }, { session: session.sessionId, chat: chat.resource.toString(), canvas: dashboard.resource.toString() }, @@ -2224,16 +2541,18 @@ suite('SessionChatInputToolbar', () => { instantiationService.stub(ICommandService, upcastPartial<ICommandService>({ executeCommand: async () => { opened++; return undefined; } })); const toolbar = store.add(instantiationService.createInstance(SessionChatInputToolbar, false, undefined)); toolbar.setSession(session, chat); + store.add(autorun(reader => toolbar.activityBarActions.read(reader))); await timeout(0); const labels = () => [...toolbar.element.querySelectorAll('.artifact-integration-pill .chat-pill-label')].map(element => element.textContent); const initial = labels(); const contribution = snapshot.get().contributions[0]; snapshot.set({ ...snapshot.get(), contributions: [{ ...contribution, view: { ...contribution.view, sections: [contribution.view.sections[0]] } }] }, undefined); toolbar.element.querySelector<HTMLElement>('.artifact-integration-pill .chat-dropdown-pill-button')!.click(); + await toolbar.activityBarActions.get()[0].run(); assert.deepStrictEqual({ initial, updated: labels(), integratedPills: toolbar.element.querySelectorAll('.artifact-integration-pill').length, opened, referencesPresent: !!toolbar.element.querySelector('.chat-dropdown-pill-button[aria-label="Show 1 reference"]'), - }, { initial: ['#42', '3/5', '2'], updated: ['#42', '3/5'], integratedPills: 1, opened: 0, referencesPresent: true }); + }, { initial: ['#42', '3/5', '2'], updated: ['#42', '3/5'], integratedPills: 1, opened: 1, referencesPresent: true }); }); for (const providerId of [LOCAL_AGENT_HOST_PROVIDER_ID, `${REMOTE_AGENT_HOST_PROVIDER_PREFIX}custom-host`]) { test(`renders the explicitly selected PR above the main input with automatic association disabled on ${providerId}`, () => { @@ -2295,7 +2614,7 @@ suite('SessionChatInputToolbar', () => { }); }); - test(`PR pills follow chat ownership and react to automatic association on ${providerId}`, () => { + test(`PR pills follow chat ownership and react to automatic association on ${providerId}`, async () => { const { instantiationService } = createServices(); const onDidChangeRootConfig = store.add(new Emitter<void>()); const schema: RootConfigState['schema'] = { @@ -2339,34 +2658,46 @@ suite('SessionChatInputToolbar', () => { capabilities: constObservable({ supportsMultipleChats: true }), }); const toolbar = store.add(instantiationService.createInstance(SessionChatInputToolbar, false, undefined)); - const pill = () => toolbar.element.querySelector('.chat-dropdown-pill-button[aria-label^="Open Pull Request"]')?.getAttribute('aria-label') ?? null; + store.add(autorun(reader => toolbar.activityBarActions.read(reader))); + const activityBarLabels: (string | null)[] = []; + const pill = () => { + activityBarLabels.push(toolbar.activityBarActions.get().find(action => action.id === OPEN_PULL_REQUEST_ACTION_ID)?.label ?? null); + return toolbar.element.querySelector('.chat-dropdown-pill-button[aria-label^="Open Pull Request"]')?.getAttribute('aria-label') ?? null; + }; toolbar.setSession(session, main); + await timeout(0); const restrictedMain = pill(); toolbar.setSession(session, peer); + await timeout(0); const restrictedPeer = pill(); toolbar.setSession(session, main); config = { schema, values: { [AgentHostAutoAttachPullRequestsConfigKey]: true } }; onDidChangeRootConfig.fire(); + await timeout(0); const automaticMain = pill(); config = { schema, values: { [AgentHostAutoAttachPullRequestsConfigKey]: false } }; onDidChangeRootConfig.fire(); + await timeout(0); const restrictedAgain = pill(); config = { schema: { ...schema, properties: { [AgentHostAutoAttachPullRequestsConfigKey]: { type: 'boolean', title: 'Automatic Pull Request Association', default: false } } }, values: {}, }; onDidChangeRootConfig.fire(); + await timeout(0); const restrictedDefault = pill(); config = undefined; onDidChangeRootConfig.fire(); + await timeout(0); const absentExtension = pill(); - assert.deepStrictEqual({ restrictedMain, restrictedPeer, automaticMain, restrictedAgain, restrictedDefault, absentExtension }, { + assert.deepStrictEqual({ restrictedMain, restrictedPeer, automaticMain, restrictedAgain, restrictedDefault, absentExtension, activityBarLabels }, { restrictedMain: null, restrictedPeer: 'Open Pull Request #42: Peer PR', automaticMain: 'Open Pull Request #42', restrictedAgain: null, restrictedDefault: null, absentExtension: 'Open Pull Request #42', + activityBarLabels: [null, 'Open Pull Request #42: Peer PR', 'Open Pull Request #42', null, null, 'Open Pull Request #42'], }); }); } diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionWorkspacePicker.test.ts b/src/vs/sessions/contrib/chat/test/browser/sessionWorkspacePicker.test.ts index a6d6344c9a5895..49427efae1b391 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionWorkspacePicker.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionWorkspacePicker.test.ts @@ -1219,6 +1219,9 @@ suite('WorkspacePicker - Connection Status', () => { hosts: consolidated ? items.find(item => item.label === 'Remote')?.filterItems?.map(item => item.label) ?? [] : items.filter(item => item.label?.startsWith('Provider ')).map(item => item.label), + hostIcons: consolidated + ? items.find(item => item.label === 'Remote')?.filterItems?.map(item => item.group?.icon?.id) ?? [] + : items.filter(item => item.label?.startsWith('Provider ')).map(item => item.group?.icon?.id), }; }; const states = [snapshot()]; @@ -1229,6 +1232,7 @@ suite('WorkspacePicker - Connection Status', () => { const offline = { workspaces: [tunnel.id], browse: ['Browse Tunnel'], hosts: [consolidated ? `Manage ${tunnel.label}` : tunnel.label], + hostIcons: [Codicon.remote.id], }; assert.deepStrictEqual({ states, retainedSessions: environment.getSessions().length, @@ -1237,6 +1241,7 @@ suite('WorkspacePicker - Connection Status', () => { states: [offline, { workspaces: [environment.id, tunnel.id], browse: ['Browse Environment', 'Browse Tunnel'], hosts: [environment, tunnel].map(provider => consolidated ? `Manage ${provider.label}` : provider.label), + hostIcons: [Codicon.remote.id, Codicon.remote.id], }, offline], retainedSessions: 1, recentsUnchanged: true, }); @@ -1474,9 +1479,9 @@ suite('WorkspacePicker - Connection Status', () => { { label: 'Manage Provider agenthost-wsl', ariaLabel: 'Provider agenthost-wsl, Online · 2 active sessions' }, ], unifiedSubmenu: [ - { label: 'Manage Provider agenthost-tunnel-one', icon: Codicon.cloud.id }, - { label: 'Manage Provider agenthost-tunnel-two', icon: Codicon.cloud.id }, - { label: 'Manage Provider agenthost-tunnel-idle', icon: Codicon.cloud.id }, + { label: 'Manage Provider agenthost-tunnel-one', icon: Codicon.remote.id }, + { label: 'Manage Provider agenthost-tunnel-two', icon: Codicon.remote.id }, + { label: 'Manage Provider agenthost-tunnel-idle', icon: Codicon.remote.id }, { label: 'Manage Provider agenthost-ssh', icon: Codicon.remote.id }, { label: 'Manage Provider agenthost-wsl', icon: Codicon.remote.id }, ], diff --git a/src/vs/sessions/contrib/chat/test/browser/sessionsChatAccessibilityHelp.test.ts b/src/vs/sessions/contrib/chat/test/browser/sessionsChatAccessibilityHelp.test.ts index b294e6fbf9a12d..594cb3e2778962 100644 --- a/src/vs/sessions/contrib/chat/test/browser/sessionsChatAccessibilityHelp.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/sessionsChatAccessibilityHelp.test.ts @@ -35,13 +35,37 @@ import { SESSION_ARCHIVE_NUDGE_SETTING } from '../../browser/sessionArchiveNudge import { SessionComparisonAccessibleView, SessionsChatAccessibilityHelp } from '../../browser/sessionsChatAccessibilityHelp.js'; import { CustomizationMarketplaceConfiguration } from '../../../../../platform/customizationMarketplace/common/customizationMarketplaceSources.js'; import { SESSIONS_LIST_PROMOTE_NEW_CHAT_ACTION_DEFAULT, SessionsListPromoteNewChatActionContext } from '../../../../common/contextkeys.js'; -import { SESSIONS_CHAT_TABS_SETTING, SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, SessionsChatTabsMode } from '../../../../common/sessionConfig.js'; +import { SESSION_ACTIVITY_BAR_SETTING, SESSIONS_CHAT_TABS_SETTING, SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, SessionsChatTabsMode } from '../../../../common/sessionConfig.js'; +import { AgentWorkbenchLayout, IAgentWorkbenchLayoutService } from '../../../../browser/workbench.js'; import { RemoteSessionToolsEnabledSettingId } from '../../../remoteSessions/common/remoteSessions.js'; import { DevContainerAgentHostEnabledSettingId, DevContainerSamplesEnabledSettingId } from '../../../../common/devContainerAgentHostService.js'; import { getCloudSandboxPreparationAccessibilityHelp } from '../../../../../workbench/contrib/chat/browser/actions/chatAccessibilityHelp.js'; suite('SessionsChatAccessibilityHelp', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + for (const enabled of [true, false]) { + test(`documents chat-scoped activity bar selection only when enabled: ${enabled}`, () => { + const instantiationService = store.add(new TestInstantiationService()); + const configuration = new TestConfigurationService({ [SESSION_ACTIVITY_BAR_SETTING]: enabled }); + store.add(configuration.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configuration); + stubContextKeyService(instantiationService, configuration); + instantiationService.stub(ISessionsPartService, new class extends mock<ISessionsPartService>() { }()); + instantiationService.stub(ISessionsService, new class extends mock<ISessionsService>() { }()); + instantiationService.stub(IAgentHostFilterService, { selectedHost: undefined }); + const container = mainWindow.document.createElement('div'); + instantiationService.stub(IWorkbenchLayoutService, { mainContainer: container }); + instantiationService.stub(IAgentWorkbenchLayoutService, { agentWorkbenchLayout: AgentWorkbenchLayout.Desktop, mainContainer: container }); + const content = store.add(new SessionsChatAccessibilityHelp().getProvider(instantiationService)).provideContent(); + assert.deepStrictEqual({ + optIn: content.includes('Pull request and issue actions are off by default. Enable Show Pull Request and Issue Actions in the activity bar\'s context menu to show them.'), + chatScope: content.includes('Open Pull Request and Open Issue are also available for the active chat\'s pull requests and issues when a contributed opener is available for their links.'), + singleAndMultiple: content.includes('A single supported reference opens directly; multiple supported references open a picker.'), + cancel: content.includes('Enter to choose a reference, or Escape to cancel.'), + }, { optIn: enabled, chatScope: enabled, singleAndMultiple: enabled, cancel: enabled }); + }); + } + test('documents navigation through sessions and singleton views', () => { const instantiationService = store.add(new TestInstantiationService()); const configuration = new TestConfigurationService(); diff --git a/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts b/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts index 78f594d792cea7..986ca215391f84 100644 --- a/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts +++ b/src/vs/sessions/contrib/chat/test/browser/voiceBridge.test.ts @@ -15,7 +15,8 @@ import { CommandsRegistry } from '../../../../../platform/commands/common/comman import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { IChatWidget, IChatWidgetService } from '../../../../../workbench/contrib/chat/browser/chat.js'; -import { IChatResponseModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { IChatModel, IChatResponseModel } from '../../../../../workbench/contrib/chat/common/model/chatModel.js'; +import { ChatRequestQueueKind } from '../../../../../workbench/contrib/chat/common/chatService/chatService.js'; import { IChatViewModel } from '../../../../../workbench/contrib/chat/common/model/chatViewModel.js'; import { IVoiceSessionController } from '../../../../../workbench/contrib/chat/browser/voiceClient/voiceSessionController.js'; import { IChat, ISession, ISessionWorkspace, SessionStatus } from '../../../../services/sessions/common/session.js'; @@ -61,7 +62,12 @@ suite('SessionsVoiceBridgeContribution - input ownership', () => { let resource = URI.parse('chat-session:/a'); const inputs: string[] = []; const widget = new class extends mock<IChatWidget>() { - override get viewModel() { return upcastPartial<IChatViewModel>({ sessionResource: resource }); } + override get viewModel() { + return upcastPartial<IChatViewModel>({ + sessionResource: resource, + model: upcastPartial<IChatModel>({ requestInProgress: constObservable(false) }), + }); + } override getInput() { return 'Already typed'; } override async acceptInput(text?: string) { inputs.push(text ?? ''); @@ -77,6 +83,57 @@ suite('SessionsVoiceBridgeContribution - input ownership', () => { }); }); + for (const inProgress of [false, true]) { + test(`voice bridge ${inProgress ? 'steers ongoing work' : 'sends normally when idle'}`, async () => { + const resource = URI.parse('chat-session:/a'); + const inputs: { text: string | undefined; options: Parameters<IChatWidget['acceptInput']>[1] }[] = []; + const widget = new class extends mock<IChatWidget>() { + override readonly viewModel = upcastPartial<IChatViewModel>({ + sessionResource: resource, + model: upcastPartial<IChatModel>({ requestInProgress: constObservable(inProgress) }), + }); + override getInput() { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters<IChatWidget['acceptInput']>[1]) { + inputs.push({ text, options }); + return undefined; + } + }(); + await registerBridge(widget, undefined)('Voice request', resource.toString()); + assert.deepStrictEqual(inputs, [{ + text: 'Typed draft Voice request', + options: { preserveFocus: true, ...(inProgress ? { queue: ChatRequestQueueKind.Steering } : {}) }, + }]); + }); + } + + for (const hasModel of [false, true]) { + test(`voice bridge submits normally when ${hasModel ? 'request progress' : 'the model'} is unavailable`, async () => { + const resource = URI.parse('chat-session:/a'); + const inputs: { text: string | undefined; options: Parameters<IChatWidget['acceptInput']>[1] }[] = []; + const widget = new class extends mock<IChatWidget>() { + override readonly viewModel = upcastPartial<IChatViewModel>({ + sessionResource: resource, + ...(hasModel ? { model: upcastPartial<IChatModel>({}) } : {}), + }); + override getInput() { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters<IChatWidget['acceptInput']>[1]) { + inputs.push({ text, options }); + return undefined; + } + }(); + await registerBridge(widget, undefined)('Voice request', resource.toString()); + assert.deepStrictEqual(inputs, [{ + text: 'Typed draft Voice request', + options: { preserveFocus: true }, + }]); + }); + } + + test('voice bridge rejects input when the widget has no view model', async () => { + const widget = new class extends mock<IChatWidget>() { }(); + assert.strictEqual(await registerBridge(widget, undefined)('Voice request', 'chat-session:/a'), false); + }); + test('does not redirect an existing session turn to a new composer and reports a busy composer honestly', async () => { const sent: string[] = []; const composer = upcastPartial<INewChatVoiceComposer>({ diff --git a/src/vs/sessions/contrib/editor/browser/emptyFileEditor.contribution.ts b/src/vs/sessions/contrib/editor/browser/emptyFileEditor.contribution.ts index 1eff2344e28284..c9dba2a4a2fed0 100644 --- a/src/vs/sessions/contrib/editor/browser/emptyFileEditor.contribution.ts +++ b/src/vs/sessions/contrib/editor/browser/emptyFileEditor.contribution.ts @@ -8,26 +8,30 @@ import { Disposable } from '../../../../base/common/lifecycle.js'; import { Codicon } from '../../../../base/common/codicons.js'; import { KeyCode, KeyMod } from '../../../../base/common/keyCodes.js'; import { KeybindingsRegistry, KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; -import { MenuRegistry } from '../../../../platform/actions/common/actions.js'; +import { Action2, MenuRegistry, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationNode, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; import { SyncDescriptor } from '../../../../platform/instantiation/common/descriptors.js'; import product from '../../../../platform/product/common/product.js'; import { Registry } from '../../../../platform/registry/common/platform.js'; +import { registerIcon } from '../../../../platform/theme/common/iconRegistry.js'; import { EditorPaneDescriptor, IEditorPaneRegistry } from '../../../../workbench/browser/editor.js'; import { EditorExtensions, IEditorFactoryRegistry } from '../../../../workbench/common/editor.js'; import { IWorkbenchContribution, registerWorkbenchContribution2, WorkbenchPhase } from '../../../../workbench/common/contributions.js'; import { AccessibleViewRegistry } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; +import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; import { NEW_UNTITLED_FILE_COMMAND_ID } from '../../../../workbench/contrib/files/browser/fileConstants.js'; import { Menus } from '../../../browser/menus.js'; import { AgentWorkbenchLayout, IAgentWorkbenchLayoutService } from '../../../browser/workbench.js'; import { SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING } from '../../../common/sessionConfig.js'; -import { EmptyFileEditor } from './emptyFileEditor.js'; +import { EmptyFileEditor, EmptyFileEditorFocusedContext, OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID } from './emptyFileEditor.js'; import { EmptyFileEditorAccessibilityHelp } from './emptyFileEditorAccessibility.js'; import { EmptyFileEditorInput, EmptyFileEditorSerializer } from './emptyFileEditorInput.js'; import { EmptyFileEditorSearchPickerFocusedContext } from './emptyFileEditorSearch.js'; /** - * Registers the empty-file editor (the "Select a file or search with <kbd>" placeholder pane) and + * Registers the empty-file editor and * its serializer, but only in the desktop layout where the "Files" add-tab flow uses it. * Registered at startup (before editor restore) so persisted empty-file tabs can be deserialized. * Opening it is owned by `addTabActions.ts`'s "Files" action. @@ -63,6 +67,35 @@ class DesktopEmptyFileEditorContribution extends Disposable implements IWorkbenc registerWorkbenchContribution2(DesktopEmptyFileEditorContribution.ID, DesktopEmptyFileEditorContribution, WorkbenchPhase.BlockStartup); AccessibleViewRegistry.register(new EmptyFileEditorAccessibilityHelp()); +const emptyFileEditorActionsEnabled = ContextKeyExpr.equals(`config.${SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING}`, true); +registerAction2(class extends Action2 { + constructor() { + super({ + id: OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID, + title: localize2('emptyFileEditor.openFile', "Open File..."), + icon: registerIcon('sessions-open-file', Codicon.goToFile, localize('emptyFileEditor.openFileIcon', "Icon for opening a file from the Files editor.")), + precondition: emptyFileEditorActionsEnabled, + keybinding: { + weight: KeybindingWeight.SessionsContrib, + when: EmptyFileEditorFocusedContext, + primary: KeyMod.CtrlCmd | KeyCode.KeyP, + }, + menu: { + id: Menus.EmptyFileEditorActions, + group: 'navigation', + order: 1, + when: emptyFileEditorActionsEnabled, + }, + }); + } + + run(accessor: ServicesAccessor, context?: EmptyFileEditor): void { + const editor = context ?? accessor.get(IEditorService).activeEditorPane; + if (editor instanceof EmptyFileEditor) { + editor.openFile(); + } + } +}); MenuRegistry.appendMenuItem(Menus.EmptyFileEditorActions, { command: { id: NEW_UNTITLED_FILE_COMMAND_ID, @@ -70,7 +103,7 @@ MenuRegistry.appendMenuItem(Menus.EmptyFileEditorActions, { icon: Codicon.newFile, }, group: 'navigation', - order: 1, + order: 2, }); // The search picker renders outside the editor area, where Cmd+N otherwise starts a new session. KeybindingsRegistry.registerKeybindingRule({ @@ -89,7 +122,7 @@ export const emptyFileEditorConfiguration = { scope: ConfigurationScope.WINDOW, tags: ['experimental'], experiment: { mode: 'auto' }, - description: localize('sessions.experimental.emptyFileEditorActions', "Enables file search and a New File action in the empty Files editor."), + description: localize('sessions.experimental.emptyFileEditorActions', "Enables search, Open File, and New File actions in the empty Files editor."), }, }, } satisfies IConfigurationNode; diff --git a/src/vs/sessions/contrib/editor/browser/emptyFileEditor.ts b/src/vs/sessions/contrib/editor/browser/emptyFileEditor.ts index 3f5d6584a4cc83..f76f4dbbea73ce 100644 --- a/src/vs/sessions/contrib/editor/browser/emptyFileEditor.ts +++ b/src/vs/sessions/contrib/editor/browser/emptyFileEditor.ts @@ -5,19 +5,14 @@ import './media/emptyFileEditor.css'; import { $, addDisposableListener, append, clearNode, Dimension, EventHelper, EventType, isHTMLElement } from '../../../../base/browser/dom.js'; -import { IAction } from '../../../../base/common/actions.js'; import { CancellationToken } from '../../../../base/common/cancellation.js'; -import { Codicon } from '../../../../base/common/codicons.js'; import { DisposableStore, MutableDisposable } from '../../../../base/common/lifecycle.js'; import { localize } from '../../../../nls.js'; -import { HiddenItemStrategy, MenuWorkbenchToolBar } from '../../../../platform/actions/browser/toolbar.js'; import { ICommandService } from '../../../../platform/commands/common/commands.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; -import { IContextKeyService } from '../../../../platform/contextkey/common/contextkey.js'; -import { IHoverService } from '../../../../platform/hover/browser/hover.js'; +import { IContextKeyService, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { ServiceCollection } from '../../../../platform/instantiation/common/serviceCollection.js'; -import { IKeybindingService } from '../../../../platform/keybinding/common/keybinding.js'; import { IStorageService } from '../../../../platform/storage/common/storage.js'; import { logSettingExperimentTrigger } from '../../../../platform/telemetry/common/experimentTrigger.js'; import { ITelemetryService } from '../../../../platform/telemetry/common/telemetry.js'; @@ -28,50 +23,16 @@ import { NEW_UNTITLED_FILE_COMMAND_ID } from '../../../../workbench/contrib/file import { IEditorOptions } from '../../../../platform/editor/common/editor.js'; import { IEditorGroup } from '../../../../workbench/services/editor/common/editorGroupsService.js'; import { Menus } from '../../../browser/menus.js'; +import { SessionsEmptyStateActions } from '../../../browser/parts/sessionsEmptyStateActions.js'; +import { SessionsEmptyStateLayout } from '../../../browser/parts/sessionsEmptyStateLayout.js'; import { renderSessionsEmptyState } from '../../../browser/parts/sessionsEmptyState.js'; import { SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING } from '../../../common/sessionConfig.js'; import { ISessionWorkspace } from '../../../services/sessions/common/session.js'; -import { CompactButtonActionViewItem } from '../../sessions/browser/sessionsActions.js'; import { EmptyFileEditorSearch } from './emptyFileEditorSearch.js'; import { EmptyFileEditorInput } from './emptyFileEditorInput.js'; -class EmptyFileEditorActionViewItem extends CompactButtonActionViewItem { - - constructor( - action: IAction, - private readonly actionCommandId: string, - @IKeybindingService keybindingService: IKeybindingService, - @IHoverService hoverService: IHoverService, - @IContextKeyService contextKeyService: IContextKeyService, - ) { - super(action, keybindingService, hoverService, contextKeyService); - } - - protected override get commandId(): string { - return this.actionCommandId; - } - - protected override get label(): string { - return this.action.label; - } - - protected override get icon() { - return Codicon.newFile; - } - - protected override getHoverContent(keybindingLabel: string | undefined): string { - return keybindingLabel - ? localize('emptyFileEditor.actionTooltip', "{0} ({1})", this.action.label, keybindingLabel) - : this.action.label; - } - - protected override getAriaLabel(keybindingAriaLabel: string | undefined): string { - return keybindingAriaLabel - ? localize('emptyFileEditor.actionAria', "{0} ({1})", this.action.label, keybindingAriaLabel) - : this.action.label; - } - -} +export const EmptyFileEditorFocusedContext = new RawContextKey<boolean>('emptyFileEditorFocused', false, localize('emptyFileEditorFocused', "Whether focus is in the empty Files editor.")); +export const OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID = 'workbench.action.agentSessions.openFileInEmptyEditor'; export class EmptyFileEditor extends EditorPane { @@ -81,6 +42,7 @@ export class EmptyFileEditor extends EditorPane { private container: HTMLElement | undefined; private content: HTMLElement | undefined; private search: EmptyFileEditorSearch | undefined; + private emptyStateLayout: SessionsEmptyStateLayout | undefined; private workspace: ISessionWorkspace | undefined; constructor( @@ -114,51 +76,54 @@ export class EmptyFileEditor extends EditorPane { } private renderContent(): void { - if (!this.content) { + if (!this.content || !this.container) { return; } this.featureDisposables.clear(); this.search = undefined; + this.emptyStateLayout = undefined; clearNode(this.content); - renderSessionsEmptyState( - this.content, - localize('emptyFileEditor.title', "Files"), - localize('emptyFileEditor.description', "Select a file from the Files view"), - ); - logSettingExperimentTrigger(this.telemetryService, SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING); - if (!this.configurationService.getValue<boolean>(SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING)) { + const showActions = this.configurationService.getValue<boolean>(SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING); + this.content.classList.toggle('has-actions', showActions); + if (!showActions) { + renderSessionsEmptyState( + this.content, + localize('emptyFileEditor.title', "Files"), + localize('emptyFileEditor.description', "Select a file from the Files view"), + ); return; } const featureDisposables = new DisposableStore(); this.featureDisposables.value = featureDisposables; - if (this.container) { - // Like an empty editor group, double-clicking empty space opens an untitled file. - featureDisposables.add(addDisposableListener(this.container, EventType.DBLCLICK, event => { - if (isHTMLElement(event.target) && event.target.closest('.empty-file-editor-search, .empty-file-editor-actions')) { - return; - } - EventHelper.stop(event); - void this.commandService.executeCommand(NEW_UNTITLED_FILE_COMMAND_ID); - })); - } + // Like an empty editor group, double-clicking empty space opens an untitled file. + featureDisposables.add(addDisposableListener(this.container, EventType.DBLCLICK, event => { + if (isHTMLElement(event.target) && event.target.closest('.empty-file-editor-search, .empty-file-editor-actions')) { + return; + } + EventHelper.stop(event); + void this.commandService.executeCommand(NEW_UNTITLED_FILE_COMMAND_ID); + })); const searchContainer = append(this.content, $('.empty-file-editor-search')); this.search = featureDisposables.add(this.instantiationService.createInstance(EmptyFileEditorSearch, searchContainer)); this.search.setWorkspace(this.workspace); - const actions = append(this.content, $('.empty-file-editor-actions')); - const scopedContextKeyService = featureDisposables.add(this.contextKeyService.createScoped(actions)); + const actions = append(this.content, $('.empty-file-editor-actions.sessions-watermark-actions')); + const scopedContextKeyService = featureDisposables.add(this.contextKeyService.createScoped(this.container)); + EmptyFileEditorFocusedContext.bindTo(scopedContextKeyService).set(true); const scopedInstantiationService = featureDisposables.add(this.instantiationService.createChild(new ServiceCollection([IContextKeyService, scopedContextKeyService]))); - featureDisposables.add(scopedInstantiationService.createInstance(MenuWorkbenchToolBar, actions, Menus.EmptyFileEditorActions, { - hiddenItemStrategy: HiddenItemStrategy.NoHide, + featureDisposables.add(scopedInstantiationService.createInstance(SessionsEmptyStateActions, actions, Menus.EmptyFileEditorActions, { + ariaLabel: localize('emptyFileEditor.actions', "Files"), telemetrySource: 'emptyFileEditor.actions', - toolbarOptions: { primaryGroup: group => group === 'navigation' }, - actionViewItemProvider: action => action.id === NEW_UNTITLED_FILE_COMMAND_ID - ? scopedInstantiationService.createInstance(EmptyFileEditorActionViewItem, action, NEW_UNTITLED_FILE_COMMAND_ID) - : undefined, + menuOptions: { arg: this }, })); + this.emptyStateLayout = featureDisposables.add(new SessionsEmptyStateLayout(this.container, [this.content], actions)); + } + + openFile(): void { + this.search?.show(); } override async setInput(input: EmptyFileEditorInput, options: IEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { @@ -180,11 +145,10 @@ export class EmptyFileEditor extends EditorPane { override focus(): void { super.focus(); - if (!this.search?.focusIfEmpty()) { - this.container?.focus(); - } + this.container?.focus(); } override layout(dimension: Dimension): void { + this.emptyStateLayout?.layout(); } } diff --git a/src/vs/sessions/contrib/editor/browser/emptyFileEditorAccessibility.ts b/src/vs/sessions/contrib/editor/browser/emptyFileEditorAccessibility.ts index 8d8f2770a10a99..af16d1baf80176 100644 --- a/src/vs/sessions/contrib/editor/browser/emptyFileEditorAccessibility.ts +++ b/src/vs/sessions/contrib/editor/browser/emptyFileEditorAccessibility.ts @@ -10,13 +10,14 @@ import { AccessibleContentProvider, AccessibleViewProviderId, AccessibleViewType import { IAccessibleViewImplementation } from '../../../../platform/accessibility/browser/accessibleViewRegistry.js'; import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; import { AccessibilityVerbositySettingId } from '../../../../workbench/contrib/accessibility/browser/accessibilityConfiguration.js'; -import { EmptyFileEditorSearchFocusedContext, EmptyFileEditorSearchPickerFocusedContext } from './emptyFileEditorSearch.js'; +import { EmptyFileEditorFocusedContext } from './emptyFileEditor.js'; +import { EmptyFileEditorSearchPickerFocusedContext } from './emptyFileEditorSearch.js'; export class EmptyFileEditorAccessibilityHelp implements IAccessibleViewImplementation { readonly priority = 115; readonly name = 'emptyFileEditorSearch'; readonly type = AccessibleViewType.Help; - readonly when = ContextKeyExpr.or(EmptyFileEditorSearchFocusedContext, EmptyFileEditorSearchPickerFocusedContext); + readonly when = ContextKeyExpr.or(EmptyFileEditorFocusedContext, EmptyFileEditorSearchPickerFocusedContext); getProvider(_accessor: ServicesAccessor): AccessibleContentProvider { const focusedElement = getActiveElement(); @@ -24,9 +25,10 @@ export class EmptyFileEditorAccessibilityHelp implements IAccessibleViewImplemen AccessibleViewProviderId.EmptyFileEditorSearch, { type: AccessibleViewType.Help }, () => [ - localize('emptyFileEditor.searchHelp.overview', "You are in the Files editor search. Type part of a file name to search the active session workspace."), - localize('emptyFileEditor.searchHelp.navigation', "Use Up Arrow and Down Arrow to move the highlighted result while focus remains in the search input. Press Enter to open the highlighted file."), - localize('emptyFileEditor.searchHelp.dismiss', "Press Escape to clear the search text and close the search results."), + localize('emptyFileEditor.searchHelp.overview', "The Files editor offers a search field, followed by Open File and New File actions. Use Tab to reach the search field and actions. Use Up Arrow or Down Arrow to move between actions and Enter or Space to run one."), + localize('emptyFileEditor.searchHelp.inlineSearch', "Type part of a file name in the search field to search the active session workspace. Use Up Arrow and Down Arrow to choose a result, and Enter to open it. Press Escape to clear the search and return to the search field."), + localize('emptyFileEditor.searchHelp.open', "Open File searches the active session workspace. Type part of a file name, use Up Arrow and Down Arrow to choose a result, and press Enter to open it."), + localize('emptyFileEditor.searchHelp.dismiss', "Press Escape to close the search results and return to the Files editor."), ].join('\n'), () => { if (isHTMLElement(focusedElement)) { diff --git a/src/vs/sessions/contrib/editor/browser/emptyFileEditorSearch.ts b/src/vs/sessions/contrib/editor/browser/emptyFileEditorSearch.ts index 3c2459fcecc398..9ad93a83e69393 100644 --- a/src/vs/sessions/contrib/editor/browser/emptyFileEditorSearch.ts +++ b/src/vs/sessions/contrib/editor/browser/emptyFileEditorSearch.ts @@ -4,9 +4,9 @@ *--------------------------------------------------------------------------------------------*/ import * as dom from '../../../../base/browser/dom.js'; -import * as glob from '../../../../base/common/glob.js'; import { StandardKeyboardEvent } from '../../../../base/browser/keyboardEvent.js'; import { InputBox } from '../../../../base/browser/ui/inputbox/inputBox.js'; +import * as glob from '../../../../base/common/glob.js'; import { CancellationToken, CancellationTokenSource } from '../../../../base/common/cancellation.js'; import { Event } from '../../../../base/common/event.js'; import { prepareQuery } from '../../../../base/common/fuzzyScorer.js'; @@ -21,7 +21,7 @@ import { localize } from '../../../../nls.js'; import { IAccessibilityService } from '../../../../platform/accessibility/common/accessibility.js'; import { IAccessibleViewService } from '../../../../platform/accessibility/browser/accessibleView.js'; import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; -import { IContextKeyService, RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; +import { RawContextKey } from '../../../../platform/contextkey/common/contextkey.js'; import { FileOperationResult, IFileService, IFileStat, toFileOperationResult } from '../../../../platform/files/common/files.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { ILogService } from '../../../../platform/log/common/log.js'; @@ -34,7 +34,6 @@ import { QueryBuilder } from '../../../../workbench/services/search/common/query import { getExcludes, hasSiblingFn, ISearchComplete, ISearchConfiguration, ISearchService } from '../../../../workbench/services/search/common/search.js'; import { ISessionFolder, ISessionWorkspace } from '../../../services/sessions/common/session.js'; -export const EmptyFileEditorSearchFocusedContext = new RawContextKey<boolean>('emptyFileEditorSearchFocused', false, localize('emptyFileEditorSearchFocused', "Whether focus is in the empty Files editor search.")); export const EmptyFileEditorSearchPickerFocusedContext = new RawContextKey<boolean>('emptyFileEditorSearchPickerFocused', false, localize('emptyFileEditorSearchPickerFocused', "Whether the empty Files editor search picker is active.")); const MAX_SEARCH_RESULTS = 512; @@ -52,21 +51,20 @@ interface IVirtualFileSearchIndex { export class EmptyFileEditorSearch extends Disposable { - private readonly input: InputBox; - private readonly inputContainer: HTMLElement; private readonly pickerDisposables = this._register(new MutableDisposable<DisposableStore>()); + private readonly input: InputBox; private picker: IQuickPick<IQuickPickItem, { useSeparators: true }> | undefined; + private pickerAnchored = false; + private syncingInputValue = false; private restoreInputFocusOnHide = false; - private syncingPickerValue = false; private workspace: ISessionWorkspace | undefined; private accessibilityHelpHintAnnounced = false; private readonly fileQueryBuilder: QueryBuilder; constructor( - container: HTMLElement, + private readonly container: HTMLElement, @IAccessibilityService private readonly accessibilityService: IAccessibilityService, @IAccessibleViewService private readonly accessibleViewService: IAccessibleViewService, - @IContextKeyService contextKeyService: IContextKeyService, @IConfigurationService private readonly configurationService: IConfigurationService, @IFileService private readonly fileService: IFileService, @IInstantiationService instantiationService: IInstantiationService, @@ -77,81 +75,54 @@ export class EmptyFileEditorSearch extends Disposable { ) { super(); this.fileQueryBuilder = instantiationService.createInstance(QueryBuilder); - const scopedContextKeyService = this._register(contextKeyService.createScoped(container)); - const focusedContext = EmptyFileEditorSearchFocusedContext.bindTo(scopedContextKeyService); - const focusTracker = this._register(dom.trackFocus(container)); - this._register(focusTracker.onDidFocus(() => focusedContext.set(true))); - this._register(focusTracker.onDidBlur(() => focusedContext.set(false))); - this._register(toDisposable(() => focusedContext.reset())); - - this.inputContainer = dom.append(container, dom.$('.empty-file-editor-search-input')); - this.input = this._register(new InputBox(this.inputContainer, undefined, { + this.input = this._register(new InputBox(container, undefined, { ariaLabel: localize('emptyFileEditor.searchAriaLabel', "Search files in the session workspace"), placeholder: localize('emptyFileEditor.searchPlaceholder', "Search files by name"), inputBoxStyles: defaultInputBoxStyles, })); - - this._register(this.input.onDidChange(value => this.onDidChangeValue(value))); + this._register(this.input.onDidChange(value => { + if (!this.syncingInputValue && value.trim()) { + this.showPicker(value, this.input.element); + } + })); this._register(dom.addDisposableListener(this.input.inputElement, dom.EventType.FOCUS, () => { - this.showPicker(); this.announceAccessibilityHelpHint(); - })); - this._register(dom.addDisposableListener(dom.getWindow(this.inputContainer), dom.EventType.KEY_DOWN, event => { - if (this.picker && new StandardKeyboardEvent(event).equals(KeyCode.Escape)) { - this.restoreInputFocusOnHide = true; - this.picker.value = ''; - } - }, true)); - this._register(dom.addDisposableListener(dom.getWindow(this.inputContainer), dom.EventType.POINTER_DOWN, event => { - if (this.picker && dom.isHTMLElement(event.target) && event.target.closest('.monaco-sash')) { - this.picker.hide(); + if (this.input.value.trim()) { + this.showPicker(this.input.value, this.input.element); } - }, true)); + })); this._register(dom.addDisposableListener(this.input.inputElement, dom.EventType.KEY_DOWN, event => { - if (!this.picker && this.input.value && new StandardKeyboardEvent(event).equals(KeyCode.Escape)) { + if (!this.picker && new StandardKeyboardEvent(event).equals(KeyCode.Escape)) { event.preventDefault(); event.stopPropagation(); this.input.value = ''; } })); - } - - /** - * Focuses the search input if it has no text. A non-empty input is left alone because - * focusing it would reopen the search results. - * @returns whether the input was focused. - */ - focusIfEmpty(): boolean { - if (this.input.value) { - return false; - } - this.input.focus(); - return true; + this._register(dom.addDisposableListener(dom.getWindow(container), dom.EventType.KEY_DOWN, event => { + if (this.pickerAnchored && this.picker && new StandardKeyboardEvent(event).equals(KeyCode.Escape)) { + this.restoreInputFocusOnHide = true; + this.picker.value = ''; + } + }, true)); + this._register(dom.addDisposableListener(dom.getWindow(container), dom.EventType.POINTER_DOWN, event => { + if (this.pickerAnchored && dom.isHTMLElement(event.target) && event.target.closest('.monaco-sash')) { + this.picker?.hide(); + } + }, true)); } setWorkspace(workspace: ISessionWorkspace | undefined): void { this.workspace = workspace; - if (this.picker?.value) { - this.restoreInputFocusOnHide = true; - this.picker.hide(); - } + this.setInputValue(''); + this.picker?.hide(); } - private onDidChangeValue(value: string): void { - if (this.syncingPickerValue) { - return; - } - if (!value.trim()) { - this.restoreInputFocusOnHide = !!this.picker; - this.picker?.hide(); - return; - } - - this.showPicker(); + show(): void { + this.showPicker(''); } - private showPicker(): void { - if (this.picker || !this.input.value.trim()) { + private showPicker(value: string, anchor?: HTMLElement): void { + if (this.picker || this._store.isDisposed) { return; } @@ -169,11 +140,11 @@ export class EmptyFileEditorSearch extends Disposable { disposables.add(toDisposable(() => { void this.searchService.clearCache(cacheKey); })); - this.quickInputService.quickAccess.show(this.input.value, { + this.quickInputService.quickAccess.show(value, { providerPrefix: '', - anchor: this.input.element, - anchorPosition: 'overlay', - preserveValue: true, + anchor, + anchorPosition: anchor ? 'overlay' : undefined, + preserveValue: false, placeholder: localize('emptyFileEditor.searchPlaceholder', "Search files by name"), providerOptions, }); @@ -184,6 +155,7 @@ export class EmptyFileEditorSearch extends Disposable { } const picker = currentQuickInput as IQuickPick<IQuickPickItem, { useSeparators: true }>; this.picker = picker; + this.pickerAnchored = !!anchor; // The picker renders outside the editor group, so its context key must be set by the quick input service // (window-wide while visible) to be visible to keybindings and accessibility help evaluated from the picker. picker.contextKey = EmptyFileEditorSearchPickerFocusedContext.key; @@ -194,9 +166,11 @@ export class EmptyFileEditorSearch extends Disposable { } const restoreInputFocus = this.restoreInputFocusOnHide; this.restoreInputFocusOnHide = false; - this.setInputValue(picker.value); - this.inputContainer.style.visibility = ''; + if (anchor) { + this.container.style.visibility = ''; + } this.picker = undefined; + this.pickerAnchored = false; this.pickerDisposables.clear(); if (restoreInputFocus) { this.input.focus(); @@ -207,14 +181,26 @@ export class EmptyFileEditorSearch extends Disposable { picker.ignoreFocusOut = false; picker.valueSelection = [picker.value.length, picker.value.length]; - disposables.add(picker.onDidChangeValue(value => { - this.setInputValue(value); - if (!value.trim()) { - this.restoreInputFocusOnHide = true; - picker.hide(); - } - })); - this.inputContainer.style.visibility = 'hidden'; + if (anchor) { + disposables.add(picker.onDidChangeValue(value => { + this.setInputValue(value); + if (!value.trim()) { + this.restoreInputFocusOnHide = true; + picker.hide(); + } + })); + this.container.style.visibility = 'hidden'; + } + this.announceAccessibilityHelpHint(); + } + + private setInputValue(value: string): void { + this.syncingInputValue = true; + try { + this.input.value = value; + } finally { + this.syncingInputValue = false; + } } private announceAccessibilityHelpHint(): void { @@ -229,15 +215,6 @@ export class EmptyFileEditorSearch extends Disposable { } } - private setInputValue(value: string): void { - this.syncingPickerValue = true; - try { - this.input.value = value; - } finally { - this.syncingPickerValue = false; - } - } - private createFileSearchDelegate(workspace: ISessionWorkspace | undefined, cacheKey: string, lifetimeToken: CancellationToken): IAnythingQuickAccessFileSearchDelegate { const folders = workspace?.folders ?? []; const isSearchable = (folder: ISessionFolder) => folder.workingDirectory.scheme === Schemas.file diff --git a/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css b/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css index 532bc676b182a2..a0ec33fe3770e2 100644 --- a/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css +++ b/src/vs/sessions/contrib/editor/browser/media/emptyFileEditor.css @@ -26,34 +26,18 @@ width: min(440px, calc(100% - var(--vscode-spacing-size400))); } -.empty-file-editor-search { - position: relative; - z-index: 1; - width: 100%; - height: var(--vscode-spacing-size400); -} - -.empty-file-editor-search-input { - position: relative; - width: 100%; - box-sizing: border-box; - padding: var(--vscode-spacing-size60) var(--vscode-spacing-size60) var(--vscode-spacing-size40); -} - -.empty-file-editor-search-input .monaco-inputbox { - border-radius: var(--vscode-cornerRadius-medium); +.empty-file-editor-content.has-actions { + position: static; + transform: none; + padding: 0; + width: min(320px, calc(100% - 2 * var(--vscode-spacing-size240))); } +.empty-file-editor-search, .empty-file-editor-actions { - display: flex; - align-items: center; - justify-content: center; - gap: var(--vscode-spacing-size60); - margin-top: var(--vscode-spacing-size20); + width: 100%; } -.empty-file-editor-actions .new-session-button-icon { - flex-shrink: 0; - margin-right: var(--vscode-spacing-size20); - font-size: var(--vscode-codiconFontSize-compact); +.empty-file-editor-search .monaco-inputbox { + border-radius: var(--vscode-cornerRadius-small); } diff --git a/src/vs/sessions/contrib/editor/electron-browser/browserEmptyState.contribution.ts b/src/vs/sessions/contrib/editor/electron-browser/browserEmptyState.contribution.ts new file mode 100644 index 00000000000000..76b6e75a9f516f --- /dev/null +++ b/src/vs/sessions/contrib/editor/electron-browser/browserEmptyState.contribution.ts @@ -0,0 +1,125 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import './media/browserEmptyState.css'; +import { $ } from '../../../../base/browser/dom.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { DisposableStore, toDisposable } from '../../../../base/common/lifecycle.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { MenuRegistry } from '../../../../platform/actions/common/actions.js'; +import { BrowserViewCommandId } from '../../../../platform/browserView/common/browserView.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { registerIcon } from '../../../../platform/theme/common/iconRegistry.js'; +import { BrowserEditorInput } from '../../../../workbench/contrib/browserView/common/browserEditorInput.js'; +import { IBrowserViewModel } from '../../../../workbench/contrib/browserView/common/browserView.js'; +import { BrowserEditor, BrowserEditorContribution, BrowserWidgetLocation, IBrowserEditorWidget } from '../../../../workbench/contrib/browserView/electron-browser/browserEditor.js'; +import { Menus } from '../../../browser/menus.js'; +import { SessionsEmptyStateActions } from '../../../browser/parts/sessionsEmptyStateActions.js'; +import { SessionsEmptyStateLayout } from '../../../browser/parts/sessionsEmptyStateLayout.js'; + +export class SessionsBrowserEmptyState extends BrowserEditorContribution { + private readonly element = $('.sessions-browser-empty-state'); + private root: HTMLElement | undefined; + private empty = true; + private emptyStateLayout: SessionsEmptyStateLayout | undefined; + private readonly actions: SessionsEmptyStateActions; + + constructor( + editor: BrowserEditor, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(editor); + this.actions = this._register(instantiationService.createInstance(SessionsEmptyStateActions, this.element, Menus.EmptyBrowserEditorActions, { + ariaLabel: localize('browser.emptyActions', "Browser actions"), + telemetrySource: 'browser.emptyState', + menuOptions: { arg: editor }, + })); + this._register(toDisposable(() => this.root?.classList.remove('sessions-browser-empty'))); + } + + override get widgets(): readonly IBrowserEditorWidget[] { + return [{ location: BrowserWidgetLocation.Toolbar, element: this.element, order: 1 }]; + } + + override onContainerCreated(container: HTMLElement): void { + this.root = container.closest<HTMLElement>('.browser-root') ?? undefined; + this.setEmpty(this.empty); + if (this.root) { + this.emptyStateLayout = this._register(new SessionsEmptyStateLayout(this.root, [this.element])); + } + } + + override onPaneResized(): void { + this.emptyStateLayout?.layout(); + } + + override afterContainerLayout(): void { + this.emptyStateLayout?.layout(); + } + + override tryFocus(): boolean { + if (!this.empty) { + return false; + } + this.actions.focus(); + return true; + } + + override prerenderInput(input: BrowserEditorInput): void { + this.setEmpty(!input.url); + } + + protected override onModelAttached(model: IBrowserViewModel, store: DisposableStore): void { + this.setEmpty(!model.url); + store.add(model.onWillNavigate(url => { + if (url) { + this.setEmpty(false); + } + })); + store.add(model.onDidNavigate(event => this.setEmpty(!event.url))); + } + + override onModelDetached(): void { + this.setEmpty(true); + } + + private setEmpty(empty: boolean): void { + this.empty = empty; + this.element.hidden = !empty; + if (this.root && this.root.classList.contains('sessions-browser-empty') !== empty) { + this.root.classList.toggle('sessions-browser-empty', empty); + this.editor.layoutBrowserContainer(); + } + this.emptyStateLayout?.layout(); + } +} + +BrowserEditor.registerContribution(SessionsBrowserEmptyState); +MenuRegistry.appendMenuItems([ + { + id: Menus.EmptyBrowserEditorActions, + item: { + command: { + id: BrowserViewCommandId.FocusUrlInput, + title: localize2('browser.openAddress', "Open Address..."), + icon: registerIcon('sessions-browser-open-address', Codicon.link, localize('browser.openAddressIcon', "Icon for entering a browser address.")), + }, + group: 'navigation', + order: 1, + }, + }, + { + id: Menus.EmptyBrowserEditorActions, + item: { + command: { + id: BrowserViewCommandId.ShowHistory, + title: localize2('browser.history', "History"), + icon: registerIcon('sessions-browser-history', Codicon.history, localize('browser.historyIcon', "Icon for browser history.")), + }, + group: 'navigation', + order: 2, + }, + }, +]); diff --git a/src/vs/sessions/contrib/editor/electron-browser/media/browserEmptyState.css b/src/vs/sessions/contrib/editor/electron-browser/media/browserEmptyState.css new file mode 100644 index 00000000000000..bcbcfd40ad171a --- /dev/null +++ b/src/vs/sessions/contrib/editor/electron-browser/media/browserEmptyState.css @@ -0,0 +1,30 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +.agent-sessions-workbench .browser-root.sessions-browser-empty { + position: relative; +} + +.agent-sessions-workbench .browser-root .browser-welcome-container { + display: none; +} + +.agent-sessions-workbench .browser-root.sessions-browser-empty > .browser-container-wrapper { + position: absolute; + inset: 0; + pointer-events: none; + visibility: hidden; +} + +.sessions-browser-empty-state { + display: none; +} + +.agent-sessions-workbench .sessions-browser-empty-state:not([hidden]) { + display: block; + flex: 0 0 auto; + width: min(320px, calc(100% - 2 * var(--vscode-spacing-size240))); + margin: auto; +} diff --git a/src/vs/sessions/contrib/editor/test/browser/editor.contribution.test.ts b/src/vs/sessions/contrib/editor/test/browser/editor.contribution.test.ts index 969a1f79d7e260..afc01dcbecd9fc 100644 --- a/src/vs/sessions/contrib/editor/test/browser/editor.contribution.test.ts +++ b/src/vs/sessions/contrib/editor/test/browser/editor.contribution.test.ts @@ -4,12 +4,14 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; +import { Dimension } from '../../../../../base/browser/dom.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { Codicon } from '../../../../../base/common/codicons.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { ThemeIcon } from '../../../../../base/common/themables.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { Disposable, DisposableStore, toDisposable } from '../../../../../base/common/lifecycle.js'; -import { decodeKeybinding } from '../../../../../base/common/keybindings.js'; +import { decodeKeybinding, ResolvedKeybinding } from '../../../../../base/common/keybindings.js'; import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; import { OS } from '../../../../../base/common/platform.js'; import { constObservable } from '../../../../../base/common/observable.js'; @@ -29,7 +31,9 @@ import { TestConfigurationService } from '../../../../../platform/configuration/ import { ContextKeyExpression, ContextKeyValue, IContext, IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; import { IInstantiationService, ServicesAccessor } from '../../../../../platform/instantiation/common/instantiation.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; -import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { MockContextKeyService, MockKeybindingService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { USLayoutResolvedKeybinding } from '../../../../../platform/keybinding/common/usLayoutResolvedKeybinding.js'; import { ILogService } from '../../../../../platform/log/common/log.js'; import { IEditorOptions } from '../../../../../platform/editor/common/editor.js'; import { FileOperationError, FileOperationResult, IFileService } from '../../../../../platform/files/common/files.js'; @@ -67,7 +71,7 @@ import { ISessionsService } from '../../../../services/sessions/browser/sessions import { ISessionChangesService } from '../../../changes/browser/sessionChangesService.js'; import { SessionChangesEditorInput } from '../../../changes/browser/sessionChangesEditorInput.js'; import { NEW_BROWSER_TAB_COMMAND_ID, NEW_CHANGES_TAB_COMMAND_ID, NEW_SEARCH_TAB_COMMAND_ID, NewBrowserTabAction, NewChangesTabAction, NewFileTabAction, NewSearchTabAction, OPEN_BROWSER_COMMAND_ID, OpenBrowserAction, registerSessionActivityBarTabEntries } from '../../browser/addTabActions.js'; -import { EmptyFileEditor } from '../../browser/emptyFileEditor.js'; +import { EmptyFileEditor, EmptyFileEditorFocusedContext, OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID } from '../../browser/emptyFileEditor.js'; import { emptyFileEditorConfiguration } from '../../browser/emptyFileEditor.contribution.js'; import { EmptyFileEditorSearch, EmptyFileEditorSearchPickerFocusedContext } from '../../browser/emptyFileEditorSearch.js'; import { EmptyFileEditorInput, EmptyFileEditorSerializer } from '../../browser/emptyFileEditorInput.js'; @@ -138,6 +142,12 @@ function hasResource(value: unknown): value is { resource: URI } { suite('Sessions - Editor Contribution', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + function createFileSearch(instantiationService: TestInstantiationService): EmptyFileEditorSearch { + const container = appendElement(mainWindow.document.body, 'empty-file-editor-search'); + store.add(toDisposable(() => container.remove())); + return store.add(instantiationService.createInstance(EmptyFileEditorSearch, container)); + } + test('shares the connected tab setting across Agents windows independently of Modern UI', async () => { const configurationService = new TestConfigurationService({ [LayoutSettings.MODERN_UI]: false, @@ -660,8 +670,8 @@ suite('Sessions - Editor Contribution', () => { triggers: telemetryService.triggers, }, { disabledContent: ['sessions-empty-state'], - enabledContent: ['sessions-empty-state', 'empty-file-editor-search', 'empty-file-editor-actions'], - description: 'Select a file from the Files view', + enabledContent: ['empty-file-editor-search', 'empty-file-editor-actions sessions-watermark-actions'], + description: undefined, triggers: [`config.${SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING}`], }); }); @@ -705,19 +715,19 @@ suite('Sessions - Editor Contribution', () => { assert.deepStrictEqual({ disabled, emptySpace: doubleClick('.empty-file-editor'), - emptyStateText: doubleClick('.sessions-empty-state-description'), searchInput: doubleClick('.empty-file-editor-search input'), + actionLabel: doubleClick('.sessions-add-tab-watermark-label'), actions: doubleClick('.empty-file-editor-actions'), }, { disabled: [], emptySpace: ['workbench.action.files.newUntitledFile'], - emptyStateText: ['workbench.action.files.newUntitledFile'], searchInput: [], + actionLabel: [], actions: [], }); }); - test('empty file editor shows file search and new file action', () => { + test('empty file editor shows quiet open and new file action rows without repeated copy', () => { const instantiationService = workbenchInstantiationService(undefined, store); store.add(registerEmptyFileEditorActions()); instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { @@ -747,35 +757,56 @@ suite('Sessions - Editor Contribution', () => { store.add({ dispose: () => container.remove() }); editor.create(container); - const buttons = Array.from(container.querySelectorAll<HTMLAnchorElement>('.empty-file-editor-actions .monaco-button')); + const buttons = Array.from(container.querySelectorAll<HTMLAnchorElement>('.empty-file-editor-actions .sessions-add-tab-watermark-entry')); + container.style.cssText = 'height: 400px; width: 400px; --vscode-spacing-size160: 16px; --vscode-spacing-size240: 24px; --vscode-spacing-size280: 28px;'; + editor.layout(new Dimension(400, 400)); + const panel = container.querySelector<HTMLElement>('.empty-file-editor'); + const search = container.querySelector<HTMLElement>('.empty-file-editor-search'); + assert.ok(panel && search && buttons[0]); + const panelBounds = panel.getBoundingClientRect(); + const firstButtonTop = buttons[0].getBoundingClientRect().top; buttons.forEach(button => button.click()); assert.deepStrictEqual({ - searchPlaceholder: container.querySelector<HTMLInputElement>('.empty-file-editor-search input')?.placeholder, + search: { + placeholder: container.querySelector<HTMLInputElement>('input')?.placeholder, + ariaLabel: container.querySelector('input')?.getAttribute('aria-label'), + }, content: Array.from(container.querySelector('.empty-file-editor-content')?.children ?? []).map(element => element.className), description: container.querySelector('.sessions-empty-state-description')?.textContent, + layout: { + firstButtonAligned: Math.abs(firstButtonTop - (panelBounds.top + panelBounds.bottom) / 2 + 42) < 1, + searchAboveButtons: search.getBoundingClientRect().bottom < firstButtonTop, + }, buttons: buttons.map(button => ({ text: button.textContent, ariaLabel: button.getAttribute('aria-label'), - icon: button.querySelector('.new-session-button-icon.codicon-new-file')?.getAttribute('aria-hidden'), + role: button.getAttribute('role'), + icon: button.querySelector('.sessions-add-tab-watermark-icon')?.getAttribute('aria-hidden'), })), - commands, + commands: commands.map(({ id, args }) => ({ id, editorContext: args[0] === editor })), triggers: telemetryService.triggers, }, { - searchPlaceholder: 'Search files by name', - content: ['sessions-empty-state', 'empty-file-editor-search', 'empty-file-editor-actions'], - description: 'Select a file from the Files view', + search: { + placeholder: 'Search files by name', + ariaLabel: 'Search files in the session workspace', + }, + content: ['empty-file-editor-search', 'empty-file-editor-actions sessions-watermark-actions'], + description: undefined, + layout: { firstButtonAligned: true, searchAboveButtons: true }, buttons: [ - { text: 'New File', ariaLabel: 'New File', icon: 'true' }, + { text: 'Open File...', ariaLabel: 'Open File...', role: 'button', icon: 'true' }, + { text: 'New File', ariaLabel: 'New File', role: 'button', icon: 'true' }, ], commands: [ - { id: 'workbench.action.files.newUntitledFile', args: [] }, + { id: OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID, editorContext: true }, + { id: 'workbench.action.files.newUntitledFile', editorContext: true }, ], triggers: [`config.${SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING}`], }); }); - test('empty file editor focuses an empty search input, otherwise its container', () => { + test('empty file editor focuses its container without opening the file picker', () => { const instantiationService = workbenchInstantiationService(undefined, store); store.add(registerEmptyFileEditorActions()); const configurationService = new TestConfigurationService({ @@ -793,37 +824,168 @@ suite('Sessions - Editor Contribution', () => { store.add({ dispose: () => container.remove() }); editor.create(container); - const input = container.querySelector<HTMLInputElement>('.empty-file-editor-search input'); - assert.ok(input); // Keyboard focus must be inside the editor part so `editorAreaFocus` keeps Cmd+N on New File. - const focusedElement = () => { - const activeElement = mainWindow.document.activeElement; - return activeElement === input ? 'searchInput' : activeElement === container.querySelector('.empty-file-editor') ? 'editorContainer' : 'other'; - }; - - editor.focus(); - const emptySearch = focusedElement(); - // Set the text without an input event so no picker opens; focusing the input would open one. - input.value = 'app'; editor.focus(); - const nonEmptySearch = focusedElement(); const editorContainer = container.querySelector('.empty-file-editor'); assert.deepStrictEqual({ role: editorContainer?.getAttribute('role'), ariaLabel: editorContainer?.getAttribute('aria-label'), - emptySearch, - nonEmptySearch, + containerFocused: mainWindow.document.activeElement === editorContainer, pickerOpen: !!instantiationService.get(IQuickInputService).currentQuickInput, }, { role: 'group', ariaLabel: 'Files editor', - emptySearch: 'searchInput', - nonEmptySearch: 'editorContainer', + containerFocused: true, pickerOpen: false, }); }); + test('empty file editor updates shortcut hints and accessible names when keybindings change', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + store.add(registerEmptyFileEditorActions()); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + const configurationService = new TestConfigurationService({ + [SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING]: true, + }); + store.add(configurationService.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configurationService); + const onDidUpdateKeybindings = store.add(new Emitter<void>()); + let keybinding: ResolvedKeybinding | undefined = USLayoutResolvedKeybinding.resolveKeybinding(decodeKeybinding(KeyMod.CtrlCmd | KeyCode.KeyP, OS)!, OS)[0]; + instantiationService.stub(IKeybindingService, new class extends MockKeybindingService { + override get onDidUpdateKeybindings() { return onDidUpdateKeybindings.event; } + override lookupKeybinding(id: string) { + return id === OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID ? keybinding : undefined; + } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + const editor = store.add(instantiationService.createInstance(EmptyFileEditor, new class extends mock<IEditorGroup>() { + override windowId = mainWindow.vscodeWindowId; + }())); + const container = appendElement(mainWindow.document.body, 'empty-file-editor-test'); + store.add(toDisposable(() => container.remove())); + editor.create(container); + const row = container.querySelector<HTMLElement>('.sessions-add-tab-watermark-entry'); + const before = row?.getAttribute('aria-label'); + const beforeExpected = `Open File... (${keybinding.getAriaLabel()})`; + keybinding = USLayoutResolvedKeybinding.resolveKeybinding(decodeKeybinding(KeyMod.CtrlCmd | KeyCode.KeyO, OS)!, OS)[0]; + onDidUpdateKeybindings.fire(); + const afterExpected = `Open File... (${keybinding.getAriaLabel()})`; + const after = row?.getAttribute('aria-label'); + const hintHidden = row?.querySelector<HTMLElement>('.sessions-add-tab-watermark-keybinding')?.hidden; + const updatedKeybinding = keybinding; + keybinding = undefined; + onDidUpdateKeybindings.fire(); + const removed = { label: row?.getAttribute('aria-label'), trailing: row?.lastElementChild?.className }; + keybinding = updatedKeybinding; + onDidUpdateKeybindings.fire(); + assert.deepStrictEqual({ + before, + after, + hintHidden, + removed, + restored: { label: row?.getAttribute('aria-label'), hints: row?.querySelectorAll('.sessions-add-tab-watermark-keybinding').length }, + }, { + before: beforeExpected, + after: afterExpected, + hintHidden: false, + removed: { label: 'Open File...', trailing: 'sessions-add-tab-watermark-label' }, + restored: { label: afterExpected, hints: 1 }, + }); + }); + + test('empty file editor Open File command searches its own session workspace', async () => { + const instantiationService = workbenchInstantiationService(undefined, store); + const configurationService = new TestConfigurationService({ + [SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING]: true, + }); + store.add(configurationService.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + const queries: IFileQuery[] = []; + const onDidSearch = store.add(new Emitter<void>()); + instantiationService.stub(ISearchService, new class extends mock<ISearchService>() { + override async fileSearch(query: IFileQuery): Promise<ISearchComplete> { + queries.push(query); + onDidSearch.fire(); + return { results: [], messages: [], limitHit: false }; + } + override async clearCache(): Promise<void> { } + }); + const editor = store.add(instantiationService.createInstance(EmptyFileEditor, new class extends mock<IEditorGroup>() { + override windowId = mainWindow.vscodeWindowId; + }())); + const container = appendElement(mainWindow.document.body, 'empty-file-editor-test'); + store.add(toDisposable(() => container.remove())); + editor.create(container); + const input = store.add(instantiationService.createInstance(EmptyFileEditorInput, createWorkspace(URI.file('/repo/session')))); + await editor.setInput(input, undefined, {}, CancellationToken.None); + const handler = CommandsRegistry.getCommand(OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID)?.handler; + assert.ok(handler); + handler(instantiationService, editor); + const picker = getQuickPick(instantiationService); + const pickerContainer = mainWindow.document.activeElement?.closest('.quick-input-widget'); + assert.ok(pickerContainer); + store.add(toDisposable(() => pickerContainer.remove())); + const initialValue = picker.value; + picker.value = 'app'; + await waitForCondition(onDidSearch.event, () => queries.length === 1); + picker.value = ''; + const staysOpenWhenCleared = instantiationService.get(IQuickInputService).currentQuickInput === picker; + input.setWorkspace(createWorkspace(URI.file('/repo/other-session'))); + assert.deepStrictEqual({ + initialValue, + folders: queries[0].folderQueries.map(folder => folder.folder.toString()), + staysOpenWhenCleared, + closedOnWorkspaceChange: !instantiationService.get(IQuickInputService).currentQuickInput, + }, { + initialValue: '', + folders: [URI.file('/repo/session').toString()], + staysOpenWhenCleared: true, + closedOnWorkspaceChange: true, + }); + }); + + test('empty file editor gates Open File and its shortcut on the experimental actions setting', () => { + const ctrlCmdP = decodeKeybinding(KeyMod.CtrlCmd | KeyCode.KeyP, OS)!.getHashCode(); + const rule = KeybindingsRegistry.getDefaultKeybindings() + .find(item => item.command === OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID && item.keybinding?.getHashCode() === ctrlCmdP); + const menuItem = MenuRegistry.getMenuItems(Menus.EmptyFileEditorActions) + .find(item => isIMenuItem(item) && item.command.id === OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID); + assert.ok(menuItem && isIMenuItem(menuItem)); + const states = [undefined, false, true, false].map(enabled => { + const values: Record<string, boolean | undefined> = { + [`config.${SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING}`]: enabled, + [EmptyFileEditorFocusedContext.key]: true, + }; + const context = { getValue: <T>(key: string) => values[key] as T | undefined }; + const focused = rule?.when?.evaluate(context); + delete values[EmptyFileEditorFocusedContext.key]; + return { + enabled, + focused, + elsewhere: rule?.when?.evaluate(context), + menuVisible: menuItem.when?.evaluate(context), + actionEnabled: menuItem.command.precondition?.evaluate(context), + }; + }); + assert.deepStrictEqual({ + registered: !!rule, + states, + }, { + registered: true, + states: [undefined, false, true, false].map(enabled => ({ + enabled, + focused: enabled === true, + elsewhere: false, + menuVisible: enabled === true, + actionEnabled: enabled === true, + })), + }); + }); + test('empty file editor search picker keeps Cmd+N on New File', () => { const ctrlCmdN = decodeKeybinding(KeyMod.CtrlCmd | KeyCode.KeyN, OS)!.getHashCode(); const rule = KeybindingsRegistry.getDefaultKeybindings() @@ -880,10 +1042,7 @@ suite('Sessions - Editor Contribution', () => { return undefined; } }); - const container = appendElement(mainWindow.document.body, 'empty-file-editor-search empty-file-editor-search-test'); - container.style.width = '420px'; - store.add({ dispose: () => container.remove() }); - const search = store.add(instantiationService.createInstance(EmptyFileEditorSearch, container)); + const search = createFileSearch(instantiationService); search.setWorkspace(createWorkspaceWithFolders([{ root: URI.file('/repo'), workingDirectory: URI.file('/repo/.worktrees/session'), @@ -891,32 +1050,24 @@ suite('Sessions - Editor Contribution', () => { description: undefined, }])); - const input = container.querySelector<HTMLInputElement>('input'); - assert.ok(input); - const inputBox = container.querySelector<HTMLElement>('.monaco-inputbox'); - assert.ok(inputBox); - const getInputBounds = () => { - const { left, top, width, height } = inputBox.getBoundingClientRect(); - return { left, top, width, height }; - }; - const inputBoundsBeforeSearch = getInputBounds(); - input.value = 'a'; - input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + search.show(); const onDidShowResults = getQuickPick(instantiationService).onDidChangeActive; - const pickerTextInput = mainWindow.document.querySelector<HTMLInputElement>('.quick-input-widget.quick-input-widget-overlay .quick-input-filter input'); + const picker = mainWindow.document.activeElement?.closest<HTMLElement>('.quick-input-widget'); + assert.ok(picker); + store.add(toDisposable(() => picker.remove())); + const pickerTextInput = picker.querySelector<HTMLInputElement>('.quick-input-filter input'); assert.ok(pickerTextInput); + pickerTextInput.setRangeText('a', pickerTextInput.selectionStart ?? 0, pickerTextInput.selectionEnd ?? 0, 'end'); + pickerTextInput.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); pickerTextInput.setRangeText('p', pickerTextInput.selectionStart ?? 0, pickerTextInput.selectionEnd ?? 0, 'end'); pickerTextInput.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); pickerTextInput.setRangeText('p', pickerTextInput.selectionStart ?? 0, pickerTextInput.selectionEnd ?? 0, 'end'); pickerTextInput.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); await waitForCondition(onDidShowResults, () => queries.length >= 1 - && mainWindow.document.querySelectorAll('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row').length === 2); + && picker.querySelectorAll('.quick-input-list .monaco-list-row').length === 2); const valueAfterPickerOpened = pickerTextInput.value; - const picker = mainWindow.document.querySelector<HTMLElement>('.quick-input-widget.quick-input-widget-overlay'); - const pickerInput = picker?.querySelector<HTMLElement>('.quick-input-filter'); const rows = Array.from(picker?.querySelectorAll<HTMLElement>('.quick-input-list .monaco-list-row') ?? []); - const pickerInputBounds = pickerInput?.getBoundingClientRect(); const pickerHelpContext = instantiationService.get(IContextKeyService).getContextKeyValue(EmptyFileEditorSearchPickerFocusedContext.key); const activePicker = instantiationService.get(IQuickInputService).currentQuickInput; assert.strictEqual(activePicker?.type, QuickInputType.QuickPick); @@ -929,23 +1080,22 @@ suite('Sessions - Editor Contribution', () => { }; (activePicker as IQuickPick<IQuickPickItem, { useSeparators: true }>).value = '#app'; await waitForCondition(onDidShowResults, () => queries.some(query => query.filePattern === '#app') - && mainWindow.document.querySelectorAll('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row').length === 1); + && picker.querySelectorAll('.quick-input-list .monaco-list-row').length === 1); const prefixedRows = Array.from( - mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row') + picker.querySelectorAll<HTMLElement>('.quick-input-list .monaco-list-row') ).map(row => row.textContent); const queryCountBeforeMultiTerm = queries.length; (activePicker as IQuickPick<IQuickPickItem, { useSeparators: true }>).value = 'app test'; await waitForCondition(onDidShowResults, () => queries.length > queryCountBeforeMultiTerm - && mainWindow.document.querySelectorAll('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row').length === 1); + && picker.querySelectorAll('.quick-input-list .monaco-list-row').length === 1); const multiTermRows = Array.from( - mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row') + picker.querySelectorAll<HTMLElement>('.quick-input-list .monaco-list-row') ).map(row => row.textContent); (activePicker as IQuickPick<IQuickPickItem, { useSeparators: true }>).accept(); await waitForCondition(onDidOpen.event, () => opened.length === 2); const onDidHidePicker = (activePicker as IQuickPick<IQuickPickItem, { useSeparators: true }>).onDidHide; await waitForCondition(onDidHidePicker, () => picker?.style.display === 'none'); await waitForCondition(onDidClearCache.event, () => queries.every(query => typeof query.cacheKey === 'string' && clearedCacheKeys.includes(query.cacheKey))); - input.blur(); await waitForCondition(onDidHidePicker, () => instantiationService.get(IContextKeyService).getContextKeyValue(EmptyFileEditorSearchPickerFocusedContext.key) === false); assert.deepStrictEqual({ @@ -962,13 +1112,9 @@ suite('Sessions - Editor Contribution', () => { prefixedRows, multiTermRows, usesFileIcon: rows[0]?.querySelector('.monaco-icon-label')?.classList.contains('file-icon'), - usesRealQuickPick: picker?.classList.contains('quick-input-widget-overlay'), + usesCenteredQuickPick: picker?.classList.contains('quick-input-widget') && !picker.classList.contains('quick-input-widget-overlay'), hasItemButtons: rows.some(row => !!row.querySelector('.quick-input-list-entry.has-actions')), valueAfterPickerOpened, - inputBoundsStable: pickerInputBounds?.left === inputBoundsBeforeSearch.left - && pickerInputBounds.top === inputBoundsBeforeSearch.top - && pickerInputBounds.width === inputBoundsBeforeSearch.width - && pickerInputBounds.height === inputBoundsBeforeSearch.height, pickerHelpContext, backgroundAcceptState, opened: opened.map(({ resource, preserveFocus, pinned }) => ({ resource: resource.toString(), preserveFocus, pinned })), @@ -987,10 +1133,9 @@ suite('Sessions - Editor Contribution', () => { prefixedRows: ['#app.tssrc'], multiTermRows: ['app.test.tstest'], usesFileIcon: true, - usesRealQuickPick: true, + usesCenteredQuickPick: true, hasItemButtons: false, valueAfterPickerOpened: 'app', - inputBoundsStable: true, pickerHelpContext: true, backgroundAcceptState: { pickerVisible: true, @@ -1005,6 +1150,96 @@ suite('Sessions - Editor Contribution', () => { }); }); + test('empty file editor inline search anchors results and restores the field on Escape', async () => { + await mainWindow.document.fonts.ready; + const instantiationService = workbenchInstantiationService(undefined, store); + const queries: IFileQuery[] = []; + const onDidSearch = store.add(new Emitter<void>()); + instantiationService.stub(ISearchService, new class extends mock<ISearchService>() { + override async fileSearch(query: IFileQuery): Promise<ISearchComplete> { + queries.push(query); + onDidSearch.fire(); + return { + results: [{ resource: URI.file(`/repo/${query.filePattern}.ts`) }], + messages: [], + limitHit: false, + }; + } + override async clearCache(): Promise<void> { } + }); + const container = appendElement(mainWindow.document.body, 'empty-file-editor-search'); + container.style.width = '320px'; + container.style.height = '28px'; + store.add(toDisposable(() => container.remove())); + store.add(toDisposable(() => mainWindow.scrollTo(0, 0))); + const search = store.add(instantiationService.createInstance(EmptyFileEditorSearch, container)); + search.setWorkspace(createWorkspace(URI.file('/repo'))); + const input = container.querySelector<HTMLInputElement>('input'); + const inputBox = container.querySelector<HTMLElement>('.monaco-inputbox'); + assert.ok(input && inputBox); + input.focus(); + const pickerClosedBeforeTyping = !instantiationService.get(IQuickInputService).currentQuickInput; + const inputBounds = inputBox.getBoundingClientRect(); + const typeQuery = (value: string) => { + input.value = value; + input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + }; + typeQuery('app'); + const picker = getQuickPick(instantiationService); + const pickerContainer = mainWindow.document.activeElement?.closest<HTMLElement>('.quick-input-widget'); + assert.ok(pickerContainer); + store.add(toDisposable(() => pickerContainer.remove())); + const pickerInputBounds = pickerContainer.querySelector('.quick-input-filter')?.getBoundingClientRect(); + assert.ok(pickerInputBounds); + const initialState = { + anchored: pickerContainer.classList.contains('quick-input-widget-overlay'), + query: picker.value, + fieldHidden: container.style.visibility, + bounds: { left: pickerInputBounds.left, top: pickerInputBounds.top, width: pickerInputBounds.width, height: pickerInputBounds.height }, + }; + picker.value = 'other'; + await waitForCondition(onDidSearch.event, () => queries.some(query => query.filePattern === 'other')); + const mirroredValue = input.value; + pickerContainer.querySelector('input')?.dispatchEvent(new mainWindow.KeyboardEvent('keydown', { + key: 'Escape', code: 'Escape', keyCode: 27, bubbles: true, + })); + const afterEscape = { + value: input.value, + fieldVisibility: container.style.visibility, + fieldFocused: mainWindow.document.activeElement === input, + pickerClosed: !instantiationService.get(IQuickInputService).currentQuickInput, + }; + typeQuery('app'); + search.setWorkspace(createWorkspace(URI.file('/other'))); + const afterWorkspaceChange = { + value: input.value, + fieldVisibility: container.style.visibility, + pickerClosed: !instantiationService.get(IQuickInputService).currentQuickInput, + }; + typeQuery('app'); + search.dispose(); + assert.deepStrictEqual({ + pickerClosedBeforeTyping, + initialState, + mirroredValue, + afterEscape, + afterWorkspaceChange, + pickerClosedOnDispose: !instantiationService.get(IQuickInputService).currentQuickInput, + }, { + pickerClosedBeforeTyping: true, + initialState: { + anchored: true, + query: 'app', + fieldHidden: 'hidden', + bounds: { left: inputBounds.left, top: inputBounds.top, width: inputBounds.width, height: inputBounds.height }, + }, + mirroredValue: 'other', + afterEscape: { value: '', fieldVisibility: '', fieldFocused: true, pickerClosed: true }, + afterWorkspaceChange: { value: '', fieldVisibility: '', pickerClosed: true }, + pickerClosedOnDispose: true, + }); + }); + test('empty file editor search combines session working directories before native ranking', async () => { const instantiationService = workbenchInstantiationService(undefined, store); const queries: IFileQuery[] = []; @@ -1019,9 +1254,7 @@ suite('Sessions - Editor Contribution', () => { return Promise.resolve(); } }); - const container = appendElement(mainWindow.document.body, 'empty-file-editor-search'); - store.add({ dispose: () => container.remove() }); - const search = store.add(instantiationService.createInstance(EmptyFileEditorSearch, container)); + const search = createFileSearch(instantiationService); search.setWorkspace(createWorkspaceWithFolders([ { root: URI.file('/repo'), @@ -1037,10 +1270,8 @@ suite('Sessions - Editor Contribution', () => { }, ])); - const input = container.querySelector<HTMLInputElement>('input'); - assert.ok(input); - input.value = 'file'; - input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + search.show(); + getQuickPick(instantiationService).value = 'file'; await waitForCondition(onDidSearch.event, () => queries.length === 1); assert.deepStrictEqual({ @@ -1057,6 +1288,9 @@ suite('Sessions - Editor Contribution', () => { test('empty file editor search announces its accessibility help hint once', () => { const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(ISearchService, new class extends mock<ISearchService>() { + override async clearCache(): Promise<void> { } + }); const announcements: string[] = []; let hint: string | null = null; instantiationService.stub(IAccessibilityService, new class extends mock<IAccessibilityService>() { @@ -1072,17 +1306,13 @@ suite('Sessions - Editor Contribution', () => { return hint; } }); - const container = appendElement(mainWindow.document.body, 'empty-file-editor-search'); - store.add({ dispose: () => container.remove() }); - store.add(instantiationService.createInstance(EmptyFileEditorSearch, container)); - const input = container.querySelector<HTMLInputElement>('input'); - assert.ok(input); - - input.focus(); - input.blur(); + const search = createFileSearch(instantiationService); + search.show(); + getQuickPick(instantiationService).hide(); hint = 'Inspect accessibility help'; - input.dispatchEvent(new mainWindow.FocusEvent('focus')); - input.dispatchEvent(new mainWindow.FocusEvent('focus')); + search.show(); + getQuickPick(instantiationService).hide(); + search.show(); assert.deepStrictEqual(announcements, ['Inspect accessibility help']); }); @@ -1158,21 +1388,17 @@ suite('Sessions - Editor Contribution', () => { return undefined; } }); - const container = appendElement(mainWindow.document.body, 'empty-file-editor-search'); - store.add({ dispose: () => container.remove() }); - const search = store.add(instantiationService.createInstance(EmptyFileEditorSearch, container)); + const search = createFileSearch(instantiationService); search.setWorkspace(createWorkspace(root)); - const input = container.querySelector<HTMLInputElement>('input'); - assert.ok(input); - input.value = 'app'; - input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + search.show(); const picker = getQuickPick(instantiationService); - await waitForCondition(picker.onDidChangeActive, () => mainWindow.document.querySelectorAll('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row').length === 1); + picker.value = 'app'; + await waitForCondition(picker.onDidChangeActive, () => mainWindow.document.querySelectorAll('.quick-input-widget .quick-input-list .monaco-list-row').length === 1); const unquotedResult = picker.activeItems[0]; picker.value = '"app*.test.ts"'; await waitForCondition(picker.onDidChangeActive, () => picker.activeItems[0] !== unquotedResult); - const rows = Array.from(mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row')); + const rows = Array.from(mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget .quick-input-list .monaco-list-row')); rows[0]?.dispatchEvent(new mainWindow.MouseEvent('dblclick', { bubbles: true })); await waitForCondition(onDidOpen.event, () => opened.length === 1); @@ -1225,25 +1451,21 @@ suite('Sessions - Editor Contribution', () => { }; } }); - const container = appendElement(mainWindow.document.body, 'empty-file-editor-search'); - store.add({ dispose: () => container.remove() }); - const search = store.add(instantiationService.createInstance(EmptyFileEditorSearch, container)); + const search = createFileSearch(instantiationService); search.setWorkspace(createWorkspaceWithFolders([ { root: nativeRoot, workingDirectory: nativeRoot, name: 'native', description: undefined }, { root: virtualRoot, workingDirectory: virtualRoot, name: 'virtual', description: undefined }, ])); - const input = container.querySelector<HTMLInputElement>('input'); - assert.ok(input); - input.value = 'app'; - input.dispatchEvent(new mainWindow.Event('input', { bubbles: true })); + search.show(); const picker = getQuickPick(instantiationService); + picker.value = 'app'; await waitForCondition(picker.onDidChangeActive, () => virtualResolveAttempts >= 1 - && mainWindow.document.querySelectorAll('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row').length === 1); - const firstRows = Array.from(mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row')).map(row => row.textContent); + && mainWindow.document.querySelectorAll('.quick-input-widget .quick-input-list .monaco-list-row').length === 1); + const firstRows = Array.from(mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget .quick-input-list .monaco-list-row')).map(row => row.textContent); picker.value = 'other'; await waitForCondition(picker.onDidChangeActive, () => fileSearchPatterns.includes('other')); - const secondRows = Array.from(mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget.quick-input-widget-overlay .quick-input-list .monaco-list-row')).map(row => row.textContent); + const secondRows = Array.from(mainWindow.document.querySelectorAll<HTMLElement>('.quick-input-widget .quick-input-list .monaco-list-row')).map(row => row.textContent); assert.deepStrictEqual({ firstRows, diff --git a/src/vs/sessions/contrib/editor/test/browser/emptyFileEditor.fixture.ts b/src/vs/sessions/contrib/editor/test/browser/emptyFileEditor.fixture.ts new file mode 100644 index 00000000000000..56de81e1f7816c --- /dev/null +++ b/src/vs/sessions/contrib/editor/test/browser/emptyFileEditor.fixture.ts @@ -0,0 +1,83 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import '../../../../browser/parts/media/editorPart.css'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { mock } from '../../../../../base/test/common/mock.js'; +import { IMenuService } from '../../../../../platform/actions/common/actions.js'; +import { ICommandService } from '../../../../../platform/commands/common/commands.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { IThemeService } from '../../../../../platform/theme/common/themeService.js'; +import { TestThemeService } from '../../../../../platform/theme/test/common/testThemeService.js'; +import { NEW_UNTITLED_FILE_COMMAND_ID } from '../../../../../workbench/contrib/files/browser/fileConstants.js'; +import { IEditorGroup } from '../../../../../workbench/services/editor/common/editorGroupsService.js'; +import { ComponentFixtureContext, defineComponentFixture, defineThemedFixtureGroup } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING } from '../../../../common/sessionConfig.js'; +import { FixtureKeybindingService, FixtureMenuService, IFixtureEntry } from '../../../../test/browser/addTabFixtureUtils.js'; +import { EmptyFileEditor, OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID } from '../../browser/emptyFileEditor.js'; + +const entries: readonly IFixtureEntry[] = [ + { id: OPEN_FILE_IN_EMPTY_EDITOR_COMMAND_ID, title: 'Open File...', icon: Codicon.goToFile, keybinding: KeyMod.CtrlCmd | KeyCode.KeyP }, + { id: NEW_UNTITLED_FILE_COMMAND_ID, title: 'New File', icon: Codicon.newFile, keybinding: KeyMod.CtrlCmd | KeyCode.KeyN }, +]; + +export default defineThemedFixtureGroup({ path: 'sessions/emptyFileEditor/' }, { + Default: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: context => renderEditor(context), + }), + Narrow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + render: context => renderEditor(context, 240), + }), + KeyboardFocused: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: context => renderEditor(context, 480, 'action'), + }), + SearchFocused: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: context => renderEditor(context, 480, 'search'), + }), +}); + +function renderEditor({ container, disposableStore, theme, focus }: ComponentFixtureContext, width = 480, focusTarget?: 'action' | 'search'): void { + container.style.width = `${width}px`; + container.style.height = '360px'; + container.classList.add('agent-sessions-workbench'); + const instantiationService = workbenchInstantiationService(undefined, disposableStore); + const configurationService = new TestConfigurationService({ + [SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING]: true, + }); + disposableStore.add(configurationService.onDidChangeConfigurationEmitter); + instantiationService.stub(IConfigurationService, configurationService); + const themeService = new TestThemeService(theme); + disposableStore.add(themeService._onThemeChange); + disposableStore.add(themeService._onFileIconThemeChange); + disposableStore.add(themeService._onProductIconThemeChange); + instantiationService.stub(IThemeService, themeService); + const menuService = new FixtureMenuService(entries); + menuService.commandService = instantiationService.get(ICommandService); + instantiationService.stub(IMenuService, menuService); + instantiationService.stub(IKeybindingService, new FixtureKeybindingService(entries)); + const editor = disposableStore.add(instantiationService.createInstance(EmptyFileEditor, new class extends mock<IEditorGroup>() { + override windowId = mainWindow.vscodeWindowId; + }())); + editor.create(container); + if (focusTarget) { + const target = container.querySelector<HTMLElement>(focusTarget === 'action' ? '.sessions-add-tab-watermark-entry' : '.empty-file-editor-search input'); + if (!target) { + throw new Error(`Expected the ${focusTarget} focus target`); + } + focus(target); + } +} diff --git a/src/vs/sessions/contrib/editor/test/electron-browser/browserEmptyState.test.ts b/src/vs/sessions/contrib/editor/test/electron-browser/browserEmptyState.test.ts new file mode 100644 index 00000000000000..5cae9738fa733b --- /dev/null +++ b/src/vs/sessions/contrib/editor/test/electron-browser/browserEmptyState.test.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 assert from 'assert'; +import { $, append, getWindow } from '../../../../../base/browser/dom.js'; +import { mainWindow } from '../../../../../base/browser/window.js'; +import { Emitter } from '../../../../../base/common/event.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { decodeKeybinding } from '../../../../../base/common/keybindings.js'; +import { toDisposable } from '../../../../../base/common/lifecycle.js'; +import { OS } from '../../../../../base/common/platform.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IMenuService } from '../../../../../platform/actions/common/actions.js'; +import { BrowserViewCommandId, IBrowserViewNavigationEvent } from '../../../../../platform/browserView/common/browserView.js'; +import { MenuService } from '../../../../../platform/actions/common/menuService.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { USLayoutResolvedKeybinding } from '../../../../../platform/keybinding/common/usLayoutResolvedKeybinding.js'; +import { MockContextKeyService, MockKeybindingService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IBrowserViewModel } from '../../../../../workbench/contrib/browserView/common/browserView.js'; +import { BrowserEditorInput } from '../../../../../workbench/contrib/browserView/common/browserEditorInput.js'; +import { BrowserEditor, BrowserWidgetLocation } from '../../../../../workbench/contrib/browserView/electron-browser/browserEditor.js'; +import '../../../../../workbench/contrib/browserView/electron-browser/media/browser.css'; +import { workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { SessionsBrowserEmptyState } from '../../electron-browser/browserEmptyState.contribution.js'; + +suite('Sessions - Browser empty state', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('centers controls only for blank pages and removes model listeners on detach', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + const onDidChangeModel = store.add(new Emitter<{ model: IBrowserViewModel | undefined; isNew: boolean }>()); + const onDidNavigate = store.add(new Emitter<IBrowserViewNavigationEvent>()); + const onWillNavigate = store.add(new Emitter<string>()); + const navigate = (url: string) => onDidNavigate.fire({ url, title: '', canGoBack: false, canGoForward: false, certificateError: undefined }); + let layouts = 0; + const editor = upcastPartial<BrowserEditor>({ + onDidChangeModel: onDidChangeModel.event, + layoutBrowserContainer: () => { layouts++; }, + }); + const feature = store.add(instantiationService.createInstance(SessionsBrowserEmptyState, editor)); + const root = append(mainWindow.document.body, $('.agent-sessions-workbench.browser-root')); + store.add(toDisposable(() => root.remove())); + const container = append(root, $('.browser-container')); + const widget = feature.widgets[0].element; + append(container, widget); + feature.onContainerCreated(container); + const states: { centered: boolean; actionsHidden: boolean }[] = []; + const record = () => states.push({ centered: root.classList.contains('sessions-browser-empty'), actionsHidden: widget.hidden === true }); + record(); + feature.prerenderInput(upcastPartial<BrowserEditorInput>({ url: 'https://example.com' })); + record(); + onDidChangeModel.fire({ model: upcastPartial<IBrowserViewModel>({ url: '', onDidNavigate: onDidNavigate.event, onWillNavigate: onWillNavigate.event }), isNew: true }); + record(); + onWillNavigate.fire('https://example.com'); + const headerRestoredBeforeNavigation = !root.classList.contains('sessions-browser-empty'); + navigate('https://example.com'); + record(); + onDidChangeModel.fire({ model: undefined, isNew: false }); + record(); + navigate('https://stale.example.com'); + record(); + const rows = [...widget.querySelectorAll('.sessions-add-tab-watermark-label')].map(row => row.textContent); + feature.dispose(); + assert.deepStrictEqual({ states, rows, layouts, headerRestoredBeforeNavigation, centeredAfterDispose: root.classList.contains('sessions-browser-empty') }, { + states: [ + { centered: true, actionsHidden: false }, + { centered: false, actionsHidden: true }, + { centered: true, actionsHidden: false }, + { centered: false, actionsHidden: true }, + { centered: true, actionsHidden: false }, + { centered: true, actionsHidden: false }, + ], + rows: ['Open Address...', 'History'], + layouts: 5, + headerRestoredBeforeNavigation: true, + centeredAfterDispose: false, + }); + }); + + test('keeps whole action rows outside the inset browser viewport', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + instantiationService.stub(IKeybindingService, new class extends MockKeybindingService { + override lookupKeybinding(commandId: string) { + const keyCode = commandId === BrowserViewCommandId.FocusUrlInput ? KeyCode.KeyL : commandId === BrowserViewCommandId.ShowHistory ? KeyCode.KeyY : undefined; + const keybinding = keyCode === undefined ? null : decodeKeybinding(KeyMod.CtrlCmd | keyCode, OS); + return keybinding ? USLayoutResolvedKeybinding.resolveKeybinding(keybinding, OS)[0] : undefined; + } + }); + const onDidChangeModel = store.add(new Emitter<{ model: IBrowserViewModel | undefined; isNew: boolean }>()); + const editor = upcastPartial<BrowserEditor>({ + onDidChangeModel: onDidChangeModel.event, + layoutBrowserContainer: () => { }, + }); + const feature = store.add(instantiationService.createInstance(SessionsBrowserEmptyState, editor)); + const workbench = append(mainWindow.document.body, $('.agent-sessions-workbench')); + workbench.style.cssText = '--vscode-spacing-size80: 8px; --vscode-spacing-size160: 16px; --vscode-spacing-size240: 24px; --vscode-spacing-size280: 28px; --vscode-codiconFontSize: 16px;'; + store.add(toDisposable(() => workbench.remove())); + const root = append(workbench, $('.browser-root')); + const navbar = append(root, $('.browser-navbar')); + append(navbar, $('input')); + const widget = feature.widgets[0]; + assert.strictEqual(widget.location, BrowserWidgetLocation.Toolbar); + append(root, widget.element); + const wrapper = append(root, $('.browser-container-wrapper')); + const container = append(wrapper, $('.browser-container')); + container.style.cssText = 'width: calc(100% - 6px); height: calc(100% - 6px); left: 3px; top: 3px;'; + const placeholder = append(container, $('.browser-placeholder-contents')); + feature.onContainerCreated(container); + const rows = [...widget.element.querySelectorAll<HTMLElement>('.sessions-add-tab-watermark-entry')]; + const keycaps = [...widget.element.querySelectorAll<HTMLElement>('.monaco-keybinding-key')]; + assert.strictEqual(keycaps.length, 4); + const results = []; + for (const width of [600, 240]) { + for (const height of [360, 160]) { + workbench.style.width = `${width}px`; + workbench.style.height = `${height}px`; + feature.onPaneResized(); + const rootBounds = root.getBoundingClientRect(); + const actionBounds = widget.element.getBoundingClientRect(); + const navbarBounds = navbar.getBoundingClientRect(); + results.push({ + width, + height, + addressBarAtTop: navbarBounds.top === rootBounds.top, + fullWidthToolbar: navbarBounds.width === rootBounds.width, + firstActionAligned: Math.abs(actionBounds.top - (rootBounds.top + rootBounds.bottom) / 2 + 42) < 1, + outsideViewport: !placeholder.contains(widget.element), + wholeRowsVisible: rows.every(row => { + const bounds = row.getBoundingClientRect(); + return bounds.top >= actionBounds.top && bounds.bottom <= actionBounds.bottom + && bounds.top >= rootBounds.top && bounds.bottom <= rootBounds.bottom; + }), + rowHeights: rows.map(row => row.getBoundingClientRect().height), + wholeVisibleKeycaps: keycaps.filter(keycap => keycap.getClientRects().length > 0).every(keycap => { + const bounds = keycap.getBoundingClientRect(); + return bounds.top >= actionBounds.top && bounds.bottom <= actionBounds.bottom; + }), + clippedPageHidden: getWindow(wrapper).getComputedStyle(wrapper).visibility === 'hidden', + }); + } + } + feature.prerenderInput(upcastPartial<BrowserEditorInput>({ url: 'https://example.com' })); + assert.deepStrictEqual({ + results, + loadedPage: { + actionsHidden: widget.element.hidden, + viewportVisible: getWindow(wrapper).getComputedStyle(wrapper).visibility === 'visible', + viewportPosition: getWindow(wrapper).getComputedStyle(wrapper).position, + addressBarAtTop: navbar.getBoundingClientRect().top === root.getBoundingClientRect().top, + }, + }, { + results: [600, 240].flatMap(width => [360, 160].map(height => ({ + width, + height, + addressBarAtTop: true, + fullWidthToolbar: true, + firstActionAligned: true, + outsideViewport: true, + wholeRowsVisible: true, + rowHeights: [28, 28], + wholeVisibleKeycaps: true, + clippedPageHidden: true, + }))), + loadedPage: { actionsHidden: true, viewportVisible: true, viewportPosition: 'relative', addressBarAtTop: true }, + }); + }); + + test('focuses a visible action in blank Browser tabs without taking loaded-page focus', () => { + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + const onDidChangeModel = store.add(new Emitter<{ model: IBrowserViewModel | undefined; isNew: boolean }>()); + const editor = upcastPartial<BrowserEditor>({ + onDidChangeModel: onDidChangeModel.event, + layoutBrowserContainer: () => { }, + }); + const feature = store.add(instantiationService.createInstance(SessionsBrowserEmptyState, editor)); + const root = append(mainWindow.document.body, $('.agent-sessions-workbench.browser-root')); + root.style.cssText = 'width: 400px; height: 300px;'; + store.add(toDisposable(() => root.remove())); + const outside = append(root, $('button', undefined, 'Outside')); + append(root, feature.widgets[0].element); + const wrapper = append(root, $('.browser-container-wrapper')); + const viewport = append(wrapper, $('.browser-container', { tabIndex: 0 })); + feature.onContainerCreated(viewport); + outside.focus(); + const blankClaimed = feature.tryFocus(); + const blankFocus = mainWindow.document.activeElement?.closest('.sessions-add-tab-watermark-entry')?.textContent; + feature.prerenderInput(upcastPartial<BrowserEditorInput>({ url: 'https://example.com' })); + outside.focus(); + const loadedClaimed = feature.tryFocus(); + assert.deepStrictEqual({ + blankClaimed, + blankFocus, + loadedClaimed, + loadedFocusPreserved: mainWindow.document.activeElement === outside, + }, { + blankClaimed: true, + blankFocus: 'Open Address...', + loadedClaimed: false, + loadedFocusPreserved: true, + }); + }); +}); diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/emptyStates.fixture.ts b/src/vs/sessions/contrib/editor/test/electron-browser/emptyStates.fixture.ts similarity index 65% rename from src/vs/workbench/test/browser/componentFixtures/sessions/emptyStates.fixture.ts rename to src/vs/sessions/contrib/editor/test/electron-browser/emptyStates.fixture.ts index a3e13c6695433e..b671fe18c6484a 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/emptyStates.fixture.ts +++ b/src/vs/sessions/contrib/editor/test/electron-browser/emptyStates.fixture.ts @@ -26,40 +26,44 @@ import { IQuickInputService, IQuickPick, IQuickPickItem } from '../../../../../p import { QuickInputService } from '../../../../../platform/quickinput/browser/quickInputService.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; import { IOutlineModelService } from '../../../../../editor/contrib/documentSymbols/browser/outlineModel.js'; -import { createBrowserWelcome } from '../../../../contrib/browserView/browser/browserWelcome.js'; -import { IChatWidgetService, IQuickChatService } from '../../../../contrib/chat/browser/chat.js'; -import { IExternalUriOpenerService } from '../../../../contrib/externalUriOpener/common/externalUriOpenerService.js'; -import { NEW_UNTITLED_FILE_COMMAND_ID } from '../../../../contrib/files/browser/fileConstants.js'; -import '../../../../contrib/search/browser/searchQuickAccess.contribution.js'; -import { IDecorationsService } from '../../../../services/decorations/common/decorations.js'; -import { ICustomEditorLabelService } from '../../../../services/editor/common/customEditorLabelService.js'; -import { IEditorService } from '../../../../services/editor/common/editorService.js'; -import { IEditorGroup, IEditorGroupsService } from '../../../../services/editor/common/editorGroupsService.js'; -import { IWorkbenchEnvironmentService } from '../../../../services/environment/common/environmentService.js'; -import { IFilesConfigurationService } from '../../../../services/filesConfiguration/common/filesConfigurationService.js'; -import { IHistoryService } from '../../../../services/history/common/history.js'; -import { IWorkbenchLayoutService } from '../../../../services/layout/browser/layoutService.js'; -import { INotebookDocumentService } from '../../../../services/notebook/common/notebookDocumentService.js'; -import { IOutlineService } from '../../../../services/outline/browser/outline.js'; -import { IPathService } from '../../../../services/path/common/pathService.js'; -import { IFileQuery, ISearchComplete, ISearchService } from '../../../../services/search/common/search.js'; -import { ITextFileService } from '../../../../services/textfile/common/textfiles.js'; -import { IWorkingCopyService } from '../../../../services/workingCopy/common/workingCopyService.js'; -import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices, waitForFixtureCondition } from '../fixtureUtils.js'; +import { BrowserEditor } from '../../../../../workbench/contrib/browserView/electron-browser/browserEditor.js'; +import '../../../../../workbench/contrib/browserView/electron-browser/features/browserNavigationFeatures.js'; +import '../../../../../workbench/contrib/browserView/electron-browser/features/browserWelcomeFeature.js'; +import { BrowserViewCommandId } from '../../../../../platform/browserView/common/browserView.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { IPreferencesService } from '../../../../../workbench/services/preferences/common/preferences.js'; +import { TestLayoutService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { IChatWidgetService, IQuickChatService } from '../../../../../workbench/contrib/chat/browser/chat.js'; +import { IExternalUriOpenerService } from '../../../../../workbench/contrib/externalUriOpener/common/externalUriOpenerService.js'; +import { NEW_UNTITLED_FILE_COMMAND_ID } from '../../../../../workbench/contrib/files/browser/fileConstants.js'; +import '../../../../../workbench/contrib/search/browser/searchQuickAccess.contribution.js'; +import { IDecorationsService } from '../../../../../workbench/services/decorations/common/decorations.js'; +import { ICustomEditorLabelService } from '../../../../../workbench/services/editor/common/customEditorLabelService.js'; +import { IEditorService } from '../../../../../workbench/services/editor/common/editorService.js'; +import { IEditorGroup, IEditorGroupsService } from '../../../../../workbench/services/editor/common/editorGroupsService.js'; +import { IWorkbenchEnvironmentService } from '../../../../../workbench/services/environment/common/environmentService.js'; +import { IFilesConfigurationService } from '../../../../../workbench/services/filesConfiguration/common/filesConfigurationService.js'; +import { IHistoryService } from '../../../../../workbench/services/history/common/history.js'; +import { IWorkbenchLayoutService } from '../../../../../workbench/services/layout/browser/layoutService.js'; +import { INotebookDocumentService } from '../../../../../workbench/services/notebook/common/notebookDocumentService.js'; +import { IOutlineService } from '../../../../../workbench/services/outline/browser/outline.js'; +import { IPathService } from '../../../../../workbench/services/path/common/pathService.js'; +import { IFileQuery, ISearchComplete, ISearchService } from '../../../../../workbench/services/search/common/search.js'; +import { ITextFileService } from '../../../../../workbench/services/textfile/common/textfiles.js'; +import { IWorkingCopyService } from '../../../../../workbench/services/workingCopy/common/workingCopyService.js'; +import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices, waitForFixtureCondition } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; -// eslint-disable-next-line local/code-import-patterns import { Menus } from '../../../../../sessions/browser/menus.js'; -// eslint-disable-next-line local/code-import-patterns import { EmptyFileEditor } from '../../../../../sessions/contrib/editor/browser/emptyFileEditor.js'; -// eslint-disable-next-line local/code-import-patterns import '../../../../../sessions/contrib/editor/browser/emptyFileEditor.contribution.js'; -// eslint-disable-next-line local/code-import-patterns import { EmptyFileEditorInput } from '../../../../../sessions/contrib/editor/browser/emptyFileEditorInput.js'; -// eslint-disable-next-line local/code-import-patterns import { SESSIONS_EMPTY_FILE_EDITOR_ACTIONS_SETTING } from '../../../../../sessions/common/sessionConfig.js'; -// eslint-disable-next-line local/code-import-patterns -import { renderSessionsEmptyState } from '../../../../../sessions/browser/parts/sessionsEmptyState.js'; -// eslint-disable-next-line local/code-import-patterns +import { ChangesEmptyState } from '../../../../../sessions/contrib/changes/browser/changesEmptyState.js'; +import '../../../../../sessions/contrib/editor/electron-browser/browserEmptyState.contribution.js'; +import { FixtureKeybindingService } from '../../../../../sessions/test/browser/addTabFixtureUtils.js'; +import { NEW_FILE_TAB_COMMAND_ID } from '../../../../../sessions/common/sessionCommands.js'; +import { OpenEditorCommandId } from '../../../../../workbench/contrib/searchEditor/browser/constants.js'; import '../../../../../sessions/browser/parts/media/editorPart.css'; const FIXTURE_WIDTH = 600; @@ -89,8 +93,8 @@ function createMockEditorGroup(): IEditorGroup { }(); } -function prepareContainer(container: HTMLElement): HTMLElement { - container.style.width = `${FIXTURE_WIDTH}px`; +function prepareContainer(container: HTMLElement, width = FIXTURE_WIDTH): HTMLElement { + container.style.width = `${width}px`; container.style.height = `${FIXTURE_HEIGHT}px`; container.style.position = 'relative'; container.style.overflow = 'hidden'; @@ -99,6 +103,7 @@ function prepareContainer(container: HTMLElement): HTMLElement { const editorPart = dom.append(container, dom.$('.part.editor')); editorPart.style.width = '100%'; editorPart.style.height = '100%'; + editorPart.style.backgroundColor = 'var(--vscode-editor-background)'; return editorPart; } @@ -218,8 +223,8 @@ async function renderFilesEmptyState(context: ComponentFixtureContext, searchVal editor.create(editorPart); editor.layout(new dom.Dimension(FIXTURE_WIDTH, FIXTURE_HEIGHT)); await waitForFixtureCondition( - () => container.querySelectorAll('.empty-file-editor-actions .monaco-button').length === 1, - 'Files empty-state fixture did not render the New File action', + () => container.querySelectorAll('.empty-file-editor-actions .sessions-add-tab-watermark-entry').length === 2, + 'Files empty-state fixture did not render its action rows', ); if (searchValue) { @@ -251,7 +256,7 @@ async function renderFilesEmptyState(context: ComponentFixtureContext, searchVal () => { const widget = container.querySelector<HTMLElement>('.quick-input-widget.quick-input-widget-overlay'); const pickerFilter = widget?.querySelector<HTMLElement>('.quick-input-filter'); - const anchor = container.querySelector<HTMLElement>('.empty-file-editor-search-input .monaco-inputbox'); + const anchor = container.querySelector<HTMLElement>('.empty-file-editor-search .monaco-inputbox'); if (!widget || !pickerFilter || !anchor || container.querySelectorAll('.quick-input-list .monaco-list-row').length < 4 || container.querySelector('.quick-input-list .monaco-list-row')?.classList.contains('focused') !== true) { @@ -283,61 +288,89 @@ async function renderFilesEmptyState(context: ComponentFixtureContext, searchVal } } -function renderBrowserEmptyState({ container }: ComponentFixtureContext): void { - const browserRoot = dom.append(prepareContainer(container), dom.$('.browser-root')); - browserRoot.style.position = 'relative'; - browserRoot.style.width = '100%'; - browserRoot.style.height = '100%'; - - const browserContainerWrapper = dom.append(browserRoot, dom.$('.browser-container-wrapper')); - browserContainerWrapper.style.position = 'relative'; - browserContainerWrapper.style.width = '100%'; - browserContainerWrapper.style.height = '100%'; - - const browserContainer = dom.append(browserContainerWrapper, dom.$('.browser-container')); - browserContainer.style.position = 'absolute'; - browserContainer.style.inset = '0'; +function createEmptyStateServices({ disposableStore, theme }: ComponentFixtureContext) { + return createEditorServices(disposableStore, { + colorTheme: theme, + additionalServices: reg => { + registerWorkbenchServices(reg); + reg.define(IMenuService, MenuService); + reg.define(IContextKeyService, ContextKeyService); + reg.define(ILayoutService, TestLayoutService); + reg.defineInstance(IPreferencesService, new class extends mock<IPreferencesService>() { }()); + reg.defineInstance(IKeybindingService, new FixtureKeybindingService([ + { id: BrowserViewCommandId.FocusUrlInput, title: 'Open Address...', icon: Codicon.link, keybinding: KeyMod.CtrlCmd | KeyCode.KeyL }, + { id: BrowserViewCommandId.ShowHistory, title: 'History', icon: Codicon.history, keybinding: KeyMod.CtrlCmd | KeyCode.KeyY }, + { id: NEW_FILE_TAB_COMMAND_ID, title: 'Open Files', icon: Codicon.files, keybinding: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyE }, + { id: OpenEditorCommandId, title: 'Search in Files', icon: Codicon.search, keybinding: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyF }, + ])); + }, + }); +} - const placeholderContents = dom.append(browserContainer, dom.$('.browser-placeholder-contents')); - placeholderContents.style.position = 'relative'; - placeholderContents.style.width = '100%'; - placeholderContents.style.height = '100%'; - placeholderContents.appendChild(createBrowserWelcome('Browser', 'Use Add Element to Chat to reference UI elements in chat prompts.')); +function renderBrowserEmptyState(context: ComponentFixtureContext, width = FIXTURE_WIDTH, focusHistory = false): void { + const editorPart = prepareContainer(context.container, width); + const instantiationService = createEmptyStateServices(context); + const editor = context.disposableStore.add(instantiationService.createInstance(BrowserEditor, createMockEditorGroup())); + editor.create(editorPart); + editor.layout(new dom.Dimension(width, FIXTURE_HEIGHT)); + if (focusHistory) { + const rows = editorPart.querySelectorAll<HTMLElement>('.sessions-browser-empty-state .sessions-add-tab-watermark-entry'); + if (rows.length !== 2) { + throw new Error('Expected Open Address and History action rows'); + } + context.focus(rows[1]); + } } -function renderChangesEmptyState({ container }: ComponentFixtureContext): void { - const editorPart = prepareContainer(container); +function renderChangesEmptyState(context: ComponentFixtureContext, width = FIXTURE_WIDTH): void { + const editorPart = prepareContainer(context.container, width); editorPart.style.display = 'flex'; editorPart.style.alignItems = 'center'; editorPart.style.justifyContent = 'center'; - renderSessionsEmptyState(editorPart, 'Changes', 'No changed files'); + context.disposableStore.add(createEmptyStateServices(context).createInstance(ChangesEmptyState, editorPart)); } export default defineThemedFixtureGroup({ path: 'sessions/emptyStates/' }, { Files: defineComponentFixture({ labels: { kind: 'screenshot' }, - additionalThemes: ['darkHighContrast'], - expectedVisualDescriptions: ['A Files empty state is centered horizontally and positioned above the vertical midpoint. It has a semibold "Files" title, the secondary text "Select a file from the Files view", only a standalone icon-free Search files by name input, and a New File button with a file-add icon as the secondary action. The idle search input has no visible outer Quick Pick shell.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['Open File aligns vertically with the main empty panel first action. The Search files by name input sits above the buttons, followed by New File, with no repeated heading or description.'], render: renderFilesEmptyState, }), FilesWithSearchResults: defineComponentFixture({ labels: { kind: 'screenshot' }, deferPaint: true, virtualTime: { enabled: false }, - additionalThemes: ['darkHighContrast'], - expectedVisualDescriptions: ['A Files empty state is centered horizontally and positioned above the vertical midpoint. It has a semibold "Files" title and the secondary text "Select a file from the Files view". A native anchored Quick Pick overlays the idle search input in exactly the same position and renders its standard input, compact file result rows without item action buttons, background, spacing, typography, and first-result selection feedback. The surface covers rather than moves the New File button behind it.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['A native anchored Quick Pick overlays the centered file search field without moving it. Compact file result rows cover rather than move the Open File and New File action rows below.'], render: context => renderFilesEmptyState(context, 'app'), }), Browser: defineComponentFixture({ labels: { kind: 'screenshot' }, - additionalThemes: ['darkHighContrast'], - expectedVisualDescriptions: ['A centered Browser empty state has a semibold "Browser" title directly above a secondary two-line description, with no globe icon.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['The address/search control remains in the normal full-width browser toolbar at the top. Open Address aligns vertically with the main empty panel first action, followed by History, without a repeated Browser heading or globe illustration.'], render: renderBrowserEmptyState, }), + BrowserNarrow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: context => renderBrowserEmptyState(context, 240), + }), + BrowserHistoryFocused: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['Both Browser action rows and shortcut chips are fully visible, including the entire focus outline around the bottom History row.'], + render: context => renderBrowserEmptyState(context, FIXTURE_WIDTH, true), + }), Changes: defineComponentFixture({ labels: { kind: 'screenshot' }, - additionalThemes: ['darkHighContrast'], - expectedVisualDescriptions: ['A centered Changes empty state has a semibold "Changes" title directly above the secondary text "No changed files", with no icon.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['Open Files aligns vertically with the main empty panel first action. The No changed files status sits above it and Search in Files below it, without a repeated Changes heading.'], render: renderChangesEmptyState, }), + ChangesNarrow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + render: context => renderChangesEmptyState(context, 240), + }), }); diff --git a/src/vs/sessions/contrib/github/browser/issueActions.ts b/src/vs/sessions/contrib/github/browser/issueActions.ts index 50ffc23f741d0c..fd4860130eaa4f 100644 --- a/src/vs/sessions/contrib/github/browser/issueActions.ts +++ b/src/vs/sessions/contrib/github/browser/issueActions.ts @@ -12,6 +12,8 @@ import { ServicesAccessor } from '../../../../platform/instantiation/common/inst import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { IURLService } from '../../../../platform/url/common/url.js'; import { IExtensionService } from '../../../../workbench/services/extensions/common/extensions.js'; +import { Menus, SessionActivityBarGroup } from '../../../browser/menus.js'; +import { sessionActivityBarChatActionContext } from '../../../common/contextkeys.js'; import { ISessionsService } from '../../../services/sessions/browser/sessionsService.js'; import { IGitHubIssueRef, ISession } from '../../../services/sessions/common/session.js'; import { IActiveSession } from '../../../services/sessions/common/sessionsManagement.js'; @@ -46,6 +48,12 @@ class OpenIssueAction extends Action2 { title: localize2('agentSessions.openIssue', 'Open Issue'), icon: Codicon.issues, f1: false, + menu: { + id: Menus.SessionActivityBar, + group: SessionActivityBarGroup.GitHub, + order: 1, + when: sessionActivityBarChatActionContext(OpenIssueAction.ID), + }, }); } diff --git a/src/vs/sessions/contrib/github/browser/pullRequestActions.ts b/src/vs/sessions/contrib/github/browser/pullRequestActions.ts index f1a1f4e5e0bd0c..11322ba8f4f1a5 100644 --- a/src/vs/sessions/contrib/github/browser/pullRequestActions.ts +++ b/src/vs/sessions/contrib/github/browser/pullRequestActions.ts @@ -5,21 +5,56 @@ import { Codicon } from '../../../../base/common/codicons.js'; import { URI } from '../../../../base/common/uri.js'; -import { localize2 } from '../../../../nls.js'; -import { Action2, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { Categories } from '../../../../platform/action/common/actionCommonCategories.js'; +import { Action2, MenuRegistry, registerAction2 } from '../../../../platform/actions/common/actions.js'; import { IClipboardService } from '../../../../platform/clipboard/common/clipboardService.js'; +import { IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; import { ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; import { IOpenerService } from '../../../../platform/opener/common/opener.js'; import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; -import { Menus } from '../../../browser/menus.js'; +import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { Menus, SessionActivityBarGroup } from '../../../browser/menus.js'; import { IAgentWorkbenchLayoutService } from '../../../browser/workbench.js'; -import { SessionHasPullRequestContext } from '../../../common/contextkeys.js'; +import { DesktopLayoutContext, sessionActivityBarChatActionContext, SessionHasPullRequestContext } from '../../../common/contextkeys.js'; +import { SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../../common/sessionConfig.js'; import { ISessionsService } from '../../../services/sessions/browser/sessionsService.js'; import { getGitHubPullRequestRefs, IGitHubPullRequestRef, ISession } from '../../../services/sessions/common/session.js'; import { IActiveSession } from '../../../services/sessions/common/sessionsManagement.js'; import { OPEN_PULL_REQUEST_ACTION_ID, OPEN_PULL_REQUEST_CHANGES_ACTION_ID } from '../common/types.js'; import { createPullRequestChangesEditorInput } from './pullRequestChangesMultiDiffSourceResolver.js'; +export const TOGGLE_SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_COMMAND_ID = 'workbench.action.agentSessions.toggleSessionActivityBarGitHubActions'; + +registerAction2(class ToggleSessionActivityBarGitHubActionsAction extends Action2 { + constructor() { + super({ + id: TOGGLE_SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_COMMAND_ID, + title: localize2('toggleSessionActivityBarGitHubActions', "Toggle Pull Request and Issue Actions in Session Activity Bar"), + category: Categories.View, + f1: true, + precondition: ContextKeyExpr.and(DesktopLayoutContext, ChatContextKeys.enabled, ContextKeyExpr.equals(`config.${SESSION_ACTIVITY_BAR_SETTING}`, true)), + toggled: ContextKeyExpr.equals(`config.${SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING}`, true), + }); + } + + override run(accessor: ServicesAccessor): Promise<void> { + const configurationService = accessor.get(IConfigurationService); + return configurationService.updateValue(SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, !configurationService.getValue<boolean>(SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING)); + } +}); + +MenuRegistry.appendMenuItem(Menus.SessionActivityBarContext, { + command: { + id: TOGGLE_SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_COMMAND_ID, + title: localize('showSessionActivityBarGitHubActions', "Show Pull Request and Issue Actions"), + toggled: ContextKeyExpr.equals(`config.${SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING}`, true), + }, + group: '1_configuration', + when: ChatContextKeys.enabled, +}); + class PullRequestActionContext { constructor(readonly pullRequest: IGitHubPullRequestRef) { } } @@ -51,6 +86,11 @@ class OpenPullRequestAction extends Action2 { group: '2_pullRequest', order: 0, when: SessionHasPullRequestContext + }, { + id: Menus.SessionActivityBar, + group: SessionActivityBarGroup.GitHub, + order: 0, + when: sessionActivityBarChatActionContext(OpenPullRequestAction.ID) }], }); } diff --git a/src/vs/sessions/contrib/github/test/browser/issueActions.test.ts b/src/vs/sessions/contrib/github/test/browser/issueActions.test.ts index 4eaad33f51243c..c8fd9514265a86 100644 --- a/src/vs/sessions/contrib/github/test/browser/issueActions.test.ts +++ b/src/vs/sessions/contrib/github/test/browser/issueActions.test.ts @@ -7,15 +7,19 @@ import assert from 'assert'; import { Codicon } from '../../../../../base/common/codicons.js'; import { constObservable } from '../../../../../base/common/observable.js'; import { URI, UriComponents } from '../../../../../base/common/uri.js'; -import { mock } from '../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; +import { isIMenuItem, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; import { IClipboardService } from '../../../../../platform/clipboard/common/clipboardService.js'; +import { Context } from '../../../../../platform/contextkey/browser/contextKeyService.js'; import { IExtensionDescription } from '../../../../../platform/extensions/common/extensions.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; import { IOpenURLOptions, IURLService } from '../../../../../platform/url/common/url.js'; import { IExtensionService } from '../../../../../workbench/services/extensions/common/extensions.js'; +import { Menus, SessionActivityBarGroup } from '../../../../browser/menus.js'; +import { sessionActivityBarChatActionContext } from '../../../../common/contextkeys.js'; import { ISessionsService } from '../../../../services/sessions/browser/sessionsService.js'; import { IActiveSession } from '../../../../services/sessions/common/sessionsManagement.js'; import { ISession, ISessionWorkspace } from '../../../../services/sessions/common/session.js'; @@ -77,6 +81,50 @@ suite('Issue Actions', () => { ensureNoDisposablesAreLeakedInTestSuite(); + test('Open Issue is available in the activity bar only with an associated issue', () => { + const items = MenuRegistry.getMenuItems(Menus.SessionActivityBar) + .filter(isIMenuItem) + .filter(item => item.command.id === 'workbench.agentSessions.action.openIssue'); + const withIssue = new Context(1, null); + withIssue.setValue(sessionActivityBarChatActionContext('workbench.agentSessions.action.openIssue').key, true); + const withoutIssue = new Context(2, null); + + assert.deepStrictEqual(items.map(item => ({ + group: item.group, + order: item.order, + icon: item.command.icon, + visibleWithIssue: item.when?.evaluate(withIssue), + visibleWithoutIssue: item.when?.evaluate(withoutIssue), + })), [{ + group: SessionActivityBarGroup.GitHub, + order: 1, + icon: Codicon.issues, + visibleWithIssue: true, + visibleWithoutIssue: false, + }]); + }); + + test('Open Issue falls back to the active session without an explicit target', async () => { + const issueUri = URI.parse('https://github.com/owner/repo/issues/7'); + const session = createSessionWithIssue(issueUri); + const instantiationService = new TestInstantiationService(); + const openerService = new TestOpenerService(); + instantiationService.stub(IOpenerService, openerService); + instantiationService.stub(IURLService, new TestURLService()); + instantiationService.stub(IExtensionService, new class extends mock<IExtensionService>() { + override async getExtension(): Promise<IExtensionDescription | undefined> { + return undefined; + } + }); + instantiationService.stub(ISessionsService, new class extends mock<ISessionsService>() { + override readonly activeSession = constObservable(upcastPartial<IActiveSession>({ workspace: session.workspace })); + }); + + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand('workbench.agentSessions.action.openIssue')!.handler(accessor)); + + assert.deepStrictEqual(openerService.opened, [{ resource: issueUri, openExternal: true }]); + }); + test('Open Issue opens externally when the GitHub Pull Requests extension is unavailable', async () => { const issueUri = URI.parse('https://github.com/owner/repo/issues/7'); const session = createSessionWithIssue(issueUri); diff --git a/src/vs/sessions/contrib/github/test/browser/pullRequestActions.test.ts b/src/vs/sessions/contrib/github/test/browser/pullRequestActions.test.ts index 2893e2e3366936..553ec4c4a875eb 100644 --- a/src/vs/sessions/contrib/github/test/browser/pullRequestActions.test.ts +++ b/src/vs/sessions/contrib/github/test/browser/pullRequestActions.test.ts @@ -13,16 +13,22 @@ import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/tes import { CommandsRegistry } from '../../../../../platform/commands/common/commands.js'; import { isIMenuItem, MenuRegistry } from '../../../../../platform/actions/common/actions.js'; import { IClipboardService } from '../../../../../platform/clipboard/common/clipboardService.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { Context } from '../../../../../platform/contextkey/browser/contextKeyService.js'; +import { ContextKeyExpr } from '../../../../../platform/contextkey/common/contextkey.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { IOpenerService } from '../../../../../platform/opener/common/opener.js'; import { IResourceMultiDiffEditorInput, isResourceMultiDiffEditorInput } from '../../../../../workbench/common/editor.js'; import { IEditorService } from '../../../../../workbench/services/editor/common/editorService.js'; -import { Menus } from '../../../../browser/menus.js'; +import { Menus, SessionActivityBarGroup } from '../../../../browser/menus.js'; import { IAgentWorkbenchLayoutService } from '../../../../browser/workbench.js'; -import { SessionHasPullRequestContext } from '../../../../common/contextkeys.js'; +import { sessionActivityBarChatActionContext, SessionHasPullRequestContext } from '../../../../common/contextkeys.js'; +import { SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING } from '../../../../common/sessionConfig.js'; import { IGitHubPullRequestRef, ISession, ISessionWorkspace } from '../../../../services/sessions/common/session.js'; import { ISessionsService } from '../../../../services/sessions/browser/sessionsService.js'; -import '../../browser/pullRequestActions.js'; +import { IActiveSession } from '../../../../services/sessions/common/sessionsManagement.js'; +import { TOGGLE_SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_COMMAND_ID } from '../../browser/pullRequestActions.js'; import { createPullRequestChangesEditorInput } from '../../browser/pullRequestChangesMultiDiffSourceResolver.js'; import { SessionPullRequestPresentationModel } from '../../browser/pullRequestIconStatus.js'; import { IGitHubService } from '../../browser/githubService.js'; @@ -76,9 +82,37 @@ class TestOpenerService extends mock<IOpenerService>() { } suite('Pull Request Actions', () => { - const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('opts GitHub activity actions in from a checked AI-gated context-menu item', async () => { + const item = MenuRegistry.getMenuItems(Menus.SessionActivityBarContext).filter(isIMenuItem) + .find(item => item.command.id === TOGGLE_SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_COMMAND_ID); + const configurationService = new class extends TestConfigurationService { + override updateValue(key: string, value: unknown): Promise<void> { + return this.setUserConfiguration(key, value); + } + }(); + store.add(configurationService.onDidChangeConfigurationEmitter); + const instantiationService = store.add(new TestInstantiationService()); + instantiationService.stub(IConfigurationService, configurationService); + const run = async () => { + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand(TOGGLE_SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_COMMAND_ID)!.handler(accessor)); + return configurationService.getValue(SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING); + }; + assert.deepStrictEqual({ + title: item?.command.title, + toggled: item?.command.toggled, + when: item?.when?.serialize(), + afterFirstRun: await run(), + afterSecondRun: await run(), + }, { + title: 'Show Pull Request and Issue Actions', + toggled: ContextKeyExpr.equals(`config.${SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING}`, true), + when: 'chatIsEnabled', + afterFirstRun: true, afterSecondRun: false, + }); + }); + test('shared presentation model preserves live pull request status icons', () => { const pullRequest = upcastPartial<IGitHubPullRequest>({ number: 1, @@ -218,6 +252,48 @@ suite('Pull Request Actions', () => { assert.deepStrictEqual(clipboardService.writes, [pullRequestUri.toString(true)]); }); + test('Open Pull Request is available in the activity bar only with an associated pull request', () => { + const items = MenuRegistry.getMenuItems(Menus.SessionActivityBar) + .filter(isIMenuItem) + .filter(item => item.command.id === 'workbench.agentSessions.action.openPullRequest'); + const withPullRequest = new Context(1, null); + withPullRequest.setValue(sessionActivityBarChatActionContext('workbench.agentSessions.action.openPullRequest').key, true); + const withoutPullRequest = new Context(2, null); + + assert.deepStrictEqual(items.map(item => ({ + group: item.group, + order: item.order, + icon: item.command.icon, + visibleWithPullRequest: item.when?.evaluate(withPullRequest), + visibleWithoutPullRequest: item.when?.evaluate(withoutPullRequest), + })), [{ + group: SessionActivityBarGroup.GitHub, + order: 0, + icon: Codicon.gitPullRequest, + visibleWithPullRequest: true, + visibleWithoutPullRequest: false, + }]); + }); + + test('Open Pull Request falls back to the active session without an explicit target', async () => { + const pullRequestUri = URI.parse('https://github.com/owner/repo/pull/1'); + const session = createSessionWithPullRequest(pullRequestUri); + const instantiationService = new TestInstantiationService(); + const openerService = new TestOpenerService(); + instantiationService.stub(IOpenerService, openerService); + instantiationService.stub(ISessionsService, new class extends mock<ISessionsService>() { + override readonly activeSession = constObservable(upcastPartial<IActiveSession>({ workspace: session.workspace })); + }); + + await instantiationService.invokeFunction(accessor => CommandsRegistry.getCommand('workbench.agentSessions.action.openPullRequest')!.handler(accessor)); + + assert.deepStrictEqual(openerService.opened, [{ + resource: pullRequestUri, + openExternal: true, + allowContributedOpeners: true, + }]); + }); + test('Copy Pull Request URL is a no-op when the session has no pull request', async () => { const session = createSessionWithPullRequest(undefined); diff --git a/src/vs/sessions/contrib/layout/browser/desktop/desktopDraftSessionStrategy.ts b/src/vs/sessions/contrib/layout/browser/desktop/desktopDraftSessionStrategy.ts index d748207b2d6a10..69a310db71ac28 100644 --- a/src/vs/sessions/contrib/layout/browser/desktop/desktopDraftSessionStrategy.ts +++ b/src/vs/sessions/contrib/layout/browser/desktop/desktopDraftSessionStrategy.ts @@ -5,6 +5,7 @@ import { mainWindow } from '../../../../../base/browser/window.js'; import { Event } from '../../../../../base/common/event.js'; +import { ResourceMap } from '../../../../../base/common/map.js'; import { autorun, IObservable, @@ -20,6 +21,7 @@ import { IEditorService } from '../../../../../workbench/services/editor/common/ import { Parts } from '../../../../../workbench/services/layout/browser/layoutService.js'; import { IAgentWorkbenchLayoutService } from '../../../../browser/workbench.js'; import { ISessionsService } from '../../../../services/sessions/browser/sessionsService.js'; +import { IActiveSession } from '../../../../services/sessions/common/sessionsManagement.js'; import { ISessionChangesService } from '../../../changes/browser/sessionChangesService.js'; import { EmptyFileEditorInput } from '../../../editor/browser/emptyFileEditorInput.js'; import { ISessionWorkspace } from '../../../../services/sessions/common/session.js'; @@ -53,6 +55,7 @@ export class DesktopDraftSessionStrategy extends DesktopLayoutStrategy { private _pendingEditorRestoreKey: string | undefined; private _changingVisibility = false; private _togglingQuickChatSidePane = false; + private readonly _quickChatSidePaneVisibility = new ResourceMap<boolean>(); constructor( ctx: IDesktopLayoutContext, @@ -263,7 +266,7 @@ export class DesktopDraftSessionStrategy extends DesktopLayoutStrategy { ? sessionKey : undefined; if (!multipleSessionsVisible && hasSavedWorkingSet) { - this._applyQuickChatSharedVisibility(); + this._applyQuickChatVisibility(); } else if (!multipleSessionsVisible && !isRestoringSessionLayout && isMainPartEmpty(this._editorGroupsService)) { this._pendingEditorRestoreKey = undefined; this._hideQuickChatSidePaneTransiently(); @@ -291,7 +294,7 @@ export class DesktopDraftSessionStrategy extends DesktopLayoutStrategy { return; } - this._applyQuickChatSharedVisibility(); + this._applyQuickChatVisibility(); })); this._register(this._layoutService.onDidChangePartVisibility(event => { @@ -305,13 +308,20 @@ export class DesktopDraftSessionStrategy extends DesktopLayoutStrategy { this._register(this._layoutService.onDidToggleSidePane(({ before, after }) => { try { const activeSession = this._sessionsService.activeSession.get(); - const opened = !before.editor && !before.auxiliaryBar && (after.editor || after.auxiliaryBar); - if (opened - && activeSession?.isQuickChat?.get() - && !this._ctx.chatLayoutSuspended() - && !this._ctx.multipleSessionsVisibleObs.get() - && !isMainPartEmpty(this._editorGroupsService)) { - this._applyQuickChatSharedVisibility(); + if (!activeSession?.isQuickChat?.get() + || this._ctx.chatLayoutSuspended() + || this._ctx.multipleSessionsVisibleObs.get() + || isMainPartEmpty(this._editorGroupsService)) { + return; + } + const wasVisible = before.editor || before.auxiliaryBar; + const isVisible = after.editor || after.auxiliaryBar; + const ownerKey = this._quickChatVisibilityOwnerKey(activeSession); + if (ownerKey && wasVisible !== isVisible) { + this._quickChatSidePaneVisibility.set(ownerKey, isVisible); + } + if (!wasVisible && isVisible) { + this._applyQuickChatVisibility(); } } finally { this._togglingQuickChatSidePane = false; @@ -336,8 +346,13 @@ export class DesktopDraftSessionStrategy extends DesktopLayoutStrategy { return; } + const editorVisible = this._layoutService.isVisible(Parts.EDITOR_PART, mainWindow); + const ownerKey = this._quickChatVisibilityOwnerKey(activeSession); + if (ownerKey) { + this._quickChatSidePaneVisibility.set(ownerKey, this._layoutService.isSidePaneVisible()); + } this._visibilityStore.set(SessionVisibilityProfile.Existing, { - editorVisible: this._layoutService.isVisible(Parts.EDITOR_PART, mainWindow), + editorVisible, auxiliaryBarVisible: false, }); } @@ -351,10 +366,26 @@ export class DesktopDraftSessionStrategy extends DesktopLayoutStrategy { } } - private _applyQuickChatSharedVisibility(): void { + /** + * The key for a Quick Chat's own side-pane visibility, which only exists in the + * chat-specific layout mode. + */ + private _quickChatVisibilityOwnerKey(session: IActiveSession): URI | undefined { + return session.isQuickChat?.get() && this._ctx.chatLayoutActive() && !this._ctx.sharedChatLayout ? this._ctx.ownerKeyFor(session) : undefined; + } + + /** + * In the chat-specific layout mode, applies the active Quick Chat's own last side-pane + * visibility, revealing a closed side pane for it. Otherwise, or when none has been recorded + * in this window, applies the shared Existing profile without revealing a closed side pane. + */ + private _applyQuickChatVisibility(): void { + const activeSession = this._sessionsService.activeSession.get(); + const ownerKey = activeSession && this._quickChatVisibilityOwnerKey(activeSession); + const ownVisibility = ownerKey ? this._quickChatSidePaneVisibility.get(ownerKey) : undefined; const sharedState = this._visibilityStore.get(SessionVisibilityProfile.Existing); - const sidePaneVisible = sharedState.editorVisible || sharedState.auxiliaryBarVisible; - const allowReveal = this._layoutService.isSidePaneVisible(); + const sidePaneVisible = ownVisibility ?? (sharedState.editorVisible || sharedState.auxiliaryBarVisible); + const allowReveal = ownVisibility !== undefined || this._layoutService.isSidePaneVisible(); const suppression = this._layoutService.suppressEditorPartAutoVisibility(); this._changingVisibility = true; try { diff --git a/src/vs/sessions/contrib/layout/browser/sessions.layout.contribution.ts b/src/vs/sessions/contrib/layout/browser/sessions.layout.contribution.ts index 5700881cf1c8b5..59f3edabcfcaff 100644 --- a/src/vs/sessions/contrib/layout/browser/sessions.layout.contribution.ts +++ b/src/vs/sessions/contrib/layout/browser/sessions.layout.contribution.ts @@ -15,7 +15,7 @@ import { ConfigurationScope, Extensions, IConfigurationRegistry } from '../../.. import product from '../../../../platform/product/common/product.js'; import { Registry } from '../../../../platform/registry/common/platform.js'; import { SESSIONS_LAYOUT_SCOPE_SETTING } from '../../../common/chatLayout.js'; -import { LEGACY_SESSION_TOOLBAR_SETTING, SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../../common/sessionConfig.js'; +import { LEGACY_SESSION_TOOLBAR_SETTING, SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_LAYOUT_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../../common/sessionConfig.js'; import { ConfigurationKeyValuePairs, Extensions as WorkbenchConfigurationExtensions, IConfigurationMigrationRegistry } from '../../../../workbench/common/configuration.js'; import { ISessionEditorWorkingSetService, SessionEditorWorkingSetService } from '../common/sessionEditorWorkingSet.js'; @@ -71,6 +71,11 @@ Registry.as<IConfigurationRegistry>(Extensions.Configuration).registerConfigurat default: false, markdownDescription: localize('sessions.sessionActivityBar.showLayoutActions', "Controls whether the Session Activity Bar shows the Toggle Side Panel and Toggle Panel actions in place of their title bar buttons. Only applies when {0} is enabled.", '`#sessions.showSessionActivityBar#`'), }, + [SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING]: { + type: 'boolean', + default: false, + markdownDescription: localize('sessions.sessionActivityBar.showGitHubActions', "Controls whether the Session Activity Bar shows pull request and issue actions for the active chat when a contributed opener is available for their links. Does not affect pills above the chat input. Only applies when {0} is enabled.", '`#sessions.showSessionActivityBar#`'), + }, }, }); diff --git a/src/vs/sessions/contrib/layout/test/browser/desktopStrategies.test.ts b/src/vs/sessions/contrib/layout/test/browser/desktopStrategies.test.ts index 45dc9f158e4fde..1ab6954a1dee57 100644 --- a/src/vs/sessions/contrib/layout/test/browser/desktopStrategies.test.ts +++ b/src/vs/sessions/contrib/layout/test/browser/desktopStrategies.test.ts @@ -1278,4 +1278,49 @@ suite('Desktop layout strategies', () => { auxiliaryBarVisible: false, }); }); + + for (const mode of ['session-shared', 'chat-shared', 'chat'] as const) { + for (const leftOpen of [true, false]) { + test(`Quick Chat side pane left ${leftOpen ? 'open' : 'closed'} is ${mode === 'chat' ? 'restored' : 'shared'} (${mode})`, () => { + harness = createTestHarness(store); + const { ctx: baseCtx, state } = createStrategyTestContext(store, harness); + const ctx: IDesktopLayoutContext = { + ...baseCtx, + get isRestoringSessionLayout() { return baseCtx.isRestoringSessionLayout; }, + get togglingSidePane() { return baseCtx.togglingSidePane; }, + chatLayoutActive: () => mode !== 'session-shared', + sharedChatLayout: mode === 'chat-shared', + }; + const quickChat = makeSession(URI.parse('session:/quick'), { isQuickChat: true }); + const otherSession = makeSession(URI.parse('session:/other')); + state.setHasSavedWorkingSet(quickChat.resource, true); + const visibilityStore = createVisibilityStore(); + createDraftStrategy(ctx, visibilityStore); + const canvas = store.add(new TestStubEditorInput(URI.parse('canvas://quick'))); + + activate(quickChat); + harness.activeGroupEditors.push(canvas); + harness.editorGroupsHaveContent = true; + harness.activeEditorInput = canvas; + harness.partVisibility.set(Parts.AUXILIARYBAR_PART, false); + harness.partVisibility.set(Parts.EDITOR_PART, leftOpen); + harness.onDidChangePartVisibility.fire({ partId: Parts.EDITOR_PART, visible: leftOpen }); + + activate(otherSession); + harness.partVisibility.set(Parts.EDITOR_PART, !leftOpen); + visibilityStore.set(SessionVisibilityProfile.Existing, { editorVisible: !leftOpen, auxiliaryBarVisible: false }); + + activate(quickChat); + state.endSessionLayoutRestore(); + + assert.deepStrictEqual({ + editorVisible: harness.partVisibility.get(Parts.EDITOR_PART), + auxiliaryBarVisible: harness.partVisibility.get(Parts.AUXILIARYBAR_PART), + }, { + editorVisible: mode === 'chat' ? leftOpen : !leftOpen, + auxiliaryBarVisible: false, + }); + }); + } + } }); diff --git a/src/vs/sessions/contrib/layout/test/browser/sessions.layout.contribution.test.ts b/src/vs/sessions/contrib/layout/test/browser/sessions.layout.contribution.test.ts index 35911516d8b804..ff314ca9ef13c8 100644 --- a/src/vs/sessions/contrib/layout/test/browser/sessions.layout.contribution.test.ts +++ b/src/vs/sessions/contrib/layout/test/browser/sessions.layout.contribution.test.ts @@ -18,7 +18,7 @@ import { AgentWorkbenchLayout, IAgentWorkbenchLayoutService } from '../../../../ import { SESSIONS_LAYOUT_SCOPE_SETTING, ChatLayoutPresentation } from '../../../../common/chatLayout.js'; import { SessionsLayoutContribution } from '../../browser/sessions.layout.contribution.js'; import { ConfigurationMigration, Extensions as WorkbenchConfigurationExtensions, IConfigurationMigrationRegistry } from '../../../../../workbench/common/configuration.js'; -import { LEGACY_SESSION_TOOLBAR_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../../../common/sessionConfig.js'; +import { LEGACY_SESSION_TOOLBAR_SETTING, SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, SESSION_ACTIVITY_BAR_SETTING } from '../../../../common/sessionConfig.js'; // Capture registration before configuration tests reset the shared registry. const registeredProperties = { ...Registry.as<IConfigurationRegistry>(Extensions.Configuration).getConfigurationProperties() }; @@ -38,6 +38,13 @@ suite('Sessions chat layout configuration', () => { assert.deepStrictEqual(['sessions.experimental.chatSpecificLayout', 'sessions.layout.mode'].map(key => registeredProperties[key]), [undefined, undefined]); }); + test('registers GitHub activity actions as one opt-in setting', () => { + const property = registeredProperties[SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING]; + assert.deepStrictEqual({ + key: SESSION_ACTIVITY_BAR_GITHUB_ACTIONS_SETTING, type: property.type, default: property.default, + }, { key: 'sessions.sessionActivityBar.showGitHubActions', type: 'boolean', default: false }); + }); + test('migrates the Session Toolbar setting to the Session Activity Bar setting unless that is already set', async () => { const migration = Registry.as<IConfigurationMigrationRegistry & { readonly migrations: readonly ConfigurationMigration[] }>(WorkbenchConfigurationExtensions.ConfigurationMigration).migrations .find(migration => migration.key === LEGACY_SESSION_TOOLBAR_SETTING); diff --git a/src/vs/sessions/contrib/providers/agentHost/browser/baseAgentHostSessionsProvider.ts b/src/vs/sessions/contrib/providers/agentHost/browser/baseAgentHostSessionsProvider.ts index 9d2adb8247f3dd..b4f0dc18f38f05 100644 --- a/src/vs/sessions/contrib/providers/agentHost/browser/baseAgentHostSessionsProvider.ts +++ b/src/vs/sessions/contrib/providers/agentHost/browser/baseAgentHostSessionsProvider.ts @@ -8725,15 +8725,10 @@ export abstract class BaseAgentHostSessionsProvider extends Disposable implement if (!cached) { return; } - const previousChats = cached.chats.get(); cached.applyChatCatalog(state); this._cacheDirty = true; - // Session lists read `chats` when sessions change. Added and removed chats reach them with the root summary - // change, but a reorder of a subscribed session's chats leaves the root summary as it was. - const chats = cached.chats.get(); - if (!arrayEquals(previousChats, chats) && previousChats.length === chats.length && chats.every(chat => previousChats.includes(chat))) { - this._onDidChangeSessions.fire({ added: [], removed: [], changed: [cached] }); - } + // Chat order reaches consumers through the `chats` observable, not `onDidChangeSessions`: this runs + // while session lists observe chat details during rendering, and a session change would re-enter them. } /** diff --git a/src/vs/sessions/contrib/providers/agentHost/test/browser/localAgentHostSessionsProvider.test.ts b/src/vs/sessions/contrib/providers/agentHost/test/browser/localAgentHostSessionsProvider.test.ts index 0c9633bdb2fc16..b915b88d8f6a13 100644 --- a/src/vs/sessions/contrib/providers/agentHost/test/browser/localAgentHostSessionsProvider.test.ts +++ b/src/vs/sessions/contrib/providers/agentHost/test/browser/localAgentHostSessionsProvider.test.ts @@ -10948,6 +10948,37 @@ suite('LocalAgentHostSessionsProvider', () => { }); }); + test('a chat that moved away with its Agent Merge leaves its folder off for the chats that stay, at once', () => { + const provider = createProvider(disposables, agentHost); + const directory = URI.file('/workspace-moved-away'); + const session = setupMultiChatSession(provider, 'agent-merge-moved-away', [directory]); + const sessionUri = AgentSession.uri('copilotcli', 'agent-merge-moved-away').toString(); + const defaultChat = buildDefaultChatUri(sessionUri); + const movedChat = buildChatUri(sessionUri, 'moved'); + const meta = withWorkingDirectoryKey(undefined, directory.toString(), directory.toString()); + const setConfigValues = (values: Record<string, unknown>) => agentHost.setSessionState('agent-merge-moved-away', 'copilotcli', { + ...makeState([makeChatSummary(defaultChat, '', ProtocolSessionStatus.Idle, [directory.toString()])], { defaultChat, meta, workingDirectories: [directory.toString()] }), + config: { schema: { type: 'object', properties: {} }, values }, + }); + const mainChat = session.mainChat.get(); + const observable = provider.getAgentMergeClientStateObservable(session.sessionId, mainChat.resource); + const read = () => ({ state: provider.getAgentMergeSessionState(session.sessionId, mainChat.resource)?.enabled, observable: observable.get()?.enabled }); + setConfigValues({ [SessionConfigKey.AgentMergeFolders]: { [directory.toString()]: { enabled: true, chat: movedChat } } }); + const before = read(); + // What the host publishes for the source of the move: the folder is off, with nothing of the chat's. + setConfigValues({ [SessionConfigKey.AgentMergeFolders]: { [directory.toString()]: { enabled: false } } }); + const afterMove = read(); + setConfigValues({ [SessionConfigKey.AgentMergeFolders]: { [directory.toString()]: { enabled: true, chat: movedChat } } }); + // Had the host removed the folder's entry instead, clients would keep showing it on. + setConfigValues({ [SessionConfigKey.AgentMergeFolders]: {} }); + + assert.deepStrictEqual({ before, afterMove, afterRemoval: read() }, { + before: { state: true, observable: true }, + afterMove: { state: false, observable: false }, + afterRemoval: { state: true, observable: true }, + }); + }); + test('uses host-published folder keys and scope ids for mixed-case remote paths', () => { const provider = createProvider(disposables, agentHost); const primaryDirectory = URI.file('/work/MyRepo'); @@ -11718,7 +11749,7 @@ suite('LocalAgentHostSessionsProvider', () => { }); }); - test('tells session lists when a subscribed session reorders its chats, also when its root summary stays the same (Block 5)', async () => { + test('a subscribed session reorders its chats through its chats observable, also when its root summary stays the same (Block 5)', async () => { const provider = createProvider(disposables, agentHost); const session = setupMultiChatSession(provider, 'reorder-notify'); const sessionUri = AgentSession.uri('copilotcli', 'reorder-notify').toString(); @@ -11727,15 +11758,44 @@ suite('LocalAgentHostSessionsProvider', () => { const [first, second] = ['first', 'second'].map(id => buildDefaultChatUri(AgentSession.uri('copilotcli', id).toString())); const peer = (resource: string, title: string): ChatSummary => ({ ...makeChatSummary(resource, title), origin: { kind: ProtocolChatOriginKind.User }, movable: true }); agentHost.setSessionState('reorder-notify', 'copilotcli', makeState([makeChatSummary(defaultChat, ''), peer(first, 'First'), peer(second, 'Second')], { defaultChat })); - const changed: string[][] = []; - disposables.add(provider.onDidChangeSessions(e => changed.push(e.changed.filter(candidate => candidate.sessionId === session.sessionId).map(candidate => candidate.chats.get().map(chat => chat.title.get()).join(','))))); + // Session lists read `chats` reactively, so a reorder reaches them without a session change event. + const observed: string[] = []; + disposables.add(autorun(reader => observed.push(session.chats.read(reader).map(chat => chat.title.read(reader)).join(',')))); agentHost.setSessionState('reorder-notify', 'copilotcli', makeState([makeChatSummary(defaultChat, ''), peer(second, 'Second'), peer(first, 'First')], { defaultChat })); - // An added chat reaches session lists with the root summary change, not again from the catalog. const third = buildDefaultChatUri(AgentSession.uri('copilotcli', 'third').toString()); agentHost.setSessionState('reorder-notify', 'copilotcli', makeState([makeChatSummary(defaultChat, ''), peer(second, 'Second'), peer(first, 'First'), peer(third, 'Third')], { defaultChat })); - assert.deepStrictEqual(changed.filter(entry => entry.length > 0), [['Session,Second,First']]); + assert.deepStrictEqual(observed, ['Session,First,Second', 'Session,Second,First', 'Session,Second,First,Third']); + }); + + test('observing chat details applies a cached chat reorder without telling session lists while they observe', async () => { + const rawId = 'observe-cached-reorder'; + const sessionUri = AgentSession.uri('copilotcli', rawId).toString(); + const defaultChat = buildDefaultChatUri(sessionUri); + const [first, second] = ['first', 'second'].map(id => buildChatUri(sessionUri, id)); + agentHost.addSession(createSession(rawId, { + summary: 'Session', + chats: [ + { chat: URI.parse(defaultChat), kind: 'default', summary: 'Default' }, + { chat: URI.parse(first), kind: 'peer', summary: 'First' }, + { chat: URI.parse(second), kind: 'peer', summary: 'Second' }, + ], + })); + const provider = createProvider(disposables, agentHost); + provider.getSessions(); + await timeout(0); + const session = provider.getSessions().find(candidate => AgentSession.id(candidate.resource.toString()) === rawId); + assert.ok(session); + // Another client already holds the session's state, which orders its chats differently. + agentHost.setSessionState(rawId, 'copilotcli', makeState([makeChatSummary(defaultChat, 'Default'), makeChatSummary(second, 'Second'), makeChatSummary(first, 'First')], { defaultChat })); + const notified: string[] = []; + disposables.add(provider.onDidChangeSessions(e => notified.push(...e.changed.filter(candidate => candidate.sessionId === session.sessionId).map(candidate => candidate.sessionId)))); + + // Session list rows observe chat details while the list renders them, and must not be re-entered. + disposables.add(autorun(reader => session.chats.read(reader).at(-1)?.title.read(reader))); + + assert.deepStrictEqual({ notified, chats: session.chats.get().map(chat => chat.title.get()) }, { notified: [], chats: ['Default', 'Second', 'First'] }); }); test('explains a workspace-less refusal by whether the chat shares its scratch folder with another chat (Block 9)', async () => { diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/cloudSandboxAgentHostContribution.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/cloudSandboxAgentHostContribution.ts index 7fb73f61899bec..05fada01d4a938 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/cloudSandboxAgentHostContribution.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/cloudSandboxAgentHostContribution.ts @@ -12,7 +12,6 @@ import { isEqual } from '../../../../../base/common/resources.js'; import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { AgentSession } from '../../../../../platform/agentHost/common/agent.js'; -import { IAgentHostService } from '../../../../../platform/agentHost/common/agentService.js'; import { ChangesetKind } from '../../../../../platform/agentHost/common/changesetUri.js'; import { CLOUD_SANDBOX_AGENT_PROVIDER, CLOUD_SANDBOX_SESSION_SCHEME, cloudSandboxAddress, ICloudSandboxAgentHostService, ICloudSandboxApiService, ICloudSandboxCreatedSession, ICloudSandboxCreateSessionRequest, ICloudSandboxDraftPreparationService } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import { IRemoteAgentHostService } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; @@ -83,9 +82,8 @@ export class CloudSandboxAgentHostContribution extends CloudSandboxSessionContri @IHostService hostService: IHostService, @IStorageService storageService: IStorageService, @IWorkspaceTrustManagementService workspaceTrustManagementService: IWorkspaceTrustManagementService, - @IAgentHostService localAgentHostService: IAgentHostService, ) { - super(cloudSandboxService, apiService, draftPreparationService, _remoteService, _sandboxConnectionCustomizations, configurationService, instantiationService, chatSessionsService, logService, chatEntitlementService, hostService, storageService, workspaceTrustManagementService, localAgentHostService); + super(cloudSandboxService, apiService, draftPreparationService, _remoteService, _sandboxConnectionCustomizations, configurationService, instantiationService, chatSessionsService, logService, chatEntitlementService, hostService, storageService, workspaceTrustManagementService); this._updateRegistration(); this._register(this._agentHostFilterService.registerDiscoveryHandler(() => this._discoverAndSeed())); this._register(this._agentHostFilterService.onDidChange(() => { diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts index aa499eb4864381..43a65a9d131527 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/browser/remoteAgentHostActions.ts @@ -1154,7 +1154,7 @@ registerAction2(class extends Action2 { shortTitle: localize2('connectViaTunnelShort', "Tunnels"), category: SessionsCategories.Sessions, f1: true, - icon: Codicon.cloud, + icon: Codicon.remote, precondition: ContextKeyExpr.equals(`config.${RemoteAgentHostsEnabledSettingId}`, true), menu: { id: Menus.SessionWorkspaceManage, diff --git a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostActions.test.ts b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostActions.test.ts index d9311fe9c1fd38..9fe06b5f133734 100644 --- a/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostActions.test.ts +++ b/src/vs/sessions/contrib/providers/remoteAgentHost/test/browser/remoteAgentHostActions.test.ts @@ -33,10 +33,15 @@ import { SessionView } from '../../../../../browser/parts/sessionView.js'; import { ISessionWorkspace } from '../../../../../services/sessions/common/session.js'; import { ConnectMissionControlEnvironmentCommand } from '../../../../../../workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentActions.js'; import { TestNotificationService } from '../../../../../../platform/notification/test/common/testNotificationService.js'; +import { MenuRegistry } from '../../../../../../platform/actions/common/actions.js'; suite('Remote Agent Host actions', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('Tunnels uses the standard remote icon', () => { + assert.deepStrictEqual(MenuRegistry.getCommand(RemoteAgentHostCommandIds.connectViaTunnel)?.icon, Codicon.remote); + }); + for (const outcome of ['selected', 'cancelled-connection', 'cancelled-folder', 'missing-provider'] as const) { test(`Mission Control environment selection opens its folder picker: ${outcome}`, async () => { const instantiation = store.add(new TestInstantiationService()); diff --git a/src/vs/sessions/contrib/search/browser/media/searchEditorEmptyState.css b/src/vs/sessions/contrib/search/browser/media/searchEditorEmptyState.css index 6fe7bc41b15e96..2c174a59621164 100644 --- a/src/vs/sessions/contrib/search/browser/media/searchEditorEmptyState.css +++ b/src/vs/sessions/contrib/search/browser/media/searchEditorEmptyState.css @@ -10,6 +10,64 @@ align-items: center; justify-content: center; box-sizing: border-box; - padding: var(--vscode-spacing-size200); pointer-events: none; } + +.sessions-search-empty-state .sessions-empty-state-content { + width: min(320px, 100%); + pointer-events: auto; +} + +.agent-sessions-workbench .search-editor.search-editor-empty > .query-container { + --search-editor-query-controls-hidden: true; +} + +.agent-sessions-workbench.dock-detail-panel .part.editor .search-editor.search-editor-empty > .query-container { + margin: auto auto var(--vscode-spacing-size160); + padding: 0; + width: calc(100% - 2 * var(--vscode-spacing-size240)); + max-width: 320px; + min-height: 0; + border-bottom: 0; + grid-template-columns: minmax(0, 1fr); + column-gap: 0; +} + +.agent-sessions-workbench .search-editor.search-editor-empty .monaco-findInput > .controls, +.agent-sessions-workbench .search-editor.search-editor-empty .context-lines-input, +.agent-sessions-workbench .search-editor.search-editor-empty .search-container > .monaco-custom-toggle, +.agent-sessions-workbench .search-editor.search-editor-empty .query-container > .includes-excludes { + display: none; +} + +.agent-sessions-workbench .search-editor.search-editor-empty .monaco-findInput { + flex: 1 0 100%; +} + +.agent-sessions-workbench .search-editor.search-editor-empty .query-container > .messages { + margin-top: 0; +} + +.agent-sessions-workbench.dock-detail-panel .part.editor .search-editor.search-editor-empty > .search-results { + flex: 0 0 calc(2 * var(--vscode-spacing-size280)); + min-height: 0; + min-width: 0; + width: min(320px, calc(100% - 2 * var(--vscode-spacing-size240))); + margin: 0 auto auto; +} + +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .margin, +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .view-lines, +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .view-overlays, +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .cursors-layer, +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .scroll-decoration, +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .minimap, +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .decorationsOverviewRuler, +.agent-sessions-workbench .search-editor.search-editor-empty .search-results .scrollbar { + display: none; + visibility: hidden; +} + +.agent-sessions-workbench .search-editor.search-editor-empty .messages .message.prominent { + display: none; +} diff --git a/src/vs/sessions/contrib/search/browser/searchEditorEmptyState.contribution.ts b/src/vs/sessions/contrib/search/browser/searchEditorEmptyState.contribution.ts index c31b4ce9ccb06e..fd95dee4048344 100644 --- a/src/vs/sessions/contrib/search/browser/searchEditorEmptyState.contribution.ts +++ b/src/vs/sessions/contrib/search/browser/searchEditorEmptyState.contribution.ts @@ -4,22 +4,38 @@ *--------------------------------------------------------------------------------------------*/ import './media/searchEditorEmptyState.css'; -import { $ } from '../../../../base/browser/dom.js'; +import { $, append, isHTMLElement } from '../../../../base/browser/dom.js'; import { Disposable } from '../../../../base/common/lifecycle.js'; import { autorun, constObservable } from '../../../../base/common/observable.js'; import { ICodeEditor } from '../../../../editor/browser/editorBrowser.js'; import { EditorContributionInstantiation, registerEditorContribution } from '../../../../editor/browser/editorExtensions.js'; import { observableCodeEditor } from '../../../../editor/browser/observableCodeEditor.js'; import { IEditorContribution } from '../../../../editor/common/editorCommon.js'; -import { localize } from '../../../../nls.js'; -import { SearchEditorScheme } from '../../../../workbench/contrib/searchEditor/browser/constants.js'; -import { renderSessionsEmptyState } from '../../../browser/parts/sessionsEmptyState.js'; +import { localize, localize2 } from '../../../../nls.js'; +import { Action2, MenuRegistry, registerAction2 } from '../../../../platform/actions/common/actions.js'; +import { IInstantiationService, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; +import { InSearchEditor, SearchEditorScheme } from '../../../../workbench/contrib/searchEditor/browser/constants.js'; +import { SearchEditor } from '../../../../workbench/contrib/searchEditor/browser/searchEditor.js'; +import { IEditorService } from '../../../../workbench/services/editor/common/editorService.js'; +import { searchViewIcon } from '../../../../workbench/contrib/search/browser/searchIcons.js'; +import { Menus } from '../../../browser/menus.js'; +import { SessionsEmptyStateActions } from '../../../browser/parts/sessionsEmptyStateActions.js'; +import { SessionsEmptyStateLayout } from '../../../browser/parts/sessionsEmptyStateLayout.js'; +import { NEW_FILE_TAB_COMMAND_ID } from '../../../common/sessionCommands.js'; +import { KeyCode, KeyMod } from '../../../../base/common/keyCodes.js'; +import { KeybindingWeight } from '../../../../platform/keybinding/common/keybindingsRegistry.js'; +import { EmptyFileEditorInput } from '../../editor/browser/emptyFileEditorInput.js'; + +export const RUN_EMPTY_SEARCH_COMMAND_ID = 'sessions.searchEditor.runSearch'; export class SearchEditorEmptyStateContribution extends Disposable implements IEditorContribution { static readonly ID = 'sessions.searchEditor.emptyState'; - constructor(editor: ICodeEditor) { + constructor( + editor: ICodeEditor, + @IInstantiationService instantiationService: IInstantiationService, + ) { super(); const editorObservable = observableCodeEditor(editor); @@ -34,24 +50,64 @@ export class SearchEditorEmptyStateContribution extends Disposable implements IE } const container = $('.sessions-search-empty-state'); - renderSessionsEmptyState( - container, - localize('searchEditor.emptyTitle', "Search"), - localize('searchEditor.emptyDescription', "Search for text in your files"), - ); + const content = append(container, $('.sessions-empty-state-content')); + reader.store.add(instantiationService.createInstance(SessionsEmptyStateActions, content, Menus.EmptySearchEditorActions, { + ariaLabel: localize('searchEditor.emptyActions', "Search actions"), + telemetrySource: 'searchEditor.emptyState', + menuOptions: { arg: editor }, + })); reader.store.add(editorObservable.createOverlayWidget({ domNode: container, position: constObservable(null), minContentWidthInPx: constObservable(0), allowEditorOverflow: false, })); + const results = editor.getContainerDomNode(); + const pane = results.parentElement; + const query = results.previousElementSibling; + const layout = pane?.classList.contains('search-editor') && isHTMLElement(query) + ? reader.store.add(new SessionsEmptyStateLayout(pane, [query, results], content)) + : undefined; reader.store.add(autorun(reader => { const { width, height } = editorObservable.layoutInfo.read(reader); container.style.width = `${width}px`; container.style.height = `${height}px`; + layout?.layout(); })); })); } } registerEditorContribution(SearchEditorEmptyStateContribution.ID, SearchEditorEmptyStateContribution, EditorContributionInstantiation.AfterFirstRender); + +registerAction2(class extends Action2 { + constructor() { + super({ + id: RUN_EMPTY_SEARCH_COMMAND_ID, + title: localize2('searchEditor.runSearch', "Run Search"), + icon: searchViewIcon, + keybinding: { + primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyR, + when: InSearchEditor, + weight: KeybindingWeight.SessionsContrib, + }, + menu: { id: Menus.EmptySearchEditorActions, group: 'navigation', order: 1 }, + }); + } + + async run(accessor: ServicesAccessor, control?: ICodeEditor): Promise<void> { + const editorService = accessor.get(IEditorService); + const pane = control + ? editorService.visibleEditorPanes.find(pane => pane instanceof SearchEditor && pane.getControl() === control) + : editorService.activeEditorPane; + if (pane instanceof SearchEditor) { + await pane.triggerSearch({ resetCursor: false }); + } + } +}); + +MenuRegistry.appendMenuItem(Menus.EmptySearchEditorActions, { + command: { id: NEW_FILE_TAB_COMMAND_ID, title: localize2('searchEditor.openFiles', "Open Files"), icon: EmptyFileEditorInput.ICON }, + group: 'navigation', + order: 2, +}); diff --git a/src/vs/sessions/contrib/search/test/browser/searchEditor.fixture.ts b/src/vs/sessions/contrib/search/test/browser/searchEditor.fixture.ts index e75cc05445fbac..c3472ce13faafd 100644 --- a/src/vs/sessions/contrib/search/test/browser/searchEditor.fixture.ts +++ b/src/vs/sessions/contrib/search/test/browser/searchEditor.fixture.ts @@ -4,7 +4,7 @@ *--------------------------------------------------------------------------------------------*/ import '../../../../browser/parts/media/editorPart.css'; -import { SearchEditorEmptyStateContribution } from '../../browser/searchEditorEmptyState.contribution.js'; +import { RUN_EMPTY_SEARCH_COMMAND_ID, SearchEditorEmptyStateContribution } from '../../browser/searchEditorEmptyState.contribution.js'; import { $, append, Dimension } from '../../../../../base/browser/dom.js'; import { CancellationToken } from '../../../../../base/common/cancellation.js'; import { Event } from '../../../../../base/common/event.js'; @@ -15,6 +15,12 @@ import { IConfigurationService } from '../../../../../platform/configuration/com import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IFileDialogService } from '../../../../../platform/dialogs/common/dialogs.js'; import { IFileService } from '../../../../../platform/files/common/files.js'; +import { IMenuService } from '../../../../../platform/actions/common/actions.js'; +import { MenuService } from '../../../../../platform/actions/common/menuService.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { MockContextKeyService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; import { IEditorProgressService } from '../../../../../platform/progress/common/progress.js'; import { UriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentityService.js'; import { IUriIdentityService } from '../../../../../platform/uriIdentity/common/uriIdentity.js'; @@ -34,27 +40,39 @@ import { INotebookSearchService } from '../../../../../workbench/contrib/search/ import { ComponentFixtureContext, createEditorServices, defineComponentFixture, defineThemedFixtureGroup, registerWorkbenchServices } from '../../../../../workbench/test/browser/componentFixtures/fixtureUtils.js'; import { TestEditorGroupsService, TestEditorGroupView, TestEditorService, TestPathService, TestTextResourceConfigurationService, TestWorkingCopyService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; import { TestFileService } from '../../../../../workbench/test/common/workbenchTestServices.js'; +import { FixtureKeybindingService } from '../../../../test/browser/addTabFixtureUtils.js'; +import { NEW_FILE_TAB_COMMAND_ID } from '../../../../common/sessionCommands.js'; +import { Codicon } from '../../../../../base/common/codicons.js'; let modelCounter = 0; -async function renderSearchEditor({ container, disposableStore, theme }: ComponentFixtureContext, compact: boolean, results?: string, width = 600, query = ''): Promise<void> { +async function renderSearchEditor({ container, disposableStore, theme }: ComponentFixtureContext, compact: boolean, results?: string, width = 600, query = '', minimap = false): Promise<void> { const height = results === undefined ? 200 : 400; container.style.width = `${width}px`; container.style.height = `${height}px`; container.classList.add('agent-sessions-workbench', 'dock-detail-panel'); const part = append(container, $('.part.editor')); + part.style.backgroundColor = 'var(--vscode-editor-background)'; const groupContainer = append(part, $('.editor-group-container')); groupContainer.classList.toggle('editor-tabs-compact-height', compact); const group = new TestEditorGroupView(1); const configurationService = new TestConfigurationService({ - editor: { minimap: { enabled: false } }, + editor: { minimap: { enabled: minimap } }, search: { searchOnType: false, searchEditor: { defaultNumberOfContextLines: 1 } }, }); const instantiationService = createEditorServices(disposableStore, { colorTheme: theme, additionalServices: reg => { registerWorkbenchServices(reg); + reg.define(IMenuService, MenuService); + reg.defineInstance(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + reg.defineInstance(IKeybindingService, new FixtureKeybindingService([ + { id: RUN_EMPTY_SEARCH_COMMAND_ID, title: 'Run Search', icon: Codicon.search, keybinding: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyR }, + { id: NEW_FILE_TAB_COMMAND_ID, title: 'Open Files', icon: Codicon.files, keybinding: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KeyE }, + ])); reg.defineInstance(IConfigurationService, configurationService); reg.defineInstance(ITextResourceConfigurationService, new TestTextResourceConfigurationService(configurationService)); reg.defineInstance(IEditorGroupsService, new TestEditorGroupsService([group])); @@ -103,16 +121,22 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { }), Empty: defineComponentFixture({ labels: { kind: 'screenshot' }, - additionalThemes: ['darkHighContrast'], - expectedVisualDescriptions: ['A centered Search heading and secondary description appear below the unchanged query controls.'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['Run Search aligns vertically with the main empty panel first action. A plain search field sits above the buttons, followed by Open Files, without case, word, regex, context-line, or search-details controls.'], render: context => renderSearchEditor(context, false, ''), }), EmptyCompact: defineComponentFixture({ - additionalThemes: ['darkHighContrast'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], render: context => renderSearchEditor(context, true, ''), }), + EmptyWithMinimap: defineComponentFixture({ + labels: { kind: 'screenshot' }, + additionalThemes: ['darkHighContrast', 'lightHighContrast'], + expectedVisualDescriptions: ['All shortcut chips remain fully visible and unobstructed even with the editor minimap enabled.'], + render: context => renderSearchEditor(context, false, '', 600, '', true), + }), EmptyNarrow: defineComponentFixture({ - additionalThemes: ['darkHighContrast'], + additionalThemes: ['darkHighContrast', 'lightHighContrast'], render: context => renderSearchEditor(context, false, '', 240), }), Results: defineComponentFixture({ diff --git a/src/vs/sessions/contrib/search/test/browser/searchEditorEmptyState.test.ts b/src/vs/sessions/contrib/search/test/browser/searchEditorEmptyState.test.ts index ebe6c5f2bbf610..ba0ef237aa850d 100644 --- a/src/vs/sessions/contrib/search/test/browser/searchEditorEmptyState.test.ts +++ b/src/vs/sessions/contrib/search/test/browser/searchEditorEmptyState.test.ts @@ -4,17 +4,40 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { $, append, getActiveElement, getWindow } from '../../../../../base/browser/dom.js'; +import { $, append, Dimension, getActiveElement, getWindow } from '../../../../../base/browser/dom.js'; +import { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { Event } from '../../../../../base/common/event.js'; import { mainWindow } from '../../../../../base/browser/window.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; import { URI } from '../../../../../base/common/uri.js'; +import { KeyCode, KeyMod } from '../../../../../base/common/keyCodes.js'; +import { decodeKeybinding } from '../../../../../base/common/keybindings.js'; +import { OS } from '../../../../../base/common/platform.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { mock } from '../../../../../base/test/common/mock.js'; import { EditorExtensionsRegistry } from '../../../../../editor/browser/editorExtensions.js'; import { CodeEditorWidget } from '../../../../../editor/browser/widget/codeEditor/codeEditorWidget.js'; -import { createCodeEditorServices } from '../../../../../editor/test/browser/testCodeEditor.js'; +import { EditorOption } from '../../../../../editor/common/config/editorOptions.js'; import { createTextModel } from '../../../../../editor/test/common/testTextModel.js'; +import { IMenuService } from '../../../../../platform/actions/common/actions.js'; +import { MenuService } from '../../../../../platform/actions/common/menuService.js'; +import { IContextKeyService } from '../../../../../platform/contextkey/common/contextkey.js'; +import { MockContextKeyService, MockKeybindingService } from '../../../../../platform/keybinding/test/common/mockKeybindingService.js'; +import { IKeybindingService } from '../../../../../platform/keybinding/common/keybinding.js'; +import { USLayoutResolvedKeybinding } from '../../../../../platform/keybinding/common/usLayoutResolvedKeybinding.js'; +import { IUserInteractionService, MockUserInteractionService } from '../../../../../platform/userInteraction/browser/userInteractionService.js'; +import { TestEditorGroupView, workbenchInstantiationService } from '../../../../../workbench/test/browser/workbenchTestServices.js'; +import { SearchEditor } from '../../../../../workbench/contrib/searchEditor/browser/searchEditor.js'; +import { getOrMakeSearchEditorInput } from '../../../../../workbench/contrib/searchEditor/browser/searchEditorInput.js'; +import { IReplaceService } from '../../../../../workbench/contrib/search/browser/replace.js'; +import { INotebookSearchService } from '../../../../../workbench/contrib/search/common/notebookSearch.js'; +import { INotebookEditorService } from '../../../../../workbench/contrib/notebook/browser/services/notebookEditorService.js'; +import { IEditorProgressService } from '../../../../../platform/progress/common/progress.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import '../../../../browser/parts/media/editorPart.css'; import { SearchEditorScheme } from '../../../../../workbench/contrib/searchEditor/browser/constants.js'; -import { SearchEditorEmptyStateContribution } from '../../browser/searchEditorEmptyState.contribution.js'; +import { RUN_EMPTY_SEARCH_COMMAND_ID, SearchEditorEmptyStateContribution } from '../../browser/searchEditorEmptyState.contribution.js'; +import { NEW_FILE_TAB_COMMAND_ID } from '../../../../common/sessionCommands.js'; suite('Sessions - Search editor empty state', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); @@ -25,7 +48,12 @@ suite('Sessions - Search editor empty state', () => { container.style.width = '600px'; container.style.height = '300px'; container.style.setProperty('--vscode-spacing-size200', '20px'); - const instantiationService = createCodeEditorServices(store); + const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IUserInteractionService, new MockUserInteractionService()); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); const editor = store.add(instantiationService.createInstance(CodeEditorWidget, container, { dimension: { width: 600, height: 300 }, minimap: { enabled: false }, @@ -40,7 +68,7 @@ suite('Sessions - Search editor empty state', () => { return store.add(createTextModel(text, null, undefined, URI.from({ scheme: SearchEditorScheme, fragment: 'test' }))); } - test('shows a semantic, non-interactive empty state without taking focus', () => { + test('shows quiet action rows without a repeated heading or taking focus', () => { const { editor, container } = createEditor(); const input = append(container, $('input')); input.focus(); @@ -50,12 +78,15 @@ suite('Sessions - Search editor empty state', () => { assert.deepStrictEqual({ title: emptyState.querySelector('h2')?.textContent, description: emptyState.querySelector('.sessions-empty-state-description')?.textContent, - tabStops: emptyState.querySelectorAll('a, button, input, [tabindex]').length, + actions: [...emptyState.querySelectorAll('.sessions-add-tab-watermark-entry')].map(row => ({ + label: row.textContent, + role: row.getAttribute('role'), + })), focusPreserved: getActiveElement() === input, }, { - title: 'Search', - description: 'Search for text in your files', - tabStops: 0, + title: undefined, + description: undefined, + actions: [{ label: 'Run Search', role: 'button' }, { label: 'Open Files', role: 'button' }], focusPreserved: true, }); }); @@ -94,14 +125,14 @@ suite('Sessions - Search editor empty state', () => { assert.deepStrictEqual(states, [false, false]); }); - test('centers the message in the results editor and follows layout changes', () => { + test('centers the action rows in the results editor and follows layout changes', () => { const { editor, container } = createEditor(); editor.setModel(searchModel()); const dimensions = []; for (const size of [{ width: 600, height: 300 }, { width: 240, height: 400 }]) { editor.layout(size); const overlay = container.querySelector<HTMLElement>('.sessions-search-empty-state'); - const content = overlay?.querySelector<HTMLElement>('.sessions-empty-state'); + const content = overlay?.querySelector<HTMLElement>('.sessions-empty-state-content'); assert.ok(overlay && content); // Exercise subpixel flex centering independently of the platform's font metrics. content.style.width = `${size.width / 2 + 1 / 64}px`; @@ -134,4 +165,155 @@ suite('Sessions - Search editor empty state', () => { editor.layout({ width: 240, height: 400 }); assert.strictEqual(container.querySelector('.sessions-search-empty-state'), null); }); + + test('centers blank Search controls without minimap overlap and restores the results layout', async () => { + const configurationService = new TestConfigurationService({ + editor: { minimap: { enabled: true } }, + search: { searchOnType: false, searchEditor: { defaultNumberOfContextLines: 1 } }, + }); + store.add(configurationService.onDidChangeConfigurationEmitter); + const instantiationService = workbenchInstantiationService({ configurationService: () => configurationService }, store); + instantiationService.stub(IUserInteractionService, new MockUserInteractionService()); + instantiationService.stub(IContextKeyService, new class extends MockContextKeyService { + override contextMatchesRules(): boolean { return true; } + }); + instantiationService.stub(IKeybindingService, new class extends MockKeybindingService { + override lookupKeybinding(commandId: string) { + const keyCode = commandId === RUN_EMPTY_SEARCH_COMMAND_ID ? KeyCode.KeyR : commandId === NEW_FILE_TAB_COMMAND_ID ? KeyCode.KeyE : undefined; + const keybinding = keyCode === undefined ? null : decodeKeybinding(KeyMod.CtrlCmd | KeyMod.Shift | keyCode, OS); + return keybinding ? USLayoutResolvedKeybinding.resolveKeybinding(keybinding, OS)[0] : undefined; + } + }); + instantiationService.stub(IMenuService, store.add(instantiationService.createInstance(MenuService))); + instantiationService.stub(IReplaceService, new class extends mock<IReplaceService>() { }()); + instantiationService.stub(INotebookSearchService, new class extends mock<INotebookSearchService>() { }()); + instantiationService.stub(INotebookEditorService, new class extends mock<INotebookEditorService>() { + override onDidAddNotebookEditor = Event.None; + }()); + instantiationService.stub(IEditorProgressService, new class extends mock<IEditorProgressService>() { }()); + const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench.dock-detail-panel')); + root.style.cssText = '--vscode-spacing-size240: 24px; --vscode-spacing-size160: 16px; --vscode-spacing-size280: 28px; --vscode-spacing-size80: 8px;'; + store.add(toDisposable(() => root.remove())); + const host = append(root, $('.part.editor')); + const pane = store.add(instantiationService.createInstance(SearchEditor, new TestEditorGroupView(1))); + pane.create(host); + const input = store.add(instantiationService.invokeFunction(getOrMakeSearchEditorInput, { + from: 'rawData', + resultsContents: '', + config: { query: '' }, + modelUri: URI.from({ scheme: SearchEditorScheme, fragment: 'centered-search-test' }), + })); + await pane.setInput(input, { preserveFocus: true }, { newInGroup: true }, CancellationToken.None); + pane.getControl().getContribution(SearchEditorEmptyStateContribution.ID); + pane.layout(new Dimension(600, 400)); + const container = host.querySelector<HTMLElement>('.search-editor'); + const query = host.querySelector<HTMLElement>('.query-container'); + assert.ok(container && query); + const model = pane.getControl().getModel(); + const minimap = container.querySelector<HTMLElement>('.search-results .minimap'); + const field = query.querySelector<HTMLElement>('.monaco-findInput .input'); + const inputBox = field?.closest<HTMLElement>('.monaco-inputbox'); + assert.ok(model && minimap && field && inputBox); + const advancedControls = [...query.querySelectorAll<HTMLElement>('.search-widget > .search-container > .monaco-findInput > .controls, .search-widget > .search-container > .context-lines-input, .search-widget > .search-container > .monaco-custom-toggle, :scope > .includes-excludes')]; + const chips = [...container.querySelectorAll<HTMLElement>('.sessions-search-empty-state .monaco-keybinding-key')]; + const firstButton = container.querySelector<HTMLElement>('.sessions-search-empty-state .sessions-add-tab-watermark-entry'); + assert.ok(firstButton); + const panelBounds = container.getBoundingClientRect(); + const firstButtonTop = firstButton.getBoundingClientRect().top; + assert.deepStrictEqual({ + minimapConfigured: pane.getControl().getLayoutInfo().minimap.minimapWidth > 0, + shortcutCount: chips.length, + advancedControlCount: advancedControls.length, + firstButtonAligned: Math.abs(firstButtonTop - (panelBounds.top + panelBounds.bottom) / 2 + 42) < 1, + searchAboveButtons: query.getBoundingClientRect().bottom < firstButtonTop, + shortcutsUnobstructed: chips.every(chip => { + const bounds = chip.getBoundingClientRect(); + return mainWindow.document.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + bounds.height / 2)?.closest('.sessions-add-tab-watermark-entry') === chip.closest('.sessions-add-tab-watermark-entry'); + }), + }, { + minimapConfigured: true, + shortcutCount: 6, + advancedControlCount: 4, + firstButtonAligned: true, + searchAboveButtons: true, + shortcutsUnobstructed: true, + }); + const states = []; + for (const text of ['', '1 result - 1 file\n\napp.ts:\n 1: hello', 'No Results\n', '']) { + model.setValue(text); + const tab = new mainWindow.KeyboardEvent('keydown', { key: 'Tab', code: 'Tab', keyCode: 9, bubbles: true, cancelable: true }); + field.dispatchEvent(tab); + states.push({ + centered: container.classList.contains('search-editor-empty'), + queryBelowHeader: query.getBoundingClientRect().top > container.getBoundingClientRect().top + 40, + queryConstrained: query.clientWidth <= 320, + actionRows: container.querySelectorAll('.sessions-add-tab-watermark-entry').length, + minimapVisible: getWindow(minimap).getComputedStyle(minimap).visibility === 'visible', + visibleAdvancedControls: advancedControls.filter(control => control.getClientRects().length > 0).length, + inputUsesFullWidth: Math.abs(field.getBoundingClientRect().width - inputBox.clientWidth) < 1, + tabDefaultPrevented: tab.defaultPrevented, + resultsTabIndex: pane.getControl().getOption(EditorOption.tabIndex), + }); + } + assert.deepStrictEqual(states, [ + { centered: true, queryBelowHeader: true, queryConstrained: true, actionRows: 2, minimapVisible: false, visibleAdvancedControls: 0, inputUsesFullWidth: true, tabDefaultPrevented: false, resultsTabIndex: -1 }, + { centered: false, queryBelowHeader: false, queryConstrained: false, actionRows: 0, minimapVisible: true, visibleAdvancedControls: 4, inputUsesFullWidth: false, tabDefaultPrevented: true, resultsTabIndex: 0 }, + { centered: false, queryBelowHeader: false, queryConstrained: false, actionRows: 0, minimapVisible: true, visibleAdvancedControls: 4, inputUsesFullWidth: false, tabDefaultPrevented: true, resultsTabIndex: 0 }, + { centered: true, queryBelowHeader: true, queryConstrained: true, actionRows: 2, minimapVisible: false, visibleAdvancedControls: 0, inputUsesFullWidth: true, tabDefaultPrevented: false, resultsTabIndex: -1 }, + ]); + pane.layout(new Dimension(240, 400)); + const queryInput = container.querySelector<HTMLElement>('.search-widget .monaco-findInput'); + const overviewRuler = container.querySelector<HTMLElement>('.decorationsOverviewRuler'); + assert.ok(queryInput && overviewRuler); + assert.deepStrictEqual({ + readableQuery: queryInput.getBoundingClientRect().width >= 150, + searchBarFillsControl: Math.abs(queryInput.getBoundingClientRect().width - query.getBoundingClientRect().width) < 1, + controlsFit: query.getBoundingClientRect().right <= container.getBoundingClientRect().right, + overviewRulerHidden: getWindow(overviewRuler).getComputedStyle(overviewRuler).visibility === 'hidden', + }, { + readableQuery: true, + searchBarFillsControl: true, + controlsFit: true, + overviewRulerHidden: true, + }); + + model.setValue('1 result - 1 file\n\napp.ts:\n 1: hello'); + const resultsContainer = container.querySelector<HTMLElement>('.search-results'); + const detailsToggle = query.querySelector<HTMLElement>('.includes-excludes > .expand'); + assert.ok(resultsContainer && detailsToggle); + // Keep the browser runner's quirks mode from stretching single-line inputs to the pane height. + for (const input of query.querySelectorAll<HTMLInputElement>('.file-types input')) { + input.style.height = 'auto'; + } + const populatedLayouts = []; + for (const agentsWindow of [true, false]) { + root.classList.toggle('agent-sessions-workbench', agentsWindow); + root.classList.toggle('dock-detail-panel', agentsWindow); + pane.layout(new Dimension(600, 400)); + const tallHeight = pane.getControl().getLayoutInfo().height; + pane.layout(new Dimension(600, 200)); + const shortHeight = pane.getControl().getLayoutInfo().height; + const resizedBottom = resultsContainer.getBoundingClientRect().bottom; + detailsToggle.click(); + const expandedHeight = pane.getControl().getLayoutInfo().height; + const expandedBottom = resultsContainer.getBoundingClientRect().bottom; + populatedLayouts.push({ + agentsWindow, + shrinksWithPane: shortHeight < tallHeight, + shrinksForDetails: expandedHeight < shortHeight, + resizedResultsFit: resizedBottom <= container.getBoundingClientRect().bottom + 1, + expandedResultsFit: expandedBottom <= container.getBoundingClientRect().bottom + 1, + editorMatchesAvailableHeight: expandedHeight === resultsContainer.clientHeight, + }); + detailsToggle.click(); + } + assert.deepStrictEqual(populatedLayouts, [true, false].map(agentsWindow => ({ + agentsWindow, + shrinksWithPane: true, + shrinksForDetails: true, + resizedResultsFit: true, + expandedResultsFit: true, + editorMatchesAvailableHeight: true, + }))); + }); }); diff --git a/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts b/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts index 7749c0ed804ba4..641de50bf7746c 100644 --- a/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts +++ b/src/vs/sessions/contrib/sessions/browser/sessions.contribution.ts @@ -22,11 +22,12 @@ import { KeyCode, KeyMod } from '../../../../base/common/keyCodes.js'; import { ConfigurationScope, Extensions as ConfigurationExtensions, IConfigurationNode, IConfigurationRegistry } from '../../../../platform/configuration/common/configurationRegistry.js'; import { SESSIONS_LIST_SHOW_ARCHIVED_BY_DEFAULT_SETTING, SESSIONS_LIST_SHOW_EMPTY_DEFAULT_GROUPS_SETTING, SESSIONS_LIST_SHOW_UNREAD_IN_COLLAPSED_SECTIONS_SETTING } from './views/sessionsList.js'; import { SessionsMouseNavigationContribution } from './sessionsMouseNavigation.js'; +import { SessionsListToolsContribution } from './sessionsListTools.js'; import './sessionDetailsAction.js'; import './updateSessionFoldersAction.js'; import { SESSIONS_MARK_AS_DONE_CONFETTI_SETTING } from '../../../../platform/chat/common/sessionArchiveActions.js'; import { SessionsWindowNotifier } from './sessionsWindowNotifier.js'; -import { ExternalSessionApplicationBadgeMode, SESSIONS_CHAT_TABS_DEFAULT, SESSIONS_CHAT_TABS_SETTING, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SHOW_FROM_SETTING, SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING, SESSIONS_LIST_REARRANGE_TREATMENT, SessionsChatTabsMode, USE_WORKTREE_SETTING } from '../../../common/sessionConfig.js'; +import { ExternalSessionApplicationBadgeMode, SESSIONS_CHAT_TABS_DEFAULT, SESSIONS_CHAT_TABS_SETTING, SESSIONS_LIST_AGENT_TOOLS_SETTING, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING, SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SHOW_FROM_SETTING, SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, SESSIONS_SIDEBAR_SEPARATE_NAVIGATION_SETTING, SESSIONS_LIST_REARRANGE_TREATMENT, SessionsChatTabsMode, USE_WORKTREE_SETTING } from '../../../common/sessionConfig.js'; const agentSessionsViewIcon = registerIcon('chat-sessions-icon', Codicon.commentDiscussionSparkle, localize('agentSessionsViewIcon', 'Icon for Agent Sessions View')); const AGENT_SESSIONS_VIEW_TITLE = localize2('agentSessions.view.label', "Sessions"); @@ -83,6 +84,13 @@ export const sessionsConfiguration = { default: false, experiment: { mode: 'auto' } }, + [SESSIONS_LIST_AGENT_TOOLS_SETTING]: { + type: 'boolean', + tags: ['preview'], + description: localize('sessions.list.agentTools.enabled', "Controls whether agents can read and organize the Sessions list: create, nest, and reorder custom groups, move, pin, and archive sessions, and change the list's grouping, sorting, and filters. This only applies to the Sessions list of the Agents window."), + default: true, + experiment: { mode: 'auto' } + }, [SESSIONS_LIST_EXTERNAL_APPLICATION_BADGE_SETTING]: { type: 'string', tags: ['experimental'], @@ -181,3 +189,4 @@ registerWorkbenchContribution2(SessionsTelemetryContribution.ID, SessionsTelemet registerWorkbenchContribution2(SessionsAccountTelemetryContribution.ID, SessionsAccountTelemetryContribution, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(SessionsWindowNotifier.ID, SessionsWindowNotifier, WorkbenchPhase.AfterRestored); registerWorkbenchContribution2(SessionConversationActionsContribution.ID, SessionConversationActionsContribution, WorkbenchPhase.AfterRestored); +registerWorkbenchContribution2(SessionsListToolsContribution.ID, SessionsListToolsContribution, WorkbenchPhase.Eventually); diff --git a/src/vs/sessions/contrib/sessions/browser/sessionsListTools.ts b/src/vs/sessions/contrib/sessions/browser/sessionsListTools.ts new file mode 100644 index 00000000000000..5bb8a43a7a68c2 --- /dev/null +++ b/src/vs/sessions/contrib/sessions/browser/sessionsListTools.ts @@ -0,0 +1,676 @@ +/*--------------------------------------------------------------------------------------------- + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for license information. + *--------------------------------------------------------------------------------------------*/ + +import { CancellationToken } from '../../../../base/common/cancellation.js'; +import { Codicon } from '../../../../base/common/codicons.js'; +import { IJSONSchema } from '../../../../base/common/jsonSchema.js'; +import { Disposable } from '../../../../base/common/lifecycle.js'; +import { isObject } from '../../../../base/common/types.js'; +import { URI } from '../../../../base/common/uri.js'; +import { localize } from '../../../../nls.js'; +import { ConfigurationTarget, IConfigurationService } from '../../../../platform/configuration/common/configuration.js'; +import { ContextKeyExpr } from '../../../../platform/contextkey/common/contextkey.js'; +import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IWorkbenchContribution } from '../../../../workbench/common/contributions.js'; +import { IsSessionsWindowContext } from '../../../../workbench/common/contextkeys.js'; +import { ChatContextKeys } from '../../../../workbench/contrib/chat/common/actions/chatContextKeys.js'; +import { CountTokensCallback, ILanguageModelToolsService, IPreparedToolInvocation, IToolData, IToolImpl, IToolInvocation, IToolInvocationPreparationContext, IToolResult, ToolDataSource, ToolProgress } from '../../../../workbench/contrib/chat/common/tools/languageModelToolsService.js'; +import { IViewsService } from '../../../../workbench/services/views/common/viewsService.js'; +import { SESSIONS_LIST_AGENT_TOOLS_SETTING, SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING } from '../../../common/sessionConfig.js'; +import { ISessionsProvidersService } from '../../../services/sessions/browser/sessionsProvidersService.js'; +import { getSessionGroupSectionId, ISessionGroupsService } from '../../../services/sessions/browser/sessionGroupsService.js'; +import { ISession, SessionStatus } from '../../../services/sessions/common/session.js'; +import { ISessionsManagementService } from '../../../services/sessions/common/sessionsManagement.js'; +import { SESSIONS_LIST_UNGROUPED_PLACEMENT, SessionsGrouping, SessionsList, SessionsListSessionPosition, SessionsListSnapshotNode, SessionsSorting } from './views/sessionsList.js'; +import { getSessionFilterOptions, SessionFilter, sessionFilterKey } from './views/sessionsListFilters.js'; +import { SessionsView, SessionsViewId } from './views/sessionsView.js'; + +export const ReadSessionsListToolId = 'vscode_readSessionsList'; +export const OrganizeSessionsListToolId = 'vscode_organizeSessionsList'; + +const sessionsListToolsWhen = ContextKeyExpr.and(IsSessionsWindowContext, ChatContextKeys.enabled, ContextKeyExpr.equals(`config.${SESSIONS_LIST_AGENT_TOOLS_SETTING}`, true)); + +/** How many sessions each header lists when the whole list is read. */ +const MAX_SESSIONS_PER_HEADER = 25; + +const sessionStatusNames: Record<SessionStatus, string> = { + [SessionStatus.Untitled]: 'untitled', + [SessionStatus.InProgress]: 'inProgress', + [SessionStatus.NeedsInput]: 'needsInput', + [SessionStatus.Completed]: 'completed', + [SessionStatus.Error]: 'error', +}; + +const sessionsListActions = ['setView', 'createGroup', 'renameGroup', 'deleteGroup', 'moveSessions', 'moveHeader', 'setCollapsed'] as const; +type SessionsListAction = typeof sessionsListActions[number]; +/** Actions that resolve their targets against the composed list rather than only the list's state services. */ +const listReadingActions: ReadonlySet<string> = new Set<SessionsListAction>(['createGroup', 'moveSessions', 'moveHeader', 'setCollapsed']); + +type SessionsListNodeOutput = + | { + readonly type: 'section' | 'group'; + readonly id: string; + readonly label: string; + readonly collapsed: boolean; + readonly hidden?: true; + readonly comparison?: true; + readonly children: readonly SessionsListNodeOutput[]; + readonly omittedSessions?: number; + } + | { + readonly type: 'session'; + readonly id: string; + readonly title: string; + readonly status: string; + readonly workspace?: string; + readonly unread?: true; + readonly current?: true; + readonly hidden?: true; + }; + +interface ISessionsListOperationResult { + readonly action: string; + readonly ok: boolean; + readonly id?: string; + readonly error?: string; +} + +class SessionsListToolInputError extends Error { } + +/** Reveals the Sessions list without focusing it, so its list state can be read and changed. */ +async function getSessionsView(viewsService: IViewsService, configurationService: IConfigurationService): Promise<SessionsView & { readonly sessionsControl: SessionsList }> { + if (configurationService.getValue<boolean>(SESSIONS_LIST_AGENT_TOOLS_SETTING) !== true) { + throw new Error('The Sessions list tools are disabled.'); + } + const view = viewsService.getViewWithId<SessionsView>(SessionsViewId) ?? await viewsService.openView<SessionsView>(SessionsViewId, false); + if (!view?.sessionsControl) { + throw new Error('The Sessions list is not available.'); + } + // The list renders state changes only while visible; bring it up to date. + view.sessionsControl.refresh(); + return view as SessionsView & { readonly sessionsControl: SessionsList }; +} + +function toolResult(value: unknown, message: string): IToolResult { + return { content: [{ kind: 'text', value: JSON.stringify(value) }], toolResultMessage: message }; +} + +function toolError(message: string): IToolResult { + return { content: [{ kind: 'text', value: `Error: ${message}` }], toolResultError: message }; +} + +export class ReadSessionsListTool implements IToolImpl { + + constructor( + @IViewsService private readonly viewsService: IViewsService, + @IConfigurationService private readonly configurationService: IConfigurationService, + @ISessionsManagementService private readonly sessionsManagementService: ISessionsManagementService, + @ISessionsProvidersService private readonly sessionsProvidersService: ISessionsProvidersService, + ) { } + + getToolData(): IToolData { + return { + id: ReadSessionsListToolId, + toolReferenceName: 'readSessionsList', + canBeReferencedInPrompt: false, + icon: Codicon.listTree, + displayName: localize('sessionsList.tool.read.displayName', "Read Sessions List"), + userDescription: localize('sessionsList.tool.read.userDescription', "Read how the Sessions list is grouped, sorted, filtered, and organized"), + modelDescription: `Read the Agents window Sessions list as the user sees it: its view options (grouping, sorting, filters, archived visibility, section capping) and its tree of sections, nested custom groups, and session rows. Use it to find where sessions are and to get the IDs that organizeSessionsList takes before changing the list. Header IDs are stable section IDs: "pinned", "quickchats", "external", "archived" (the Done section), "recent"/"older" when grouped by time, "workspace:<label>", "repository:<owner/name>", "environment:<id>", and "group:<id>" for custom groups. The tree reflects the current filters: sessions they exclude are not listed. Rows and sections that capping hides behind "Show more" are listed with hidden: true. Without headerId, each header lists at most ${MAX_SESSIONS_PER_HEADER} sessions and reports omittedSessions; pass headerId to list every session of one header. The session running this tool is marked current: true. This tool changes nothing.`, + source: ToolDataSource.Internal, + when: sessionsListToolsWhen, + runsInWorkspace: false, + agentHostPreferences: { defer: 'auto' }, + inputSchema: { + type: 'object', + properties: { + headerId: { + type: 'string', + description: 'Section or custom group ID to read with all of its sessions. Omit to read the whole list.', + }, + }, + additionalProperties: false, + }, + }; + } + + async prepareToolInvocation(_context: IToolInvocationPreparationContext, _token: CancellationToken): Promise<IPreparedToolInvocation> { + return { + invocationMessage: localize('sessionsList.tool.read.invocationMessage', "Reading the Sessions list"), + pastTenseMessage: localize('sessionsList.tool.read.pastTenseMessage', "Read the Sessions list"), + }; + } + + async invoke(invocation: IToolInvocation, _countTokens: CountTokensCallback, _progress: ToolProgress, _token: CancellationToken): Promise<IToolResult> { + const headerId = isObject(invocation.parameters) && typeof (invocation.parameters as { headerId?: unknown }).headerId === 'string' + ? (invocation.parameters as { headerId: string }).headerId + : undefined; + let view: SessionsView & { readonly sessionsControl: SessionsList }; + try { + view = await getSessionsView(this.viewsService, this.configurationService); + } catch (error) { + return toolError(error instanceof Error ? error.message : String(error)); + } + const currentSessionId = getInvokingSession(this.sessionsManagementService, invocation.context?.sessionResource)?.sessionId; + const snapshot = view.sessionsControl.getTreeSnapshot(); + let tree: readonly SessionsListSnapshotNode[] = snapshot; + if (headerId !== undefined) { + const header = findHeader(snapshot, headerId); + if (!header) { + return toolError(`The Sessions list has no section or group "${headerId}". Call readSessionsList without headerId to see the list.`); + } + tree = [header]; + } + const output = { + view: this.getViewState(view), + tree: tree.map(node => toNodeOutput(node, currentSessionId, headerId === undefined ? MAX_SESSIONS_PER_HEADER : undefined)), + }; + return toolResult(output, headerId === undefined + ? localize('sessionsList.tool.read.result', "Read the Sessions list") + : localize('sessionsList.tool.read.result.header', "Read the {0} section of the Sessions list", headerId)); + } + + private getViewState(view: SessionsView & { readonly sessionsControl: SessionsList }) { + const list = view.sessionsControl; + const filterOptions = getSessionFilterOptions(this.sessionsManagementService.getSessions(), this.sessionsProvidersService.getProviders().map(provider => provider.environment)); + return { + grouping: view.grouping, + sorting: view.sorting, + showArchived: !list.isExcludeArchived(), + sessionsPerSection: list.isWorkspaceGroupCapped() ? 'recent' : 'all', + compact: view.compact, + externalSection: this.configurationService.getValue<boolean>(SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING) === true, + filters: filterOptions.map(option => ({ ...option.filter, label: option.label, included: !list.filters.isExcluded(option.filter) })), + }; + } +} + +export class OrganizeSessionsListTool implements IToolImpl { + + constructor( + @IViewsService private readonly viewsService: IViewsService, + @IConfigurationService private readonly configurationService: IConfigurationService, + @ISessionsManagementService private readonly sessionsManagementService: ISessionsManagementService, + @ISessionsProvidersService private readonly sessionsProvidersService: ISessionsProvidersService, + @ISessionGroupsService private readonly sessionGroupsService: ISessionGroupsService, + ) { } + + getToolData(): IToolData { + return { + id: OrganizeSessionsListToolId, + toolReferenceName: 'organizeSessionsList', + canBeReferencedInPrompt: false, + icon: Codicon.listTree, + displayName: localize('sessionsList.tool.organize.displayName', "Organize Sessions List"), + userDescription: localize('sessionsList.tool.organize.userDescription', "Group, order, filter, and sort the Sessions list"), + modelDescription: `Change how the Agents window Sessions list is organized and displayed, as the user can by hand: create, rename, nest, reorder, collapse, and delete custom groups; move sessions into a group, Pinned, archived (Done), or back to their ungrouped section, and reorder them; nest or reorder workspace, repository, and environment sections; and change grouping, sorting, filters, archived visibility, and section capping. Use it whenever the user asks to arrange, group, pin, sort, or filter their sessions. It does not rename, open, or delete sessions. + +Call readSessionsList first: operations take its header IDs and session IDs. Operations run in order, and later operations can refer to a group created earlier in the same call by its "key". The call stops at the first failing operation; the result reports each operation that ran. + +Placement follows the list's precedence: archived > pinned > custom group > ungrouped section. Moving sessions changes only what their destination needs (unarchive, pin or unpin, join or leave a group). Moving sessions to "archived" marks them done; the user can undo it. Archived sessions keep a fixed order, and comparison groups own their membership and cannot be renamed or deleted. Deleting a group deletes its subgroups, ungroups their sessions, and returns their nested sections to the top level. The changes are local presentation state of the list, persisted for the user.`, + source: ToolDataSource.Internal, + when: sessionsListToolsWhen, + runsInWorkspace: false, + agentHostPreferences: { defer: 'auto' }, + inputSchema: organizeInputSchema, + }; + } + + async prepareToolInvocation(context: IToolInvocationPreparationContext, _token: CancellationToken): Promise<IPreparedToolInvocation> { + const count = getOperations(context.parameters)?.length ?? 0; + return { + invocationMessage: count === 1 + ? localize('sessionsList.tool.organize.invocationMessage.single', "Organizing the Sessions list") + : localize('sessionsList.tool.organize.invocationMessage', "Organizing the Sessions list ({0} changes)", count), + pastTenseMessage: localize('sessionsList.tool.organize.pastTenseMessage', "Organized the Sessions list"), + }; + } + + async invoke(invocation: IToolInvocation, _countTokens: CountTokensCallback, _progress: ToolProgress, token: CancellationToken): Promise<IToolResult> { + const operations = getOperations(invocation.parameters); + if (!operations || operations.length === 0) { + return toolError('"operations" must be a non-empty array.'); + } + let view: SessionsView & { readonly sessionsControl: SessionsList }; + try { + view = await getSessionsView(this.viewsService, this.configurationService); + } catch (error) { + return toolError(error instanceof Error ? error.message : String(error)); + } + + const keys = new Map<string, string>(); + const results: ISessionsListOperationResult[] = []; + // A hidden list does not render state changes, so recompose it only before operations that read it, and once at the end. + let stale = false; + for (const operation of operations) { + if (token.isCancellationRequested) { + break; + } + const action = isObject(operation) && typeof operation.action === 'string' ? operation.action : ''; + if (stale && listReadingActions.has(action)) { + view.sessionsControl.update(); + stale = false; + } + try { + const id = await this.applyOperation(view, operation, keys); + results.push(id ? { action, ok: true, id } : { action, ok: true }); + } catch (error) { + results.push({ action, ok: false, error: error instanceof Error ? error.message : String(error) }); + break; + } finally { + stale = true; + } + } + if (stale) { + view.sessionsControl.update(); + } + + const failed = results.some(result => !result.ok); + const skipped = operations.length - results.length; + const output = { + results, + ...(skipped > 0 ? { skippedOperations: skipped } : {}), + ...(failed ? { hint: 'Operations after the failure did not run. Call readSessionsList to see the current state before retrying.' } : {}), + }; + const succeeded = results.filter(result => result.ok).length; + return toolResult(output, failed + ? localize('sessionsList.tool.organize.result.failed', "Applied {0} of {1} Sessions list changes", succeeded, operations.length) + : succeeded === 1 + ? localize('sessionsList.tool.organize.result.single', "Applied 1 Sessions list change") + : localize('sessionsList.tool.organize.result', "Applied {0} Sessions list changes", succeeded)); + } + + /** Applies one operation; returns the ID of the group it creates. */ + private async applyOperation(view: SessionsView & { readonly sessionsControl: SessionsList }, operation: Record<string, unknown>, keys: Map<string, string>): Promise<string | undefined> { + const list = view.sessionsControl; + const action = operation.action as SessionsListAction; + switch (action) { + case 'setView': + await this.setView(view, operation); + return undefined; + case 'createGroup': { + const name = readName(operation); + const parent = optionalString(operation, 'parent'); + const sessions = optionalStringArray(operation, 'sessions'); + const key = optionalString(operation, 'key'); + if (key !== undefined && keys.has(key)) { + throw new SessionsListToolInputError(`Key "${key}" already names a group created in this call.`); + } + const group = list.addGroup(name, parent === undefined ? undefined : this.resolveHeader(parent, keys)); + const headerId = getSessionGroupSectionId(group.id); + if (key !== undefined) { + keys.set(key, headerId); + } + if (sessions?.length) { + await list.moveSessionsTo(this.resolveSessions(sessions), headerId, undefined); + } + return headerId; + } + case 'renameGroup': + list.renameGroup(this.resolveHeader(requiredString(operation, 'id'), keys), readName(operation)); + return undefined; + case 'deleteGroup': + await list.deleteGroup(this.resolveHeader(requiredString(operation, 'id'), keys)); + return undefined; + case 'moveSessions': { + const sessions = this.resolveSessions(optionalStringArray(operation, 'sessions') ?? []); + if (sessions.length === 0) { + throw new SessionsListToolInputError('"sessions" must list at least one session ID.'); + } + const to = optionalString(operation, 'to'); + await list.moveSessionsTo(sessions, to === undefined ? undefined : this.resolvePlacement(to, keys), this.readSessionPosition(operation)); + return undefined; + } + case 'moveHeader': { + const headerId = this.resolveHeader(requiredString(operation, 'id'), keys); + const sibling = this.readHeaderSibling(operation, keys); + let parentId: string | undefined; + if (operation.parent === null) { + parentId = undefined; + } else if (operation.parent !== undefined) { + parentId = this.resolveHeader(requiredString(operation, 'parent'), keys); + } else if (sibling) { + // Without a parent, the header joins its sibling's parent. + parentId = findHeaderParent(list.getTreeSnapshot(), sibling.siblingId); + } else { + throw new SessionsListToolInputError('"moveHeader" needs "parent" (a group ID, or null for the top level), "before", or "after".'); + } + list.moveHeaderTo(headerId, parentId, sibling); + return undefined; + } + case 'setCollapsed': { + if (typeof operation.collapsed !== 'boolean') { + throw new SessionsListToolInputError('"setCollapsed" needs a boolean "collapsed".'); + } + list.setHeaderCollapsed(this.resolveHeader(requiredString(operation, 'id'), keys), operation.collapsed); + return undefined; + } + default: + throw new SessionsListToolInputError(`Unknown action "${String(operation.action)}". Use one of: ${sessionsListActions.join(', ')}.`); + } + } + + private async setView(view: SessionsView & { readonly sessionsControl: SessionsList }, operation: Record<string, unknown>): Promise<void> { + const list = view.sessionsControl; + const grouping = optionalEnum(operation, 'grouping', Object.values(SessionsGrouping)); + const sorting = optionalEnum(operation, 'sorting', Object.values(SessionsSorting)); + const sessionsPerSection = optionalEnum(operation, 'sessionsPerSection', ['recent', 'all'] as const); + const showArchived = optionalBoolean(operation, 'showArchived'); + const compact = optionalBoolean(operation, 'compact'); + const externalSection = optionalBoolean(operation, 'externalSection'); + const resetFilters = optionalBoolean(operation, 'resetFilters'); + const filters = this.readFilters(operation); + + // Validate before changing anything, so a rejected operation changes nothing. + if (resetFilters) { + view.resetFilters(); + } + if (grouping !== undefined) { + view.setGrouping(grouping); + } + if (sorting !== undefined) { + view.setSorting(sorting); + } + for (const { filter, included } of filters) { + list.filters.setExcluded(filter, !included); + } + if (showArchived !== undefined) { + view.setShowArchived(showArchived); + } + if (sessionsPerSection !== undefined) { + view.setWorkspaceGroupCapped(sessionsPerSection === 'recent'); + } + if (compact !== undefined) { + view.setCompact(compact); + } + if (externalSection !== undefined && this.configurationService.getValue<boolean>(SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING) !== externalSection) { + await this.configurationService.updateValue(SESSIONS_LIST_GROUP_EXTERNAL_SESSIONS_SETTING, externalSection, ConfigurationTarget.USER); + } + } + + private readFilters(operation: Record<string, unknown>): { readonly filter: SessionFilter; readonly included: boolean }[] { + if (operation.filters === undefined) { + return []; + } + if (!Array.isArray(operation.filters)) { + throw new SessionsListToolInputError('"filters" must be an array.'); + } + const options = new Map(getSessionFilterOptions(this.sessionsManagementService.getSessions(), this.sessionsProvidersService.getProviders().map(provider => provider.environment)) + .map(option => [sessionFilterKey(option.filter), option.filter])); + return operation.filters.map((entry: unknown) => { + if (!isObject(entry)) { + throw new SessionsListToolInputError('Each filter must be an object with "kind", "id", and "included".'); + } + const { kind, id, environment, included } = entry as Record<string, unknown>; + if (typeof id !== 'string' || typeof included !== 'boolean' || (kind !== 'harness' && kind !== 'environment' && kind !== 'application')) { + throw new SessionsListToolInputError('Each filter needs "kind" (harness, environment, or application), a string "id", and a boolean "included".'); + } + if (kind === 'application' && typeof environment !== 'string') { + throw new SessionsListToolInputError('An application filter needs the "environment" it belongs to.'); + } + const filter: SessionFilter = kind === 'application' ? { kind, environment: environment as string, id } : { kind, id }; + const option = options.get(sessionFilterKey(filter)); + if (!option) { + throw new SessionsListToolInputError(`There is no ${kind} filter "${id}"${kind === 'application' ? ` in environment "${environment}"` : ''}. Use the filters that readSessionsList reports.`); + } + return { filter: option, included }; + }); + } + + private readSessionPosition(operation: Record<string, unknown>): SessionsListSessionPosition | undefined { + const before = optionalString(operation, 'before'); + const after = optionalString(operation, 'after'); + const position = optionalEnum(operation, 'position', ['top', 'bottom'] as const); + if ([before, after, position].filter(value => value !== undefined).length > 1) { + throw new SessionsListToolInputError('Use only one of "before", "after", and "position".'); + } + if (before !== undefined || after !== undefined) { + return { session: this.resolveSessions([before ?? after!])[0], position: before !== undefined ? 'before' : 'after' }; + } + return position; + } + + private readHeaderSibling(operation: Record<string, unknown>, keys: Map<string, string>): { readonly siblingId: string; readonly position: 'before' | 'after' } | undefined { + const before = optionalString(operation, 'before'); + const after = optionalString(operation, 'after'); + if (before !== undefined && after !== undefined) { + throw new SessionsListToolInputError('Use only one of "before" and "after".'); + } + const sibling = before ?? after; + return sibling === undefined ? undefined : { siblingId: this.resolveHeader(sibling, keys), position: before !== undefined ? 'before' : 'after' }; + } + + /** A header ID from readSessionsList, a key of a group created in this call, or a bare group ID. */ + private resolveHeader(ref: string, keys: ReadonlyMap<string, string>): string { + const keyed = keys.get(ref); + if (keyed !== undefined) { + return keyed; + } + return this.sessionGroupsService.getGroup(ref) ? getSessionGroupSectionId(ref) : ref; + } + + private resolvePlacement(ref: string, keys: ReadonlyMap<string, string>): string { + return ref === 'pinned' || ref === 'archived' || ref === SESSIONS_LIST_UNGROUPED_PLACEMENT ? ref : this.resolveHeader(ref, keys); + } + + private resolveSessions(ids: readonly string[]): ISession[] { + const sessions = this.sessionsManagementService.getSessions(); + return ids.map(id => { + const session = sessions.find(candidate => candidate.sessionId === id || candidate.resource.toString() === id); + if (!session) { + throw new SessionsListToolInputError(`Session "${id}" does not exist. Use the session IDs that readSessionsList reports.`); + } + return session; + }); + } +} + +const organizeInputSchema: IJSONSchema & { type: 'object' } = { + type: 'object', + properties: { + operations: { + type: 'array', + minItems: 1, + description: 'Changes to apply in order.', + items: { + type: 'object', + properties: { + action: { + type: 'string', + enum: [...sessionsListActions], + description: [ + 'setView: change any of grouping, sorting, filters, resetFilters, showArchived, sessionsPerSection, compact, externalSection.', + 'createGroup: create a group named "name", optionally nested first in "parent" and holding "sessions"; returns its ID. "key" lets later operations refer to it.', + 'renameGroup: rename group "id" to "name".', + 'deleteGroup: delete group "id".', + 'moveSessions: move "sessions" to "to", optionally positioned with "before"/"after" (a session ID in the destination) or "position". Without "to", the sessions join the placement of the "before"/"after" session, which also reorders them.', + 'moveHeader: move group or workspace/repository/environment section "id" into group "parent" (null for the top level), optionally next to sibling header "before"/"after". Without "parent", it joins the parent of its "before"/"after" sibling. Nested without a sibling, it becomes the first child.', + 'setCollapsed: collapse or expand section or group "id".', + ].join('\n'), + }, + id: { type: 'string', description: 'Header ID of the group or section the action changes (renameGroup, deleteGroup, moveHeader, setCollapsed).' }, + name: { type: 'string', description: 'Group name (createGroup, renameGroup).' }, + key: { type: 'string', description: 'Name for the group createGroup creates, which later operations of this call can use instead of its ID.' }, + parent: { type: ['string', 'null'], description: 'Group to nest in (createGroup, moveHeader); null moves a header to the top level.' }, + sessions: { type: 'array', items: { type: 'string' }, description: 'Session IDs (createGroup, moveSessions), moved in their current list order.' }, + to: { type: 'string', description: 'Destination of moveSessions: "pinned", "archived", "ungrouped" (each session\'s own workspace, repository, environment, chats, or date section), or the header ID of a custom group or an ungrouped section.' }, + before: { type: 'string', description: 'Position before this session ID (moveSessions) or sibling header ID (moveHeader).' }, + after: { type: 'string', description: 'Position after this session ID (moveSessions) or sibling header ID (moveHeader).' }, + position: { type: 'string', enum: ['top', 'bottom'], description: 'Position first or last in the destination (moveSessions).' }, + collapsed: { type: 'boolean', description: 'Whether to collapse (setCollapsed).' }, + grouping: { type: 'string', enum: Object.values(SessionsGrouping), description: 'Section the list by workspace, repository, environment, or date (setView).' }, + sorting: { type: 'string', enum: Object.values(SessionsSorting), description: 'Sort sessions by creation or last update time (setView).' }, + filters: { + type: 'array', + description: 'Filters to include or exclude, as readSessionsList reports them (setView).', + items: { + type: 'object', + properties: { + kind: { type: 'string', enum: ['harness', 'environment', 'application'] }, + id: { type: 'string' }, + environment: { type: 'string', description: 'Environment of an application filter.' }, + included: { type: 'boolean' }, + }, + required: ['kind', 'id', 'included'], + }, + }, + resetFilters: { type: 'boolean', description: 'Before applying the other options, reset the filters, archived visibility, sessions per section, and each section\'s show more or show less choice to their defaults; grouping, sorting, compact, and externalSection are unaffected. The user can undo it (setView).' }, + showArchived: { type: 'boolean', description: 'Show archived (Done) sessions (setView).' }, + sessionsPerSection: { type: 'string', enum: ['recent', 'all'], description: 'Cap workspace, repository, and environment sections to recent sessions, or show all (setView).' }, + compact: { type: 'boolean', description: 'Use compact rows (setView).' }, + externalSection: { type: 'boolean', description: 'Show sessions created outside VS Code in their own External section (setView).' }, + }, + required: ['action'], + }, + }, + }, + required: ['operations'], + additionalProperties: false, +}; + +function getOperations(parameters: unknown): Record<string, unknown>[] | undefined { + const operations = isObject(parameters) ? (parameters as { operations?: unknown }).operations : undefined; + return Array.isArray(operations) ? operations.map(operation => isObject(operation) ? operation as Record<string, unknown> : {}) : undefined; +} + +function optionalString(operation: Record<string, unknown>, property: string): string | undefined { + const value = operation[property]; + if (value !== undefined && typeof value !== 'string') { + throw new SessionsListToolInputError(`"${property}" must be a string.`); + } + return value; +} + +function requiredString(operation: Record<string, unknown>, property: string): string { + const value = optionalString(operation, property); + if (value === undefined) { + throw new SessionsListToolInputError(`"${operation.action}" needs "${property}".`); + } + return value; +} + +function optionalStringArray(operation: Record<string, unknown>, property: string): string[] | undefined { + const value = operation[property]; + if (value !== undefined && (!Array.isArray(value) || !value.every(item => typeof item === 'string'))) { + throw new SessionsListToolInputError(`"${property}" must be an array of strings.`); + } + return value; +} + +function optionalBoolean(operation: Record<string, unknown>, property: string): boolean | undefined { + const value = operation[property]; + if (value !== undefined && typeof value !== 'boolean') { + throw new SessionsListToolInputError(`"${property}" must be a boolean.`); + } + return value; +} + +function optionalEnum<T extends string>(operation: Record<string, unknown>, property: string, values: readonly T[]): T | undefined { + const value = operation[property]; + if (value !== undefined && !values.includes(value as T)) { + throw new SessionsListToolInputError(`"${property}" must be one of: ${values.join(', ')}.`); + } + return value as T | undefined; +} + +function readName(operation: Record<string, unknown>): string { + const name = requiredString(operation, 'name').trim(); + if (!name) { + throw new SessionsListToolInputError('"name" must not be empty.'); + } + return name; +} + +function getInvokingSession(sessionsManagementService: ISessionsManagementService, resource: URI | undefined): ISession | undefined { + return resource && (sessionsManagementService.getSession(resource) ?? sessionsManagementService.getSessionForChatResource(resource)?.session); +} + +function findHeader(nodes: readonly SessionsListSnapshotNode[], headerId: string): SessionsListSnapshotNode | undefined { + for (const node of nodes) { + if (node.type === 'session') { + continue; + } + if (node.id === headerId) { + return node; + } + const match = findHeader(node.children, headerId); + if (match) { + return match; + } + } + return undefined; +} + +/** The custom group the header is nested in, or `undefined` at the top level. */ +function findHeaderParent(nodes: readonly SessionsListSnapshotNode[], headerId: string, parentId?: string): string | undefined { + for (const node of nodes) { + if (node.type === 'session') { + continue; + } + if (node.id === headerId) { + return parentId; + } + const match = findHeaderParent(node.children, headerId, node.id); + if (match !== undefined) { + return match; + } + } + return undefined; +} + +function toNodeOutput(node: SessionsListSnapshotNode, currentSessionId: string | undefined, maxSessions: number | undefined): SessionsListNodeOutput { + if (node.type === 'session') { + const session = node.session; + const workspace = session.workspace.get()?.label; + return { + type: 'session', + id: session.sessionId, + title: session.title.get(), + status: sessionStatusNames[session.status.get()] ?? 'unknown', + ...(workspace ? { workspace } : {}), + ...(!session.isRead.get() ? { unread: true } : {}), + ...(session.sessionId === currentSessionId ? { current: true } : {}), + ...(node.hidden ? { hidden: true } : {}), + }; + } + let sessionCount = 0; + let omittedSessions = 0; + const children: SessionsListNodeOutput[] = []; + for (const child of node.children) { + if (child.type === 'session' && maxSessions !== undefined && sessionCount >= maxSessions) { + omittedSessions++; + continue; + } + if (child.type === 'session') { + sessionCount++; + } + children.push(toNodeOutput(child, currentSessionId, maxSessions)); + } + return { + type: node.type, + id: node.id, + label: node.label, + collapsed: node.collapsed, + ...(node.hidden ? { hidden: true } : {}), + ...(node.comparison ? { comparison: true } : {}), + children, + ...(omittedSessions > 0 ? { omittedSessions } : {}), + }; +} + +export class SessionsListToolsContribution extends Disposable implements IWorkbenchContribution { + + static readonly ID = 'sessions.contrib.sessionsListTools'; + + constructor( + @ILanguageModelToolsService toolsService: ILanguageModelToolsService, + @IInstantiationService instantiationService: IInstantiationService, + ) { + super(); + for (const tool of [instantiationService.createInstance(ReadSessionsListTool), instantiationService.createInstance(OrganizeSessionsListTool)]) { + this._register(toolsService.registerTool(tool.getToolData(), tool)); + } + } +} diff --git a/src/vs/sessions/contrib/sessions/browser/views/sessionsList.ts b/src/vs/sessions/contrib/sessions/browser/views/sessionsList.ts index 28593c41c785b3..88f0a015476f4d 100644 --- a/src/vs/sessions/contrib/sessions/browser/views/sessionsList.ts +++ b/src/vs/sessions/contrib/sessions/browser/views/sessionsList.ts @@ -12,6 +12,7 @@ import { IListStyles } from '../../../../../base/browser/ui/list/listWidget.js'; import { IObjectTreeElement, ITreeNode, ITreeRenderer, ITreeContextMenuEvent, ObjectTreeElementCollapseState, ITreeDragAndDrop, ITreeDragOverReaction, TreeDragOverBubble } from '../../../../../base/browser/ui/tree/tree.js'; import { LabelFuzzyScore, RenderIndentGuides, TreeFindMode } from '../../../../../base/browser/ui/tree/abstractTree.js'; import { Codicon } from '../../../../../base/common/codicons.js'; +import { groupByMap } from '../../../../../base/common/collections.js'; import { onUnexpectedError } from '../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../base/common/event.js'; import { HighlightedLabel } from '../../../../../base/browser/ui/highlightedlabel/highlightedLabel.js'; @@ -3307,6 +3308,12 @@ function getSectionPlacement(sectionId: string): SessionListPlacement | undefine return isShortcutSection(sectionId) ? undefined : { kind: 'section', sectionId }; } +function isSamePlacement(a: SessionListPlacement, b: SessionListPlacement): boolean { + const header = getPlacementHeader(a); + const other = getPlacementHeader(b); + return header.kind === other.kind && header.id === other.id; +} + function getPlacementHeader(placement: SessionListPlacement): ISessionDropTargetHeader { switch (placement.kind) { case 'archived': @@ -3956,6 +3963,46 @@ export interface ISessionsList { getGroupsInDisplayOrder(): ISessionGroup[]; } +/** + * A node of {@link SessionsList.getTreeSnapshot}: a section or custom group + * header with its rows, or a session row. Headers are identified by their + * section id, such as `pinned`, `workspace:<label>`, or `group:<groupId>`. + */ +export type SessionsListSnapshotNode = + | { + readonly type: 'section' | 'group'; + readonly id: string; + readonly label: string; + readonly collapsed: boolean; + /** Capping hides the header behind the "+N more" row. */ + readonly hidden?: boolean; + /** A comparison group, which owns its membership and position. */ + readonly comparison?: boolean; + readonly children: readonly SessionsListSnapshotNode[]; + } + | { + readonly type: 'session'; + readonly session: ISession; + /** Capping hides the row behind its section's "Show more" row. */ + readonly hidden?: boolean; + }; + +/** Where {@link SessionsList.moveSessionsTo} positions sessions within their placement. */ +export type SessionsListSessionPosition = + | 'top' + | 'bottom' + | { readonly session: ISession; readonly position: 'before' | 'after' }; + +/** Where {@link SessionsList.moveHeaderTo} positions a header among its new siblings. */ +export interface ISessionsListHeaderPosition { + /** The section id of a sibling header. */ + readonly siblingId: string; + readonly position: 'before' | 'after'; +} + +/** The placement of the section a session renders in when it is neither archived, pinned, nor grouped. */ +export const SESSIONS_LIST_UNGROUPED_PLACEMENT = 'ungrouped'; + /** The resettable state of a single value, which Reset Filters sets to `defaultValue`. */ function resettableValue<T>(read: () => T, write: (value: T) => void, defaultValue: T): ISessionsListResettableState { return { @@ -4083,6 +4130,8 @@ export class SessionsList extends Disposable implements ISessionsList { /** How many groups each rendered custom group is nested in, by group id. */ private readonly groupDepths = new Map<string, number>(); private expandedMoreFolders = false; + /** The grouping sections that capping currently hides behind the "+N more" row. */ + private hiddenGroupingSections: readonly ISessionSection[] = []; private openWindowSourceFolder: URI | undefined; private hasFindPattern = false; private suspendCollapseStatePersistence = false; @@ -5404,6 +5453,7 @@ export class SessionsList extends Disposable implements ISessionsList { } }; + this.hiddenGroupingSections = []; if (grouping === SessionsGrouping.Date) { // Groups form a contiguous, fully user-ordered block right below the // Pinned section. They no longer interleave with the date sections by @@ -5466,6 +5516,7 @@ export class SessionsList extends Disposable implements ISessionsList { element: { showMore: true as const, kind, mode: 'less' as const, sectionId: SHOW_MORE_FOLDERS_LABEL, stateId: SHOW_MORE_FOLDERS_LABEL, sectionLabel: SHOW_MORE_FOLDERS_LABEL, remainingCount: 0 }, }); } else { + this.hiddenGroupingSections = moreFolderSections; children.push({ element: { showMore: true as const, kind, mode: 'more' as const, sectionId: SHOW_MORE_FOLDERS_LABEL, stateId: SHOW_MORE_FOLDERS_LABEL, sectionLabel: SHOW_MORE_FOLDERS_LABEL, remainingCount: moreFolderSections.length }, }); @@ -6682,7 +6733,11 @@ export class SessionsList extends Disposable implements ISessionsList { * top-level headers, which include grouping sections. */ private moveHeader(header: IDraggedHeader, drop: SessionHeaderDrop): void { - const groupId = header.group?.group.id; + this.applyHeaderDrop(header.id, header.group?.group.id, drop); + } + + /** Moves the header with the given section id, the header of `groupId` when it is a group, to where `drop` says. */ + private applyHeaderDrop(headerId: string, groupId: string | undefined, drop: SessionHeaderDrop): void { if (drop.kind !== 'topLevel') { const parentId = drop.kind === 'into' ? drop.groupId : drop.parentId; if (groupId === undefined ? !this.canHoldSubgroups(parentId) : !this.canNestGroup(groupId, parentId)) { @@ -6695,14 +6750,14 @@ export class SessionsList extends Disposable implements ISessionsList { if (groupId !== undefined) { this._sessionGroupsService.moveGroup(groupId, drop.groupId); } else { - this._sessionGroupsService.moveSection(this.getSectionGroupKey(header.id), drop.groupId); + this._sessionGroupsService.moveSection(this.getSectionGroupKey(headerId), drop.groupId); } return; case 'subgroup': if (groupId !== undefined) { this._sessionGroupsService.moveGroup(groupId, drop.parentId, drop.placement); } else { - this._sessionGroupsService.moveSection(this.getSectionGroupKey(header.id), drop.parentId, drop.placement); + this._sessionGroupsService.moveSection(this.getSectionGroupKey(headerId), drop.parentId, drop.placement); } return; case 'topLevel': { @@ -6710,10 +6765,10 @@ export class SessionsList extends Disposable implements ISessionsList { if (groupId !== undefined) { this._sessionGroupsService.moveGroup(groupId, undefined); } else { - this._sessionGroupsService.moveSection(this.getSectionGroupKey(header.id), undefined); + this._sessionGroupsService.moveSection(this.getSectionGroupKey(headerId), undefined); } // A moved grouping section is promoted so it stays visible (escapes the "+N more" capping). - this._sessionSectionOrderService.reorder(topLevelOrder, header.id, drop.targetId, drop.position, groupId === undefined ? header.id : undefined); + this._sessionSectionOrderService.reorder(topLevelOrder, headerId, drop.targetId, drop.position, groupId === undefined ? headerId : undefined); return; } } @@ -6765,6 +6820,280 @@ export class SessionsList extends Disposable implements ISessionsList { return result; } + // -- Programmatic organization -- + + /** + * The list as it is composed, independent of scrolling, collapsing, and the + * find filter, including the sections and session rows that capping hides. + * Shortcut sections and nested chat rows are omitted. + */ + getTreeSnapshot(): SessionsListSnapshotNode[] { + const toSessionNodes = (sessions: readonly ISession[], hidden: boolean): SessionsListSnapshotNode[] => + sessions.map(session => hidden ? { type: 'session', session, hidden } : { type: 'session', session }); + const collectSessionIds = (nodes: readonly SessionsListSnapshotNode[], ids: Set<string>): Set<string> => { + for (const node of nodes) { + if (node.type === 'session') { + ids.add(node.session.sessionId); + } else { + collectSessionIds(node.children, ids); + } + } + return ids; + }; + const visitRows = (node: ITreeNode<SessionListItem | null, FuzzyScore>, sessions: readonly ISession[]): SessionsListSnapshotNode[] => { + const rows = visit(node.children); + if (node.children.some(child => child.element && isSessionShowMore(child.element) && child.element.kind === 'sessions' && child.element.mode === 'more')) { + const shown = collectSessionIds(rows, new Set()); + rows.push(...toSessionNodes(sessions.filter(session => !shown.has(session.sessionId)), true)); + } + return rows; + }; + const visit = (nodes: readonly ITreeNode<SessionListItem | null, FuzzyScore>[]): SessionsListSnapshotNode[] => nodes.flatMap((node): SessionsListSnapshotNode[] => { + const element = node.element; + if (!element) { + return []; + } + if (isSessionGroupItem(element)) { + return [{ + type: 'group', + id: getSessionGroupSectionId(element.group.id), + label: element.group.name, + collapsed: node.collapsed, + ...(element.comparison ? { comparison: true } : {}), + children: visitRows(node, element.sessions), + }]; + } + if (isSessionSection(element)) { + return isShortcutSection(element.id) ? [] : [{ type: 'section', id: element.id, label: element.label, collapsed: node.collapsed, children: visitRows(node, element.sessions) }]; + } + if (isSessionShowMore(element)) { + return element.kind !== 'sessions' && element.mode === 'more' + ? this.hiddenGroupingSections.map(section => ({ type: 'section', id: section.id, label: section.label, collapsed: true, hidden: true, children: toSessionNodes(section.sessions, true) })) + : []; + } + return isSessionItem(element) ? [{ type: 'session', session: element }] : []; + }); + return visit(this.tree.getNode().children); + } + + /** + * Moves sessions as dropping them does: into a placement, which is `pinned`, + * `archived`, {@link SESSIONS_LIST_UNGROUPED_PLACEMENT}, or the section id of + * a custom group or an ungrouped section, and optionally to a position among + * the sessions there. Without a placement, the sessions move to the placement + * of the session they are positioned against. + * @throws when the sessions cannot move there. + */ + async moveSessionsTo(sessions: readonly ISession[], placementId: string | undefined, position: SessionsListSessionPosition | undefined): Promise<void> { + const anchorSession = typeof position === 'object' ? position.session : undefined; + if (anchorSession && sessions.some(session => session.sessionId === anchorSession.sessionId)) { + throw new Error(`Session "${anchorSession.sessionId}" cannot be positioned relative to itself.`); + } + if (placementId === undefined && !anchorSession) { + throw new Error('Provide a destination, a session to position against, or both.'); + } + if (placementId === SESSIONS_LIST_UNGROUPED_PLACEMENT && !anchorSession) { + // Each session has its own ungrouped section. + for (const [sectionId, sectionSessions] of groupByMap([...sessions], session => this.getUngroupedSectionId(session))) { + await this.moveSessionsToPlacement(sectionSessions, { kind: 'section', sectionId }, position); + } + return; + } + const placement = placementId === undefined || placementId === SESSIONS_LIST_UNGROUPED_PLACEMENT + ? this.getSessionPlacement(anchorSession!) + : getSectionPlacement(placementId); + if (!placement || (placement.kind === 'group' && !this._sessionGroupsService.getGroup(placement.groupId))) { + throw new Error(`"${placementId}" is not a placement that holds sessions.`); + } + if (placementId === SESSIONS_LIST_UNGROUPED_PLACEMENT && placement.kind !== 'section') { + throw new Error(`Session "${anchorSession!.sessionId}" is not in an ungrouped section.`); + } + if (anchorSession && !isSamePlacement(this.getSessionPlacement(anchorSession), placement)) { + throw new Error(`Session "${anchorSession.sessionId}" is not in "${placementId}".`); + } + await this.moveSessionsToPlacement(sessions, placement, position); + } + + private async moveSessionsToPlacement(sessions: readonly ISession[], placement: SessionListPlacement, position: SessionsListSessionPosition | undefined): Promise<void> { + // Archived sessions keep a fixed order. + const anchor = placement.kind === 'archived' || position === undefined ? undefined + : typeof position === 'object' ? { session: position.session, position: position.position, staysInSection: isDateSectionPlacement(placement) } + : this.getEdgeAnchor(sessions, placement, position); + const destination: ISessionDropDestination = { placement, anchor, restoresArchived: true }; + if (!anchor && !sessions.some(session => this.changesPlacement(session, placement))) { + return; + } + if (!this.getSessionDropEffect(sessions, destination)) { + const target = placement.kind === 'group' ? getSessionGroupSectionId(placement.groupId) : getPlacementHeader(placement).id; + throw new Error(`The sessions cannot move to "${target}"${anchor ? ' at that position' : ''}: comparison groups own their membership, an ungrouped section only takes the sessions that render in it, and date sections only take sessions that their sort order places there.`); + } + await this.moveSessions(sessions, destination); + } + + /** The section a session renders in when it is neither archived, pinned, nor grouped. */ + private getUngroupedSectionId(session: ISession): string { + const sectionIds = this.getUngroupedSectionIds(session); + return sectionIds.find(sectionId => this.getSessionDropEffect([session], { placement: { kind: 'section', sectionId }, restoresArchived: true }) !== undefined) ?? sectionIds[0]; + } + + /** Where a session renders: its row's placement, or for a row that capping hides, the placement its state selects. */ + private getSessionPlacement(session: ISession): SessionListPlacement { + const rowPlacement = this.getRowPlacement(session); + if (rowPlacement) { + return rowPlacement; + } + if (session.isArchived.get()) { + return { kind: 'archived' }; + } + if (this.isSessionPinned(session)) { + return { kind: 'pinned' }; + } + const group = this.getRenderedSessionGroup(session); + return group ? { kind: 'group', groupId: group.id } : { kind: 'section', sectionId: this.getUngroupedSectionIds(session)[0] }; + } + + /** The anchor that places sessions first or last among the other sessions the list composes into the placement. */ + private getEdgeAnchor(sessions: readonly ISession[], placement: SessionListPlacement, edge: 'top' | 'bottom'): ISessionDropAnchor | undefined { + const movedIds = new Set(sessions.map(session => session.sessionId)); + const candidates = this.getComposedPlacementSessions(placement).filter(session => !movedIds.has(session.sessionId) && this.getReorderScope(session) !== undefined); + const anchorSession = edge === 'top' ? candidates.at(0) : candidates.at(-1); + return anchorSession && { session: anchorSession, position: edge === 'top' ? 'before' : 'after', staysInSection: isDateSectionPlacement(placement) }; + } + + /** + * The sessions the list composes into the placement, in display order and + * including those that capping hides. A section also lists the members of + * comparison groups nested in it, which belong to their group's placement. + */ + private getComposedPlacementSessions(placement: SessionListPlacement): readonly ISession[] { + const header = placement.kind === 'group' + ? this.findTreeElement((element): element is ISessionGroupItem => isSessionGroupItem(element) && element.group.id === placement.groupId) + : this.findTreeElement((element): element is ISessionSection => isSessionSection(element) && element.id === getPlacementHeader(placement).id) + ?? this.hiddenGroupingSections.find(section => section.id === getPlacementHeader(placement).id); + return (header?.sessions ?? []).filter(session => isSamePlacement(this.getSessionPlacement(session), placement)); + } + + /** + * Moves a custom group or a workspace, repository, or environment section as + * dragging its header does: into the custom group with section id + * `parentId`, or to the top level when it is `undefined`, optionally next to + * one of its new siblings. A group nested without a sibling becomes the first + * child of its parent. + * @throws when the header cannot move there. + */ + moveHeaderTo(headerId: string, parentId: string | undefined, sibling: ISessionsListHeaderPosition | undefined): void { + const groupId = getSessionGroupIdOfSection(headerId); + if (groupId !== undefined) { + if (!this._sessionGroupsService.getGroup(groupId)) { + throw new Error(`Group "${headerId}" does not exist.`); + } + if (this.isComparisonGroup(groupId) && this.options.grouping() !== SessionsGrouping.Date) { + throw new Error(`Comparison group "${headerId}" keeps its place inside its grouping section.`); + } + } else if (!isSessionGroupingSection(headerId) || this.options.grouping() === SessionsGrouping.Date) { + throw new Error(`"${headerId}" cannot move: only custom groups and workspace, repository, or environment sections of the current grouping move.`); + } + if (sibling?.siblingId === headerId) { + throw new Error(`"${headerId}" cannot be positioned relative to itself.`); + } + + let drop: SessionHeaderDrop; + if (parentId === undefined) { + if (!sibling) { + // The list arranges a top-level header among the others. + if (groupId !== undefined) { + this._sessionGroupsService.moveGroup(groupId, undefined); + } else { + this._sessionGroupsService.moveSection(this.getSectionGroupKey(headerId), undefined); + } + return; + } + if (!this._topLevelOrder.includes(sibling.siblingId)) { + throw new Error(`"${sibling.siblingId}" is not a top-level header that can be ordered.`); + } + drop = { kind: 'topLevel', targetId: sibling.siblingId, position: sibling.position }; + } else { + const parentGroupId = getSessionGroupIdOfSection(parentId); + if (parentGroupId === undefined || !this.canHoldSubgroups(parentGroupId)) { + throw new Error(`"${parentId}" is not a custom group that can hold groups and sections.`); + } + if (groupId !== undefined && !this.canNestGroup(groupId, parentGroupId)) { + throw new Error(`"${headerId}" cannot move into "${parentId}": a group never moves into itself or one of its subgroups.`); + } + if (sibling) { + const siblingKey = getSessionGroupIdOfSection(sibling.siblingId) ?? this.getSectionGroupKey(sibling.siblingId); + if (!this._sessionGroupsService.getChildIds(parentGroupId).includes(siblingKey)) { + throw new Error(`"${sibling.siblingId}" is not a group or section nested directly in "${parentId}".`); + } + drop = { kind: 'subgroup', parentId: parentGroupId, depth: 0, placement: { siblingId: siblingKey, position: sibling.position } }; + } else { + drop = { kind: 'into', groupId: parentGroupId }; + } + } + this.applyHeaderDrop(headerId, groupId, drop); + } + + /** + * Collapses or expands the section or group header with the given section id. + * @throws when the list does not show the header. + */ + setHeaderCollapsed(headerId: string, collapsed: boolean): void { + const header = this.findTreeElement((element): element is ISessionSection | ISessionGroupItem => + isSessionGroupItem(element) ? getSessionGroupSectionId(element.group.id) === headerId : isSessionSection(element) && element.id === headerId && !isShortcutSection(element.id)); + if (!header) { + throw new Error(`The list does not show a section or group "${headerId}".`); + } + if (collapsed) { + this.tree.collapse(header); + } else { + this.tree.expand(header); + } + } + + /** + * Creates an empty custom group, nested first in the custom group with + * section id `parentId` when given. + * @throws when the parent cannot hold groups. + */ + addGroup(name: string, parentId: string | undefined): ISessionGroup { + const parentGroupId = parentId === undefined ? undefined : getSessionGroupIdOfSection(parentId); + if (parentId !== undefined && (parentGroupId === undefined || !this.canHoldSubgroups(parentGroupId))) { + throw new Error(`"${parentId}" is not a custom group that can hold groups.`); + } + if (parentGroupId !== undefined) { + this.saveSectionCollapseState(getSessionGroupSectionId(parentGroupId), false); + } + return this._sessionGroupsService.createGroup(name, [], parentGroupId); + } + + /** + * Renames the custom group with the given section id. + * @throws when the group does not exist or is a comparison group. + */ + renameGroup(headerId: string, name: string): void { + this._sessionGroupsService.renameGroup(this.getEditableGroupId(headerId), name); + } + + /** + * Deletes the custom group with the given section id as its Delete Group + * action does, offering Undo when subgroups or nested sections are affected. + * @throws when the group does not exist or is a comparison group. + */ + async deleteGroup(headerId: string): Promise<void> { + await this.commandService.executeCommand(DELETE_SESSION_GROUP_WITH_UNDO_COMMAND_ID, this.getEditableGroupId(headerId)); + } + + private getEditableGroupId(headerId: string): string { + const groupId = getSessionGroupIdOfSection(headerId); + if (groupId === undefined || !this._sessionGroupsService.getGroup(groupId)) { + throw new Error(`Group "${headerId}" does not exist.`); + } + if (this.isComparisonGroup(groupId)) { + throw new Error(`Comparison group "${headerId}" is managed by its comparison.`); + } + return groupId; + } + /** * The set of top-level reorder identities that currently exist (every * top-level group, plus every workspace label and repository present across diff --git a/src/vs/sessions/contrib/sessions/browser/views/sessionsView.ts b/src/vs/sessions/contrib/sessions/browser/views/sessionsView.ts index 7a85d533dbdebe..37d4bec42f9328 100644 --- a/src/vs/sessions/contrib/sessions/browser/views/sessionsView.ts +++ b/src/vs/sessions/contrib/sessions/browser/views/sessionsView.ts @@ -380,7 +380,7 @@ export class SessionsView extends ViewPane { this.registerSessionFilters(sessionsControl); this.registerArchivedFilter(sessionsControl); - this.registerResetFiltersAction(sessionsControl); + this.registerResetFiltersAction(); // Refresh sessions when window gets focus to compensate for missing events this._register(this.hostService.onDidChangeFocus(hasFocus => { @@ -745,20 +745,8 @@ export class SessionsView extends ViewPane { })); } - private registerResetFiltersAction(sessionsControl: SessionsList): void { - const resetFilters = () => { - const restore = sessionsControl.resetFilters(); - this.syncFilterContextKeys(sessionsControl); - this.listNotification?.show({ - message: localize('filtersReset', "Filters reset"), - help: localize('filtersResetHelp', "This notice appears after resetting the filters. Undo restores the previous filters, including which sessions are shown and how many each section lists."), - undo: async () => { - restore(); - this.syncFilterContextKeys(sessionsControl); - status(localize('filtersRestored', "Filters restored.")); - }, - }); - }; + private registerResetFiltersAction(): void { + const resetFilters = () => this.resetFilters(); this._register(registerAction2(class extends Action2 { constructor() { super({ @@ -777,6 +765,41 @@ export class SessionsView extends ViewPane { })); } + /** Returns every filter and display option to its default, offering Undo. */ + resetFilters(): void { + const sessionsControl = this.sessionsControl; + if (!sessionsControl) { + return; + } + const restore = sessionsControl.resetFilters(); + this.syncFilterContextKeys(sessionsControl); + this.listNotification?.show({ + message: localize('filtersReset', "Filters reset"), + help: localize('filtersResetHelp', "This notice appears after resetting the filters. Undo restores the previous filters, including which sessions are shown and how many each section lists."), + undo: async () => { + restore(); + this.syncFilterContextKeys(sessionsControl); + status(localize('filtersRestored', "Filters restored.")); + }, + }); + } + + /** Shows or hides archived sessions, as the filter menu's toggle does. */ + setShowArchived(show: boolean): void { + if (this.sessionsControl && this.sessionsControl.isExcludeArchived() === show) { + this.sessionsControl.setExcludeArchived(!show); + this.syncFilterContextKeys(this.sessionsControl); + } + } + + /** Caps workspace, repository, and environment sections to their recent sessions, or shows all of them. */ + setWorkspaceGroupCapped(capped: boolean): void { + if (this.sessionsControl && this.sessionsControl.isWorkspaceGroupCapped() !== capped) { + this.sessionsControl.setWorkspaceGroupCapped(capped); + this.syncFilterContextKeys(this.sessionsControl); + } + } + /** Updates the filter menu context keys to the list's current state, such as after resetting the filters or undoing that. */ private syncFilterContextKeys(sessionsControl: SessionsList): void { for (const { key, read } of this.filterContextKeys.values()) { @@ -940,6 +963,18 @@ export class SessionsView extends ViewPane { }); } + get grouping(): SessionsGrouping { + return this.currentGrouping; + } + + get sorting(): SessionsSorting { + return this.currentSorting; + } + + get compact(): boolean { + return this.currentCompact; + } + setGrouping(grouping: SessionsGrouping): void { if (this.currentGrouping === grouping) { return; diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsList.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsList.test.ts index a0b3451adb67d8..0fb98f4496f01e 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsList.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsList.test.ts @@ -6814,6 +6814,29 @@ suite('Sessions - SessionsList', () => { }); }); + test('reorders nested chat rows when the session reorders its chats, without a session change event', async () => { + const main = createChat('Main chat'); + const first = { ...createChat('First chat'), createdAt: new Date('2024-01-01') }; + const second = { ...createChat('Second chat'), createdAt: new Date('2024-01-01') }; + const chats = observableValue<readonly IChat[]>('chats', [main, first, second]); + const session: ISession = { + ...createTestSession('Session').session, + chats, + mainChat: constObservable(main), + capabilities: constObservable({ supportsMultipleChats: true }), + }; + const { container } = renderSessionChatsList(session); + const initial = chatRowTitles(container); + + chats.set([main, second, first], undefined); + await new Promise<void>(resolve => mainWindow.requestAnimationFrame(() => resolve())); + + assert.deepStrictEqual({ initial, reordered: chatRowTitles(container) }, { + initial: ['First chat', 'Second chat'], + reordered: ['Second chat', 'First chat'], + }); + }); + test('observes updated ordering after archived nested sessions are shown', async () => { const main = createChat('Main chat'); const archivedUpdatedAt = observableValue<Date | undefined>('archived-updated-at', new Date('2024-01-01')); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts index d86671dc14ef56..03eda9c052e809 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsListFixtureUtils.ts @@ -703,8 +703,8 @@ export async function renderSessionsListFixture(context: ComponentFixtureContext }()); const configurationService = instantiationService.get(IConfigurationService) as TestConfigurationService; - // Render terminal-approval labels as real (monospace) code blocks; otherwise the command is blank. - await configurationService.setUserConfiguration('editor', { fontFamily: 'monospace' }); + // Pin the Linux screenshot font instead of depending on Chromium's generic monospace fallback. + await configurationService.setUserConfiguration('editor', { fontFamily: 'Liberation Mono, monospace' }); for (const [key, value] of Object.entries(state.settings ?? {})) { await configurationService.setUserConfiguration(key, value); } diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsListTools.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsListTools.test.ts new file mode 100644 index 00000000000000..4dc71dbdbde4fb --- /dev/null +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsListTools.test.ts @@ -0,0 +1,231 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { CancellationToken } from '../../../../../base/common/cancellation.js'; +import { Event } from '../../../../../base/common/event.js'; +import { URI } from '../../../../../base/common/uri.js'; +import { upcastPartial } from '../../../../../base/test/common/mock.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; +import { IToolImpl, IToolResult } from '../../../../../workbench/contrib/chat/common/tools/languageModelToolsService.js'; +import { IViewsService } from '../../../../../workbench/services/views/common/viewsService.js'; +import { SESSIONS_LIST_AGENT_TOOLS_SETTING } from '../../../../common/sessionConfig.js'; +import { ISessionGroup, ISessionGroupsService, SessionGroupsService } from '../../../../services/sessions/browser/sessionGroupsService.js'; +import { ISessionSectionOrderService, SessionSectionOrderService } from '../../../../services/sessions/browser/sessionSectionOrderService.js'; +import { ISession } from '../../../../services/sessions/common/session.js'; +import { ISessionsManagementService } from '../../../../services/sessions/common/sessionsManagement.js'; +import { OrganizeSessionsListTool, ReadSessionsListTool } from '../../browser/sessionsListTools.js'; +import { SessionsGrouping, SessionsSorting } from '../../browser/views/sessionsList.js'; +import { SessionsView } from '../../browser/views/sessionsView.js'; +import { createListHarness, createTestSession } from './sessionsListTestUtils.js'; +import { TestSessionsList } from './testSessionsList.js'; + +interface ITreeNodeOutput { + readonly type: string; + readonly id: string; + readonly label?: string; + readonly title?: string; + readonly collapsed?: boolean; + readonly current?: boolean; + readonly children?: readonly ITreeNodeOutput[]; +} + +/** A compact outline of the tree that readSessionsList reports: `id` for headers (`+` when collapsed, `*` for the current session), with their rows. */ +function outline(nodes: readonly ITreeNodeOutput[]): unknown[] { + return nodes.map(node => node.type === 'session' + ? `${node.title}${node.current ? '*' : ''}` + : { [`${node.label}${node.collapsed ? '+' : ''}`]: outline(node.children ?? []) }); +} + +function parse(result: IToolResult): { readonly view: Record<string, unknown>; readonly tree: readonly ITreeNodeOutput[]; readonly results: unknown[]; readonly skippedOperations?: number } { + const part = result.content[0]; + assert.ok(part?.kind === 'text'); + return JSON.parse(part.value); +} + +suite('Sessions - Sessions list tools', () => { + const disposables = ensureNoDisposablesAreLeakedInTestSuite(); + + function setup(sessions: ISession[], options: { readonly groups?: readonly ISessionGroup[]; readonly memberships?: Record<string, string>; readonly pinnedSessionIds?: ReadonlySet<string> } = {}) { + const harness = createListHarness(disposables, sessions, { liveListModel: true, pinnedSessionIds: options.pinnedSessionIds }); + const configurationService = harness.instantiationService.get(IConfigurationService) as TestConfigurationService; + void configurationService.setUserConfiguration(SESSIONS_LIST_AGENT_TOOLS_SETTING, true); + const storageService = harness.instantiationService.get(IStorageService); + storageService.store('sessionsListControl.groups', JSON.stringify({ groups: options.groups ?? [], membership: options.memberships ?? {}, sectionMembership: {} }), StorageScope.PROFILE, StorageTarget.USER); + const orderService = harness.store.add(new SessionSectionOrderService(storageService)); + harness.instantiationService.stub(ISessionSectionOrderService, orderService); + harness.instantiationService.stub(ISessionGroupsService, harness.store.add(new SessionGroupsService(storageService, upcastPartial<ISessionsManagementService>({ + onDidChangeSessions: Event.None, + onDidDeleteSession: Event.None, + onDidArchiveSession: Event.None, + onWillSendRequest: Event.None, + onDidReplaceSession: Event.None, + onDidReplaceNewDraftSession: Event.None, + onDidStartSession: Event.None, + onDidDiscardNewSession: Event.None, + onDidMoveChat: Event.None, + getSessions: () => harness.managementService.sessions, + getInFlightNewSessionRequests: () => [], + getSession: resource => harness.managementService.getSession(resource), + }), orderService))); + + const state = { grouping: SessionsGrouping.Workspace, sorting: SessionsSorting.Created, compact: false }; + const list = harness.store.add(harness.instantiationService.createInstance(TestSessionsList, harness.createContainer(400, 800), { + grouping: () => state.grouping, + sorting: () => state.sorting, + onSessionOpen: () => { }, + })); + list.layout(800, 400); + const view = upcastPartial<SessionsView>({ + sessionsControl: list, + get grouping() { return state.grouping; }, + get sorting() { return state.sorting; }, + get compact() { return state.compact; }, + setGrouping: grouping => { state.grouping = grouping; list.update(true); }, + setSorting: sorting => { state.sorting = sorting; list.update(); }, + setCompact: compact => { state.compact = compact; }, + setShowArchived: show => list.setExcludeArchived(!show), + setWorkspaceGroupCapped: capped => list.setWorkspaceGroupCapped(capped), + resetFilters: () => { list.resetFilters(); }, + }); + harness.instantiationService.stub(IViewsService, upcastPartial<IViewsService>({ getViewWithId: <T>() => view as T })); + + const invoke = (tool: IToolImpl, parameters: Record<string, unknown>, sessionResource?: URI) => tool.invoke({ callId: 'call', toolId: 'tool', parameters, context: sessionResource && { sessionResource } }, async () => 0, { report: () => { } }, CancellationToken.None); + const read = harness.instantiationService.createInstance(ReadSessionsListTool); + const organize = harness.instantiationService.createInstance(OrganizeSessionsListTool); + return { + harness, + list, + configurationService, + invokeRaw: (tool: 'read' | 'organize', parameters: Record<string, unknown>) => invoke(tool === 'read' ? read : organize, parameters), + read: async (parameters: Record<string, unknown> = {}, sessionResource?: URI) => parse(await invoke(read, parameters, sessionResource)), + organize: async (...operations: Record<string, unknown>[]) => parse(await invoke(organize, { operations })), + }; + } + + function session(title: string, minutesAgo: number, workspaceLabel = 'vscode'): ISession { + return createTestSession(title, { workspaceLabel, createdAt: new Date(Date.now() - minutesAgo * 60_000) }).session; + } + + test('reads the view options and the list as a tree of sections, nested groups, and sessions', async () => { + const sessions = [session('Ship notes', 1), session('Fix login', 2), session('Ungrouped', 3), session('Pinned one', 4)]; + const { read } = setup(sessions, { + groups: [{ id: 'release', name: 'Release', createdAt: 1 }, { id: 'hotfixes', name: 'Hotfixes', createdAt: 2, parentId: 'release' }], + memberships: { 'Ship notes': 'release', 'Fix login': 'hotfixes' }, + pinnedSessionIds: new Set(['Pinned one']), + }); + + const { view, tree } = await read({}, sessions[2].resource); + + assert.deepStrictEqual({ view: { ...view, filters: undefined }, tree: outline(tree), headerIds: tree.map(node => node.id) }, { + view: { grouping: 'workspace', sorting: 'created', showArchived: false, sessionsPerSection: 'recent', compact: false, externalSection: false, filters: undefined }, + tree: [ + { 'Pinned+': ['Pinned one'] }, + { 'Release': [{ 'Hotfixes': ['Fix login'] }, 'Ship notes'] }, + { 'vscode': ['Ungrouped*'] }, + ], + headerIds: ['pinned', 'group:release', 'workspace:vscode'], + }); + }); + + test('applies a batch that creates nested groups, moves sessions and sections into them, and collapses one', async () => { + const sessions = [session('Alpha', 1), session('Beta', 2), session('Gamma', 3)]; + const { read, organize, harness } = setup(sessions); + + const { results } = await organize( + { action: 'createGroup', name: 'Release', key: 'release', sessions: ['Alpha'] }, + { action: 'createGroup', name: 'Hotfixes', parent: 'release', key: 'hotfixes', sessions: ['Beta'] }, + { action: 'moveHeader', id: 'workspace:vscode', parent: 'release', after: 'hotfixes' }, + { action: 'setCollapsed', id: 'hotfixes', collapsed: true }, + { action: 'moveSessions', sessions: ['Gamma'], to: 'pinned' }, + ); + const { tree } = await read(); + + assert.deepStrictEqual({ + results: results.map(result => ({ ...result as object, id: (result as { id?: string }).id?.replace(/[0-9a-f-]{36}/, '<id>') })), + tree: outline(tree), + pinChanges: harness.pinChanges, + }, { + results: [ + { action: 'createGroup', ok: true, id: 'group:<id>' }, + { action: 'createGroup', ok: true, id: 'group:<id>' }, + { action: 'moveHeader', ok: true, id: undefined }, + { action: 'setCollapsed', ok: true, id: undefined }, + { action: 'moveSessions', ok: true, id: undefined }, + ], + tree: [{ 'Release': [{ 'Hotfixes+': ['Beta'] }, { 'vscode': ['Gamma'] }, 'Alpha'] }], + pinChanges: [{ sessionId: 'Gamma', pinned: true }], + }); + }); + + test('reorders sessions within their group relative to another session or to an edge', async () => { + const sessions = [session('Newest', 1), session('Middle', 2), session('Oldest', 3)]; + const { read, organize } = setup(sessions, { + groups: [{ id: 'release', name: 'Release', createdAt: 1 }], + memberships: { 'Newest': 'release', 'Middle': 'release', 'Oldest': 'release' }, + }); + + const before = outline((await read()).tree); + await organize({ action: 'moveSessions', sessions: ['Oldest'], before: 'Newest' }); + const anchored = outline((await read()).tree); + await organize({ action: 'moveSessions', sessions: ['Middle'], to: 'group:release', position: 'top' }); + const topAfterManualOrder = outline((await read()).tree); + await organize({ action: 'moveSessions', sessions: ['Middle'], to: 'group:release', position: 'bottom' }); + + assert.deepStrictEqual({ before, anchored, topAfterManualOrder, bottom: outline((await read()).tree) }, { + before: [{ 'Release': ['Newest', 'Middle', 'Oldest'] }], + anchored: [{ 'Release': ['Oldest', 'Newest', 'Middle'] }], + topAfterManualOrder: [{ 'Release': ['Middle', 'Oldest', 'Newest'] }], + bottom: [{ 'Release': ['Oldest', 'Newest', 'Middle'] }], + }); + }); + + test('changes grouping, sorting, filters, and archived visibility', async () => { + const { read, organize, list } = setup([session('Alpha', 1)]); + + const { results } = await organize({ action: 'setView', grouping: 'date', sorting: 'updated', showArchived: true, sessionsPerSection: 'all', filters: [{ kind: 'harness', id: 'claude', included: false }] }); + const { view } = await read(); + + assert.deepStrictEqual({ results, view: { ...view, filters: undefined }, claudeExcluded: list.filters.isExcluded({ kind: 'harness', id: 'claude' }) }, { + results: [{ action: 'setView', ok: true }], + view: { grouping: 'date', sorting: 'updated', showArchived: true, sessionsPerSection: 'all', compact: false, externalSection: false, filters: undefined }, + claudeExcluded: true, + }); + }); + + test('stops at the first failing operation and reports the rest as skipped', async () => { + const { organize, harness } = setup([session('Alpha', 1)]); + + const output = await organize( + { action: 'setView', filters: [{ kind: 'harness', id: 'unknown-harness', included: false }] }, + { action: 'createGroup', name: 'Never created' }, + ); + + assert.deepStrictEqual({ ...output, groups: harness.instantiationService.get(ISessionGroupsService).getGroups() }, { + results: [{ action: 'setView', ok: false, error: 'There is no harness filter "unknown-harness". Use the filters that readSessionsList reports.' }], + skippedOperations: 1, + hint: 'Operations after the failure did not run. Call readSessionsList to see the current state before retrying.', + groups: [], + }); + }); + + test('refuses to read or change the list while the setting is off', async () => { + const { invokeRaw, configurationService, harness } = setup([session('Alpha', 1)]); + await configurationService.setUserConfiguration(SESSIONS_LIST_AGENT_TOOLS_SETTING, false); + + const results = [await invokeRaw('read', {}), await invokeRaw('organize', { operations: [{ action: 'createGroup', name: 'Never created' }] })]; + + assert.deepStrictEqual({ + results: results.map(result => ({ content: result.content, error: result.toolResultError })), + groups: harness.instantiationService.get(ISessionGroupsService).getGroups(), + }, { + results: [0, 1].map(() => ({ content: [{ kind: 'text', value: 'Error: The Sessions list tools are disabled.' }], error: 'The Sessions list tools are disabled.' })), + groups: [], + }); + }); +}); diff --git a/src/vs/sessions/contrib/sessions/test/browser/sessionsViewMenu.test.ts b/src/vs/sessions/contrib/sessions/test/browser/sessionsViewMenu.test.ts index 2e1a3d17b001c7..0e8521be16493a 100644 --- a/src/vs/sessions/contrib/sessions/test/browser/sessionsViewMenu.test.ts +++ b/src/vs/sessions/contrib/sessions/test/browser/sessionsViewMenu.test.ts @@ -116,14 +116,16 @@ suite('Sessions - View Menu', () => { getProviders: () => environments.map(environment => ({ environment })), }, _register: <T extends IDisposable>(disposable: T): T => store.add(disposable), + sessionsControl, registerSessionFilters: Reflect.get(SessionsView.prototype, 'registerSessionFilters') as (control: SessionsList) => void, registerArchivedFilter: Reflect.get(SessionsView.prototype, 'registerArchivedFilter') as (control: SessionsList) => void, - registerResetFiltersAction: Reflect.get(SessionsView.prototype, 'registerResetFiltersAction') as (control: SessionsList) => void, + registerResetFiltersAction: Reflect.get(SessionsView.prototype, 'registerResetFiltersAction') as () => void, + resetFilters: SessionsView.prototype.resetFilters, syncFilterContextKeys: Reflect.get(SessionsView.prototype, 'syncFilterContextKeys') as (control: SessionsList) => void, }; host.registerSessionFilters(sessionsControl); host.registerArchivedFilter(sessionsControl); - host.registerResetFiltersAction(sessionsControl); + host.registerResetFiltersAction(); const snapshot = (menu: MenuId) => MenuRegistry.getMenuItems(menu) .filter(item => contextKeyService.contextMatchesRules(item.when)) diff --git a/src/vs/sessions/sessions.desktop.main.ts b/src/vs/sessions/sessions.desktop.main.ts index fb292b69906487..b75872d866ee12 100644 --- a/src/vs/sessions/sessions.desktop.main.ts +++ b/src/vs/sessions/sessions.desktop.main.ts @@ -199,6 +199,7 @@ import '../workbench/contrib/webview/electron-browser/webview.contribution.js'; // Browser import '../workbench/contrib/browserView/electron-browser/browserView.contribution.js'; +import './contrib/editor/electron-browser/browserEmptyState.contribution.js'; // Splash import '../workbench/contrib/splash/electron-browser/splash.contribution.js'; diff --git a/src/vs/sessions/test/browser/chatGroupsView.test.ts b/src/vs/sessions/test/browser/chatGroupsView.test.ts index 99fb5041c74489..4058473513f04d 100644 --- a/src/vs/sessions/test/browser/chatGroupsView.test.ts +++ b/src/vs/sessions/test/browser/chatGroupsView.test.ts @@ -7,6 +7,7 @@ import assert from 'assert'; import { $ } from '../../../base/browser/dom.js'; import { mainWindow } from '../../../base/browser/window.js'; import { DeferredPromise, timeout } from '../../../base/common/async.js'; +import { IAction, toAction } from '../../../base/common/actions.js'; import { errorHandler, setUnexpectedErrorHandler } from '../../../base/common/errors.js'; import { Emitter, Event } from '../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../base/common/lifecycle.js'; @@ -38,6 +39,7 @@ import { AgentWorkbenchLayout } from '../../browser/workbench.js'; import { IChatSessionHistoryStatus } from '../../../platform/chat/common/chatSessionHistory.js'; import { AbstractChatView, ChatViewKind, IChatViewOptions } from '../../browser/parts/chatView.js'; import { ChatGroupsView } from '../../browser/parts/chatGroupsView.js'; +import { ChatGroupView } from '../../browser/parts/chatGroupView.js'; import { GRID_GAP_SASH_CLASS } from '../../browser/parts/gridGap.js'; import { SessionDropTarget } from '../../browser/parts/sessionDropTarget.js'; import { DraggedSessionIdentifier, SessionsDataTransfers } from '../../browser/dnd.js'; @@ -404,6 +406,22 @@ suite('Sessions - ChatGroupsView', () => { assert.deepStrictEqual([before, view['_mainChatResource']], [true, undefined]); }); + test('clearing a chat group releases its activity action observation', async () => { + const { instantiationService, configurationService } = createHarness(disposables, true, true); + await configurationService.setUserConfiguration(SESSION_ACTIVITY_BAR_SETTING, true); + const group = disposables.add(instantiationService.createInstance(ChatGroupView)); + let observations = 0; + const actions = derived<readonly IAction[]>(reader => { + observations++; + reader.store.add(toDisposable(() => observations--)); + return [toAction({ id: 'test.chatAction', label: 'Chat Action', run: () => { } })]; + }); + group['_sessionActivityBar'].setChatActions(actions); + const before = observations; + group.setContext(undefined); + assert.deepStrictEqual({ before, after: observations }, { before: 1, after: 0 }); + }); + test('releases the main chat resource observable on disposal', () => { const { view } = createHarness(disposables); view.setSession(new TestActiveSession([createChat('main')]), options); diff --git a/src/vs/sessions/test/browser/desktopEditorPart.test.ts b/src/vs/sessions/test/browser/desktopEditorPart.test.ts index 38e3c3d6114874..ea5aa76222995b 100644 --- a/src/vs/sessions/test/browser/desktopEditorPart.test.ts +++ b/src/vs/sessions/test/browser/desktopEditorPart.test.ts @@ -63,6 +63,8 @@ suite('Sessions - Desktop editor part empty group', () => { const root = append(mainWindow.document.body, $('.monaco-workbench.agent-sessions-workbench')); disposables.add(toDisposable(() => root.remove())); root.style.setProperty('--vscode-spacing-size80', '8px'); + root.style.setProperty('--vscode-spacing-size240', '24px'); + root.style.setProperty('--vscode-spacing-size280', '28px'); root.style.setProperty('--vscode-codiconFontSize', '16px'); const part = append(root, $('.part.editor')); const element = append(append(part, $('.content')), $('.editor-group-container.empty.active')); @@ -164,9 +166,9 @@ suite('Sessions - Desktop editor part empty group', () => { return { root, part, element, logo, control, contextViewService, keybindingService, requestedMenus, ran, notifiedErrors, telemetry, state, setEmpty, fireMenuChanged, addTab, list, entries, entry }; } - const isShown = (target: Element | null | undefined) => !!target && mainWindow.getComputedStyle(target).display !== 'none'; + const isShown = (target: Element | null | undefined) => !!target?.getClientRects().length; - test('renders the Add Tab menu as a top `+` and a centered watermark list only while the group is empty', () => { + test('renders the Add Tab menu as a top `+` and a first-row-aligned watermark only while the group is empty', () => { const { element, logo, control, contextViewService, requestedMenus, ran, state, setEmpty, fireMenuChanged, addTab, list, entries } = createEmptyGroup(store); const snapshot = () => { const groupBounds = element.getBoundingClientRect(); @@ -176,8 +178,8 @@ suite('Sessions - Desktop editor part empty group', () => { return { plus: isShown(plus) && isShown(plus!.querySelector('.tabs-bar-add-tab')) ? { top: plus!.getBoundingClientRect().top - groupBounds.top, left: plus!.getBoundingClientRect().left - groupBounds.left } : undefined, list: isShown(listElement) && listBounds ? { - centered: Math.abs((listBounds.top + listBounds.height / 2) - (groupBounds.top + groupBounds.height / 2)) < 1 - && Math.abs((listBounds.left + listBounds.width / 2) - (groupBounds.left + groupBounds.width / 2)) < 1, + firstRowAligned: Math.abs(listBounds.top - (groupBounds.top + groupBounds.height / 2 - 42)) < 1, + centeredHorizontally: Math.abs((listBounds.left + listBounds.width / 2) - (groupBounds.left + groupBounds.width / 2)) < 1, // What ends each row: rows without a keybinding end with the label or, for submenus, the chevron. trailing: entries().map(row => row.lastElementChild?.className), entries: entries().map(row => ({ @@ -255,7 +257,8 @@ suite('Sessions - Desktop editor part empty group', () => { emptyWithActions: { plus: { top: 0, left: 0 }, list: { - centered: true, + firstRowAligned: true, + centeredHorizontally: true, trailing: ['sessions-add-tab-watermark-label', 'sessions-add-tab-watermark-label', 'sessions-add-tab-watermark-submenu-indicator codicon codicon-chevron-right'], entries: [ { label: 'Browser', icon: true, popup: null, submenuIndicator: false }, @@ -266,7 +269,8 @@ suite('Sessions - Desktop editor part empty group', () => { logoShown: false, }, emptyWithoutSubmenu: { - centered: true, + firstRowAligned: true, + centeredHorizontally: true, trailing: ['sessions-add-tab-watermark-label', 'sessions-add-tab-watermark-label'], entries: [ { label: 'Browser', icon: true, popup: null, submenuIndicator: false }, @@ -274,7 +278,7 @@ suite('Sessions - Desktop editor part empty group', () => { ], }, emptyWithoutActions: { plus: undefined, list: undefined, logoShown: true }, - notEmpty: { plus: undefined, list: undefined, logoShown: true, rendered: false }, + notEmpty: { plus: undefined, list: undefined, logoShown: false, rendered: false }, emptyAgain: { rendered: true, entries: 3 }, removedOnDispose: true, }); diff --git a/src/vs/sessions/test/browser/layoutActions.test.ts b/src/vs/sessions/test/browser/layoutActions.test.ts index 746a5e556627c7..e73632bd83c709 100644 --- a/src/vs/sessions/test/browser/layoutActions.test.ts +++ b/src/vs/sessions/test/browser/layoutActions.test.ts @@ -151,6 +151,7 @@ suite('Sessions - Layout Actions', () => { test('toggles the session activity bar layout actions from its context menu', async () => { const items = MenuRegistry.getMenuItems(Menus.SessionActivityBarContext).filter(isIMenuItem) + .filter(item => item.group === 'navigation') .map(item => ({ id: item.command.id, title: item.command.title, toggled: item.command.toggled, order: item.order })) .sort((first, second) => (first.order ?? 0) - (second.order ?? 0)); const configurationService = new class extends TestConfigurationService { diff --git a/src/vs/sessions/test/browser/sessionActivityBar.test.ts b/src/vs/sessions/test/browser/sessionActivityBar.test.ts index 8549bca4f90567..cf4beddafe21cf 100644 --- a/src/vs/sessions/test/browser/sessionActivityBar.test.ts +++ b/src/vs/sessions/test/browser/sessionActivityBar.test.ts @@ -11,6 +11,8 @@ import { retry, timeout } from '../../../base/common/async.js'; import { Codicon } from '../../../base/common/codicons.js'; import { Emitter, Event } from '../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../base/common/lifecycle.js'; +import { toAction } from '../../../base/common/actions.js'; +import { derived, observableValue } from '../../../base/common/observable.js'; import { AnchorAlignment } from '../../../base/common/layout.js'; import { ThemeIcon } from '../../../base/common/themables.js'; import { IHoverDelegate } from '../../../base/browser/ui/hover/hoverDelegate.js'; @@ -22,6 +24,7 @@ import { IAccessibilityService } from '../../../platform/accessibility/common/ac import { IMenu, IMenuActionOptions, IMenuChangeEvent, IMenuService, MenuId, MenuItemAction, MenuRegistry, SubmenuItemAction } from '../../../platform/actions/common/actions.js'; import { ICommandService } from '../../../platform/commands/common/commands.js'; import { ContextKeyExpr, ContextKeyExpression, IContextKeyService } from '../../../platform/contextkey/common/contextkey.js'; +import { ContextKeyService } from '../../../platform/contextkey/browser/contextKeyService.js'; import { IConfigurationChangeEvent, IConfigurationService } from '../../../platform/configuration/common/configuration.js'; import { TestConfigurationService } from '../../../platform/configuration/test/common/testConfigurationService.js'; import { IContextMenuMenuDelegate, IContextMenuService, IContextViewService } from '../../../platform/contextview/browser/contextView.js'; @@ -32,6 +35,7 @@ import { TogglePanelAction } from '../../../workbench/browser/parts/panel/panelA import { AgentWorkbenchLayout, IAgentWorkbenchLayoutService } from '../../browser/workbench.js'; import { SESSION_ACTIVITY_BAR_SETTING } from '../../common/sessionConfig.js'; import { TOGGLE_SIDE_PANEL_COMMAND_ID } from '../../common/sessionCommands.js'; +import { sessionActivityBarChatActionContext } from '../../common/contextkeys.js'; import { ISessionActivityBarActivityService, SessionActivityBarActivityService } from '../../services/activity/common/sessionActivityBarActivityService.js'; import { IconBadge, NumberBadge } from '../../../workbench/services/activity/common/activity.js'; import { TestContextViewService } from './testContextViewService.js'; @@ -47,6 +51,7 @@ interface ITestEntry { readonly group?: string; /** Whether the entry is checked, as when the side pane shows its editor. */ readonly checked?: boolean; + readonly when?: ContextKeyExpression; } const changes: ITestEntry = { id: 'test.changes', title: 'Changes', icon: Codicon.gitCompare }; @@ -99,13 +104,16 @@ suite('Sessions - Session Activity Bar', () => { let createdMenu: IMenu | undefined; const onDidChangeMenu = testStore.add(new Emitter<IMenuChangeEvent>()); instantiationService.stub(IMenuService, new class extends mock<IMenuService>() { - override createMenu(): IMenu { + override createMenu(_id: MenuId, contextKeyService: IContextKeyService): IMenu { const menu: IMenu = { onDidChange: onDidChangeMenu.event, dispose: () => { }, getActions: options => { const groups = new Map<string, (MenuItemAction | SubmenuItemAction)[]>(); for (const entry of entries) { + if (entry.when && !contextKeyService.contextMatchesRules(entry.when)) { + continue; + } const group = entry.group ?? 'navigation'; groups.set(group, [...groups.get(group) ?? [], entry.submenu ? new SubmenuItemAction({ submenu: MenuId.for(entry.id), title: entry.title, icon: entry.icon }, undefined, entry.submenu.map(item => @@ -142,6 +150,7 @@ suite('Sessions - Session Activity Bar', () => { const configurationService = new TestConfigurationService({ [SESSION_ACTIVITY_BAR_SETTING]: true }); instantiationService.stub(IConfigurationService, configurationService); + instantiationService.stub(IContextKeyService, testStore.add(instantiationService.createInstance(ContextKeyService))); const activityService = testStore.add(new SessionActivityBarActivityService()); instantiationService.stub(ISessionActivityBarActivityService, activityService); @@ -171,7 +180,7 @@ suite('Sessions - Session Activity Bar', () => { }, setEnabled: (enabled: boolean) => { configurationService.setUserConfiguration(SESSION_ACTIVITY_BAR_SETTING, enabled); - configurationService.onDidChangeConfigurationEmitter.fire(upcastPartial<IConfigurationChangeEvent>({ affectsConfiguration: (key: string) => key === SESSION_ACTIVITY_BAR_SETTING })); + configurationService.onDidChangeConfigurationEmitter.fire(upcastPartial<IConfigurationChangeEvent>({ affectedKeys: new Set([SESSION_ACTIVITY_BAR_SETTING]), affectsConfiguration: (key: string) => key === SESSION_ACTIVITY_BAR_SETTING })); }, }; } @@ -180,6 +189,57 @@ suite('Sessions - Session Activity Bar', () => { target.dispatchEvent(new KeyboardEvent('keydown', { key, keyCode, bubbles: true, cancelable: true })); } + test('does not subscribe to chat actions while the activity bar is disabled', () => { + const { activityBar, setEnabled } = createActivityBar(store, [browser]); + let subscriptions = 0; + const actions = derived(reader => { + subscriptions++; + reader.store.add(toDisposable(() => subscriptions--)); + return []; + }); + setEnabled(false); + activityBar.setChatActions(actions); + const disabled = subscriptions; + setEnabled(true); + const enabled = subscriptions; + setEnabled(false); + assert.deepStrictEqual({ disabled, enabled, disabledAgain: subscriptions }, { disabled: 0, enabled: 1, disabledAgain: 0 }); + }); + + test('scopes chat actions to their bar and refreshes their labels and callbacks', async () => { + const id = 'test.pullRequest'; + const entry = { id, title: 'Open Pull Request', icon: Codicon.gitPullRequest, group: SessionActivityBarGroup.GitHub, when: sessionActivityBarChatActionContext(id) }; + const first = createActivityBar(store, [browser, entry]); + const second = createActivityBar(store, [browser, entry]); + const opened: number[] = []; + const action = (number: number) => toAction({ id, label: `Open Pull Request #${number}`, class: ThemeIcon.asClassName(Codicon.gitPullRequest), run: () => { opened.push(number); } }); + const original = action(1); + let originalIdReads = 0; + Object.defineProperty(original, 'id', { get: () => { originalIdReads++; return id; } }); + const actions = observableValue('actions', [original]); + first.activityBar.setChatActions(actions); + first.label('Open Pull Request').click(); + key(first.label('Open Pull Request'), 35, 'End'); + actions.set([action(2)], undefined); + originalIdReads = 0; + const focusPreserved = getActiveElement() === first.label('Open Pull Request'); + key(first.label('Open Pull Request'), 13, 'Enter'); + first.label('Open Pull Request').dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter', keyCode: 13, bubbles: true, cancelable: true })); + key(first.label('Open Pull Request'), 32, ' '); + first.label('Open Pull Request').dispatchEvent(new KeyboardEvent('keyup', { key: ' ', keyCode: 32, bubbles: true, cancelable: true })); + const updated = first.label('Open Pull Request').getAttribute('aria-label'); + const otherBar = !!second.activityBar.element.querySelector('.action-label[aria-label^="Open Pull Request"]'); + first.setEnabled(false); + first.setEnabled(true); + const restored = !!first.label('Open Pull Request'); + first.activityBar.setChatActions(undefined); + await timeout(0); + + assert.deepStrictEqual({ opened, originalIdReads, updated, otherBar, restored, focusPreserved, cleared: !!first.label('Open Pull Request'), commands: first.ran }, { + opened: [1, 2, 2], originalIdReads: 0, updated: 'Open Pull Request #2', otherBar: false, restored: true, focusPreserved: true, cleared: false, commands: [], + }); + }); + test('shows icon-only entries while enabled and has entries, outside the phone layout', () => { const { root, activityBar, setEntries, setEnabled } = createActivityBar(store, [changes, browser, canvas]); const displayed = () => mainWindow.getComputedStyle(activityBar.element).display !== 'none'; diff --git a/src/vs/sessions/test/browser/sessionsEmptyStateLayout.test.ts b/src/vs/sessions/test/browser/sessionsEmptyStateLayout.test.ts new file mode 100644 index 00000000000000..e595e53f42a88f --- /dev/null +++ b/src/vs/sessions/test/browser/sessionsEmptyStateLayout.test.ts @@ -0,0 +1,176 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { $, append } from '../../../base/browser/dom.js'; +import { mainWindow } from '../../../base/browser/window.js'; +import { toDisposable } from '../../../base/common/lifecycle.js'; +import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../base/test/common/utils.js'; +import { SessionsEmptyStateLayout } from '../../browser/parts/sessionsEmptyStateLayout.js'; + +suite('Sessions - Empty state layout', () => { + const store = ensureNoDisposablesAreLeakedInTestSuite(); + + test('aligns the first button with search fields and status text above it', () => { + const observers: TestResizeObserver[] = []; + class TestResizeObserver implements ResizeObserver { + constructor(readonly callback: ResizeObserverCallback) { observers.push(this); } + observe(): void { } + unobserve(): void { } + disconnect(): void { } + } + const fixtures = [ + { name: 'main', header: 0, toolbar: 0, heights: [84], status: 0 }, + { name: 'main-with-extra-action', header: 0, toolbar: 0, heights: [112], status: 0 }, + { name: 'files', header: 35, toolbar: 0, heights: [98], status: 42 }, + { name: 'browser', header: 35, toolbar: 32, heights: [56], status: 0 }, + { name: 'search', header: 35, toolbar: 0, heights: [26, 56], status: 0 }, + { name: 'search-with-multiline-query', header: 35, toolbar: 0, heights: [52, 56], status: 0 }, + { name: 'changes', header: 35, toolbar: 0, heights: [90], status: 34 }, + { name: 'changes-with-wrapped-status', header: 35, toolbar: 0, heights: [108], status: 52 }, + ].map(options => { + const group = append(mainWindow.document.body, $('.editor-group-container')); + group.style.cssText = 'position: relative; width: 400px; height: 400px; display: flex; flex-direction: column;'; + store.add(toDisposable(() => group.remove())); + const header = append(group, $('div')); + header.style.flex = `0 0 ${options.header}px`; + const container = append(group, $('div')); + container.style.cssText = 'display: flex; flex-direction: column; flex: 1; min-height: 0;'; + if (options.toolbar) { + const toolbar = append(container, $('div')); + toolbar.style.flex = `0 0 ${options.toolbar}px`; + } + const elements = options.heights.map(height => { + const element = append(container, $('div')); + element.style.cssText = `flex: 0 0 ${height}px;`; + return element; + }); + elements[0].style.marginTop = 'auto'; + elements.at(-1)!.style.marginBottom = 'auto'; + if (elements.length > 1) { + elements[0].style.marginBottom = '16px'; + } + const anchor = options.status ? append(elements[0], $('button')) : elements.at(-1)!; + if (options.status) { + anchor.style.cssText = `display: block; position: relative; top: ${options.status}px; height: 28px;`; + } + store.add(new SessionsEmptyStateLayout(container, elements, anchor, TestResizeObserver)); + return { ...options, group, headerElement: header, elements, anchor }; + }); + const results = []; + for (const height of [400, 640]) { + for (const headerHeight of [28, 35]) { + for (const fixture of fixtures) { + fixture.group.style.height = `${height}px`; + fixture.headerElement.style.flexBasis = `${fixture.header ? headerHeight : 0}px`; + } + for (const observer of observers) { + observer.callback([], observer); + } + results.push(...fixtures.map(fixture => { + const groupBounds = fixture.group.getBoundingClientRect(); + const firstButtonTop = fixture.anchor.getBoundingClientRect().top; + const mainFirstRowTop = (groupBounds.top + groupBounds.bottom) / 2 - 42; + return { + name: fixture.name, + height, + headerHeight, + firstButtonAligned: Math.abs(firstButtonTop - mainFirstRowTop) < 1, + }; + })); + } + } + assert.deepStrictEqual(results, results.map(result => ({ ...result, firstButtonAligned: true }))); + }); + + test('observes only alignment targets and preceding toolbars while following header changes', () => { + const observed: Element[] = []; + let observer: TestResizeObserver | undefined; + class TestResizeObserver implements ResizeObserver { + constructor(readonly callback: ResizeObserverCallback) { observer = this; } + observe(target: Element): void { observed.push(target); } + unobserve(): void { } + disconnect(): void { } + } + const group = append(mainWindow.document.body, $('.editor-group-container')); + group.style.cssText = 'height: 220px; width: 400px; display: flex; flex-direction: column;'; + store.add(toDisposable(() => group.remove())); + const header = append(group, $('div')); + header.style.flex = '0 0 35px'; + const wrapper = append(group, $('div')); + wrapper.style.cssText = 'display: flex; flex: 1; min-height: 0;'; + const container = append(wrapper, $('div')); + container.style.cssText = 'display: flex; flex-direction: column; flex: 1; min-height: 0;'; + const toolbar = append(container, $('div')); + toolbar.style.flex = '0 0 20px'; + const content = append(container, $('div')); + content.style.cssText = 'flex: 0 0 56px; margin: auto 0;'; + const anchor = append(content, $('button')); + anchor.style.cssText = 'display: block; height: 28px;'; + const unrelated = append(container, $('div')); + unrelated.style.cssText = 'position: absolute; height: 10px;'; + store.add(new SessionsEmptyStateLayout(container, [content], anchor, TestResizeObserver)); + assert.ok(observer); + const geometry = () => ({ + aligned: Math.abs(anchor.getBoundingClientRect().top - (group.getBoundingClientRect().top + group.getBoundingClientRect().bottom) / 2 + 42) < 1, + belowToolbar: content.getBoundingClientRect().top >= toolbar.getBoundingClientRect().bottom, + insidePanel: content.getBoundingClientRect().bottom <= group.getBoundingClientRect().bottom, + }); + const before = geometry(); + header.style.flexBasis = '40px'; + toolbar.style.flexBasis = '80px'; + observer.callback([], observer); + const clamped = geometry(); + group.style.height = '400px'; + observer.callback([], observer); + assert.deepStrictEqual({ + targets: observed.map(element => element === container ? 'container' : element === group ? 'group' : element === anchor ? 'anchor' : element === content ? 'content' : element === toolbar ? 'toolbar' : 'unrelated'), + before, + clamped, + resized: geometry(), + }, { + targets: ['container', 'group', 'anchor', 'content', 'toolbar'], + before: { aligned: true, belowToolbar: true, insidePanel: true }, + clamped: { aligned: false, belowToolbar: true, insidePanel: true }, + resized: { aligned: true, belowToolbar: true, insidePanel: true }, + }); + }); + + test('clamps short panels below the toolbar and cleans up positioning on dispose', () => { + let disconnected = false; + class TestResizeObserver implements ResizeObserver { + observe(): void { } + unobserve(): void { } + disconnect(): void { disconnected = true; } + } + const group = append(mainWindow.document.body, $('.editor-group-container')); + group.style.cssText = 'height: 160px; width: 400px; display: flex; flex-direction: column;'; + store.add(toDisposable(() => group.remove())); + const header = append(group, $('div')); + header.style.flex = '0 0 35px'; + const container = append(group, $('div')); + container.style.cssText = 'flex: 1; min-height: 0; display: flex; flex-direction: column;'; + const toolbar = append(container, $('div')); + toolbar.style.flex = '0 0 48px'; + const content = append(container, $('div')); + content.style.cssText = 'flex: 0 0 56px; margin: auto 0;'; + const layout = store.add(new SessionsEmptyStateLayout(container, [content], content, TestResizeObserver)); + const contentBounds = content.getBoundingClientRect(); + const before = { + belowToolbar: contentBounds.top >= toolbar.getBoundingClientRect().bottom, + insidePanel: contentBounds.bottom <= group.getBoundingClientRect().bottom, + }; + layout.dispose(); + assert.deepStrictEqual({ + before, + disconnected, + positioningRemoved: !content.classList.contains('sessions-empty-state-aligned') && content.style.translate === '', + }, { + before: { belowToolbar: true, insidePanel: true }, + disconnected: true, + positioningRemoved: true, + }); + }); +}); diff --git a/src/vs/workbench/api/browser/mainThreadMcp.ts b/src/vs/workbench/api/browser/mainThreadMcp.ts index fab0be75b7a564..6d1dfb6f1860d8 100644 --- a/src/vs/workbench/api/browser/mainThreadMcp.ts +++ b/src/vs/workbench/api/browser/mainThreadMcp.ts @@ -19,6 +19,7 @@ import { IDialogService, IPromptButton } from '../../../platform/dialogs/common/ import { ExtensionIdentifier } from '../../../platform/extensions/common/extensions.js'; import { LogLevel } from '../../../platform/log/common/log.js'; import { IAllowedMcpServersService } from '../../../platform/mcp/common/mcpManagement.js'; +import { McpServerPolicyValues } from '../../../platform/mcp/common/allowedMcpServers.js'; import { ITelemetryService } from '../../../platform/telemetry/common/telemetry.js'; import { ISecretStorageService } from '../../../platform/secrets/common/secrets.js'; import { IWorkbenchMcpGatewayService } from '../../contrib/mcp/common/mcpGatewayService.js'; @@ -45,6 +46,7 @@ export class MainThreadMcp extends Disposable implements MainThreadMcpShape { private readonly _servers = new Map<number, ExtHostMcpServerLaunch>(); private readonly _serverDefinitions = new Map<number, McpServerDefinition>(); private readonly _serverRequestUrls = new Map<number, Set<string>>(); + private readonly _serverPolicyValues = new Map<number, McpServerPolicyValues>(); private readonly _serverAuthTracking = new McpServerAuthTracker(); private readonly _proxy: Proxied<ExtHostMcpShape>; private readonly _collectionDefinitions = this._register(new DisposableMap<string, { @@ -80,7 +82,7 @@ export class MainThreadMcp extends Disposable implements MainThreadMcpShape { continue; } for (const url of urls) { - const allowed = this._allowedMcpServersService.isServerAllowed({ name: definition.label, url }); + const allowed = this._allowedMcpServersService.isServerAllowed({ name: definition.label, url, policyValues: this._serverPolicyValues.get(id) }); if (allowed !== true) { this.$onDidChangeState(id, { state: McpConnectionState.Kind.Error, message: allowed.value }); proxy.$stopMcp(id); @@ -115,6 +117,7 @@ export class MainThreadMcp extends Disposable implements MainThreadMcpShape { const ser = await proxy.$expandEnvironmentVariables(McpServerLaunch.toSerialized(launch), serverDefinition.environmentVariableExpansion); return McpServerLaunch.fromSerialized(ser); }, + resolvePolicyVariables: values => proxy.$resolveMcpPolicyVariables(values), start: (_collection, serverDefiniton, resolveLaunch, options) => { const id = ++this._serverIdCounter; const launch = new ExtHostMcpServerLaunch( @@ -124,6 +127,9 @@ export class MainThreadMcp extends Disposable implements MainThreadMcpShape { ); this._servers.set(id, launch); this._serverDefinitions.set(id, serverDefiniton); + if (options?.policyValues) { + this._serverPolicyValues.set(id, options.policyValues); + } if (resolveLaunch.type === McpServerTransportType.HTTP) { this._serverRequestUrls.set(id, new Set([resolveLaunch.uri.toString(true)])); } @@ -233,7 +239,13 @@ export class MainThreadMcp extends Disposable implements MainThreadMcpShape { throw new CancellationError(); } - const allowed = this._allowedMcpServersService.isServerAllowed({ name: definition.label, url }); + const values = this._allowedMcpServersService.getServerPolicyVariableValues(); + const policyValues = values.length ? await this._proxy.$resolveMcpPolicyVariables(values) : {}; + if (!this._serverDefinitions.has(id)) { + throw new CancellationError(); + } + this._serverPolicyValues.set(id, policyValues); + const allowed = this._allowedMcpServersService.isServerAllowed({ name: definition.label, url, policyValues }); if (allowed !== true) { return allowed.value; } @@ -254,6 +266,7 @@ export class MainThreadMcp extends Disposable implements MainThreadMcpShape { this._servers.delete(id); this._serverDefinitions.delete(id); this._serverRequestUrls.delete(id); + this._serverPolicyValues.delete(id); this._serverAuthTracking.untrack(id); } } @@ -623,6 +636,7 @@ export class MainThreadMcp extends Disposable implements MainThreadMcpShape { this._servers.clear(); this._serverDefinitions.clear(); this._serverRequestUrls.clear(); + this._serverPolicyValues.clear(); this._serverAuthTracking.clear(); super.dispose(); } diff --git a/src/vs/workbench/api/common/extHost.protocol.ts b/src/vs/workbench/api/common/extHost.protocol.ts index 76e78037f4e8fe..76e9e91b02e900 100644 --- a/src/vs/workbench/api/common/extHost.protocol.ts +++ b/src/vs/workbench/api/common/extHost.protocol.ts @@ -43,6 +43,7 @@ import * as files from '../../../platform/files/common/files.js'; import { ResourceLabelFormatter } from '../../../platform/label/common/label.js'; import { ILoggerOptions, ILoggerResource, LogLevel } from '../../../platform/log/common/log.js'; import { IMarkerData } from '../../../platform/markers/common/markers.js'; +import { McpServerPolicyValues } from '../../../platform/mcp/common/allowedMcpServers.js'; import { IProgressOptions, IProgressStep } from '../../../platform/progress/common/progress.js'; import { NotificationTelemetryId } from '../../../platform/notification/common/notificationTelemetry.js'; import * as quickInput from '../../../platform/quickinput/common/quickInput.js'; @@ -3782,6 +3783,8 @@ export interface IStartMcpOptions { export interface ExtHostMcpShape { $substituteVariables(workspaceFolder: UriComponents | undefined, value: McpServerLaunch.Serialized): Promise<McpServerLaunch.Serialized>; $expandEnvironmentVariables(launch: McpServerLaunch.Serialized, expansion: McpServerEnvironmentVariableExpansion): Promise<McpServerLaunch.Serialized>; + /** Expands matcher strings on the executing host; the client must still enforce allow/deny rules using the returned values. */ + $resolveMcpPolicyVariables(values: readonly string[]): Promise<McpServerPolicyValues>; $resolveMcpLaunch(collectionId: string, label: string): Promise<McpServerLaunch.Serialized | undefined>; $startMcp(id: number, opts: IStartMcpOptions): void; $stopMcp(id: number): void; diff --git a/src/vs/workbench/api/common/extHostMcp.ts b/src/vs/workbench/api/common/extHostMcp.ts index c9571c6b12fe47..d054ebbb8892b5 100644 --- a/src/vs/workbench/api/common/extHostMcp.ts +++ b/src/vs/workbench/api/common/extHostMcp.ts @@ -18,6 +18,7 @@ import { ConfigurationTarget } from '../../../platform/configuration/common/conf import { ExtensionIdentifier, IExtensionDescription } from '../../../platform/extensions/common/extensions.js'; import { createDecorator } from '../../../platform/instantiation/common/instantiation.js'; import { canLog, ILogService, LogLevel } from '../../../platform/log/common/log.js'; +import { McpServerPolicyValues } from '../../../platform/mcp/common/allowedMcpServers.js'; import product from '../../../platform/product/common/product.js'; import { StorageScope } from '../../../platform/storage/common/storage.js'; import { extensionPrefixedIdentifier, McpCollectionDefinition, McpConnectionState, McpServerDefinition, McpServerEnvironmentVariableExpansion, McpServerLaunch, McpServerStaticMetadata, McpServerStaticToolAvailability, McpServerTransportHTTP, McpServerTransportType, UserInteractionRequiredError } from '../../contrib/mcp/common/mcpTypes.js'; @@ -141,6 +142,10 @@ export class ExtHostMcpService extends Disposable implements IExtHostMpcService return launch; } + async $resolveMcpPolicyVariables(values: readonly string[]): Promise<McpServerPolicyValues> { + return Object.fromEntries(values.map(value => [value, value])); + } + $stopMcp(id: number): void { this._sseEventSources.get(id) ?.close() diff --git a/src/vs/workbench/api/node/extHostMcpNode.ts b/src/vs/workbench/api/node/extHostMcpNode.ts index e05b7b7432223d..51a42829d69087 100644 --- a/src/vs/workbench/api/node/extHostMcpNode.ts +++ b/src/vs/workbench/api/node/extHostMcpNode.ts @@ -17,6 +17,8 @@ import { URI } from '../../../base/common/uri.js'; import { StreamSplitter } from '../../../base/node/nodeStreams.js'; import { findExecutable } from '../../../base/node/processes.js'; import { LogLevel } from '../../../platform/log/common/log.js'; +import { McpServerPolicyValues } from '../../../platform/mcp/common/allowedMcpServers.js'; +import { createEnvVarResolver } from '../../../platform/mcp/common/envVarResolution.js'; import { expandEnvironmentVariablesInLaunch } from '../../contrib/mcp/common/mcpEnvironmentVariableExpansion.js'; import { McpConnectionState, McpServerEnvironmentVariableExpansion, McpServerLaunch, McpServerTransportStdio, McpServerTransportType } from '../../contrib/mcp/common/mcpTypes.js'; import { McpStdioStateHandler } from '../../contrib/mcp/node/mcpStdioStateHandler.js'; @@ -49,6 +51,12 @@ export class NodeExtHostMpcService extends ExtHostMcpService { } else { super.$stopMcp(id); } + + } + + override async $resolveMcpPolicyVariables(values: readonly string[]): Promise<McpServerPolicyValues> { + const resolve = createEnvVarResolver(process.env, isWindows); + return Object.fromEntries(values.map(value => [value, resolve(value)])); } override $sendMessage(id: number, message: string): void { diff --git a/src/vs/workbench/api/test/browser/mainThreadMcp.test.ts b/src/vs/workbench/api/test/browser/mainThreadMcp.test.ts index 362f68c22d733b..3ee836f52f6d94 100644 --- a/src/vs/workbench/api/test/browser/mainThreadMcp.test.ts +++ b/src/vs/workbench/api/test/browser/mainThreadMcp.test.ts @@ -38,6 +38,7 @@ import { TestExtensionService } from '../../../test/common/workbenchTestServices import { IMcpServerAuthContext, MainThreadMcp, McpServerAuthTracker } from '../../browser/mainThreadMcp.js'; import { ExtHostMcpShape, IMcpAuthenticationDetails } from '../../common/extHost.protocol.js'; import { CommonRequestInit, CommonResponse, McpHTTPHandle } from '../../common/extHostMcp.js'; +import { createEnvVarResolver } from '../../../../platform/mcp/common/envVarResolution.js'; import { SingleProxyRPCProtocol } from '../common/testRPCProtocol.js'; function createMainThreadMcp(disposables: Pick<DisposableStore, 'add'>, proxy: Partial<ExtHostMcpShape>, registry: IMcpRegistry, configure?: (services: TestInstantiationService) => void): MainThreadMcp { @@ -58,6 +59,7 @@ function createMainThreadMcp(disposables: Pick<DisposableStore, 'add'>, proxy: P services.stub(IAllowedMcpServersService, { onDidChangeAllowedMcpServers: Event.None, isServerAllowed: () => true, + getServerPolicyVariableValues: () => [], }); configure?.(services); return disposables.add(services.createInstance(MainThreadMcp, SingleProxyRPCProtocol(proxy))); @@ -399,6 +401,7 @@ suite('MainThreadMcp - request policy', () => { denied?: readonly IMcpServerMatcher[]; access?: McpAccessValue; destination?: string; + env?: Record<string, string>; } = {}) { const configuration = new TestConfigurationService({ [mcpAllowedServersConfig]: options.allowed, @@ -425,6 +428,10 @@ suite('MainThreadMcp - request policy', () => { }, $sendMessage() { }, $onDidChangeMcpServerDefinitions() { }, + async $resolveMcpPolicyVariables(values) { + const resolve = createEnvVarResolver(options.env, false); + return Object.fromEntries(values.map(value => [value, resolve(value)])); + }, }, registry, services => { services.stub(IConfigurationService, configuration); services.stub(IAllowedMcpServersService, policy); @@ -489,6 +496,31 @@ suite('MainThreadMcp - request policy', () => { assert.deepStrictEqual(requests, [initialUrl]); }); + test('a name entry cannot bypass a URL entry at the request boundary', async () => { + const { fetch, requests } = createConnection({ allowed: [{ serverName: name }, { serverUrl: initialUrl }] }); + await assert.rejects(fetch(), /not in the list of servers allowed/); + assert.deepStrictEqual(requests, [initialUrl]); + }); + + test('expands URL policies on the connecting host for initial and redirected requests', async () => { + const { fetch, requests } = createConnection({ + allowed: [{ serverUrl: 'https://${INITIAL}/mcp' }, { serverUrl: 'https://${REDIRECTED}/mcp' }], + env: { INITIAL: 'allowed.example', REDIRECTED: 'redirected.example' }, + }); + await fetch(); + assert.deepStrictEqual(requests, [initialUrl, redirectedUrl]); + }); + + test('an expanded URL denial wins over an expanded allow entry', async () => { + const { fetch, requests } = createConnection({ + allowed: [{ serverUrl: 'https://${INITIAL}/mcp' }, { serverUrl: 'https://${REDIRECTED}/mcp' }], + denied: [{ serverUrl: 'https://${REDIRECTED}/mcp' }], + env: { INITIAL: 'allowed.example', REDIRECTED: 'redirected.example' }, + }); + await assert.rejects(fetch(), /blocked by your organization's policy/); + assert.deepStrictEqual(requests, [initialUrl]); + }); + test('preserves the configured server name for destination policy decisions', async () => { const { fetch, requests } = createConnection({ allowed: [{ serverName: name }] }); await fetch(); diff --git a/src/vs/workbench/browser/chatDropdownPill.ts b/src/vs/workbench/browser/chatDropdownPill.ts index 3b9d42b3692243..6cf7309acb5644 100644 --- a/src/vs/workbench/browser/chatDropdownPill.ts +++ b/src/vs/workbench/browser/chatDropdownPill.ts @@ -3,11 +3,9 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { $, addDisposableListener, EventHelper, EventType } from '../../base/browser/dom.js'; -import { Gesture, EventType as TouchEventType } from '../../base/browser/touch.js'; +import { $ } from '../../base/browser/dom.js'; import { IActionViewItemOptions } from '../../base/browser/ui/actionbar/actionViewItems.js'; import type { IManagedHoverContent, IManagedHoverOptions } from '../../base/browser/ui/hover/hover.js'; -import { getDefaultHoverDelegate } from '../../base/browser/ui/hover/hoverDelegateFactory.js'; import { IAction } from '../../base/common/actions.js'; import { Codicon } from '../../base/common/codicons.js'; import { onUnexpectedError } from '../../base/common/errors.js'; @@ -23,7 +21,7 @@ import { ILanguageService } from '../../editor/common/languages/language.js'; import { IModelService } from '../../editor/common/services/model.js'; import { FileKind, IFileService } from '../../platform/files/common/files.js'; import { IHoverService } from '../../platform/hover/browser/hover.js'; -import { ChatPillActionViewItem, createChatPillImagePreview, getChatPillEntries, getChatPillEntryHoverContents, getChatPillEntryHoverOptions, getChatPillEntryToolbarActions, type IChatPill, type IChatPillAction, type IChatPillEntry, type IChatPillSection } from './chatPills.js'; +import { ChatPillActionViewItem, createChatPillImagePreview, getChatPillEntries, getChatPillEntryHoverContents, getChatPillEntryHoverOptions, getChatPillEntryToolbarActions, type IChatPill, type IChatPillEntry, type IChatPillSection } from './chatPills.js'; import { ChatResourcePillActionViewItem } from './chatResourcePill.js'; import type { ResourceLabels } from './labels.js'; import type { IInstantiationService } from '../../platform/instantiation/common/instantiation.js'; @@ -78,7 +76,7 @@ export interface IChatDropdownPillOptions { * interpreted, shared by the factory that picks the rendering and the view item * that picks the label. */ -function getInlineEntry(entries: readonly IChatPillEntry[], options: IChatDropdownPillOptions): IChatPillEntry | undefined { +export function getChatPillInlineEntry(entries: readonly IChatPillEntry[], options: IChatDropdownPillOptions): IChatPillEntry | undefined { if (entries.length !== 1) { return undefined; } @@ -122,8 +120,6 @@ export class ChatDropdownPillActionViewItem extends ChatPillActionViewItem { private readonly _imageHoverContents = new WeakMap<IChatPillEntry, IManagedHoverContent>(); private readonly _dropdownHovers = new WeakMap<IChatPillEntry, IActionListItemHover>(); private readonly _resourceDropdownHovers = new Map<string, { readonly entry: IChatPillEntry; readonly hover: IActionListItemHover }>(); - private _promotedAction: IChatPillAction | undefined; - private _promotedActionElement: HTMLElement | undefined; protected override renderContent(): void { this._register(autorun(reader => { @@ -154,12 +150,10 @@ export class ChatDropdownPillActionViewItem extends ChatPillActionViewItem { if (previous.ariaDescription !== current.ariaDescription) { this._updateAriaDescription(current.ariaDescription); } - if (previous.summarized !== current.summarized) { - this._updatePopupState(); - } + this._updatePopupState(); this._updatePromotedAction(); if (this._dropdownVisible) { - if (current.summarized) { + if (this.opensDropdown) { this._actionWidgetService.updateItems(this._getDropdownItems(), undefined, { preserveHover: true, preserveScrollPosition: true, animateItemMove: true }); } else { this._actionWidgetService.hide(); @@ -190,7 +184,7 @@ export class ChatDropdownPillActionViewItem extends ChatPillActionViewItem { if (!element) { return; } - if (this.isSummarized) { + if (this.opensDropdown) { element.setAttribute('aria-haspopup', 'listbox'); element.setAttribute('aria-expanded', String(this._dropdownVisible)); } else { @@ -219,50 +213,17 @@ export class ChatDropdownPillActionViewItem extends ChatPillActionViewItem { private _updatePromotedAction(): void { const icon = this._pillOptions.promotedActionIcon; const action = icon && !this.isSummarized ? this.entries.at(0)?.promotedAction : undefined; - this._promotedAction = action; - const container = this.element; - if (!container) { - return; - } - container.classList.toggle('has-promoted-action', !!action); - if (!action || !icon) { - this._promotedActionElement?.remove(); - return; - } - const element = this._promotedActionElement ??= this._createPromotedActionElement(icon); - element.setAttribute('aria-label', action.label); - if (element.parentElement !== container) { - container.appendChild(element); - } - } - - private _createPromotedActionElement(icon: ThemeIcon): HTMLElement { - // Not a tab stop: the toolbar moves focus between whole pills, so keyboard - // users take the action from the pill's context menu instead. - const element = $(`span.chat-pill-promoted-action${ThemeIcon.asCSSSelector(icon)}`, { role: 'button', tabindex: '-1' }); - // Its own hover target, so pointing at it shows the action rather than the pill's hover. - this._register(this._hoverService.setupManagedHover(this.options.hoverDelegate ?? getDefaultHoverDelegate('element'), element, () => this._promotedAction?.tooltip || this._promotedAction?.label)); - // Leave focus where it is, so a click that removes the pill cannot strand it. - this._register(addDisposableListener(element, EventType.MOUSE_DOWN, event => event.preventDefault())); - // A gesture target of its own, as for a button: an ancestor's gesture handling - // suppresses the click a tap would synthesize, and taps reach only targets. - this._register(Gesture.addTarget(element)); - for (const eventType of [EventType.CLICK, TouchEventType.Tap]) { - this._register(addDisposableListener(element, eventType, event => { - EventHelper.stop(event, true); - const action = this._promotedAction; - if (action?.enabled) { - Promise.resolve(action.run()).catch(onUnexpectedError); - } - })); - } - return element; + this.updatePromotedAction(action, icon, this._hoverService); } /** Whether the pill stands for its entries rather than showing a single one. */ protected get isSummarized(): boolean { const entries = this.entries; - return entries.length > 0 && !getInlineEntry(entries, this._pillOptions); + return entries.length > 0 && !getChatPillInlineEntry(entries, this._pillOptions); + } + + private get opensDropdown(): boolean { + return this.isSummarized || this._pillOptions.openHoverOnSelect === true; } protected get entries(): readonly IChatPillEntry[] { @@ -292,7 +253,7 @@ export class ChatDropdownPillActionViewItem extends ChatPillActionViewItem { } protected override getAdditionalLabelContent(): Array<HTMLElement | string> { - return this.isSummarized ? [$(`span.chat-pill-chevron${ThemeIcon.asCSSSelector(Codicon.chevronDownCompact)}`, { 'aria-hidden': 'true' })] : []; + return this.opensDropdown ? [$(`span.chat-pill-chevron${ThemeIcon.asCSSSelector(Codicon.chevronDownCompact)}`, { 'aria-hidden': 'true' })] : []; } protected override getTooltip(): string { @@ -323,7 +284,7 @@ export class ChatDropdownPillActionViewItem extends ChatPillActionViewItem { } protected override onDidClickButton(): void { - if (!this.isSummarized) { + if (!this.opensDropdown) { this.openEntry(this.entries.at(0)); return; } @@ -583,13 +544,13 @@ export function createChatSectionPill( instantiationService: IInstantiationService, ): IObservable<IChatPill> { const singleResourceEntry = derived<IChatPillEntry | undefined>(reader => { - const entry = getInlineEntry(getChatPillEntries(sections.read(reader)), options); + const entry = getChatPillInlineEntry(getChatPillEntries(sections.read(reader)), options); return entry?.resource ? entry : undefined; }); const isResource = derived(reader => !!singleResourceEntry.read(reader)); const resourcePill: IChatPill = { action, - createActionViewItem: viewItemOptions => instantiationService.createInstance(ChatResourcePillActionViewItem, action, viewItemOptions, singleResourceEntry, resourceLabels), + createActionViewItem: viewItemOptions => instantiationService.createInstance(ChatResourcePillActionViewItem, action, { ...viewItemOptions, promotedActionIcon: options.promotedActionIcon }, singleResourceEntry, resourceLabels), }; const dropdownPill: IChatPill = { action, diff --git a/src/vs/workbench/browser/chatPills.ts b/src/vs/workbench/browser/chatPills.ts index cc690564f0b452..c1bbb541730147 100644 --- a/src/vs/workbench/browser/chatPills.ts +++ b/src/vs/workbench/browser/chatPills.ts @@ -5,17 +5,21 @@ import { $, addDisposableListener, DisposableResizeObserver, EventHelper, EventType, isHTMLElement, reset } from '../../base/browser/dom.js'; import { StandardKeyboardEvent } from '../../base/browser/keyboardEvent.js'; +import { Gesture, EventType as TouchEventType } from '../../base/browser/touch.js'; import { mainWindow, type CodeWindow } from '../../base/browser/window.js'; import { IActionViewItem } from '../../base/browser/ui/actionbar/actionbar.js'; import { BaseActionViewItem, IActionViewItemOptions } from '../../base/browser/ui/actionbar/actionViewItems.js'; import { Button } from '../../base/browser/ui/button/button.js'; import type { IManagedHoverContent, IManagedHoverOptions } from '../../base/browser/ui/hover/hover.js'; +import { getBaseLayerHoverDelegate } from '../../base/browser/ui/hover/hoverDelegate2.js'; +import { getDefaultHoverDelegate } from '../../base/browser/ui/hover/hoverDelegateFactory.js'; import { DomScrollableElement } from '../../base/browser/ui/scrollbar/scrollableElement.js'; import { ToolBar } from '../../base/browser/ui/toolbar/toolbar.js'; import { IAction, IActionRunner } from '../../base/common/actions.js'; import { disposableTimeout } from '../../base/common/async.js'; import { CancellationToken, cancelOnDispose } from '../../base/common/cancellation.js'; import { Emitter, Event } from '../../base/common/event.js'; +import { onUnexpectedError } from '../../base/common/errors.js'; import { KeyCode } from '../../base/common/keyCodes.js'; import { isMacintosh } from '../../base/common/platform.js'; import { Disposable, DisposableStore, IDisposable, MutableDisposable } from '../../base/common/lifecycle.js'; @@ -27,6 +31,7 @@ import { localize } from '../../nls.js'; import type { IActionListItemHover } from '../../platform/actionWidget/browser/actionList.js'; import { IContextMenuService } from '../../platform/contextview/browser/contextView.js'; import { IFileService } from '../../platform/files/common/files.js'; +import type { IHoverService } from '../../platform/hover/browser/hover.js'; import { asCssVariable, asCssVariableWithDefault, buttonSecondaryBackground } from '../../platform/theme/common/colorRegistry.js'; import { defaultButtonStyles } from '../../platform/theme/browser/defaultStyles.js'; import { createChatImageHoverContent } from './chatImagePreview.js'; @@ -661,6 +666,8 @@ export function createChatPillButton(container: HTMLElement, options?: { readonl export abstract class ChatPillActionViewItemBase extends BaseActionViewItem { protected button: Button | undefined; + private _promotedAction: IChatPillAction | undefined; + private _promotedActionElement: HTMLElement | undefined; /** The rendered button owned by this pill. */ get buttonElement(): HTMLElement | undefined { @@ -715,6 +722,48 @@ export abstract class ChatPillActionViewItemBase extends BaseActionViewItem { this.actionRunner.run(this._action, this._context); } + protected updatePromotedAction(action: IChatPillAction | undefined, icon: ThemeIcon | undefined, hoverService?: IHoverService): void { + this._promotedAction = action; + const container = this.element; + if (!container) { + return; + } + container.classList.toggle('has-promoted-action', !!action && !!icon); + if (!action || !icon) { + this._promotedActionElement?.remove(); + this._promotedActionElement = undefined; + return; + } + const element = this._promotedActionElement ??= this._createPromotedActionElement(icon, hoverService); + element.setAttribute('aria-label', action.label); + if (element.parentElement !== container) { + container.appendChild(element); + } + } + + private _createPromotedActionElement(icon: ThemeIcon, hoverService: IHoverService | undefined): HTMLElement { + // Not a tab stop: the toolbar moves focus between whole pills, so keyboard + // users take the action from the pill's context menu instead. + const element = $(`span.chat-pill-promoted-action${ThemeIcon.asCSSSelector(icon)}`, { role: 'button', tabindex: '-1' }); + const hoverDelegate = this.options.hoverDelegate ?? getDefaultHoverDelegate('element'); + this._register(hoverService + ? hoverService.setupManagedHover(hoverDelegate, element, () => this._promotedAction?.tooltip || this._promotedAction?.label) + : getBaseLayerHoverDelegate().setupManagedHover(hoverDelegate, element, () => this._promotedAction?.tooltip || this._promotedAction?.label)); + // Leave focus where it is, so a click that removes the pill cannot strand it. + this._register(addDisposableListener(element, EventType.MOUSE_DOWN, event => event.preventDefault())); + this._register(Gesture.addTarget(element)); + for (const eventType of [EventType.CLICK, TouchEventType.Tap]) { + this._register(addDisposableListener(element, eventType, event => { + EventHelper.stop(event, true); + const action = this._promotedAction; + if (action?.enabled) { + Promise.resolve(action.run()).catch(onUnexpectedError); + } + })); + } + return element; + } + override focus(): void { if (this.button) { // Arrow navigation blurs the previous item, which drops it out of the diff --git a/src/vs/workbench/browser/chatResourcePill.ts b/src/vs/workbench/browser/chatResourcePill.ts index bbd885448fa080..dacf46c6b90762 100644 --- a/src/vs/workbench/browser/chatResourcePill.ts +++ b/src/vs/workbench/browser/chatResourcePill.ts @@ -14,9 +14,14 @@ import { IObservable, autorun } from '../../base/common/observable.js'; import { ThemeIcon } from '../../base/common/themables.js'; import { localize } from '../../nls.js'; import { FileKind, IFileService } from '../../platform/files/common/files.js'; +import { IHoverService } from '../../platform/hover/browser/hover.js'; import { ChatPillActionViewItemBase, getChatPillEntryHoverContents, getChatPillEntryHoverOptions, type IChatPillEntry } from './chatPills.js'; import { ResourceLabels } from './labels.js'; +interface IChatResourcePillActionViewItemOptions extends IActionViewItemOptions { + readonly promotedActionIcon?: ThemeIcon; +} + /** * A pill showing a single resource as a themed file icon and name. The * surrounding row must opt into `show-file-icons` for the icon to paint. @@ -29,12 +34,13 @@ export class ChatResourcePillActionViewItem extends ChatPillActionViewItemBase { constructor( action: IAction, - options: IActionViewItemOptions, + private readonly _resourcePillOptions: IChatResourcePillActionViewItemOptions, private readonly _entry: IObservable<IChatPillEntry | undefined>, private readonly _resourceLabels: ResourceLabels, @IFileService private readonly _fileService: IFileService, + @IHoverService private readonly _hoverService: IHoverService, ) { - super(undefined, action, options); + super(undefined, action, _resourcePillOptions); } protected override renderContent(button: Button): void { @@ -52,6 +58,7 @@ export class ChatResourcePillActionViewItem extends ChatPillActionViewItemBase { } else { button.element.removeAttribute('aria-description'); } + this.updatePromotedAction(this._resourcePillOptions.promotedActionIcon ? entry?.promotedAction : undefined, this._resourcePillOptions.promotedActionIcon, this._hoverService); })); } @@ -69,7 +76,8 @@ export class ChatResourcePillActionViewItem extends ChatPillActionViewItemBase { } protected override getHoverOptions(): IManagedHoverOptions | undefined { - return getChatPillEntryHoverOptions(this._entry.get()); + const entry = this._entry.get(); + return getChatPillEntryHoverOptions(entry && this._resourcePillOptions.promotedActionIcon ? { ...entry, promotedAction: undefined } : entry); } protected override onDidClickButton(): void { diff --git a/src/vs/workbench/browser/media/chatPills.css b/src/vs/workbench/browser/media/chatPills.css index 92b02c6f37e98c..f76893a143eb3e 100644 --- a/src/vs/workbench/browser/media/chatPills.css +++ b/src/vs/workbench/browser/media/chatPills.css @@ -70,7 +70,7 @@ gap: var(--vscode-spacing-size60); } -.chat-pill-item, +.chat-pills .monaco-action-bar .chat-pill-item, .chat-pills .monaco-action-bar .chat-pill-segmented { display: inline-flex; align-items: center; @@ -222,6 +222,7 @@ border-radius: var(--vscode-cornerRadius-small); color: var(--vscode-descriptionForeground); font-size: var(--vscode-codiconFontSize-compact); + line-height: var(--vscode-spacing-size160); cursor: pointer; } diff --git a/src/vs/workbench/contrib/canvases/test/browser/canvasesPillControl.test.ts b/src/vs/workbench/contrib/canvases/test/browser/canvasesPillControl.test.ts index 71329f79720fec..93153cfb26b736 100644 --- a/src/vs/workbench/contrib/canvases/test/browser/canvasesPillControl.test.ts +++ b/src/vs/workbench/contrib/canvases/test/browser/canvasesPillControl.test.ts @@ -86,4 +86,5 @@ suite('CanvasesPillControl', () => { unsupported: [undefined], }); }); + }); diff --git a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts index 6eb4df7667ac59..cea1b8bf467320 100644 --- a/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts +++ b/src/vs/workbench/contrib/chat/browser/actions/chatAccessibilityHelp.ts @@ -161,7 +161,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui } if (sessionStatusPillsSupported) { content.push(localize('chat.sessionStatusPillCopy', "When a pill represents a single item, its context menu offers the item's copy actions, such as copying its URL or file path. For a collection, open the dropdown and use the individual row actions instead.")); - content.push(localize('chat.sessionStatusPills', "When session status pills appear above the input, use Tab to focus the toolbar, then use the left and right arrow keys to move between pills. Press Enter or Space to activate a pill. Open the context menu{0} to choose which optional pills are visible. Pull Requests Options lets you show all pull requests or only open and draft ones, remembered across sessions. If every pull request is filtered out, these options are also available in any other pill's context menu or the toolbar context menu.", '<keybinding:editor.action.showContextMenu>')); + content.push(localize('chat.sessionStatusPills', "When session status pills appear above the input, use Tab to focus the toolbar, then use the left and right arrow keys to move between pills. Press Enter or Space to activate a pill. An aggregated pill opens a picker. Use Pin on a picker row to keep that entry as its own pill; it is removed from the picker, and a sole remaining entry is shown directly unless it requires a details picker. A pinned pill shows a trailing Unpin button that pointer users can activate to unpin it. Keyboard and screen reader users can open the pinned pill's context menu{0} and choose Unpin. Pin choices are remembered for each chat. The context menu also lets you choose which optional pills are visible. Pull Requests Options lets you show all pull requests or only open and draft ones, remembered across sessions. If every pull request is filtered out, these options are also available in any other pill's context menu or the toolbar context menu.", '<keybinding:editor.action.showContextMenu>')); if (isSessionsWindow) { content.push(localize('chat.sessionPullRequestChanges', "In the Pull Requests pill, open the dropdown and use a pull request's Open Pull Request Changes row action to view its changed files in a multi-file diff editor.")); } @@ -169,7 +169,7 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui if (!isSessionsWindow) { content.push(localize('chat.sessionStatusPillsCompact', "When space is limited, session status pills collapse to icons one at a time from right to left. Their full labels remain available to screen readers and in tooltips. Labels return as space becomes available. If the icons still do not fit, the row scrolls horizontally; use the arrow keys to reach every pill.")); content.push(localize('chat.editorArtifactsPill', "The editor window uses the same compact Artifacts pill as the Agents Window, rather than an expanded list above the input. Generated images appear automatically. In a subagent chat, the Artifacts pill shows that chat's transcript artifacts without the parent session's metadata. A single file pill opens directly; multiple artifacts open a dropdown with a Generated Images section. Use the pill's hover or context menu, or a dropdown row's actions, to save an artifact or copy its path.")); - content.push(localize('chat.editorCanvasesPill', "In local Copilot agent-host sessions with chat.canvases.enabled turned on, a Canvas submenu appears in the final section of the New Chat menu, and the chat's open canvases appear in their own pill in the main window. Open the Canvas submenu to choose a registered or closed canvas by name. Use Up and Down Arrow, Right Arrow, and Enter to navigate the menus and open or refocus a canvas. A single canvas in the pill shows its title and opens directly; multiple canvases show a count and open a picker. Activating a canvas focuses its tab beside the chat, or reopens it if it was closed. To close a canvas rather than only its tab, use Close Canvas: the X on the pill of a single canvas or on a picker row, or the pill's context menu. Closing ends the canvas and notifies the extension that provides it.")); + content.push(localize('chat.editorCanvasesPill', "In local Copilot agent-host sessions with chat.canvases.enabled turned on, a Canvas submenu appears in the final section of the New Chat menu, and the chat's open canvases appear in their own pill in the main window. Open the Canvas submenu to choose a registered or closed canvas by name. Use Up and Down Arrow, Right Arrow, and Enter to navigate the menus and open or refocus a canvas. A single canvas in the pill shows its title and opens directly; multiple canvases show a count and open a picker. Activating a canvas focuses its tab beside the chat, or reopens it if it was closed. To close a canvas rather than only its tab, use Close Canvas: the X on a canvas pill or picker row, or the pill's context menu. Closing ends the canvas and notifies the extension that provides it.")); } content.push(localize('chat.sessionActivityPills', "Subagents and Customizations are available in both the Agents Window and editor window, and are hidden by default. Enable them from the session status toolbar context menu. Subagents lists the current chat's direct subagents, grouped into in-progress and completed chats. Activate an entry to open its chat to the side. Subagent Options lets you show all subagents or only those in progress, remembered across windows. Customizations lists the agents, skills, instructions, hooks, prompts, MCP servers, and plugins used by the current chat. Activate an entry to reveal it in the Customizations editor.")); content.push(getBackgroundShellsPillAccessibilityHelp()); @@ -198,6 +198,8 @@ export function getAccessibilityHelpText(type: 'panelChat' | 'inlineChat' | 'qui content.push(localize('chat.voiceInputMode.segmented', 'When the segmented voice input control is enabled, the input toolbar offers Dictation and Voice Mode. A connected hands-free session also offers Mute or Unmute Microphone; manual Voice Mode instead offers Start or Stop Listening, where stopping sends the completed turn. Each button can be focused and activated with Enter or Space.')); content.push(localize('chat.voiceInputMode.holdToTalk', 'In manual Voice Mode, the Start or Stop Listening button toggles listening when tapped, or you can press and hold it to talk and release to send. You can also hold the Voice Mode: Hold to Talk keybinding{0} to talk and release to send; this interrupts the assistant to barge in.', '<keybinding:workbench.action.chat.voiceInputMode.holdToTalk>')); content.push(localize('chat.voiceMode.byokSession', "When using configured OpenAI BYOK Voice Mode, only the bound chat input's prompts and responses are read. Voice Mode belongs to the input where you start it, including chat editor tabs and the chat sidebar. Switching the bound input or discarding a recording stops Voice Mode to prevent buffered audio from acting on another session. Start Voice Mode again in the intended input; creating the session from the same draft does not require a restart.")); + content.push(localize('chat.voiceMode.steering', "When Voice Mode sends a new request while the coding agent is working, it is sent as steering rather than queued for after the current task. Voice-only exchanges during ongoing work are not retained as context for later requests. Answers to pending questions and approvals continue to respond to those prompts.")); + content.push(localize('chat.voiceMode.questionSequence', "For forms with multiple questions, Voice Mode identifies the current question by number. Answer only that question, then wait for the next one. Each spoken reply fills one field, not several fields.")); content.push(localize('chat.voiceMode.byokAnswers', "In OpenAI BYOK Voice Mode, say approve, approved, accept, accepted, allow, yes, I approve, or I accept to approve the current prompt, and reject, deny, or no to reject it. These approval commands must be complete, unqualified English replies. For questions, say an exact displayed choice or its number; for multiple selections, separate choices with commas or and. Answer text questions directly. To give a custom answer to a selection question that permits it, say other followed by your answer. Forms collect one answer at a time and submit when complete. Say skip only when the form permits skipping. Ambiguous replies ask for clarification without approving anything or sending a new chat request.")); content.push(localize('chat.voiceMode.introduction', 'The first time Voice Mode starts, an introduction appears above the input box. Tab to reach it, then use the arrow keys to move between the available voices; Enter or Space plays a voice and keeps it for future conversations. Its description also contains two links: Settings, which opens the Voice Mode settings, and How It Responds, which opens a file for customizing what the agent says back. Voice Mode stays connected but does not listen while the introduction is open. Press Escape, or activate the Close button, to dismiss it and return to the input box.')); if (type === 'agentView') { diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts index 817d4a88dba32e..b3f9b94672037e 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionHandler.ts @@ -7388,8 +7388,8 @@ export class AgentHostSessionHandler extends Disposable implements IChatSessionC return undefined; } if (!resolution) { - // Auto was picked, but the router has not answered yet. - return { kind: 'autoModeResolution' }; + // Router has not answered yet; Fusion's HydraFusion tiers never do. + return lookupModel(fallbackRawModelId)?.model.autoModelFusion ? undefined : { kind: 'autoModeResolution' }; } const localRouted = localTurn(usage)?.routed; if (localRouted) { diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionInputPills.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionInputPills.ts index df71c7747a9fc0..e3f50e0524124b 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionInputPills.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostSessionInputPills.ts @@ -1038,7 +1038,11 @@ export class AgentHostSessionInputPills extends Disposable { browsers: { sections: browserSections }, subagents: createSessionSubagentsPillData(subagents, visibility.subagents), backgroundShells, - }, SESSION_CHAT_PILL_KINDS)); + }, SESSION_CHAT_PILL_KINDS, derived(this, reader => { + const session = sessionResource.read(reader); + const chat = chatResource.read(reader); + return session && chat ? JSON.stringify([getLocalAgentHostSessionProvider(session), session.toString(), chat.toString()]) : undefined; + }))); const inputPills = this._register(instantiationService.createInstance(ChatInputPills, this._widget.inputPart.persistentContentContainerElement, { debugName: 'AgentHostSessionInputPills.content', compact, diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.contribution.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.contribution.ts index 6f82d41e1b02ed..18b09eaae9edbc 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.contribution.ts @@ -3,34 +3,7 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { localize2 } from '../../../../../../nls.js'; -import { Action2, registerAction2 } from '../../../../../../platform/actions/common/actions.js'; -import { AgentHostComputerUseEnabledSettingId } from '../../../../../../platform/agentHost/common/agentService.js'; -import { ContextKeyExpr } from '../../../../../../platform/contextkey/common/contextkey.js'; -import { IsMacNativeContext } from '../../../../../../platform/contextkey/common/contextkeys.js'; import { InstantiationType, registerSingleton } from '../../../../../../platform/instantiation/common/extensions.js'; -import { ServicesAccessor } from '../../../../../../platform/instantiation/common/instantiation.js'; -import { ChatContextKeys } from '../../../common/actions/chatContextKeys.js'; -import { CHAT_CATEGORY } from '../../actions/chatActions.js'; import { ComputerUseSetupService, IComputerUseSetupService } from './computerUseSetup.js'; registerSingleton(IComputerUseSetupService, ComputerUseSetupService, InstantiationType.Delayed); - -/** Opens the Computer Use permission setup modal; the chat's setup card passes its setup id. */ -export const SetUpComputerUseActionId = 'workbench.action.chat.setUpComputerUse'; - -registerAction2(class SetUpComputerUseAction extends Action2 { - constructor() { - super({ - id: SetUpComputerUseActionId, - title: localize2('chat.computerUse.setUp', "Set Up Computer Use"), - category: CHAT_CATEGORY, - f1: true, - precondition: ContextKeyExpr.and(ChatContextKeys.enabled, IsMacNativeContext, ContextKeyExpr.equals(`config.${AgentHostComputerUseEnabledSettingId}`, true)), - }); - } - - run(accessor: ServicesAccessor, setupId?: unknown): void { - accessor.get(IComputerUseSetupService).open(typeof setupId === 'string' ? setupId : undefined); - } -}); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.ts index eed31f6ba16ce2..b75ce8d73640a3 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetup.ts @@ -28,8 +28,8 @@ export const IComputerUseSetupService = createDecorator<IComputerUseSetupService export interface IComputerUseSetupService extends IComputerUseSetupModel { readonly _serviceBrand: undefined; - /** Opens the setup modal for setup `setupId`, or for the latest setup that waits; an open modal switches to it instead. */ - open(setupId?: string): void; + /** Opens the setup modal for setup `setupId`, or brings the open modal to it, while that setup waits; does nothing otherwise. */ + open(setupId: string): void; /** Lets the setup modal hand Copilot Computer Use to System Settings by hand; desktop clients register it. */ registerHelperAppSupport(support: IComputerUseHelperAppSupport): IDisposable; @@ -111,10 +111,15 @@ export class ComputerUseSetupService extends Disposable implements IComputerUseS }); } - open(setupId?: string): void { + open(setupId: string): void { if (!isComputerUseSetupPlatform()) { return; } + const state = this.status.get()?.setups.find(candidate => candidate.id === setupId)?.state; + if (state !== 'needsPermissions' && state !== 'working') { + this._logService.trace(`[ComputerUse] Not opening setup ${setupId}: it doesn't wait for the user`); + return; + } const open = this._dialog.value; if (open) { open.reveal(setupId); diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetupDialog.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetupDialog.ts index d068b7db8d88f2..b5f3a499b8f844 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetupDialog.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/computerUseSetupDialog.ts @@ -4,21 +4,27 @@ *--------------------------------------------------------------------------------------------*/ import './media/computerUseSetup.css'; -import { $, addDisposableListener, append, EventType, getWindow, hide, show } from '../../../../../../base/browser/dom.js'; +import { $, addDisposableListener, append, EventType, getWindow, isAncestor } from '../../../../../../base/browser/dom.js'; +import { ActionBar } from '../../../../../../base/browser/ui/actionbar/actionbar.js'; import { alert, status } from '../../../../../../base/browser/ui/aria/aria.js'; -import { Button, type IButton } from '../../../../../../base/browser/ui/button/button.js'; +import { Button } from '../../../../../../base/browser/ui/button/button.js'; import { Dialog, DialogContentsAlignment } from '../../../../../../base/browser/ui/dialog/dialog.js'; +import { getBaseLayerHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegate2.js'; +import { getDefaultHoverDelegate } from '../../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import type { CodeWindow } from '../../../../../../base/browser/window.js'; +import { Action } from '../../../../../../base/common/actions.js'; +import { RunOnceScheduler } from '../../../../../../base/common/async.js'; import { Codicon } from '../../../../../../base/common/codicons.js'; import { Event } from '../../../../../../base/common/event.js'; +import { KeyCode } from '../../../../../../base/common/keyCodes.js'; import { Disposable } from '../../../../../../base/common/lifecycle.js'; import { autorun, type IObservable } from '../../../../../../base/common/observable.js'; import { ThemeIcon } from '../../../../../../base/common/themables.js'; import { localize } from '../../../../../../nls.js'; -import { computerUsePermissions, type ComputerUsePermission, type ComputerUsePermissionState, type IComputerUseSetupActionV1, type IComputerUseSetupV1, type IComputerUseStatusV1 } from '../../../../../../platform/agentHost/common/computerUse.js'; +import { computerUsePermissions, type ComputerUsePermission, type ComputerUsePermissionState, type IComputerUseSetupActionV1, type IComputerUseStatusV1 } from '../../../../../../platform/agentHost/common/computerUse.js'; import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; import { ILayoutService } from '../../../../../../platform/layout/browser/layoutService.js'; -import { defaultButtonStyles } from '../../../../../../platform/theme/browser/defaultStyles.js'; +import { defaultButtonStyles, defaultDialogStyles } from '../../../../../../platform/theme/browser/defaultStyles.js'; import { createWorkbenchDialogOptions } from '../../../../../browser/parts/dialogs/dialog.js'; import { IHostService } from '../../../../../services/host/browser/host.js'; @@ -26,8 +32,6 @@ import { IHostService } from '../../../../../services/host/browser/host.js'; export interface IComputerUseHelperAppSupport { /** Drags the app at `path` out of `targetWindow` as a file; call it from a `dragstart` handler that cancels the HTML drag. */ startDrag(path: string, targetWindow: CodeWindow): void; - /** Shows the app at `path` in Finder. */ - reveal(path: string): void; } /** The status the setup modal shows and the actions it sends. */ @@ -42,39 +46,28 @@ export interface IComputerUseSetupModel { // #region View model -/** - * - `unavailable`: the local Agent Host publishes no setup status. - * - `idle`: nothing waits for the permissions; the modal only shows their last verified state. - * - otherwise the state of the setup the modal follows. - */ -export type ComputerUseSetupPhase = 'unavailable' | 'idle' | IComputerUseSetupV1['state']; - +/** One permission the setup needs. */ export interface IComputerUseSetupRowView { readonly permission: ComputerUsePermission; readonly state: ComputerUsePermissionState; - /** What the user can do for this permission now. */ - readonly action?: IComputerUseSetupActionV1; - /** Whether the action in flight covers this permission. */ - readonly busy: boolean; + /** Whether the user turns this permission on next: the first one that isn't granted while the setup waits. */ + readonly current: boolean; } +/** What the modal shows for a setup that waits, or that just became ready. */ export interface IComputerUseSetupView { - readonly phase: ComputerUseSetupPhase; - readonly setupId?: string; + readonly setupId: string; + readonly state: 'needsPermissions' | 'working' | 'ready'; readonly rows: readonly IComputerUseSetupRowView[]; - /** What the rows don't show: progress, a failure, or the outcome. Empty while the rows say it all. */ - readonly message: string; - readonly messageKind: 'info' | 'progress' | 'error' | 'success'; + /** Whether the current row's Allow in Settings sends `allow` now. */ + readonly canAllow: boolean; + /** Whether checking again sends `recheck` now. */ readonly canRecheck: boolean; - /** - * The helper already verified every permission, e.g. for another chat, while this setup still waits; checking again - * lets the waiting task continue, so the modal offers it as Continue. - */ - readonly canContinue: boolean; - /** The permission the user turns on in System Settings, because macOS's own prompt didn't. */ - readonly settingsStep?: ComputerUsePermission; + /** Why the last check the user asked for changed nothing. */ + readonly error?: string; } +/** The localized name of a macOS permission. */ export function getComputerUsePermissionLabel(permission: ComputerUsePermission): string { switch (permission) { case 'accessibility': return localize('computerUseSetup.accessibility', "Accessibility"); @@ -104,126 +97,59 @@ function getStateLabel(state: ComputerUsePermissionState): string { } } -function getActionLabel({ action }: IComputerUseSetupActionV1): string { - switch (action) { - case 'request': return localize('computerUseSetup.action.request', "Allow"); - case 'openSettings': return localize('computerUseSetup.action.openSettings', "Open Settings"); - case 'recheck': return localize('computerUseSetup.action.recheck', "Check Again"); - } -} - -function getActionAriaLabel({ action, permission }: IComputerUseSetupActionV1): string { - const label = permission && getComputerUsePermissionLabel(permission); - switch (action) { - case 'request': return localize('computerUseSetup.action.request.aria', "Allow {0}", label); - case 'openSettings': return localize('computerUseSetup.action.openSettings.aria', "Open {0} in System Settings", label); - case 'recheck': return localize('computerUseSetup.action.recheck.aria', "Check Permissions Again"); - } -} - -function getWorkingMessage(status: IComputerUseStatusV1, setupId: string): string { - const operation = status.operation?.setupId === setupId ? status.operation : undefined; - const label = operation?.permission && getComputerUsePermissionLabel(operation.permission); - switch (operation?.action) { - case 'request': return localize('computerUseSetup.working.request', "Waiting for macOS to ask about {0}…", label); - case 'openSettings': return localize('computerUseSetup.working.openSettings', "Opening {0} in System Settings…", label); - default: return localize('computerUseSetup.working.recheck', "Checking permissions…"); +/** Derives what the modal shows for setup `setupId` from the host's status; `undefined` once the modal must close. */ +export function getComputerUseSetupView(status: IComputerUseStatusV1 | undefined, setupId: string): IComputerUseSetupView | undefined { + const setup = status?.setups.find(candidate => candidate.id === setupId); + if (!status || !setup || setup.state === 'ended') { + return undefined; } + const states = new Map(status.permissions.map(entry => [entry.permission, entry.state])); + const stateOf = (permission: ComputerUsePermission) => states.get(permission) ?? 'unknown'; + const current = setup.state === 'ready' ? undefined : computerUsePermissions.find(permission => stateOf(permission) !== 'granted'); + const offers = ({ action, permission }: IComputerUseSetupActionV1) => setup.state === 'needsPermissions' && setup.actions.some(candidate => candidate.action === action && candidate.permission === permission); + return { + setupId, + state: setup.state, + rows: computerUsePermissions.map(permission => ({ permission, state: stateOf(permission), current: permission === current })), + canAllow: !!current && offers({ action: 'allow', permission: current }), + canRecheck: offers({ action: 'recheck' }), + ...(setup.error ? { error: setup.error.message } : {}), + }; } -/** Picks the setup to show: the requested one, else the newest one that waits. */ -export function findComputerUseSetup(status: IComputerUseStatusV1 | undefined, setupId: string | undefined): IComputerUseSetupV1 | undefined { - if (setupId !== undefined) { - return status?.setups.find(setup => setup.id === setupId); - } - return status?.setups.findLast(setup => setup.state === 'needsPermissions' || setup.state === 'working'); -} - -/** Derives what the modal shows for setup `setupId` from the host's status; every value is host-verified. */ -export function getComputerUseSetupView(status: IComputerUseStatusV1 | undefined, setupId: string | undefined): IComputerUseSetupView { - if (!status) { - return { - phase: 'unavailable', - rows: [], - message: localize('computerUseSetup.unavailable', "Computer Use setup is available when Computer Use is turned on for local Copilot sessions on this Mac."), - messageKind: 'info', - canRecheck: false, - canContinue: false, - }; - } - const setup = setupId !== undefined ? status.setups.find(candidate => candidate.id === setupId) : undefined; - const operation = setup?.state === 'working' && status.operation?.setupId === setup.id ? status.operation : undefined; - const rows = computerUsePermissions.map((permission): IComputerUseSetupRowView => { - const state = status.permissions.find(candidate => candidate.permission === permission)?.state ?? 'unknown'; - // Another chat may already have verified a grant this setup still offers; checking again picks it up. - const offered = state === 'granted' ? undefined : setup?.actions.filter(candidate => candidate.permission === permission); - const action = offered?.find(candidate => candidate.action === 'openSettings') ?? offered?.find(candidate => candidate.action === 'request'); - return { - permission, - state, - ...(action ? { action } : {}), - busy: !!operation && (operation.permission === permission || (!operation.permission && state !== 'granted')), - }; - }); - if (!setup) { - return { phase: 'idle', rows, message: localize('computerUseSetup.idle', "Copilot checks these permissions the next time it needs Computer Use."), messageKind: 'info', canRecheck: false, canContinue: false }; - } - const canRecheck = setup.actions.some(candidate => candidate.action === 'recheck'); - switch (setup.state) { - case 'needsPermissions': { - if (canRecheck && rows.every(row => row.state === 'granted')) { - return { phase: setup.state, setupId: setup.id, rows, message: localize('computerUseSetup.canContinue', "macOS turned on both permissions."), messageKind: 'success', canRecheck, canContinue: true }; - } - // The plugin offers System Settings once macOS's own prompt didn't turn a permission on. - const settingsStep = rows.find(row => row.action?.action === 'openSettings')?.permission; - return { - phase: setup.state, - setupId: setup.id, - rows, - message: setup.error?.message ?? '', - messageKind: setup.error ? 'error' : 'info', - canRecheck, - canContinue: false, - ...(settingsStep ? { settingsStep } : {}), - }; - } - case 'working': - return { phase: setup.state, setupId: setup.id, rows, message: getWorkingMessage(status, setup.id), messageKind: 'progress', canRecheck: false, canContinue: false }; - case 'ready': - return { phase: setup.state, setupId: setup.id, rows, message: localize('computerUseSetup.ready', "Computer Use is ready."), messageKind: 'success', canRecheck: false, canContinue: false }; - case 'ended': - return { - phase: setup.state, - setupId: setup.id, - rows, - message: setup.error?.message ?? localize('computerUseSetup.ended', "Setup was canceled. Ask Copilot to try again when you're ready."), - messageKind: 'error', - canRecheck: false, - canContinue: false, - }; - } +function getCurrentPermission(view: IComputerUseSetupView | undefined): ComputerUsePermission | undefined { + return view?.rows.find(row => row.current)?.permission; } // #endregion // #region Panel +/** How long the modal shows every permission granted before it closes on its own. */ +const READY_CLOSE_DELAY_MS = 1000; + +/** What the setup modal's body needs from the modal around it. */ export interface IComputerUseSetupPanelOptions { /** Fires `true` when the window gains focus and `false` when it loses it. */ readonly onDidChangeWindowFocus: Event<boolean>; + /** Closes the modal; the panel calls it once its setup no longer waits. */ + readonly close: () => void; } interface IRowElements { readonly row: HTMLElement; readonly status: HTMLElement; - readonly actionContainer: HTMLElement; - readonly button: Button; + /** Check Again and Allow in Settings, in the row only while it is current. */ + readonly controls: HTMLElement; + readonly recheck: Action; + readonly allow: Button; } /** - * The body of the setup modal. It renders the host's status for one setup and sends the user's explicit actions; it - * never decides whether a permission is granted. After the user goes to macOS to grant a permission, it checks again - * once when the window regains focus, unless macOS confirmed the permission meanwhile. + * The body of the setup modal. It renders the host's status for one setup, one permission at a time, and sends the + * user's explicit actions; it never decides whether a permission is granted. After the user goes to System Settings to + * turn a permission on, it checks again once when the window regains focus, unless macOS confirmed the permission + * meanwhile. It closes the modal once the setup no longer waits. */ export class ComputerUseSetupPanel extends Disposable { @@ -233,21 +159,15 @@ export class ComputerUseSetupPanel extends Disposable { private readonly _appIconImage: HTMLImageElement; private readonly _rows = new Map<ComputerUsePermission, IRowElements>(); - private readonly _settingsStep: HTMLElement; - private readonly _settingsStepCaption: HTMLElement; + /** The app, for dragging into a System Settings list; in the current row while this client can drag it. */ private readonly _helperApp: HTMLElement; private readonly _helperAppIcon: HTMLImageElement; - private readonly _message: HTMLElement; - private readonly _recheckContainer: HTMLElement; - private readonly _recheck: Button; - private _dismiss: IButton | undefined; - - /** The setup requested by the caller; without one, the newest waiting setup is picked once and kept. */ - private _requested: string | undefined; - private _pinned: string | undefined; + private readonly _closeWhenReady = this._register(new RunOnceScheduler(() => this._options.close(), READY_CLOSE_DELAY_MS)); + + private _setupId: string; private _view: IComputerUseSetupView | undefined; - /** The System Settings step shown, which stays while the step's outcome is checked. */ - private _shownSettingsStep: ComputerUsePermission | undefined; + /** Whether the host is checking the setup's permissions again. */ + private _checking = false; /** The app the modal offers for dragging into System Settings, if any. */ private _helperAppPath: string | undefined; /** Set when the user went to macOS to grant a permission: once the window loses and regains focus, check again. */ @@ -256,11 +176,11 @@ export class ComputerUseSetupPanel extends Disposable { constructor( private readonly _model: IComputerUseSetupModel, - setupId: string | undefined, - options: IComputerUseSetupPanelOptions, + setupId: string, + private readonly _options: IComputerUseSetupPanelOptions, ) { super(); - this._requested = setupId; + this._setupId = setupId; this.appIcon = $(`.computer-use-setup-app-icon${ThemeIcon.asCSSSelector(Codicon.copilotLarge)}`, { 'aria-hidden': 'true' }); this._appIconImage = append(this.appIcon, $<HTMLImageElement>('img', { alt: '' })); @@ -270,87 +190,70 @@ export class ComputerUseSetupPanel extends Disposable { const list = append(this.element, $('.computer-use-setup-permissions', { role: 'list', 'aria-label': localize('computerUseSetup.permissions', "Required permissions") })); for (const permission of computerUsePermissions) { - const row = append(list, $('.computer-use-setup-permission', { role: 'listitem' })); - append(row, $(`span.computer-use-setup-permission-icon${ThemeIcon.asCSSSelector(getPermissionIcon(permission))}`, { 'aria-hidden': 'true' })); - const text = append(row, $('.computer-use-setup-permission-text', { 'aria-hidden': 'true' })); - append(text, $('span.computer-use-setup-permission-name', undefined, getComputerUsePermissionLabel(permission))); - append(text, $('span.computer-use-setup-permission-description', undefined, getPermissionDescription(permission))); - const status = append(row, $('span.computer-use-setup-permission-status', { 'aria-hidden': 'true' })); - const actionContainer = append(row, $('.computer-use-setup-permission-action')); - const button = this._register(new Button(actionContainer, { ...defaultButtonStyles, secondary: true, small: true })); - this._register(button.onDidClick(() => this._runRowAction(permission))); - this._rows.set(permission, { row, status, actionContainer, button }); + this._rows.set(permission, this._createRow(list, permission)); } - // macOS lists the app under a permission once the app asked for it, but the user may have removed it since. Only a - // mouse can drag, so Finder is offered too. - this._settingsStep = append(this.element, $('.computer-use-setup-settings-step')); - this._settingsStepCaption = append(this._settingsStep, $('span.computer-use-setup-settings-step-caption')); - this._helperApp = append(this._settingsStep, $('.computer-use-setup-helper-app')); - const chip = append(this._helperApp, $('.computer-use-setup-helper-app-chip', { draggable: 'true', 'aria-hidden': 'true' })); - append(chip, $(`span.computer-use-setup-helper-app-grip${ThemeIcon.asCSSSelector(Codicon.gripper)}`)); - this._helperAppIcon = append(chip, $<HTMLImageElement>(`img.computer-use-setup-helper-app-icon`, { alt: '' })); - append(chip, $('span.computer-use-setup-helper-app-name', undefined, localize('computerUseSetup.helperApp.name', "Copilot Computer Use"))); - this._register(addDisposableListener(chip, EventType.DRAG_START, e => this._startHelperAppDrag(e, chip))); - const reveal = this._register(new Button(append(this._helperApp, $('.computer-use-setup-helper-app-action')), { ...defaultButtonStyles, secondary: true, small: true })); - reveal.label = localize('computerUseSetup.helperApp.reveal', "Show in Finder"); - reveal.setAriaLabel(localize('computerUseSetup.helperApp.reveal.aria', "Show Copilot Computer Use in Finder")); - this._register(reveal.onDidClick(() => this._revealHelperApp())); - - this._message = append(this.element, $('.computer-use-setup-message')); - this._recheckContainer = append(this.element, $('.computer-use-setup-actions')); - this._recheck = this._register(new Button(this._recheckContainer, { ...defaultButtonStyles, secondary: true })); - this._register(this._recheck.onDidClick(() => this._runRecheck())); - - this._register(options.onDidChangeWindowFocus(focused => this._onWindowFocus(focused))); + // macOS lists the app under a permission once the app asked for it, but the user may have removed it since. + this._helperApp = $('.computer-use-setup-helper-app-chip', { draggable: 'true', 'aria-hidden': 'true' }); + append(this._helperApp, $(`span.computer-use-setup-helper-app-grip${ThemeIcon.asCSSSelector(Codicon.gripper)}`)); + this._helperAppIcon = append(this._helperApp, $<HTMLImageElement>('img.computer-use-setup-helper-app-icon', { alt: '' })); + append(this._helperApp, $('span.computer-use-setup-helper-app-name', undefined, localize('computerUseSetup.helperApp.name', "Copilot Computer Use"))); + this._register(addDisposableListener(this._helperApp, EventType.DRAG_START, e => this._startHelperAppDrag(e))); + this._register(getBaseLayerHoverDelegate().setupManagedHover(getDefaultHoverDelegate('mouse'), this._helperApp, localize('computerUseSetup.helperApp.hover', "Drag into the list in System Settings"))); + + this._register(this._options.onDidChangeWindowFocus(focused => this._onWindowFocus(focused))); this._register(autorun(reader => this._render(this._model.status.read(reader)))); } - /** The view currently shown. */ + /** The view currently shown; `undefined` once the panel closed the modal. */ get view(): IComputerUseSetupView | undefined { return this._view; } - /** Follows setup `setupId`; without one, keeps the current setup unless it finished, then follows the newest waiting one. */ - setTarget(setupId: string | undefined): void { - if (setupId === undefined && this._view?.phase !== 'ready' && this._view?.phase !== 'ended') { - return; - } - this._requested = setupId; - this._pinned = undefined; + /** Follows setup `setupId` from now on. */ + setTarget(setupId: string): void { + this._setupId = setupId; this._render(this._model.status.get()); } - /** Adopts the modal's own button, which closes it, and relabels it with the setup's progress. */ - setDismissButton(button: IButton): void { - this._dismiss = button; - this._renderDismiss(); - } - - /** Moves focus to the most useful control: the next permission action, else Check Again, else the modal's button. */ + /** Moves focus to the current row's Allow in Settings, if a row is current. */ focus(): void { - this._primaryElement()?.focus(); + this._getCurrentAllow()?.focus(); } - private _primaryElement(): { focus(): void } | undefined { - const view = this._view; - const row = view?.phase === 'needsPermissions' ? view.rows.find(candidate => candidate.action) : undefined; - if (row) { - return this._rows.get(row.permission)?.button; - } - if (view?.phase === 'needsPermissions' && this._recheck.element.isConnected) { - return this._recheck; - } - return this._dismiss; + private _createRow(list: HTMLElement, permission: ComputerUsePermission): IRowElements { + const label = getComputerUsePermissionLabel(permission); + const row = append(list, $('.computer-use-setup-permission', { role: 'listitem' })); + append(row, $(`span.computer-use-setup-permission-icon${ThemeIcon.asCSSSelector(getPermissionIcon(permission))}`, { 'aria-hidden': 'true' })); + const text = append(row, $('.computer-use-setup-permission-text', { 'aria-hidden': 'true' })); + append(text, $('span.computer-use-setup-permission-name', undefined, label)); + append(text, $('span.computer-use-setup-permission-description', undefined, getPermissionDescription(permission))); + const status = append(row, $('span.computer-use-setup-permission-status', { 'aria-hidden': 'true' })); + + const controls = $('.computer-use-setup-permission-controls'); + const recheck = this._register(new Action('computerUseSetup.recheck', localize('computerUseSetup.recheck', "Check Again"), ThemeIcon.asClassName(Codicon.refresh), true, () => this._recheck())); + recheck.tooltip = localize('computerUseSetup.recheck.aria', "Check {0} Again", label); + // The modal stops every key release, so the action runs as the key goes down. + const actionBar = this._register(new ActionBar(controls, { triggerKeys: { keys: [KeyCode.Enter, KeyCode.Space], keyDown: true } })); + actionBar.push(recheck, { icon: true, label: false }); + const allow = this._register(new Button(controls, { ...defaultButtonStyles, small: true })); + allow.label = localize('computerUseSetup.allow', "Allow in Settings"); + allow.setAriaLabel(localize('computerUseSetup.allow.aria', "Allow {0} in System Settings", label)); + this._register(allow.onDidClick(() => this._allow(permission))); + return { row, status, controls, recheck, allow }; } private _render(status: IComputerUseStatusV1 | undefined): void { - if (this._requested === undefined && this._pinned === undefined) { - this._pinned = findComputerUseSetup(status, undefined)?.id; + const view = getComputerUseSetupView(status, this._setupId); + if (!view) { + this._view = undefined; + this._closeWhenReady.cancel(); + this._options.close(); + return; } - const view = getComputerUseSetupView(status, this._requested ?? this._pinned); const previous = this._view; - const hadFocus = this.element.contains(this.element.ownerDocument.activeElement); + const modal = this._getModal(); + const hadFocus = isAncestor(this.element.ownerDocument.activeElement, modal); this._view = view; const icon = status?.helperApp?.icon; @@ -359,141 +262,102 @@ export class ComputerUseSetupPanel extends Disposable { this._helperAppIcon.src = icon ?? ''; this._helperAppIcon.classList.toggle('missing', !icon); - const enabled = view.phase === 'needsPermissions'; - const firstActionable = view.rows.find(row => row.action)?.permission; + const working = view.state === 'working'; for (const row of view.rows) { const elements = this._rows.get(row.permission)!; elements.row.setAttribute('aria-label', localize('computerUseSetup.row', "{0}, {1}. {2}", getComputerUsePermissionLabel(row.permission), getStateLabel(row.state), getPermissionDescription(row.permission))); elements.status.className = 'computer-use-setup-permission-status'; - if (row.busy) { - elements.status.classList.add(...ThemeIcon.asClassNameArray(ThemeIcon.modify(Codicon.loading, 'spin'))); - } else if (row.state === 'granted') { + if (row.state === 'granted') { elements.status.classList.add('granted', ...ThemeIcon.asClassNameArray(Codicon.passFilled)); } - if (row.action) { - elements.button.label = getActionLabel(row.action); - elements.button.setAriaLabel(getActionAriaLabel(row.action)); - elements.button.secondary = row.permission !== firstActionable; - if (!elements.button.element.isConnected) { - elements.actionContainer.appendChild(elements.button.element); - } - } else if (view.phase !== 'working' || row.state === 'granted') { - elements.button.element.remove(); + if (!row.current) { + // Removed, not hidden: the modal moves focus itself across every link in its body, hidden ones too. + elements.controls.remove(); + continue; } // While a step runs the host offers nothing, so the controls stay put, disabled, and keep focus. - elements.button.enabled = enabled; + elements.recheck.class = ThemeIcon.asClassName(working ? ThemeIcon.modify(Codicon.loading, 'spin') : Codicon.refresh); + elements.recheck.enabled = view.canRecheck; + elements.allow.enabled = view.canAllow; + if (elements.controls.parentElement !== elements.row) { + elements.status.after(elements.controls); + } } - // Likewise the System Settings step stays while its outcome is checked. - const settingsStep = view.settingsStep ?? (view.phase === 'working' ? this._shownSettingsStep : undefined); - this._shownSettingsStep = settingsStep; - this._helperAppPath = settingsStep && this._model.helperApp ? status?.helperApp?.path : undefined; - if (settingsStep) { - const label = getComputerUsePermissionLabel(settingsStep); - this._settingsStepCaption.textContent = this._helperAppPath - ? localize('computerUseSetup.settingsStep.drag', "Turn on Copilot Computer Use under {0} in System Settings, or drag it into the list.", label) - : localize('computerUseSetup.settingsStep', "Turn on Copilot Computer Use under {0} in System Settings.", label); - show(this._settingsStep); - } else { - hide(this._settingsStep); - } - if (this._helperAppPath) { - if (!this._helperApp.isConnected) { - this._settingsStep.appendChild(this._helperApp); + const current = getCurrentPermission(view); + const currentRow = current && this._rows.get(current)?.row; + this._helperAppPath = currentRow && this._model.helperApp ? status?.helperApp?.path : undefined; + if (currentRow && this._helperAppPath) { + if (this._helperApp.parentElement !== currentRow) { + currentRow.appendChild(this._helperApp); } } else { - // Removed, not hidden: the modal moves focus itself across every link in its body, hidden ones too. this._helperApp.remove(); } - // Progress shows in the rows, so the message only reports failures and outcomes. - this._message.textContent = view.messageKind === 'progress' ? '' : view.message; - this._message.className = `computer-use-setup-message ${view.messageKind}`; - if (this._message.textContent) { - show(this._message); - } else { - hide(this._message); + if (hadFocus && (current !== getCurrentPermission(previous) || !isAncestor(this.element.ownerDocument.activeElement, modal))) { + (this._getCurrentAllow() ?? modal).focus(); } - const showRecheck = view.canContinue - || (view.canRecheck && (!!view.settingsStep || view.messageKind === 'error')) - || (view.phase === 'working' && this._recheck.element.isConnected); - this._recheck.enabled = enabled && view.canRecheck; - if (view.phase !== 'working') { - this._recheck.label = view.canContinue ? localize('computerUseSetup.continueTask', "Continue") : getActionLabel({ action: 'recheck' }); - this._recheck.setAriaLabel(view.canContinue ? localize('computerUseSetup.continueTask.aria', "Continue Your Task") : getActionAriaLabel({ action: 'recheck' })); - this._recheck.secondary = !view.canContinue; - } - if (showRecheck && !this._recheck.element.isConnected) { - this._recheckContainer.appendChild(this._recheck.element); - } else if (!showRecheck) { - this._recheck.element.remove(); - } - this._renderDismiss(); + const checking = working && status?.operation?.setupId === view.setupId && status.operation.action === 'recheck'; + this._announce(previous, view, checking && !this._checking); + this._checking = checking; - if (hadFocus && !this.element.contains(this.element.ownerDocument.activeElement)) { - this.focus(); + if (view.state !== 'ready') { + this._closeWhenReady.cancel(); + } else if (!this._closeWhenReady.isScheduled()) { + this._closeWhenReady.schedule(); } - this._announce(previous, view); this._recheckIfReturned(view); } - private _renderDismiss(): void { - const dismiss = this._dismiss; - if (!dismiss) { - return; - } - const phase = this._view?.phase; - const waiting = phase === 'needsPermissions' || phase === 'working'; - dismiss.label = waiting - ? localize('computerUseSetup.notNow', "Not Now") - : phase === 'ready' ? localize('computerUseSetup.continue', "Continue") : localize('computerUseSetup.close', "Close"); - if (dismiss instanceof Button) { - dismiss.secondary = waiting; - } + /** The modal the panel is the body of; focus anywhere in it counts as focus in the setup. */ + private _getModal(): HTMLElement { + return this.element.closest<HTMLElement>('[role="dialog"]') ?? this.element; + } + + private _getCurrentAllow(): Button | undefined { + const current = getCurrentPermission(this._view); + return current && this._rows.get(current)?.allow; } - private _announce(previous: IComputerUseSetupView | undefined, view: IComputerUseSetupView): void { - if (!previous || (previous.phase === view.phase && previous.setupId === view.setupId && previous.message === view.message && previous.settingsStep === view.settingsStep && previous.rows.every((row, index) => row.state === view.rows[index]?.state))) { + private _announce(previous: IComputerUseSetupView | undefined, view: IComputerUseSetupView, startedChecking: boolean): void { + // Opening the modal or switching setups moves focus, which tells the user where they are. + if (previous?.setupId !== view.setupId) { return; } - if (view.phase === 'needsPermissions') { - const summary = view.rows.map(row => localize('computerUseSetup.rowAnnouncement', "{0}: {1}.", getComputerUsePermissionLabel(row.permission), getStateLabel(row.state))).join(' '); - const step = this._settingsStepCaption.isConnected && view.settingsStep ? this._settingsStepCaption.textContent : ''; - (view.messageKind === 'error' ? alert : status)([summary, view.message, step].filter(Boolean).join(' ')); - } else if (view.phase === 'ended') { - alert(view.message); - } else { - status(view.message); + if (view.state === 'ready') { + if (previous.state !== 'ready') { + status(localize('computerUseSetup.ready', "Computer Use is ready.")); + } + return; + } + const messages: string[] = []; + if (startedChecking) { + messages.push(localize('computerUseSetup.checking', "Checking permissions…")); + } + if (view.rows.some((row, index) => row.state !== previous.rows[index]?.state)) { + messages.push(view.rows.map(row => localize('computerUseSetup.rowAnnouncement', "{0}: {1}.", getComputerUsePermissionLabel(row.permission), getStateLabel(row.state))).join(' ')); + } + if (messages.length) { + status(messages.join(' ')); + } + if (view.error && (view.error !== previous.error || previous.state !== 'needsPermissions')) { + alert(view.error); } } - private _runRowAction(permission: ComputerUsePermission): void { - const view = this._view; - const action = view?.rows.find(row => row.permission === permission)?.action; - if (!view?.setupId || !action || !this._model.request(view.setupId, action)) { + private _allow(permission: ComputerUsePermission): void { + const setupId = this._view?.setupId; + if (!setupId || !this._model.request(setupId, { action: 'allow', permission })) { return; } // The user goes to macOS to grant it; check again when they come back. - this._returnWatch = { setupId: view.setupId, permission, blurred: false }; + this._returnWatch = { setupId, permission, blurred: false }; this._recheckOnReturn = undefined; } - private _startHelperAppDrag(e: DragEvent, chip: HTMLElement): void { - // Only a native drag hands System Settings the app itself. - e.preventDefault(); - if (this._helperAppPath) { - this._model.helperApp?.startDrag(this._helperAppPath, getWindow(chip)); - } - } - - private _revealHelperApp(): void { - if (this._helperAppPath) { - this._model.helperApp?.reveal(this._helperAppPath); - } - } - - private _runRecheck(): void { + private _recheck(): void { const setupId = this._view?.setupId; this._returnWatch = undefined; this._recheckOnReturn = undefined; @@ -502,6 +366,14 @@ export class ComputerUseSetupPanel extends Disposable { } } + private _startHelperAppDrag(e: DragEvent): void { + // Only a native drag hands System Settings the app itself. + e.preventDefault(); + if (this._helperAppPath) { + this._model.helperApp?.startDrag(this._helperAppPath, getWindow(this._helperApp)); + } + } + private _onWindowFocus(focused: boolean): void { const watch = this._returnWatch; if (!watch) { @@ -521,13 +393,13 @@ export class ComputerUseSetupPanel extends Disposable { /** Checks again once the user came back, as soon as the plugin waits for the setup's next step. */ private _recheckIfReturned(view: IComputerUseSetupView | undefined): void { const pending = this._recheckOnReturn; - if (!pending || view?.setupId !== pending.setupId || view.phase === 'working') { + if (!pending || view?.setupId !== pending.setupId || view.state === 'working') { return; } this._recheckOnReturn = undefined; // The host checks Accessibility on its own when macOS changes it, so it may be confirmed already. const confirmed = view.rows.some(row => row.permission === pending.permission && row.state === 'granted'); - if (view.phase === 'needsPermissions' && view.canRecheck && !confirmed) { + if (view.state === 'needsPermissions' && view.canRecheck && !confirmed) { this._model.request(pending.setupId, { action: 'recheck' }); } } @@ -535,51 +407,57 @@ export class ComputerUseSetupPanel extends Disposable { // #endregion -/** The setup modal: one per window, opened from the chat's setup card or the Set Up Computer Use command. */ +/** The setup modal: one per window, opened from the chat's setup card while its setup waits. */ export class ComputerUseSetupDialog extends Disposable { - private readonly _panel: ComputerUseSetupPanel; private readonly _dialog: Dialog; - private _dismissButton: IButton | undefined; + private readonly _panel: ComputerUseSetupPanel; constructor( model: IComputerUseSetupModel, - setupId: string | undefined, + setupId: string, @ILayoutService layoutService: ILayoutService, @IKeybindingService keybindingService: IKeybindingService, @IHostService hostService: IHostService, ) { super(); - this._panel = this._register(new ComputerUseSetupPanel(model, setupId, { onDidChangeWindowFocus: hostService.onDidChangeFocus })); + // The panel may close the dialog as soon as it renders, so the dialog comes first and takes the panel's elements after. + const slots: { icon?: HTMLElement; body?: HTMLElement } = {}; this._dialog = this._register(new Dialog( layoutService.activeContainer, localize('computerUseSetup.title', "Set Up Computer Use"), - [localize('computerUseSetup.notNow', "Not Now")], + [], createWorkbenchDialogOptions({ type: 'none', alignment: DialogContentsAlignment.Vertical, - renderIcon: container => container.appendChild(this._panel.appIcon), + renderIcon: container => { slots.icon = container; }, + renderBody: container => { slots.body = container; }, extraClasses: ['computer-use-setup-dialog'], - cancelId: 0, - renderBody: body => body.appendChild(this._panel.element), - buttonOptions: [{ styleButton: button => { this._dismissButton = button; } }], + disableDefaultAction: true, + // The body has no links, so the dialog mustn't style the refresh action's label like one. + dialogStyles: { ...defaultDialogStyles, textLinkForeground: undefined }, }, keybindingService, layoutService, hostService), )); + this._panel = this._register(new ComputerUseSetupPanel(model, setupId, { + onDidChangeWindowFocus: hostService.onDidChangeFocus, + close: () => this._dialog.dispose(), + })); + slots.icon?.appendChild(this._panel.appIcon); + slots.body?.appendChild(this._panel.element); } - /** Shows the modal; resolves when the user closes it. */ + /** Shows the modal while its setup waits; resolves once it closed. */ async show(): Promise<void> { - const closed = this._dialog.show(); - // The dialog labels its buttons only after styling them, so the panel takes the button over once it has. - if (this._dismissButton) { - this._panel.setDismissButton(this._dismissButton); + if (!this._panel.view) { + return; } + const closed = this._dialog.show(); this._panel.focus(); await closed; } /** Brings the open modal to setup `setupId`. */ - reveal(setupId: string | undefined): void { + reveal(setupId: string): void { this._panel.setTarget(setupId); this._panel.focus(); } diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/computerUseSetup.css b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/computerUseSetup.css index c135c90f40b127..5eed1c2800ec1d 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/computerUseSetup.css +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/media/computerUseSetup.css @@ -25,6 +25,11 @@ height: 64px; } +/* The rows hold every control, so the modal has no buttons of its own. */ +.monaco-dialog-box.computer-use-setup-dialog > .dialog-buttons-row { + display: none; +} + .computer-use-setup-dialog .computer-use-setup { /* The dialog's surface is translucent, so strokes and fills tint the foreground rather than use opaque colors. */ --computer-use-setup-stroke: var(--vscode-contrastBorder, color-mix(in srgb, var(--vscode-foreground) 14%, transparent)); @@ -35,6 +40,7 @@ width: 400px; max-width: 100%; margin-top: var(--vscode-spacing-size40); + margin-bottom: var(--vscode-spacing-size120); text-align: start; } @@ -53,9 +59,10 @@ } .computer-use-setup-dialog .computer-use-setup-permission { - display: flex; + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; align-items: center; - gap: var(--vscode-spacing-size120); + gap: var(--vscode-spacing-size80) var(--vscode-spacing-size120); min-height: 32px; padding: var(--vscode-spacing-size100) var(--vscode-spacing-size120); } @@ -65,14 +72,12 @@ } .computer-use-setup-dialog .computer-use-setup-permission-icon { - flex-shrink: 0; color: var(--vscode-icon-foreground); } .computer-use-setup-dialog .computer-use-setup-permission-text { display: flex; flex-direction: column; - flex: 1; min-width: 0; } @@ -85,49 +90,37 @@ color: var(--vscode-descriptionForeground); } -.computer-use-setup-dialog .computer-use-setup-permission-status { - flex-shrink: 0; - color: var(--vscode-descriptionForeground); +/* A row shows either its granted check or, while it is current, its controls. */ +.computer-use-setup-dialog .computer-use-setup-permission-status, +.computer-use-setup-dialog .computer-use-setup-permission-controls { + grid-row: 1; + grid-column: 3; } .computer-use-setup-dialog .computer-use-setup-permission-status.granted { color: var(--vscode-testing-iconPassed); } -.computer-use-setup-dialog .computer-use-setup-permission-action, -.computer-use-setup-dialog .computer-use-setup-helper-app-action { +.computer-use-setup-dialog .computer-use-setup-permission-controls { display: flex; - flex-shrink: 0; + align-items: center; + gap: var(--vscode-spacing-size40); } -.computer-use-setup-dialog .computer-use-setup-permission-action > .monaco-button, -.computer-use-setup-dialog .computer-use-setup-helper-app-action > .monaco-button { +.computer-use-setup-dialog .computer-use-setup-permission-controls > .monaco-button { width: fit-content; white-space: nowrap; } -.computer-use-setup-dialog .computer-use-setup-settings-step { - display: flex; - flex-direction: column; - gap: var(--vscode-spacing-size100); - padding: var(--vscode-spacing-size120); - border: var(--vscode-strokeThickness) dashed var(--computer-use-setup-stroke); - border-radius: var(--vscode-cornerRadius-medium); - text-wrap: balance; -} - -.computer-use-setup-dialog .computer-use-setup-helper-app { - display: flex; - align-items: center; - justify-content: space-between; - gap: var(--vscode-spacing-size80); -} - .computer-use-setup-dialog .computer-use-setup-helper-app-chip { + grid-row: 2; + grid-column: 2 / -1; + justify-self: start; display: flex; align-items: center; gap: var(--vscode-spacing-size60); min-width: 0; + max-width: 100%; padding: var(--vscode-spacing-size40) var(--vscode-spacing-size100) var(--vscode-spacing-size40) var(--vscode-spacing-size40); border: var(--vscode-strokeThickness) solid var(--vscode-contrastBorder, transparent); border-radius: var(--vscode-cornerRadius-small); @@ -159,25 +152,3 @@ text-overflow: ellipsis; white-space: nowrap; } - -.computer-use-setup-dialog .computer-use-setup-message { - text-align: center; - text-wrap: balance; - color: var(--vscode-descriptionForeground); -} - -.computer-use-setup-dialog .computer-use-setup-message.error { - color: var(--vscode-errorForeground); -} - -.computer-use-setup-dialog .computer-use-setup-message.success { - color: var(--vscode-foreground); -} - -.computer-use-setup-dialog .computer-use-setup-actions:empty { - display: none; -} - -.computer-use-setup-dialog .computer-use-setup-actions > .monaco-button { - width: 100%; -} diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationAccessibility.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationAccessibility.ts index ce2e5587249bb0..1e5798c5ebd515 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationAccessibility.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationAccessibility.ts @@ -36,8 +36,9 @@ class CustomizationMigrationAccessibleView implements IAccessibleViewImplementat { type: this.type }, () => this.type === AccessibleViewType.Help ? [ localize('migrationHelpOverview', "The migrations tree groups each migration type by workspace or user. Expand a group to inspect each customization, its current source, and its destination."), + localize('migrationHelpLearnMore', "Use Learn About Migrations to read why Copilot's new agent runtime needs different customization formats and locations, and how to migrate them."), localize('migrationHelpNavigation', "Use the arrow keys to move through and expand the tree. Use each row's checkbox to include or exclude it. Open a customization to view its editor or details. Use the header actions or the row's More Actions menu to migrate or delete one item."), - localize('migrationHelpAgent', "Use Migrate to have VS Code update the selected customizations. Migrate with Agent backs up every original source before closing Agent Customizations and focusing a guided migration in chat for the selected harness. Agent migration uses credits."), + localize('migrationHelpAgent', "Use Migrate to have VS Code update the selected customizations. Migrate with Agent backs up every original source before closing Agent Customizations and focusing a guided migration in chat for the selected harness. Agent migration uses Copilot credits."), localize('migrationHelpActions', "Migrate applies to the selected items in one group and asks for confirmation before modifying files or settings. Ignore permanently hides a group. Show Ignored Migrations restores hidden groups. Agent Migration Recovery can restore original sources or delete a backup; restoring does not remove destination files created or changed by the agent."), getCustomizationMigrationCategory(CustomizationMigrationCategoryId.PromptFiles).preMigrationConsequences ?? '', localize('migrationHelpLocations', "Activate a destination path to change the destination. Workspace MCP servers migrate to the root .mcp.json. User MCP servers migrate to mcp-config.json in Copilot home. Disabled user servers may become enabled after migration."), diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationDashboard.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationDashboard.ts index 49380cc36e2241..42eeda73dd0975 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationDashboard.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/customizationMigrationDashboard.ts @@ -18,6 +18,7 @@ import { localize } from '../../../../../nls.js'; import { IHoverService } from '../../../../../platform/hover/browser/hover.js'; import { IInstantiationService } from '../../../../../platform/instantiation/common/instantiation.js'; import { WorkbenchObjectTree } from '../../../../../platform/list/browser/listService.js'; +import { Link } from '../../../../../platform/opener/browser/link.js'; import { defaultButtonStyles, defaultCheckboxStyles } from '../../../../../platform/theme/browser/defaultStyles.js'; import { PromptsType } from '../../common/promptSyntax/promptTypes.js'; import { PromptsStorage } from '../../common/promptSyntax/service/promptsService.js'; @@ -317,12 +318,12 @@ export class CustomizationMigrationDashboard extends Disposable { this.prepareRender(); const supportsAgentMigration = migrationGroups.length > 0 && overview.supportsAgentMigration !== false; const page = this.renderHeader( - localize('migrationsTitle', "Migrations"), this.allMigrationsComplete - ? localize('migrationsCompletedDescription', "Your customizations use supported formats and locations.") - : supportsAgentMigration - ? localize('migrationsDescriptionWithAgent', "Some of your agent customizations need an update to keep working. Use Migrate to have VS Code update selected customizations, or Migrate with Agent for a guided migration in chat. Agent migration uses credits.") - : localize('migrationsDescription', "Some of your agent customizations need an update to keep working. Review and migrate them to the new formats and locations."), + ? localize('migrationsTitle', "Migrations") + : localize('migrationsWelcomeTitle', "Keep your customizations working"), + this.allMigrationsComplete + ? localize('migrationsCompletedDescription', "Your customizations are ready.") + : localize('migrationsDescription', "Copilot's new agent runtime uses different formats and locations for some customizations. Review and migrate the affected items below."), overview.hasIgnoredGroups === true, supportsAgentMigration ? () => { this.callbacks.actionClicked('agentMigrationClicked'); @@ -346,6 +347,9 @@ export class CustomizationMigrationDashboard extends Disposable { this.layoutTree?.(); this.callbacks.onDidChangeContent?.(); if (this.allMigrationsComplete) { + if (focusedKey === 'learnMore') { + this.focusTargets.get('learnMore')?.focus(); + } return; } if (focusedKey === focusPreferredTarget) { @@ -458,16 +462,30 @@ export class CustomizationMigrationDashboard extends Disposable { ); } if (migrateWithAgent) { - this.button( + const description = localize('migrateWithAgentDescription', "Open a new chat with an agent to review and migrate your customizations. This uses Copilot credits."); + const button = this.button( actions, 'migrateWithAgent', localize('migrateWithAgent', "Migrate with Agent"), localize('migrateWithAgentAriaLabel', "Start a guided migration of all customization files that need migration"), migrateWithAgent, 'secondary', + undefined, + this.renderDisposables, + description, ); + button.element.setAttribute('aria-description', description); } DOM.append(header, $('p.migration-intro', {}, description)); + this.renderDisposables.add(this.instantiationService.createInstance(Link, header, { + label: localize('learnAboutMigrations', "Learn About Migrations"), + href: 'https://aka.ms/vscode-migrate-customizations', + }, {})); + const learnMore = header.lastElementChild; + if (DOM.isHTMLElement(learnMore)) { + learnMore.setAttribute('role', 'link'); + this.focusTargets.set('learnMore', learnMore); + } return page; } @@ -609,7 +627,7 @@ export class CustomizationMigrationDashboard extends Disposable { icon: Codicon.warning, count: items.length, isFirst: index === 0, - description: localize('migrationManualReviewGroupDescription', "These customizations cannot be migrated automatically. Open their details or use the item menu to resolve them."), + description: localize('migrationManualReviewGroupDescription', "These customizations cannot be migrated automatically. Select Review to see what needs to change."), collapsed: this.collapsedMigrationGroups.has(groupKey), hasConfigurableDestination: false, manualReview: true, diff --git a/src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts b/src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts index f50a69c77acc8c..d4050413bc0394 100644 --- a/src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts +++ b/src/vs/workbench/contrib/chat/browser/chat.shared.contribution.ts @@ -1174,9 +1174,9 @@ configurationRegistry.registerConfiguration({ type: 'object', additionalProperties: false, properties: { - serverName: { type: 'string', minLength: 1, description: nls.localize('chat.mcp.allowedServers.serverName', "Match a server by its configured name.") }, - serverUrl: { type: 'string', minLength: 1, description: nls.localize('chat.mcp.allowedServers.serverUrl', "Match a remote server by its URL. Supports `*` wildcards, for example `https://*.example.com/*`.") }, - serverCommand: { type: 'array', minItems: 1, items: { type: 'string' }, description: nls.localize('chat.mcp.allowedServers.serverCommand', "Match a local server by its exact command invocation, given as the command followed by its arguments.") }, + serverName: { type: 'string', minLength: 1, description: nls.localize('chat.mcp.allowedServers.serverName', "Match a server by its literal configured name. For local servers, names apply only when this allowlist has no command entries; for remote servers, only when it has no URL entries.") }, + serverUrl: { type: 'string', minLength: 1, description: nls.localize('chat.mcp.allowedServers.serverUrl', "Match a remote server by its URL, with case-insensitive scheme and host and a case-sensitive path. Supports `*` wildcards; a pattern with no path matches any path. Environment variable references expand on the host that connects to the server.") }, + serverCommand: { type: 'array', minItems: 1, items: { type: 'string' }, description: nls.localize('chat.mcp.allowedServers.serverCommand', "Match a local server by its exact command followed by its arguments, in order. Environment variable references expand on the host that runs the server.") }, }, oneOf: [ { required: ['serverName'] }, @@ -1184,7 +1184,7 @@ configurationRegistry.registerConfiguration({ { required: ['serverCommand'] }, ], }, - markdownDescription: nls.localize('chat.mcp.allowedServers', "Enterprise-managed allowlist that controls which Model Context Protocol servers may be installed and run. When set, only servers matching an entry are permitted; any other server is blocked. Servers can be matched by name, remote URL pattern (with `*` wildcards), or local command invocation. Omit entirely to allow all servers (subject to the deny list). Delivered via enterprise policy for governance; this setting is not surfaced to end users."), + markdownDescription: nls.localize('chat.mcp.allowedServers', "Enterprise-managed allowlist that controls which Model Context Protocol servers may be installed and run. Local servers must match a command entry when any command entries exist; remote servers must match a URL entry when any URL entries exist. Otherwise, servers may match a literal name entry. An empty list allows no servers; omit entirely to allow all servers, subject to the deny list. Gallery checks evaluate available installation candidates; the selected command or URL is checked again after resolution. Delivered via enterprise policy for governance; this setting is not surfaced to end users."), default: null, scope: ConfigurationScope.APPLICATION, // Governance-only: delivered via the `ChatAllowedMcpServers` enterprise policy and hidden @@ -1213,8 +1213,8 @@ configurationRegistry.registerConfiguration({ additionalProperties: false, properties: { serverName: { type: 'string', minLength: 1, description: nls.localize('chat.mcp.deniedServers.serverName', "Match a server by its configured name.") }, - serverUrl: { type: 'string', minLength: 1, description: nls.localize('chat.mcp.deniedServers.serverUrl', "Match a remote server by its URL. Supports `*` wildcards, for example `https://*.example.com/*`.") }, - serverCommand: { type: 'array', minItems: 1, items: { type: 'string' }, description: nls.localize('chat.mcp.deniedServers.serverCommand', "Match a local server by its exact command invocation, given as the command followed by its arguments.") }, + serverUrl: { type: 'string', minLength: 1, description: nls.localize('chat.mcp.deniedServers.serverUrl', "Match a remote server by its URL, with case-insensitive scheme and host and a case-sensitive path. Supports `*` wildcards; a pattern with no path matches any path. Environment variable references expand on the host that connects to the server.") }, + serverCommand: { type: 'array', minItems: 1, items: { type: 'string' }, description: nls.localize('chat.mcp.deniedServers.serverCommand', "Match a local server by its exact command followed by its arguments, in order. Environment variable references expand on the host that runs the server.") }, }, oneOf: [ { required: ['serverName'] }, diff --git a/src/vs/workbench/contrib/chat/browser/chatInputPills.ts b/src/vs/workbench/contrib/chat/browser/chatInputPills.ts index f35b65609b51af..c1b9b9a8cb6ae8 100644 --- a/src/vs/workbench/contrib/chat/browser/chatInputPills.ts +++ b/src/vs/workbench/contrib/chat/browser/chatInputPills.ts @@ -3,23 +3,26 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { status } from '../../../../base/browser/ui/aria/aria.js'; import { addDisposableListener, EventType, getWindow } from '../../../../base/browser/dom.js'; import { StandardMouseEvent } from '../../../../base/browser/mouseEvent.js'; import type { IActionViewItemOptions } from '../../../../base/browser/ui/actionbar/actionViewItems.js'; import { Action, Separator, SubmenuAction, toAction, type IAction, type IActionRunner } from '../../../../base/common/actions.js'; +import { Codicon } from '../../../../base/common/codicons.js'; import { Emitter, Event } from '../../../../base/common/event.js'; import { AnchorPosition } from '../../../../base/common/layout.js'; import { Disposable, toDisposable } from '../../../../base/common/lifecycle.js'; -import { autorun, constObservable, derived, derivedOpts, IObservable } from '../../../../base/common/observable.js'; -import type { ThemeIcon } from '../../../../base/common/themables.js'; +import { autorun, constObservable, derived, derivedOpts, IObservable, ISettableObservable, ITransaction, observableFromEvent, observableValue, transaction } from '../../../../base/common/observable.js'; +import { ThemeIcon } from '../../../../base/common/themables.js'; import type { CodeWindow } from '../../../../base/browser/window.js'; import { localize } from '../../../../nls.js'; import { IContextMenuService } from '../../../../platform/contextview/browser/contextView.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; +import { IStorageService, StorageScope, StorageTarget } from '../../../../platform/storage/common/storage.js'; import { DEFAULT_LABELS_CONTAINER, ResourceLabels } from '../../../browser/labels.js'; import { ChatChangesPillActionViewItem, type IChatChangesStats } from '../../../browser/chatChangesPill.js'; -import { ChatPillsRow, ChatPillsWidget, getChatPillEntries, getChatPillEntryHoverActions, type ChatPillsCompactMode, type IChatPill, type IChatPillSection } from '../../../browser/chatPills.js'; -import { createChatSectionPill, type IChatDropdownPillOptions } from '../../../browser/chatDropdownPill.js'; +import { ChatPillsRow, ChatPillsWidget, getChatPillEntries, getChatPillEntryHoverActions, withChatPillHoverLabel, type ChatPillsCompactMode, type IChatPill, type IChatPillAction, type IChatPillEntry, type IChatPillSection } from '../../../browser/chatPills.js'; +import { ChatPillSingleEntry, createChatSectionPill, getChatPillInlineEntry, type IChatDropdownPillOptions } from '../../../browser/chatDropdownPill.js'; import { getSessionChatPillLabel, getSessionChatPillMenu, ISessionChatPillVisibilityService, type ISessionChatPillMenuEntry, SessionChatPillKind } from '../common/sessionChatPills.js'; import { chatArtifactPillOptions } from './widget/chatTurnPills.js'; import { sessionBackgroundShellsPillOptions, sessionBrowsersPillOptions, sessionCanvasesPillOptions, sessionCustomizationsPillOptions, sessionIssuesPillOptions, sessionPullRequestsPillOptions, sessionReferencesPillOptions, sessionSubagentsPillOptions } from './sessionChatPillOptions.js'; @@ -29,10 +32,10 @@ export interface IChatInputPillSource { readonly hasData: IObservable<boolean>; /** Whether any entries remain after the pill's own filtering. */ readonly isVisible?: IObservable<boolean>; - readonly pill: IObservable<IChatPill>; + readonly pills: IObservable<readonly IChatPill[]>; getContextMenuActions?(): readonly IAction[]; /** Actions on this pill's content, shown directly when its context menu is opened. */ - getContextMenuPrimaryActions?(): readonly IAction[]; + getContextMenuPrimaryActions?(pill: IChatPill): readonly IAction[]; } export interface IChatInputPillsOptions { @@ -80,6 +83,60 @@ function setsEqual<T>(first: ReadonlySet<T>, second: ReadonlySet<T>): boolean { return first === second || (first.size === second.size && [...first].every(value => second.has(value))); } +const PINNED_CHAT_PILL_ENTRIES_STORAGE_KEY = 'chat.inputPills.pinnedEntries'; + +function readPinnedChatPillEntries(storageService: IStorageService): ReadonlyMap<string, readonly string[]> { + const value = storageService.get(PINNED_CHAT_PILL_ENTRIES_STORAGE_KEY, StorageScope.PROFILE); + if (!value) { + return new Map(); + } + try { + return new Map(JSON.parse(value) as readonly [string, readonly string[]][]); + } catch { + return new Map(); + } +} + +function getPinnedEntryStorageKey(scope: string, kind: SessionChatPillKind): string { + return JSON.stringify([scope, kind]); +} + +class PinnedChatPillModel { + private readonly entry: ISettableObservable<IChatPillEntry>; + readonly pill: IObservable<IChatPill>; + + constructor( + kind: SessionChatPillKind, + entry: IChatPillEntry, + title: string, + options: IChatDropdownPillOptions, + resourceLabels: ResourceLabels, + instantiationService: IInstantiationService, + ) { + this.entry = observableValue(this, entry); + const action = toAction({ + id: `chatInputPills.${kind}.pinned.${entry.id}`, + label: entry.label, + run: () => this.entry.get().open(), + }); + this.pill = createChatSectionPill( + action, + derived(this, reader => [{ title, entries: [this.entry.read(reader)] }]), + { ...options, singleEntry: ChatPillSingleEntry.Inline, promotedActionIcon: Codicon.unpin }, + resourceLabels, + instantiationService, + ); + } + + setEntry(entry: IChatPillEntry, tx: ITransaction): void { + this.entry.set(entry, tx); + } + + getEntry(): IChatPillEntry { + return this.entry.get(); + } +} + /** Creates a source backed by one section/dropdown pill. */ export function createChatSectionPillSource( kind: SessionChatPillKind, @@ -89,10 +146,11 @@ export function createChatSectionPillSource( resourceLabels: ResourceLabels, instantiationService: IInstantiationService, ): IChatInputPillSource { + const pill = createChatSectionPill(action, sections, options, resourceLabels, instantiationService); return { kind, hasData: derived(reader => getChatPillEntries(sections.read(reader)).length > 0), - pill: createChatSectionPill(action, sections, options, resourceLabels, instantiationService), + pills: derived(reader => [pill.read(reader)]), }; } @@ -103,11 +161,18 @@ export class StandardChatInputPillSources extends Disposable { constructor( data: IStandardChatInputPillsData, offeredKinds: readonly SessionChatPillKind[], + pinScope: IObservable<string | undefined>, @IInstantiationService instantiationService: IInstantiationService, + @IStorageService private readonly storageService: IStorageService, ) { super(); const offered = new Set(offeredKinds); + const pinnedEntryIds = observableFromEvent( + this, + storageService.onDidChangeValue(StorageScope.PROFILE, PINNED_CHAT_PILL_ENTRIES_STORAGE_KEY, this._store), + () => readPinnedChatPillEntries(storageService), + ); const resourceLabels = this._register(instantiationService.createInstance(ResourceLabels, DEFAULT_LABELS_CONTAINER)); const sources: IChatInputPillSource[] = []; if (data.changes && offered.has(SessionChatPillKind.Changes)) { @@ -125,7 +190,7 @@ export class StandardChatInputPillSources extends Disposable { sources.push({ kind: SessionChatPillKind.Changes, hasData: derived(reader => changes.stats.read(reader).files > 0), - pill: constObservable(pill), + pills: constObservable([pill]), getContextMenuActions: () => changes.getContextMenuActions?.() ?? [], getContextMenuPrimaryActions: () => changes.getContextMenuPrimaryActions?.() ?? [], }); @@ -136,22 +201,106 @@ export class StandardChatInputPillSources extends Disposable { return; } const action = this._register(new Action(`chatInputPills.${kind}`, getSessionChatPillLabel(kind))); - const pillSource = createChatSectionPillSource(kind, action, source.sections, { + const pillOptions: IChatDropdownPillOptions = { ...options, ...(source.icon ? { icon: source.icon } : {}), preferredAnchorPosition: AnchorPosition.ABOVE, + }; + const presentation = derived(this, reader => { + const sections = source.sections.read(reader); + const scope = pinScope.read(reader); + const pinnedIds = scope + ? new Set(pinnedEntryIds.read(reader).get(getPinnedEntryStorageKey(scope, kind)) ?? []) + : new Set<string>(); + const pinnedEntries: IChatPillEntry[] = []; + const unpinnedSections = sections.map(section => ({ + ...section, + entries: section.entries.filter(entry => { + if (!pinnedIds.has(entry.id)) { + return true; + } + pinnedEntries.push(this.withPinAction(entry, kind, scope, true)); + return false; + }), + })).filter(section => section.entries.length > 0); + const unpinnedEntries = getChatPillEntries(unpinnedSections); + const inlineRemaining = pinnedEntries.length > 0 && unpinnedEntries.length === 1 && pillOptions.openHoverOnSelect !== true; + const unpinnedOptions = inlineRemaining + ? { ...pillOptions, singleEntry: ChatPillSingleEntry.Inline } + : pillOptions; + const pinAvailable = !!scope && unpinnedEntries.length > 0 && !getChatPillInlineEntry(unpinnedEntries, unpinnedOptions); + return { + inlineRemaining, + pinnedEntries, + sections: pinAvailable + ? unpinnedSections.map(section => ({ + ...section, + entries: section.entries.map(entry => this.withPinAction(entry, kind, scope, false)), + })) + : unpinnedSections, + }; + }); + const unpinnedSections = derived(this, reader => presentation.read(reader).sections); + const pillSource = createChatSectionPillSource(kind, action, unpinnedSections, pillOptions, resourceLabels, instantiationService); + const inlinePillSource = createChatSectionPillSource(kind, action, unpinnedSections, { + ...pillOptions, + singleEntry: ChatPillSingleEntry.Inline, }, resourceLabels, instantiationService); + const unpinnedPills = derived(this, reader => presentation.read(reader).inlineRemaining + ? inlinePillSource.pills.read(reader) + : pillSource.pills.read(reader)); + const pinnedModels = new Map<string, PinnedChatPillModel>(); + const pinnedModelsByPill = new WeakMap<IChatPill, PinnedChatPillModel>(); + const pinnedPills = observableValue<readonly IChatPill[]>(this, []); + this._register(autorun(reader => { + const entries = presentation.read(reader).pinnedEntries; + const retainedIds = new Set(entries.map(entry => entry.id)); + transaction(tx => { + const pills = entries.map(entry => { + let model = pinnedModels.get(entry.id); + if (!model) { + model = new PinnedChatPillModel(kind, entry, pillOptions.title, pillOptions, resourceLabels, instantiationService); + pinnedModels.set(entry.id, model); + } + model.setEntry(entry, tx); + const pill = model.pill.read(reader); + pinnedModelsByPill.set(pill, model); + return pill; + }); + pinnedPills.set(pills, tx); + }); + for (const id of pinnedModels.keys()) { + if (!retainedIds.has(id)) { + pinnedModels.delete(id); + } + } + })); + const pills = derived(this, reader => { + const promotedPills = pinnedPills.read(reader); + return pillSource.hasData.read(reader) + ? [...promotedPills, ...unpinnedPills.read(reader)] + : promotedPills; + }); + const isVisible = derived(reader => presentation.read(reader).pinnedEntries.length > 0 || pillSource.hasData.read(reader)); sources.push({ ...pillSource, - hasData: source.hasData ?? pillSource.hasData, - isVisible: pillSource.hasData, + pills, + hasData: source.hasData ?? isVisible, + isVisible, getContextMenuActions: () => source.getContextMenuActions?.() ?? [], - getContextMenuPrimaryActions: () => { + getContextMenuPrimaryActions: pill => { + const pinnedModel = pinnedModelsByPill.get(pill); + if (pinnedModel) { + return getChatPillEntryHoverActions(pinnedModel.getEntry()); + } + const entries = getChatPillEntries(presentation.get().sections); + if (entries.length === 1) { + return getChatPillEntryHoverActions(entries[0]); + } if (source.getContextMenuPrimaryActions) { return source.getContextMenuPrimaryActions(); } - const entries = getChatPillEntries(source.sections.get()); - return entries.length === 1 ? getChatPillEntryHoverActions(entries[0]) : []; + return []; }, }); }; @@ -166,6 +315,61 @@ export class StandardChatInputPillSources extends Disposable { addSections(SessionChatPillKind.BackgroundShells, data.backgroundShells, sessionBackgroundShellsPillOptions); this.sources = sources; } + + private withPinAction(entry: IChatPillEntry, kind: SessionChatPillKind, scope: string | undefined, pinned: boolean): IChatPillEntry { + if (!scope) { + return entry; + } + const pinAction = this.createPinAction(entry, kind, scope, pinned); + if (pinned) { + return { + ...entry, + toolbarActions: [...entry.toolbarActions ?? [], ...(entry.promotedAction ? [entry.promotedAction] : [])], + promotedAction: pinAction, + }; + } + return { + ...entry, + toolbarActions: [...entry.toolbarActions ?? [], pinAction], + }; + } + + private createPinAction(entry: IChatPillEntry, kind: SessionChatPillKind, scope: string, pinned: boolean): IChatPillAction { + return withChatPillHoverLabel(toAction({ + id: `chatInputPills.${kind}.${pinned ? 'unpin' : 'pin'}.${entry.id}`, + label: pinned + ? localize('chatInputPills.unpinEntry', "Unpin {0}", entry.label) + : localize('chatInputPills.pinEntry', "Pin {0}", entry.label), + class: ThemeIcon.asClassName(pinned ? Codicon.unpin : Codicon.pin), + run: () => this.setPinned(kind, scope, entry.id, entry.label, !pinned), + }), pinned + ? localize('chatInputPills.unpinHoverLabel', "Unpin") + : localize('chatInputPills.pinHoverLabel', "Pin")); + } + + private setPinned(kind: SessionChatPillKind, scope: string, entryId: string, label: string, pinned: boolean): void { + const storageKey = getPinnedEntryStorageKey(scope, kind); + const pinnedForSource = new Set(readPinnedChatPillEntries(this.storageService).get(storageKey) ?? []); + if (pinned) { + pinnedForSource.add(entryId); + } else { + pinnedForSource.delete(entryId); + } + const next = new Map(readPinnedChatPillEntries(this.storageService)); + if (pinnedForSource.size > 0) { + next.set(storageKey, [...pinnedForSource]); + } else { + next.delete(storageKey); + } + if (next.size > 0) { + this.storageService.store(PINNED_CHAT_PILL_ENTRIES_STORAGE_KEY, JSON.stringify([...next]), StorageScope.PROFILE, StorageTarget.MACHINE); + } else { + this.storageService.remove(PINNED_CHAT_PILL_ENTRIES_STORAGE_KEY, StorageScope.PROFILE); + } + status(pinned + ? localize('chatInputPills.pinnedEntry', "Pinned {0}.", label) + : localize('chatInputPills.unpinnedEntry', "Unpinned {0}.", label)); + } } /** Shared renderer/controller for status pills above a chat input. */ @@ -206,7 +410,7 @@ export class ChatInputPills extends Disposable { source.hasData.read(reader) && (source.isVisible?.read(reader) ?? true) && (!source.kind || this._visibility.isVisible(source.kind, reader))); }); const model = { - pills: derived(this, reader => visibleSources.read(reader).map(source => source.pill.read(reader))), + pills: derived(this, reader => visibleSources.read(reader).flatMap(source => source.pills.read(reader))), context: _options.context, }; this._pills = this._register(instantiationService.createInstance(ChatPillsWidget, model, { @@ -232,7 +436,7 @@ export class ChatInputPills extends Disposable { } return kinds; }); - const showContextMenu = (anchor: HTMLElement | StandardMouseEvent, target?: IChatInputPillSource) => { + const showContextMenu = (anchor: HTMLElement | StandardMouseEvent, target?: { readonly source: IChatInputPillSource; readonly pill: IChatPill }) => { const kinds = kindsWithData.get(); if (kinds.size === 0) { return; @@ -246,9 +450,9 @@ export class ChatInputPills extends Disposable { event.preventDefault(); event.stopPropagation(); const anchor = new StandardMouseEvent(getWindow(this._row.content), event); - showContextMenu(anchor, this._getTargetSource(event.target as HTMLElement | null)); + showContextMenu(anchor, this._getTarget(event.target as HTMLElement | null)); })); - this._register(this._row.onDidRequestContextMenu(anchor => showContextMenu(anchor, this._getTargetSource(anchor)))); + this._register(this._row.onDidRequestContextMenu(anchor => showContextMenu(anchor, this._getTarget(anchor)))); derived(this, reader => { const anyVisible = this._pills.isVisible.read(reader); @@ -283,27 +487,27 @@ export class ChatInputPills extends Disposable { return this._pills.focusFirst(); } - private _getTargetSource(target: HTMLElement | null): IChatInputPillSource | undefined { + private _getTarget(target: HTMLElement | null): { readonly source: IChatInputPillSource; readonly pill: IChatPill } | undefined { const targetPill = this._pills.getPill(target); if (!targetPill) { return undefined; } for (const source of this._options.sources.get()) { - if (source.pill.get() === targetPill) { - return source; + if (source.pills.get().includes(targetPill)) { + return { source, pill: targetPill }; } } return undefined; } - private _getVisibilityActions(kindsWithData: ReadonlySet<SessionChatPillKind>, target?: IChatInputPillSource) { - const targetKind = target?.kind; + private _getVisibilityActions(kindsWithData: ReadonlySet<SessionChatPillKind>, target?: { readonly source: IChatInputPillSource; readonly pill: IChatPill }) { + const targetKind = target?.source.kind; const sourceKinds = new Set(this._options.sources.get().flatMap(source => source.kind ? [source.kind] : [])); const offeredKinds = this._options.offeredKinds.filter(kind => sourceKinds.has(kind)); const menu = getSessionChatPillMenu(kindsWithData, this._visibility.readHiddenKinds(undefined), targetKind, offeredKinds); const restoreFocus = () => this._row.restoreFocus(() => { const pills = this._pills.getPillElements(); - const targetElement = target ? pills.find(pill => this._getTargetSource(pill)?.pill.get() === target.pill.get()) : undefined; + const targetElement = target ? pills.find(pill => this._getTarget(pill)?.pill === target.pill) : undefined; return targetElement ? [targetElement] : pills; }, this._options.focusFallback); const withFocusRestoration = (action: IAction): IAction => { @@ -350,7 +554,7 @@ export class ChatInputPills extends Disposable { continue; } const actions = source.getContextMenuActions?.() ?? []; - const primaryActions = source.pill.get() === target?.pill.get() ? source.getContextMenuPrimaryActions?.() ?? [] : []; + const primaryActions = source === target?.source ? source.getContextMenuPrimaryActions?.(target.pill) ?? [] : []; (actions.length ? optionsActions : targetActions).push(...primaryActions.map(withFocusRestoration)); if (actions.length) { optionsActions.push(new SubmenuAction( @@ -382,5 +586,5 @@ export class ChatInputPills extends Disposable { /** Creates a source for a pill whose data presence is represented by its membership. */ export function createChatInputPillSource(pill: IChatPill, kind?: SessionChatPillKind): IChatInputPillSource { - return { kind, hasData: constObservable(true), pill: constObservable(pill) }; + return { kind, hasData: constObservable(true), pills: constObservable([pill]) }; } diff --git a/src/vs/workbench/contrib/chat/browser/chatManagement/chatModelsWidget.ts b/src/vs/workbench/contrib/chat/browser/chatManagement/chatModelsWidget.ts index 35182b8f29cbc4..ef00c704b44d5e 100644 --- a/src/vs/workbench/contrib/chat/browser/chatManagement/chatModelsWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/chatManagement/chatModelsWidget.ts @@ -51,6 +51,7 @@ import { IJSONSchema } from '../../../../../base/common/jsonSchema.js'; import { formatTokenCount } from '../../../../../base/common/numbers.js'; import { IDefaultAccountService } from '../../../../../platform/defaultAccount/common/defaultAccount.js'; import { CHAT_SETUP_ACTION_ID } from '../actions/chatActions.js'; +import { getAddModelsUnavailableReason } from '../../common/chatSessionsService.js'; const $ = DOM.$; @@ -1147,6 +1148,7 @@ export class ChatModelsWidget extends Disposable { private addButton!: Button; private dropdownActions: IAction[] = []; private defaultAccountResolved = false; + private sessionType: string | undefined; private viewModel: ChatModelsViewModel; private delayedFiltering: Delayer<void>; @@ -1644,6 +1646,14 @@ export class ChatModelsWidget extends Disposable { } private updateAddModelsButton(): void { + const unavailableReason = getAddModelsUnavailableReason(this.sessionType, this.environmentService.remoteAuthority); + if (unavailableReason) { + this.dropdownActions = []; + this.addButton.enabled = false; + this.addButton.setTitle(unavailableReason); + return; + } + const configurableVendors = this.languageModelsService.getVendors().filter(vendor => vendor.managementCommand || vendor.configuration); const entitlement = this.chatEntitlementService.entitlement; @@ -1718,7 +1728,9 @@ export class ChatModelsWidget extends Disposable { * Pass `undefined` to list every model. */ public setSessionType(sessionType: string | undefined): void { + this.sessionType = sessionType; this.viewModel.setSessionType(sessionType); + this.updateAddModelsButton(); } public render(): void { diff --git a/src/vs/workbench/contrib/chat/browser/pluginSources.ts b/src/vs/workbench/contrib/chat/browser/pluginSources.ts index cbe4611aa5af79..c6a6a4b1b5d249 100644 --- a/src/vs/workbench/contrib/chat/browser/pluginSources.ts +++ b/src/vs/workbench/contrib/chat/browser/pluginSources.ts @@ -94,7 +94,8 @@ abstract class AbstractGitPluginSource implements IPluginSource { const progressTitle = options?.progressTitle ?? localize('cloningPluginSource', "Cloning plugin source '{0}'...", label); const failureLabel = options?.failureLabel ?? label; - const ref = (descriptor as IGitHubPluginSource | IGitUrlPluginSource).ref; + const git = descriptor as IGitHubPluginSource | IGitUrlPluginSource; + const ref = git.sha ?? git.ref; await this._cloneRepository(repoDir, this._cloneUrl(descriptor), progressTitle, failureLabel, ref); await this._checkoutRevision(repoDir, descriptor, failureLabel); diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts index 6172db6c31c388..0900e92220bc29 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxAgentHostService.ts @@ -13,6 +13,8 @@ import { StopWatch } from '../../../../../base/common/stopwatch.js'; import { localize } from '../../../../../nls.js'; import { AgentHostTransportFailureReason, NonReconnectableTransportError, IProtocolTransport } from '../../../../../platform/agentHost/common/state/sessionTransport.js'; import { AgentHostProtocolClient } from '../../../../../platform/agentHost/browser/agentHostProtocolClient.js'; +import { sealAgentHostCredential } from '../../../../../platform/agentHost/browser/agentHostCredentialSealing.js'; +import type { AuthenticateParams } from '../../../../../platform/agentHost/common/agent.js'; import { agentsWindowAgentHostClientInfo, editorWindowAgentHostClientInfo } from '../../../../../platform/agentHost/common/agentHostClientInfo.js'; import { AgentHostClientConnectionKind } from '../../../../../platform/agentHost/common/agentHostTelemetry.js'; import { formatConnectionDiagnosticError, getConnectionDiagnosticError, traceConnectionOperation, type IConnectionDiagnosticEvent } from '../../../../../platform/agentHost/common/connectionDiagnostics.js'; @@ -33,6 +35,7 @@ import { CloudSandboxRequestError, type CloudSandboxConnectResult, type ICloudSandboxClientToken, + type IHostEncryptionKey, } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import { getEntryAddress, IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId, type IRemoteAgentHostConnectOptions, type IRemoteAgentHostConnectionFactory, type IRemoteAgentHostCreatedConnection, type IRemoteAgentHostEntry, type RemoteAgentHostConnectionObserver } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { DEFAULT_RECONNECT_POLICY } from '../../../../../platform/agentHost/common/reconnectPolicy.js'; @@ -44,6 +47,7 @@ import { ILogService } from '../../../../../platform/log/common/log.js'; import { MISSION_CONTROL_RETRY_BUDGET_MS, missionControlMaxRetries, missionControlRetryDelay } from '../../../../../platform/github/common/missionControl/missionControlError.js'; import { CloudSandboxCredentialRefresher, CloudSandboxCredentialRefreshState, MAX_CONSECUTIVE_CREDENTIAL_REFRESH_FAILURES, MIN_CREDENTIAL_REFRESH_DELAY_MS, type ICloudSandboxCreds } from './cloudSandboxCredentialRefresh.js'; import { getCloudSandboxConnectionSurface, ICloudSandboxTelemetryService, type CloudSandboxConnectionSurface, type ICloudSandboxConnectionTelemetry } from './cloudSandboxTelemetry.js'; +import { isMissionControlRecipientTrusted, verifyMissionControlRecipient } from './missionControlCredentialSealing.js'; const LOG_PREFIX = '[CloudSandboxAgentHost]'; @@ -72,8 +76,10 @@ interface IStagedCloudSandboxConnection { readonly clientId: string; readonly refreshState: CloudSandboxCredentialRefreshState; refresher: CloudSandboxCredentialRefresher | undefined; + authenticationLifetime: CancellationTokenSource | undefined; reconnectRequiresRefresh: boolean; lastAuthenticationToken: string | undefined; + trustedEncryptionKeys: readonly IHostEncryptionKey[] | undefined; } /** Builds cloud sandbox protocol clients from credentials staged by the caller. */ @@ -93,10 +99,16 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo @IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService, @ICloudSandboxTelemetryService private readonly _telemetryService: ICloudSandboxTelemetryService, @IPowerService private readonly _powerService: IPowerService, + @ICloudSandboxApiService private readonly _apiService: ICloudSandboxApiService, ) { super(); this.entries = this._entries; this._surface = getCloudSandboxConnectionSurface(this._environmentService.isSessionsWindow, isWeb); + this._register(toDisposable(() => { + for (const staged of this._stagedConnections.values()) { + staged.authenticationLifetime?.dispose(true); + } + })); // Staging is cleared only by an explicit `unstageConfiguration`, never by // observing the connection disappear. The service withdraws an entry // before arming a retry, so treating that as removal would delete the @@ -155,6 +167,7 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo stageConfiguration(options: ICloudSandboxConnectOptions, clientToken: ICloudSandboxClientToken): IRemoteAgentHostEntry { const address = cloudSandboxAddress(options.environmentId); this._pendingConnections.deleteAndDispose(address); + this._stagedConnections.get(address)?.authenticationLifetime?.dispose(true); const entry: IRemoteAgentHostEntry = { name: options.name, connection: { @@ -172,8 +185,10 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo clientId: clientToken.client_id, refreshState: new CloudSandboxCredentialRefreshState(), refresher: undefined, + authenticationLifetime: undefined, reconnectRequiresRefresh: true, lastAuthenticationToken: undefined, + trustedEncryptionKeys: options.trustedEncryptionKeys, }); this._updateEntries(); return entry; @@ -181,6 +196,7 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo unstageConfiguration(address: string): void { this._pendingConnections.deleteAndDispose(address); + this._stagedConnections.get(address)?.authenticationLifetime?.dispose(true); this._stagedConnections.delete(address); this._updateEntries(); } @@ -193,6 +209,27 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo return this._stagedConnections.get(cloudSandboxAddress(environmentId))?.creds.token.encrypted_github_token; } + async resolveUserLocalAuthentication(environmentId: string, resource: string, forceRefresh = false): Promise<AuthenticateParams> { + const staged = this._stagedConnections.get(cloudSandboxAddress(environmentId)); + if (!staged || staged.options.environmentKind !== 'user-local' || !staged.options.accountKey) { + throw new Error('Mission Control identity authentication requires a staged user-local connection.'); + } + const lifetime = staged.authenticationLifetime; + if (!lifetime || lifetime.token.isCancellationRequested) { + throw new CancellationError(); + } + const token = lifetime.token; + const identity = await this._apiService.getIdentityToken(staged.options.accountKey, token, forceRefresh); + if (token.isCancellationRequested || staged.authenticationLifetime !== lifetime || !this.isCurrentConfiguration(staged.entry)) { + throw new CancellationError(); + } + const expiresIn = identity.expiresAt === undefined ? undefined : Math.floor((identity.expiresAt - Date.now()) / 1000); + if (expiresIn !== undefined && expiresIn <= 0) { + throw new Error('Mission Control identity credential expired before authentication.'); + } + return { resource, token: identity.token, ...(expiresIn === undefined ? {} : { expiresIn }) }; + } + async refreshSealedGitHubToken(environmentId: string): Promise<string | undefined> { const address = cloudSandboxAddress(environmentId); const staged = this._stagedConnections.get(address); @@ -220,6 +257,10 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo const store = new DisposableStore(); this._pendingConnections.set(address, store); try { + staged.authenticationLifetime?.dispose(true); + const lifetime = new CancellationTokenSource(); + store.add(toDisposable(() => lifetime.dispose(true))); + staged.authenticationLifetime = lifetime; const telemetry = this._connectionTelemetry.get(address); const diagnosticObserver = (event: IConnectionDiagnosticEvent) => telemetry?.recordConnectionDiagnostic(event); const refresher = store.add(this._instantiationService.createInstance( @@ -293,11 +334,28 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo staged.reconnectRequiresRefresh = true; }, prepareAuthentication: async () => { - if (staged.lastAuthenticationToken && staged.lastAuthenticationToken === staged.creds.token.encrypted_github_token) { + if (staged.options.environmentKind !== 'user-local' && staged.lastAuthenticationToken && staged.lastAuthenticationToken === staged.creds.token.encrypted_github_token) { await traceConnectionOperation(diagnosticObserver, 'credentials', () => refresher.refreshAuthenticationCredentials()); } }, - resolveInitialAuthentication: () => this._resolveInitialAuthentication(staged), + resolveInitialAuthentication: () => this._resolveInitialAuthentication(staged, lifetime.token), + sealAuthenticationToken: staged.options.environmentKind === 'user-local' ? async request => { + if (await this._apiService.getAccountKey() !== staged.options.accountKey) { + throw new CancellationError(); + } + if (!isMissionControlRecipientTrusted(request, staged.trustedEncryptionKeys)) { + const environment = await this._apiService.getEnvironment(staged.options.environmentId, lifetime.token); + if (environment.id !== staged.options.environmentId) { + throw new Error('Mission Control returned a different environment for credential encryption.'); + } + staged.trustedEncryptionKeys = environment.encryption_keys; + } + verifyMissionControlRecipient(request, staged.trustedEncryptionKeys); + if (lifetime.token.isCancellationRequested || !this.isCurrentConfiguration(staged.entry)) { + throw new CancellationError(); + } + return sealAgentHostCredential(request); + } : undefined, }, ); store.add(client.onDidConnectionDiagnostic(diagnosticObserver)); @@ -312,7 +370,13 @@ class CloudSandboxConnectionFactory extends Disposable implements IRemoteAgentHo } } - private async _resolveInitialAuthentication(staged: IStagedCloudSandboxConnection): Promise<{ readonly resource: string; readonly token: string } | undefined> { + private async _resolveInitialAuthentication(staged: IStagedCloudSandboxConnection, token: CancellationToken): Promise<AuthenticateParams | undefined> { + if (token.isCancellationRequested || !this.isCurrentConfiguration(staged.entry)) { + throw new CancellationError(); + } + if (staged.options.environmentKind === 'user-local') { + return this.resolveUserLocalAuthentication(staged.options.environmentId, GITHUB_COPILOT_PROTECTED_RESOURCE.resource); + } // Throw rather than returning `undefined`: an unusable token must fail // the connection, not produce one that reports connected and then fails // every authenticated request. The protocol client classifies this as an @@ -375,6 +439,10 @@ export class CloudSandboxAgentHostService extends Disposable implements ICloudSa return this._connectionFactory.refreshSealedGitHubToken(environmentId); } + resolveUserLocalAuthentication(environmentId: string, resource: string, forceRefresh = false): Promise<AuthenticateParams> { + return this._connectionFactory.resolveUserLocalAuthentication(environmentId, resource, forceRefresh); + } + async disconnect(addressOrEnvironmentId: string): Promise<void> { const address = cloudSandboxEnvironmentId(addressOrEnvironmentId) === undefined ? cloudSandboxAddress(addressOrEnvironmentId) : addressOrEnvironmentId; this._connectionFactory.endConnectionTelemetry(address, true); @@ -539,7 +607,7 @@ export class CloudSandboxAgentHostService extends Disposable implements ICloudSa rateLimitFailures = 0; rateLimitedAt = undefined; if (result.kind === 'token') { - return await this._awaitSealedToken(options, result.token, token, telemetry); + return options.environmentKind === 'user-local' ? result.token : await this._awaitSealedToken(options, result.token, token, telemetry); } const delayMs = this._wakingRetryDelay(result.waking.retryAfterSeconds); this._logService.info(`${LOG_PREFIX} Environment ${options.environmentId} waking; retrying in ${delayMs}ms (attempt ${attempt})`); diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts index 405755168c908c..8db4a969bc10d1 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxApiService.ts @@ -354,8 +354,32 @@ export class CloudSandboxApiService extends Disposable implements ICloudSandboxA return parseSealedTokenResponse(response); } - private _requestIdentityToken(session: AuthenticationSession, token: CancellationToken): Promise<ICloudSandboxIdentityTokenResponse | undefined> { - return this._requestCredential('mintIdentityToken', 'tokens', {}, token, session); + private async _requestIdentityToken(session: AuthenticationSession, token: CancellationToken): Promise<ICloudSandboxIdentityTokenResponse | undefined> { + const store = new DisposableStore(); + try { + const signal = AbortSignal.any([CancellationToken.toAbortSignal(token, store), AbortSignal.timeout(REQUEST_TIMEOUT_MS)]); + const client = store.add(await this._githubService.acquireAccountApiClient({ + providerId: this._authenticationProviderId, sessionId: session.id, accountId: session.account.id, + scopes: session.scopes, authorizationServer: session.authorizationServer?.toString(), + }, signal)); + const result = await client.environments.mintIdentityToken(signal, { caller: 'mc.tokens.create', deadline: Date.now() + REQUEST_TIMEOUT_MS }); + this._telemetry.reportRequest('mintIdentityToken', 'succeeded'); + return result; + } catch (error) { + if (token.isCancellationRequested || isCancellationError(error)) { + throw new CancellationError(); + } + if (error instanceof ApiRequestError) { + this._telemetry.reportRequest('mintIdentityToken', requestOutcomeForStatus(error.statusCode)); + throw new CloudSandboxRequestError(error.statusCode, error.message, error.retryAfterSeconds, { + code: error.code, limitedResource: error.limitedResource, requestId: error.requestId, + }); + } + this._telemetry.reportRequest('mintIdentityToken', 'networkError'); + throw new Error(localize('cloudSandbox.identityClientFailed', "The sandbox identity-token request failed or returned an invalid response.")); + } finally { + store.dispose(); + } } private async _requestCredential<T>(action: 'mintIdentityToken' | 'sealToken', path: string, body: Record<string, unknown>, token: CancellationToken, session?: AuthenticationSession): Promise<T | undefined> { diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts index 97ad774e073055..228e80d6800ae3 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxConnectionCustomization.ts @@ -6,7 +6,6 @@ import { Event } from '../../../../../base/common/event.js'; import { DisposableStore } from '../../../../../base/common/lifecycle.js'; import { AgentHostProtocolClient } from '../../../../../platform/agentHost/browser/agentHostProtocolClient.js'; -import { GITHUB_COPILOT_PROTECTED_RESOURCE } from '../../../../../platform/agentHost/common/agentService.js'; import { AuthRequiredReason } from '../../../../../platform/agentHost/common/state/sessionActions.js'; import { CLOUD_SANDBOX_ADDRESS_PREFIX, @@ -39,8 +38,9 @@ function isGitHubResource(resource: string): boolean { * The {@link IRemoteAgentHostConnectionCustomization} for a cloud sandbox address, supplying the * ways the sandbox host deviates from the generic path: * - * - **Auth**: the host only accepts a sealed envelope, so the connection's `encrypted_github_token` - * is presented instead of the resolved bearer. Fails closed if no sealed token is available. + * - **Auth**: managed sandboxes receive the connection's sealed GitHub token. User-local hosts + * receive an identity-only token sealed at protocol dispatch against a trusted recipient and + * the current connection challenge. * - **Scheme**: the host advertises provider `copilot` but addresses sessions as `ahp-session`. * - **Directory**: prepare an advertised repository checkout before creating a session. * @@ -50,7 +50,6 @@ export function createCloudSandboxConnectionCustomization( address: string, sandboxService: ICloudSandboxAgentHostService, userLocal = false, - sealUserLocal?: (request: IAgentHostAuthenticateRequest) => Promise<IAgentHostAuthenticateRequest>, ): IRemoteAgentHostConnectionCustomization | undefined { const environmentId = cloudSandboxEnvironmentId(address); if (environmentId === undefined) { @@ -60,6 +59,9 @@ export function createCloudSandboxConnectionCustomization( if (!isGitHubResource(resource)) { throw new Error(`Cloud sandbox cannot authenticate the non-GitHub resource '${resource}'.`); } + if (userLocal) { + return { ...await sandboxService.resolveUserLocalAuthentication(environmentId, resource, renew), scopes }; + } const sealed = renew ? await sandboxService.refreshSealedGitHubToken(environmentId) : sandboxService.getSealedGitHubToken(environmentId); @@ -74,11 +76,8 @@ export function createCloudSandboxConnectionCustomization( if (reason !== AuthRequiredReason.Expired && isCloudSandboxSealedToken(request.token)) { return request; } - if (userLocal && (request.target || new URL(request.resource).origin !== new URL(GITHUB_COPILOT_PROTECTED_RESOURCE.resource).origin)) { - if (!sealUserLocal) { - throw new Error('User-local Mission Control sealing is unavailable.'); - } - return sealUserLocal(request); + if (userLocal && (request.target || !isGitHubResource(request.resource))) { + return request; } const authentication = await resolveAuthentication(request.resource, request.scopes, reason === AuthRequiredReason.Expired); return request.target ? { ...authentication, target: request.target } : authentication; diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionContribution.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionContribution.ts index a2874c8da902b4..8e9d35333a7d3b 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionContribution.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/cloudSandboxSessionContribution.ts @@ -37,7 +37,7 @@ import { type ICloudSandboxDiscoveredSession, } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import { AgentSession, type IAgentSessionMetadata } from '../../../../../platform/agentHost/common/agent.js'; -import { IAgentConnection, IAgentHostService } from '../../../../../platform/agentHost/common/agentService.js'; +import { IAgentConnection } from '../../../../../platform/agentHost/common/agentService.js'; import { AGENT_HOST_SCHEME, agentHostAuthority } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { findRemoteAgentHostSessionTypeAuthority, remoteAgentHostSessionTypeId } from '../../../../../platform/agentHost/common/agentHostSessionType.js'; import { getEntryAddress, IRemoteAgentHostService, RemoteAgentHostConnectionStatus, RemoteAgentHostEntryType, RemoteAgentHostsEnabledSettingId } from '../../../../../platform/agentHost/common/remoteAgentHostService.js'; @@ -54,7 +54,6 @@ import { IHostService } from '../../../../services/host/browser/host.js'; import { CloudSandboxSessionHandler } from './cloudSandboxSessionHandler.js'; import { IRemoteAgentHostConnectionCustomizationService } from './remoteAgentHostConnectionCustomization.js'; import { createCloudSandboxConnectionCustomization, isCloudSandboxConnectionAddress } from './cloudSandboxConnectionCustomization.js'; -import { sealMissionControlMcpCredential } from './missionControlCredentialSealing.js'; import { withSessionInitiator } from '../../../../../platform/agentHost/common/meta/agentSessionInitiatorMeta.js'; import { readCloudSandboxProjects } from '../../../../../platform/agentHost/common/meta/cloudSandboxProjectMeta.js'; import { getGitHubRepositoryFromRemoteUrl } from '../../../git/common/utils.js'; @@ -213,7 +212,6 @@ export abstract class CloudSandboxSessionContribution<T extends ICloudSandboxSes @IHostService private readonly _hostService: IHostService, @IStorageService private readonly _storageService: IStorageService, @IWorkspaceTrustManagementService private readonly _workspaceTrustManagementService: IWorkspaceTrustManagementService, - @IAgentHostService private readonly _localAgentHostService: IAgentHostService, ) { super(); @@ -225,28 +223,7 @@ export abstract class CloudSandboxSessionContribution<T extends ICloudSandboxSes address => { const connection = this._remoteAgentHostService.configuredEntries.find(entry => getEntryAddress(entry) === address)?.connection; const userLocal = connection?.type === RemoteAgentHostEntryType.CloudSandbox && connection.environmentKind === 'user-local'; - const customization = createCloudSandboxConnectionCustomization(address, this._cloudSandboxService, userLocal, async request => { - if (!userLocal) { - throw new Error('User-local MC sealing requires a user-local connection.'); - } - const environment = await this._apiService.getEnvironment(connection.environmentId, CancellationToken.None); - const client = this._remoteAgentHostService.getConnection(address); - const root = client?.rootState.value; - if (environment.id !== connection.environmentId || !client || !root || root instanceof Error) { - throw new Error('Mission Control environment or host is unavailable for sealing.'); - } - const initialization = client.initializeResult.get(); - const result = await sealMissionControlMcpCredential(request, environment.encryption_keys, root, initialization?._meta, sealingRequest => { - if (!this._localAgentHostService.sealMissionControlCredential) { - throw new Error('Trusted local credential sealing is unavailable.'); - } - return this._localAgentHostService.sealMissionControlCredential(sealingRequest); - }); - if (this._remoteAgentHostService.getConnection(address) !== client || client.initializeResult.get() !== initialization) { - throw new CancellationError(); - } - return result; - })!; + const customization = createCloudSandboxConnectionCustomization(address, this._cloudSandboxService, userLocal)!; return { ...customization, registerChatSessionContentProvider: (sessionType, provider) => this._registerLiveSessionProvider(sessionType, provider), diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/editorCloudSandboxContribution.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/editorCloudSandboxContribution.ts index 58b44e3fef4349..ae7db3f917da67 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/editorCloudSandboxContribution.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/editorCloudSandboxContribution.ts @@ -18,7 +18,6 @@ import { extUriBiasedIgnorePathCase } from '../../../../../base/common/resources import { URI } from '../../../../../base/common/uri.js'; import { localize } from '../../../../../nls.js'; import { IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; -import { IAgentHostService } from '../../../../../platform/agentHost/common/agentService.js'; import { agentHostAuthority } from '../../../../../platform/agentHost/common/agentHostUri.js'; import { ChangesetKind } from '../../../../../platform/agentHost/common/changesetUri.js'; import { CLOUD_SANDBOX_AGENT_PROVIDER, CLOUD_SANDBOX_SESSION_SCHEME, cloudSandboxAddress, ICloudSandboxAgentHostService, ICloudSandboxApiService, ICloudSandboxDraftPreparationService, isRetryableCloudSandboxError } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; @@ -122,12 +121,11 @@ export class EditorCloudSandboxSessionContribution extends CloudSandboxSessionCo @IGitService private readonly _gitService: IGitService, @ISCMService scmService: ISCMService, @IWorkspaceTrustManagementService workspaceTrustManagementService: IWorkspaceTrustManagementService, - @IAgentHostService localAgentHostService: IAgentHostService, @IChatAgentService private readonly _chatAgentService: IChatAgentService, @IChatService private readonly _chatService: IChatService, @IChatWidgetService private readonly _chatWidgetService: IChatWidgetService, ) { - super(cloudSandboxService, apiService, draftPreparationService, _remoteService, connectionCustomizations, configurationService, instantiationService, _editorChatSessionsService, _editorLogService, chatEntitlementService, hostService, storageService, workspaceTrustManagementService, localAgentHostService); + super(cloudSandboxService, apiService, draftPreparationService, _remoteService, connectionCustomizations, configurationService, instantiationService, _editorChatSessionsService, _editorLogService, chatEntitlementService, hostService, storageService, workspaceTrustManagementService); const enabled = observableFromEvent(this, Event.any(configurationService.onDidChangeConfiguration, chatEntitlementService.onDidChangeSentiment), () => this._isEnabled()); const workspaceChanged = observableSignalFromEvent(this, workspaceContextService.onDidChangeWorkspaceFolders); const repositoriesChanged = observableSignalFromEvent(this, Event.any(scmService.onDidAddRepository, scmService.onDidRemoveRepository)); diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlCredentialSealing.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlCredentialSealing.ts index 8f8e80e33ed337..14fd6cd7c80a7e 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlCredentialSealing.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlCredentialSealing.ts @@ -3,44 +3,18 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ -import { isObject } from '../../../../../base/common/types.js'; import type { IHostEncryptionKey } from '../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import type { IMissionControlCredentialSealingRequest } from '../../../../../platform/agentHost/common/agentService.js'; -import type { RootState } from '../../../../../platform/agentHost/common/state/sessionState.js'; -import type { IAgentHostAuthenticateRequest } from '../agentSessions/agentHost/agentHostAuth.js'; -/** Pins MCP sealing to the authenticated environment descriptor and this handshake's advertised key. */ -export async function sealMissionControlMcpCredential( - request: IAgentHostAuthenticateRequest, - trustedKeys: readonly IHostEncryptionKey[] | undefined, - root: RootState, - handshakeMeta: Record<string, unknown> | undefined, - seal: (request: IMissionControlCredentialSealingRequest) => Promise<string>, -): Promise<IAgentHostAuthenticateRequest> { - const advertised = root._meta?.['copilot.encryptionKeys']; - if (!Array.isArray(trustedKeys) || !Array.isArray(advertised)) { - throw new Error('Mission Control has no authenticated MCP recipient key.'); - } - const key = trustedKeys.find(key => key.use === 'mcp-auth-token' && key.algorithm === 'x25519-sealedbox' - && advertised.some(value => { - if (!isObject(value)) { - return false; - } - const candidate = value as { keyId?: string; use?: string; algorithm?: string; publicKey?: string }; - return candidate.keyId === key.key_id && candidate.use === key.use && candidate.algorithm === key.algorithm && candidate.publicKey === key.public_key; - })); - if (!key) { - throw new Error('Mission Control MCP key does not match the connected host.'); - } - const value = handshakeMeta?.['copilot.authChallenge']; - const binding = isObject(value) ? value as { challenge?: unknown; required?: unknown } : undefined; - if (binding?.required === true && typeof binding.challenge !== 'string') { - throw new Error('Mission Control requires a missing handshake challenge.'); +/** Matches the live recipient against independently authenticated MC metadata, including its algorithm and purpose. */ +export function isMissionControlRecipientTrusted(request: IMissionControlCredentialSealingRequest, trustedKeys: readonly IHostEncryptionKey[] | undefined): boolean { + return trustedKeys?.some(key => key.key_id === request.key.key_id && key.public_key === request.key.public_key + && key.use === request.key.use && key.algorithm === request.key.algorithm) === true; +} + +/** Refuses relay-supplied recipient keys unless the authenticated MC descriptor advertises the exact same key. */ +export function verifyMissionControlRecipient(request: IMissionControlCredentialSealingRequest, trustedKeys: readonly IHostEncryptionKey[] | undefined): void { + if (!isMissionControlRecipientTrusted(request, trustedKeys)) { + throw new Error('Mission Control recipient key does not match the authenticated environment.'); } - const token = await seal({ - resource: request.resource, token: request.token, - key: { ...key, use: 'mcp-auth-token' }, - challenge: typeof binding?.challenge === 'string' ? binding.challenge : undefined, - }); - return { ...request, token }; } diff --git a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts index 75c42b9884789c..613622e6b1e297 100644 --- a/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts +++ b/src/vs/workbench/contrib/chat/browser/remoteAgentHost/missionControlEnvironmentService.ts @@ -259,7 +259,10 @@ export class MissionControlEnvironmentService extends Disposable implements IMis this._requireHost(id); } connecting = true; - await raceCancellationError(this._connections.connect({ environmentId: id, name: host.name, environmentKind: 'user-local' }, source.token), source.token); + await raceCancellationError(this._connections.connect({ + environmentId: id, name: host.name, environmentKind: 'user-local', + ...(environment.encryption_keys ? { trustedEncryptionKeys: environment.encryption_keys } : {}), + }, source.token), source.token); this._checkGeneration(generation, source.token); this._requireHost(id); } catch (error) { diff --git a/src/vs/workbench/contrib/chat/browser/sessionPullRequestPill.ts b/src/vs/workbench/contrib/chat/browser/sessionPullRequestPill.ts index 954174bce99ed2..ca5db0ce320afd 100644 --- a/src/vs/workbench/contrib/chat/browser/sessionPullRequestPill.ts +++ b/src/vs/workbench/contrib/chat/browser/sessionPullRequestPill.ts @@ -32,16 +32,7 @@ export function createSessionPullRequestPillData( ...section, entries: section.entries.filter(entry => visibility.isVisible(entry.pullRequestState, reader)), })).filter(section => section.entries.length > 0); - if (getChatPillEntries(visibleSections).length <= 1) { - return visibleSections; - } - return visibleSections.map(section => ({ - ...section, - entries: section.entries.map(entry => entry.promotedAction ? { - ...entry, - toolbarActions: [...entry.toolbarActions ?? [], entry.promotedAction], - } : entry), - })); + return visibleSections; }); return { sections: filteredSections, diff --git a/src/vs/workbench/contrib/chat/browser/tools/clientToolSetsContribution.ts b/src/vs/workbench/contrib/chat/browser/tools/clientToolSetsContribution.ts index 7317210fe31e87..3dcc4c828eea50 100644 --- a/src/vs/workbench/contrib/chat/browser/tools/clientToolSetsContribution.ts +++ b/src/vs/workbench/contrib/chat/browser/tools/clientToolSetsContribution.ts @@ -80,6 +80,18 @@ export class ClientToolSetsContribution extends Disposable implements IWorkbench 'deleteAutomation', ], })); + + this._register(this._registerDynamicToolSet(toolsService, { + id: 'vscode-sessions-list', + referenceName: 'vscodeSessionsList', + icon: Codicon.listTree, + description: localize('clientToolSet.sessionsList.description', "Sessions List"), + detail: localize('clientToolSet.sessionsList.detail', "Group, order, filter, and sort the sessions in the Sessions list."), + members: [ + 'readSessionsList', + 'organizeSessionsList', + ], + })); } this._register(this._registerDynamicToolSet(toolsService, { diff --git a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts index 75898616e386f7..5038063f299dee 100644 --- a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts +++ b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceClientService.ts @@ -180,6 +180,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic private _gptLivePassiveSpeechStarted = false; private _gptLiveDelegationId: string | undefined; private _gptLiveInputTranscript = ''; + private _gptLiveInputContext: string | undefined; + private _gptLiveInputContextAllowed: boolean | undefined; private readonly _gptLiveDelegations = new Set<string>(); private _gptLiveOutputTranscript = ''; private _gptLiveOutputStarted = false; @@ -194,7 +196,7 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic private _gptLiveInputStartMs: number | undefined; private _gptLiveInputLastStartMs: number | undefined; private _gptLiveInputEndMs: number | undefined; - private readonly _gptLiveInputs: { text: string; target: IVoiceLiveInputTarget; turnId?: string; startMs?: number; lastStartMs?: number; endMs?: number; delegated: boolean; answeredByVoice: boolean }[] = []; + private readonly _gptLiveInputs: { text: string; context?: string; voiceResponse: string | undefined; target: IVoiceLiveInputTarget; turnId?: string; startMs?: number; lastStartMs?: number; endMs?: number; delegated: boolean; answeredByVoice: boolean }[] = []; private _gptLiveContext: IVoiceSessionContext | undefined; private _gptLiveInstructionsSent = false; private readonly _gptLiveRequest = this._register(new MutableDisposable<CancellationTokenSource>()); @@ -741,10 +743,17 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic for (const input of this._gptLiveInputs) { if (input.answeredByVoice) { input.delegated = true; + if (input.voiceResponse === undefined) { + input.text = ''; + } } } } this._gptLiveInputTarget ??= this._gptLiveInputRouter.captureTarget(); + this._gptLiveInputContextAllowed ??= this._canRetainGptLiveVoiceContext(this._gptLiveInputTarget); + if (!this._gptLiveInputTranscript) { + this._gptLiveInputContext = this._gptLiveInputContextAllowed ? this._captureGptLiveVoiceContext(this._gptLiveInputTarget) : undefined; + } const delta = asOptionalString(event.delta) ?? ''; if (typeof event.start_ms === 'number' && Number.isFinite(event.start_ms)) { this._gptLiveInputStartMs ??= event.start_ms; @@ -780,11 +789,14 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic if (!this._gptLiveOutputStarted && !this._gptLiveInputTarget?.session?.pending) { this._finalizeGptLiveInput(); } - const input = this._gptLiveInputs.findLast(candidate => !candidate.delegated && !candidate.target.session?.pending); - if (input) { + const input = this._gptLiveInputs.at(-1); + const delta = asOptionalString(event.delta) ?? ''; + if (input && !input.target.session?.pending && !this._gptLiveOutputSuppressedUntilInput) { input.answeredByVoice = true; + if (input.voiceResponse !== undefined) { + input.voiceResponse += delta; + } } - const delta = asOptionalString(event.delta) ?? ''; this._gptLiveOutputTranscript += delta; if (!this._gptLiveOutputStarted) { if (!this._gptLiveOutputInterrupted && !this._gptLiveOutputSuppressedUntilInput) { @@ -842,9 +854,18 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic break; } input.delegated = true; + input.answeredByVoice = false; + input.voiceResponse = input.voiceResponse === undefined ? undefined : ''; const result = this._gptLiveInputRouter.resolve(delegationId, input.text, input.target); if (result.toolCall) { - this._onToolCall.fire({ ...result.toolCall, ...(input.turnId ? { turnId: input.turnId } : {}) }); + const toolCall = result.toolCall; + this._onToolCall.fire({ + ...toolCall, + args: toolCall.name === 'send_to_chat' && input.context + ? { ...toolCall.args, text: localize('voice.live.conversationContext', "Voice conversation context:\n{0}\n\nUser: {1}", input.context, input.text) } + : toolCall.args, + ...(input.turnId ? { turnId: input.turnId } : {}), + }); } else { this._sendGptLiveAppend('session.commentary.append', result.clarification, delegationId); } @@ -860,6 +881,30 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic } } + private _canRetainGptLiveVoiceContext(target: IVoiceLiveInputTarget): boolean { + if (!target.hasContext || target.session?.pending || (target.session && target.session.agent_state !== 'idle')) { + return false; + } + const current = this._gptLiveContext?.sessions.find(session => session.id === target.session?.id); + return !target.session || (current?.agent_state === 'idle' && !current.pending); + } + + private _captureGptLiveVoiceContext(target: IVoiceLiveInputTarget): string | undefined { + if (!this._canRetainGptLiveVoiceContext(target)) { + return undefined; + } + const turns: string[] = []; + for (let index = this._gptLiveInputs.length - 1; index >= 0; index--) { + const input = this._gptLiveInputs[index]; + if (!input.answeredByVoice || !input.voiceResponse || input.target.session?.pending + || input.target.hasContext !== target.hasContext || input.target.session?.id !== target.session?.id) { + break; + } + turns.push(localize('voice.live.conversationTurn', "User: {0}\nVoice assistant: {1}", input.text, input.voiceResponse)); + } + return turns.length ? turns.reverse().join('\n\n') : undefined; + } + private _finalizeGptLiveInput(): void { if (!this._gptLiveInputTranscript) { return; @@ -874,6 +919,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic } this._gptLiveInputs.push({ text, + context: this._gptLiveInputContext, + voiceResponse: this._gptLiveInputContextAllowed ? '' : undefined, target: this._gptLiveInputTarget ?? this._gptLiveInputRouter.captureTarget(), turnId: this._gptLiveTurnId, startMs: this._gptLiveInputStartMs, @@ -886,6 +933,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic this._gptLiveInputs.shift(); } this._gptLiveInputTranscript = ''; + this._gptLiveInputContext = undefined; + this._gptLiveInputContextAllowed = undefined; this._gptLiveInputTarget = undefined; this._gptLiveInputStartMs = undefined; this._gptLiveInputLastStartMs = undefined; @@ -1235,6 +1284,8 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic this._usingGptLive = false; this._gptLiveSessionInitSent = false; this._gptLiveTurnId = undefined; + this._gptLiveInputContext = undefined; + this._gptLiveInputContextAllowed = undefined; this._gptLivePassiveTurn = false; this._gptLivePassiveSpeechStarted = false; this._gptLiveDelegationId = undefined; @@ -1312,6 +1363,7 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic this._gptLiveTurnId = turnId; this._gptLiveInputTranscript = ''; this._gptLiveInputTarget = options.passive ? undefined : this._gptLiveInputRouter.captureTarget(); + this._gptLiveInputContextAllowed = this._gptLiveInputTarget ? this._canRetainGptLiveVoiceContext(this._gptLiveInputTarget) : undefined; this._gptLiveInputStartMs = undefined; this._gptLiveInputLastStartMs = undefined; this._gptLiveInputEndMs = undefined; @@ -1373,6 +1425,16 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic const previousContext = this._gptLiveContext; const previous = previousContext?.sessions.find(session => session.is_active); this._gptLiveContext = sessionContext; + for (const input of this._gptLiveInputs) { + if (!this._canRetainGptLiveVoiceContext(input.target)) { + input.context = undefined; + input.voiceResponse = undefined; + } + } + if (this._gptLiveInputTarget && !this._canRetainGptLiveVoiceContext(this._gptLiveInputTarget)) { + this._gptLiveInputContext = undefined; + this._gptLiveInputContextAllowed = false; + } const grounding = (session: typeof active) => session ? { id: session.id, label: session.label, state: session.agent_state, pending_type: session.pending?.type } : null; if (!previousContext || previousContext.display_locale !== sessionContext.display_locale) { this._sendGptLiveAppend('session.instructions.append', `Voice language: ${JSON.stringify(sessionContext.display_locale)}. Speak in this language and interpret the user's speech in it when possible.`, null); @@ -1650,6 +1712,9 @@ export class VoiceClientService extends Disposable implements IVoiceClientServic prepareForInputTargetChange(): void { if (this._usingGptLive) { + for (const input of this._gptLiveInputs) { + input.voiceResponse = undefined; + } this._gptLiveOutputSuppressedUntilInput = true; this._updateGptLiveAudioMuted(); } diff --git a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts index ec5568e48ea257..8065f514aa5c5a 100644 --- a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts +++ b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceInputUtils.ts @@ -5,17 +5,23 @@ import { IChatResponseModel } from '../../common/model/chatModel.js'; import { IChatWidget } from '../chat.js'; +import { ChatRequestQueueKind } from '../../common/chatService/chatService.js'; /** Submit through the owning widget, preserving its input state and normal request options. */ export function acceptVoiceInput(widget: IChatWidget | undefined, text: string, isVoiceModeInput: boolean): boolean | Promise<IChatResponseModel | undefined> { - if (!text || !widget?.viewModel) { + const viewModel = widget?.viewModel; + if (!text || !widget || !viewModel) { return false; } - if (widget.viewModel.editing) { + if (viewModel.editing) { widget.input.setValue(text, false); return false; } - return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { preserveFocus: true, isVoiceModeInput }); + return widget.acceptInput(combineVoiceInput(widget.getInput(), text), { + preserveFocus: true, + isVoiceModeInput, + ...(viewModel.model?.requestInProgress?.get() === true ? { queue: ChatRequestQueueKind.Steering } : {}), + }); } /** diff --git a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts index 1211f942acc7a4..99039e02021d2a 100644 --- a/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts +++ b/src/vs/workbench/contrib/chat/browser/voiceClient/voiceSessionController.ts @@ -36,7 +36,7 @@ import { IAgentSessionsService } from '../agentSessions/agentSessionsService.js' import { AgentSessionStatus } from '../agentSessions/agentSessionsModel.js'; import { toAgentHostBackendSessionUri } from '../agentSessions/agentHost/agentHostSessionUri.js'; import { IAgentHostConnectionsService } from '../../../../../platform/agentHost/common/agentHostConnectionsService.js'; -import { ChatSendResult, ConfirmedReason, IChatConfirmation, IChatElicitationRequest, IChatPlanReview, IChatQuestionCarousel, IChatService, IChatToolInvocation, ToolConfirmKind, IChatModelReference } from '../../common/chatService/chatService.js'; +import { ChatRequestQueueKind, ChatSendResult, ConfirmedReason, IChatConfirmation, IChatElicitationRequest, IChatPlanReview, IChatQuestionCarousel, IChatService, IChatToolInvocation, ToolConfirmKind, IChatModelReference } from '../../common/chatService/chatService.js'; import { getDisplayedQuestionText, getOptionsWithDefaultsFirst } from '../../common/chatService/chatQuestionCarouselHelpers.js'; import { formatQuestionPrompt } from '../../common/voiceClient/voicePendingNarration.js'; import { IChatWidget, IChatWidgetService } from '../chat.js'; @@ -3625,7 +3625,10 @@ export class VoiceSessionController extends Disposable implements IVoiceSessionC private async _sendVoiceRequest(sessionResource: URI, text: string): Promise<ChatSendResult | undefined> { const generation = this._connectAttemptGeneration; const initializationGeneration = this._sessionInitializationGeneration; - const result = await this.chatService.sendRequest(sessionResource, text, { isVoiceModeInput: this._isVoiceProgressEnabled() }).catch(err => { + const result = await this.chatService.sendRequest(sessionResource, text, { + isVoiceModeInput: this._isVoiceProgressEnabled(), + ...(this.chatService.getSession(sessionResource)?.requestInProgress.get() ? { queue: ChatRequestQueueKind.Steering } : {}), + }).catch(err => { this.logService.warn('[voice] Error sending transcription:', err); return undefined; }); @@ -5070,7 +5073,7 @@ export class VoiceSessionController extends Disposable implements IVoiceSessionC } return { kind: 'question', - text: formatQuestionPrompt(question, pending.allow_skip === true), + text: formatQuestionPrompt(question, pending.allow_skip === true, pending.message, pending.questions?.length), pending: { pendingId: pending.pending_id }, }; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/media/modelPicker.css b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/media/modelPicker.css index d76d0c531b1404..c455202c8a88fc 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/media/modelPicker.css +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/media/modelPicker.css @@ -472,7 +472,7 @@ } .action-widget .chat-model-picker-tabbar .monaco-custom-radio .monaco-button:hover:not(.active), -.action-widget .chat-model-picker-tabbar .tabbed-action-list-tabbar-action:hover { +.action-widget .chat-model-picker-tabbar .tabbed-action-list-tabbar-action:hover:not(.disabled) { color: var(--vscode-modernTab-hoverForeground); background: var(--vscode-modernTab-hoverBackground); } diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerActionItem.ts b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerActionItem.ts index 0a8900f3c0d078..5d652966a80621 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerActionItem.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerActionItem.ts @@ -9,6 +9,7 @@ import { getBaseLayerHoverDelegate } from '../../../../../../../base/browser/ui/ import { getDefaultHoverDelegate } from '../../../../../../../base/browser/ui/hover/hoverDelegateFactory.js'; import { BaseActionViewItem } from '../../../../../../../base/browser/ui/actionbar/actionViewItems.js'; import { IAction } from '../../../../../../../base/common/actions.js'; +import { escapeMarkdownSyntaxTokens, MarkdownString } from '../../../../../../../base/common/htmlContent.js'; import { MutableDisposable } from '../../../../../../../base/common/lifecycle.js'; import { autorun, IObservable } from '../../../../../../../base/common/observable.js'; import { localize } from '../../../../../../../nls.js'; @@ -17,7 +18,7 @@ import { IContextKeyService } from '../../../../../../../platform/contextkey/com import { IInstantiationService } from '../../../../../../../platform/instantiation/common/instantiation.js'; import { IKeybindingService } from '../../../../../../../platform/keybinding/common/keybinding.js'; import { getLanguageModelDisplayNameWithSubscriptionSource } from '../../../../common/languageModelSourcePresentation.js'; -import { ILanguageModelChatMetadataAndIdentifier } from '../../../../common/languageModels.js'; +import { ILanguageModelChatMetadata, ILanguageModelChatMetadataAndIdentifier } from '../../../../common/languageModels.js'; import { IModelPickerComparison } from './modelPickerComparison.js'; import { IChatInputPickerOptions } from '../chatInputPickerActionItem.js'; import { IModelConfigurationAccess } from './modelPickerModelConfig.js'; @@ -254,20 +255,37 @@ export class ModelPickerActionItem extends BaseActionViewItem { const hover = organizationDefaultDescription ? localize('chat.modelPicker.organizationDefaultHover', "{0}\n\n{1}", label, organizationDefaultDescription) : label; - return this._appendComparisonAction(hover); + const fusionDescription = selectedModel?.metadata.autoModelFusion || this._pickerWidget.fusionDisplayName ? ILanguageModelChatMetadata.getAutoModelDescription(true) : undefined; + if (!fusionDescription) { + return this._appendComparisonAction(hover); + } + // Copilot Fusion's description carries a Learn more link, so it is rendered as Markdown. + const comparisonAction = this._getComparisonAction(); + const markdown = new MarkdownString().appendMarkdown(escapeMarkdownSyntaxTokens(hover)).appendMarkdown('\n\n').appendMarkdown(fusionDescription); + if (comparisonAction) { + markdown.appendMarkdown('\n\n').appendMarkdown(escapeMarkdownSyntaxTokens(comparisonAction)); + } + return { + markdown, + markdownNotSupportedFallback: this._appendComparisonAction(localize('chat.modelPicker.fusionHover', "{0}\n\n{1}", hover, ILanguageModelChatMetadata.getFusionSummary())), + }; } private _appendComparisonAction(hover: string): string { + const action = this._getComparisonAction(); + return action ? localize('chat.modelPicker.comparisonActionHover', "{0}\n\n{1}", hover, action) : hover; + } + + private _getComparisonAction(): string | undefined { const comparison = this.delegate.comparison; if (!comparison?.available.get() || !comparison.label) { - return hover; + return undefined; } const keybinding = comparison.startCommandId ? this.keybindingService.lookupKeybinding(comparison.startCommandId, this._contextKeyService)?.getLabel() : undefined; - const action = keybinding + return keybinding ? localize('chat.modelPicker.comparisonActionWithKeybinding', "{0} ({1})", comparison.label, keybinding) : comparison.label; - return localize('chat.modelPicker.comparisonActionHover', "{0}\n\n{1}", hover, action); } } diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabbedWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabbedWidget.ts index b60514bac4012c..eae8bef92ab391 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabbedWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerTabbedWidget.ts @@ -36,7 +36,7 @@ import { IStorageService, StorageScope, StorageTarget } from '../../../../../../ import { StateType } from '../../../../../../../platform/update/common/update.js'; import { URI } from '../../../../../../../base/common/uri.js'; import { ChatEntitlement, IChatEntitlementService } from '../../../../../../services/chat/common/chatEntitlementService.js'; -import { ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService, IModelControlEntry, isUserProvidedModel } from '../../../../common/languageModels.js'; +import { ILanguageModelChatMetadata, ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService, IModelControlEntry, isUserProvidedModel } from '../../../../common/languageModels.js'; import { ChatConfiguration } from '../../../../common/constants.js'; import { getModelConfigDescription, getModelConfigProperty, getModelConfigSummary, IModelConfigurationAccess, MODEL_CONFIG_GROUP_EFFORT, ModelConfigChangeListener } from './modelPickerModelConfig.js'; import { IModelCardOptions, IPricingDisclosure, ModelCard } from './modelPickerCard.js'; @@ -79,6 +79,8 @@ export interface ITabbedModelPickerContext { /** Whether the account is billed by credits, which is when cost numbers are shown. */ readonly isUBB: boolean; readonly showManageModels: boolean; + /** When set, the Add Models action is shown disabled with this reason as its tooltip. */ + readonly manageModelsDisabledReason?: string; /** * What it takes to unlock a curated model the user cannot select yet, used to * offer the upgrade, admin or update path instead of simply omitting the model. @@ -832,6 +834,7 @@ export class TabbedModelPicker extends Disposable { id: 'addProvider', icon: Codicon.add, tooltip: localize('chat.modelPicker.addProvider', "Add Models..."), + disabledReason: context.manageModelsDisabledReason, run: () => { this._widget.hide(); context.onManageModels(); @@ -1306,7 +1309,9 @@ export class TabbedModelPicker extends Disposable { ? [createLocalModelDetailsAction(rowLabel, () => this._showLocalModelDetails(localDirect.familyId), summary)] : [this._createDetailsAction(model, rowLabel, summary)], toolbarDialogActionIds: [MODEL_DETAILS_ACTION_ID, LOCAL_MODEL_DETAILS_ACTION_ID], - tooltip: [rowLabel, summary, defaultDescription].filter(Boolean).join(' \u00b7 '), + tooltip: isAutoModel(model) && model.metadata.autoModelFusion + ? [ILanguageModelChatMetadata.getFusionSummary(), defaultDescription].filter(Boolean).join('\n') + : [rowLabel, summary, defaultDescription].filter(Boolean).join(' \u00b7 '), }; } diff --git a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerWidget.ts b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerWidget.ts index 940a6d47466a26..48270b3da80b54 100644 --- a/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/widget/input/modelPicker/modelPickerWidget.ts @@ -31,7 +31,7 @@ import { ITelemetryService } from '../../../../../../../platform/telemetry/commo import { COPILOT_HYDRA_FUSION_MAX_MODEL_ID, COPILOT_HYDRA_FUSION_MODEL_ID, isCopilotHydraFusionModelId } from '../../../../../../../platform/agentHost/common/copilotCliConfig.js'; import { IStorageService, StorageScope, StorageTarget } from '../../../../../../../platform/storage/common/storage.js'; import { COPILOT_VENDOR_ID, getLanguageModelProviderDisplayName, IModelControlEntry, ILanguageModelChatMetadataAndIdentifier, ILanguageModelsService, isUserProvidedModel } from '../../../../common/languageModels.js'; -import { SessionType } from '../../../../common/chatSessionsService.js'; +import { getAddModelsUnavailableReason, SessionType } from '../../../../common/chatSessionsService.js'; import { ChatConfiguration } from '../../../../common/constants.js'; import { getLanguageModelDisplayNameWithSubscriptionSource } from '../../../../common/languageModelSourcePresentation.js'; import { ChatEntitlement, IChatEntitlementService } from '../../../../../../services/chat/common/chatEntitlementService.js'; @@ -42,6 +42,7 @@ import { GitHubPaths, IDefaultAccountService } from '../../../../../../../platfo import { IUpdateService } from '../../../../../../../platform/update/common/update.js'; import { IInstantiationService } from '../../../../../../../platform/instantiation/common/instantiation.js'; import { IWorkspaceTrustManagementService, IWorkspaceTrustRequestService } from '../../../../../../../platform/workspace/common/workspaceTrust.js'; +import { IWorkbenchEnvironmentService } from '../../../../../../services/environment/common/environmentService.js'; import { getCompactCodicon } from '../../../chatIcons.js'; import { renderChatInputPickerSplit } from '../chatInputPickerActionItem.js'; import { createManageModelsAction, getModelPickerControlModels, shouldShowManageModelsAction } from './modelPickerItems.js'; @@ -203,6 +204,7 @@ export class ModelPickerWidget extends Disposable { @IStorageService private readonly _storageService: IStorageService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @IConfigurationService private readonly _configurationService: IConfigurationService, + @IWorkbenchEnvironmentService private readonly _environmentService: IWorkbenchEnvironmentService, ) { super(); if (this._delegate.comparison) { @@ -758,6 +760,7 @@ export class ModelPickerWidget extends Disposable { const presentation = this._delegate.getPresentationOptions(); const canShowManageModelsAction = presentation.showManageModelsAction && shouldShowManageModelsAction(this._entitlementService); const manageModelsAction = canShowManageModelsAction ? createManageModelsAction(this._commandService, this._delegate.getSessionType?.()) : undefined; + const manageModelsDisabledReason = manageModelsAction ? getAddModelsUnavailableReason(this._delegate.getSessionType?.(), this._environmentService.remoteAuthority) : undefined; const logModelPickerInteraction = (interaction: ChatModelPickerInteraction) => { this._telemetryService.publicLog2<ChatModelPickerInteractionEvent, ChatModelPickerInteractionClassification>('chat.modelPickerInteraction', { interaction }); }; @@ -801,6 +804,7 @@ export class ModelPickerWidget extends Disposable { configurationAccess: this._delegate.modelConfiguration ?? this._languageModelsService, isUBB: !!this._entitlementService.quotas.usageBasedBilling, showManageModels: !!manageModelsAction && !restrictedMode, + manageModelsDisabledReason, providerPlaceholders: placeholders, unavailableContext: { show: presentation.showUnavailableFeatured, diff --git a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts index 5aed3d710c80f2..0e8c42a55481d3 100644 --- a/src/vs/workbench/contrib/chat/common/chatSessionsService.ts +++ b/src/vs/workbench/contrib/chat/common/chatSessionsService.ts @@ -12,7 +12,7 @@ import { IObservable } from '../../../../base/common/observable.js'; import { ThemeIcon } from '../../../../base/common/themables.js'; import { URI } from '../../../../base/common/uri.js'; import { IPosition } from '../../../../editor/common/core/position.js'; -import { isRemoteAgentHostSessionType } from '../../../../platform/agentHost/common/agentHostSessionType.js'; +import { isCopilotAgentHostSessionType, isRemoteAgentHostSessionType } from '../../../../platform/agentHost/common/agentHostSessionType.js'; import type { IAgentModelConfigurationReport } from '../../../../platform/agentHost/common/agentModelConfiguration.js'; import { createDecorator, ServicesAccessor } from '../../../../platform/instantiation/common/instantiation.js'; import { Registry } from '../../../../platform/registry/common/platform.js'; @@ -26,6 +26,7 @@ import { IChatRequestOrigin } from './chatRequestOrigin.js'; import { IChatProgress, IChatResponseErrorDetails, IChatSendRequestOptions, IChatSessionTiming } from './chatService/chatService.js'; import { ChatAgentLocation } from './constants.js'; import { Target } from './promptSyntax/promptTypes.js'; +import { localize } from '../../../../nls.js'; import type { ICanvasContext } from '../../canvases/common/canvas.js'; import type { IChatSessionHistoryStatus } from '../../../../platform/chat/common/chatSessionHistory.js'; @@ -464,6 +465,18 @@ export function isAgentHostSessionResource(resource: URI): boolean { return isAgentHostTarget(resource.scheme); } +/** + * Returns why models cannot be added for the given chat session type (harness), or `undefined` when they can. + * Added models are extension-provided BYOK models, which a remotely running Copilot agent host cannot reach: + * either a remote agent host session type, or the Copilot harness of a remote editor window. + */ +export function getAddModelsUnavailableReason(sessionType: string | undefined, remoteAuthority: string | undefined): string | undefined { + if (sessionType && isCopilotAgentHostSessionType(sessionType) && (isRemoteAgentHostSessionType(sessionType) || !!remoteAuthority)) { + return localize('chat.addModels.remoteCopilotUnsupported', "BYOK models aren't supported in remote Copilot sessions"); + } + return undefined; +} + /** Returns the registered agent implementation handling the session. */ export function getAgentHostProviderForTelemetry(sessionType: string | undefined, chatSessionsService: IChatSessionsService): string | undefined { if (!sessionType) { diff --git a/src/vs/workbench/contrib/chat/common/languageModels.ts b/src/vs/workbench/contrib/chat/common/languageModels.ts index 63a7193f3051e7..c62f22e56bba88 100644 --- a/src/vs/workbench/contrib/chat/common/languageModels.ts +++ b/src/vs/workbench/contrib/chat/common/languageModels.ts @@ -483,15 +483,19 @@ export namespace ILanguageModelChatMetadata { */ export function getAutoModelDescription(fusion?: boolean): string { if (fusion) { - const fusionBase = localize('autoModel.fusionDescription', "Copilot Fusion chooses models and workflows based on your task."); const fusionLearnMore = localize('autoModel.fusionLearnMore', "[Learn more]({0})", fusionDocsUrl); - return `${fusionBase} ${fusionLearnMore}`; + return `${getFusionSummary()} ${fusionLearnMore}`; } const base = localize('autoModel.description', "Auto routes based on your task and real-time system health and model performance."); const learnMore = localize('autoModel.learnMore', "[Learn More]({0})", autoModelSelectionDocsUrl); return `${base} ${learnMore}`; } + /** Copilot Fusion's one-sentence description, as plain text without its "Learn more" link. */ + export function getFusionSummary(): string { + return localize('autoModel.fusionDescription', "Copilot Fusion selects a single model or orchestrates multiple models to complete your task."); + } + /** * Describes Auto's discount, naming the tier it applies to when known. * diff --git a/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts b/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts index 896f79faf03245..183ad6419677aa 100644 --- a/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts +++ b/src/vs/workbench/contrib/chat/common/voiceClient/voiceLiveInputRouter.ts @@ -4,7 +4,8 @@ *--------------------------------------------------------------------------------------------*/ import { localize } from '../../../../../nls.js'; -import { IVoiceDispatchResult, IVoicePendingQuestion, IVoiceSessionContext, IVoiceToolCall } from './voiceClientService.js'; +import { IVoiceDispatchResult, IVoicePendingQuestion, IVoiceSessionContext, IVoiceSessionPending, IVoiceToolCall } from './voiceClientService.js'; +import { formatQuestionPromptTitle } from './voicePendingNarration.js'; import { IBackendQuestionAnswer } from './voiceQuestionAnswers.js'; type VoiceSession = IVoiceSessionContext['sessions'][number]; @@ -221,9 +222,10 @@ function resolveAnswer(question: IVoicePendingQuestion, text: string, language: : undefined; } -function questionPrompt(question: IVoicePendingQuestion, guidance: string): string { +function questionPrompt(question: IVoicePendingQuestion, guidance: string, pending: IVoiceSessionPending, questionIndex: number): string { const options = question.options.map((option, index) => `${index + 1}. ${option.label}`).join(' '); - return [localize('voice.live.questionPrompt', "{0} {1}", question.title, options).trim(), guidance].filter(Boolean).join(' '); + const prompt = formatQuestionPromptTitle(question, pending.message, questionIndex, pending.questions?.length); + return [localize('voice.live.questionPrompt', "{0} {1}", prompt, options).trim(), guidance].filter(Boolean).join(' '); } /** Routes only explicit, deterministic replies to captured, still-current pending occurrences, never model guesses. Ambiguous replies cannot authorize actions, and forms submit only when complete or explicitly skipped. */ @@ -286,8 +288,10 @@ export class VoiceLiveInputRouter { getQuestionPrompt(sessionId: string, pendingId: string): string | undefined { const session = this._context.sessions.find(candidate => candidate.id === sessionId && candidate.pending?.pending_id === pendingId); - const question = session?.pending?.questions?.[this._answers.get(this._key(session))?.answers.length ?? 0]; - return question ? questionPrompt(question, this.getQuestionReplyGuidance()) : undefined; + const index = session ? this._answers.get(this._key(session))?.answers.length ?? 0 : 0; + const pending = session?.pending; + const question = pending?.questions?.[index]; + return question && pending ? questionPrompt(question, this.getQuestionReplyGuidance(), pending, index) : undefined; } captureTarget(): IVoiceLiveInputTarget { @@ -354,15 +358,15 @@ export class VoiceLiveInputRouter { if (!answer) { return { clarification: question.allow_freeform - ? localize('voice.live.chooseOrCustomAnswer', "Please say an exact choice or its number, or say other followed by a custom answer. {0}", questionPrompt(question, this.getQuestionReplyGuidance())) - : localize('voice.live.chooseAnswer', "Please say an exact choice or its number. {0}", questionPrompt(question, this.getQuestionReplyGuidance())) + ? localize('voice.live.chooseOrCustomAnswer', "Please say an exact choice or its number, or say other followed by a custom answer. {0}", questionPrompt(question, this.getQuestionReplyGuidance(), pending, answers.length)) + : localize('voice.live.chooseAnswer', "Please say an exact choice or its number. {0}", questionPrompt(question, this.getQuestionReplyGuidance(), pending, answers.length)) }; } answers.push(answer); this._answers.set(key, { schema: JSON.stringify(pending), answers }); const next = pending.questions?.[answers.length]; if (next) { - return { clarification: questionPrompt(next, this.getQuestionReplyGuidance()) }; + return { clarification: questionPrompt(next, this.getQuestionReplyGuidance(), pending, answers.length) }; } response = { type: 'answer', answers }; } diff --git a/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts b/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts index 9f4981cd38a012..74652a115c4203 100644 --- a/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts +++ b/src/vs/workbench/contrib/chat/common/voiceClient/voicePendingNarration.ts @@ -3,22 +3,28 @@ * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ +import { localize } from '../../../../../nls.js'; import { IVoicePendingQuestion } from './voiceClientService.js'; -/** - * Render the canonical spoken form of a pending question. - * - * Mirrors `format_question_prompt` in the voice backend's `session_pending.py`, - * against the same fixtures. The client speaks the first question of a form and - * the backend speaks the rest, so a divergence is audible mid-form. - * - * Renders the wire shape rather than the carousel, because that is where the - * ordinals the user says back were assigned. Numbering from a second source - * could read out a number that selects something else. - */ -export function formatQuestionPrompt(question: IVoicePendingQuestion, allowSkip: boolean): string { - const parts: string[] = []; +export function formatQuestionPromptTitle(question: IVoicePendingQuestion, context?: string, questionIndex = 0, questionCount = 1): string { const title = question.title.trim(); + if (questionCount > 1) { + // A form-level message can ask for several fields, but each reply fills only the current field. + const prompt = localize('voice.questionNumber', "Question {0} of {1}: {2}", questionIndex + 1, questionCount, title); + return questionIndex === 0 + ? localize('voice.oneQuestionAtATime', "Please answer one question at a time. {0}", prompt) + : prompt; + } + const formContext = context?.trim(); + return formContext && formContext !== title + ? localize('voice.questionWithContext', "{0} {1}", formContext, title).trim() + : title; +} + +/** Render the spoken question and choices, optionally preceded by form-level context. Choice ordinals follow the displayed order in the wire payload. */ +export function formatQuestionPrompt(question: IVoicePendingQuestion, allowSkip: boolean, context?: string, questionCount = 1): string { + const parts: string[] = []; + const title = formatQuestionPromptTitle(question, context, 0, questionCount); if (title) { parts.push(title); } diff --git a/src/vs/workbench/contrib/chat/electron-browser/agentSessions/computerUseHelperApp.contribution.ts b/src/vs/workbench/contrib/chat/electron-browser/agentSessions/computerUseHelperApp.contribution.ts index d39a93cfaa4328..374821f2314b3b 100644 --- a/src/vs/workbench/contrib/chat/electron-browser/agentSessions/computerUseHelperApp.contribution.ts +++ b/src/vs/workbench/contrib/chat/electron-browser/agentSessions/computerUseHelperApp.contribution.ts @@ -29,9 +29,6 @@ class ComputerUseHelperAppContribution extends Disposable implements IWorkbenchC startDrag: (path, targetWindow) => { void nativeHostService.startFileDrag(path, { targetWindowId: isAuxiliaryWindow(targetWindow) ? targetWindow.vscodeWindowId : undefined }); }, - reveal: path => { - void nativeHostService.showItemInFolder(path); - }, })); } } diff --git a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSessionInputPills.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSessionInputPills.test.ts index 486e7260358421..5fae129694a8d8 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSessionInputPills.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentHost/agentHostSessionInputPills.test.ts @@ -890,7 +890,7 @@ suite('AgentHostSessionInputPills', () => { const summarizedClose = harness.persistentContent.querySelector('.chat-pill-promoted-action'); const dropdown = harness.dropdown('2 Canvases'); dropdown.find(item => item.label === dashboard.title)?.select(); - await dropdown.find(item => item.label === dashboard.title)?.toolbarActions[0]?.run(); + await dropdown.find(item => item.label === dashboard.title)?.toolbarActions.find(action => action.label === 'Close Canvas Dashboard')?.run(); harness.showModel(upcastPartial<IChatModel>({})); assert.deepStrictEqual({ @@ -909,7 +909,7 @@ suite('AgentHostSessionInputPills', () => { offersToggle: true, summarizedClose: null, dropdown: ['Canvases', 'Preview', 'Dashboard'], - closeActions: ['Close Canvas Preview', 'Close Canvas Dashboard'], + closeActions: ['Pin Preview', 'Close Canvas Preview', 'Pin Dashboard', 'Close Canvas Dashboard'], commands: [{ id: REVEAL_CANVAS_COMMAND_ID, args: [{ ...owner, canvas: dashboard.resource }] }], closed: [preview.resource.toString(), dashboard.resource.toString()], withoutCanvasContext: [], @@ -1998,8 +1998,10 @@ suite('AgentHostSessionInputPills', () => { hoverText: 'microsoft/vscodeon Sep 1Live pull request 332982 #332982OpenLive pull request bodymain←feature@pr-author opened this pull request', actionLabels: [ 'Copy Pull Request URL', + 'Pin Live pull request 332982', 'Remove Artifact Chat: unify Agent Host status pills across chat surfaces from Session', 'Copy Pull Request URL', + 'Pin Live pull request 335387', 'Remove Artifact sessions: preserve recorded issue titles in pills from Session', ], }, @@ -3696,12 +3698,16 @@ suite('AgentHostSessionInputPills', () => { empty: false, dropdownActionLabels: [ 'Copy Commit URL', + 'Pin Commit', 'Remove Reference Commit from Session', 'Copy Website URL', + 'Pin Preview', 'Remove Reference Preview from Session', 'Copy Path', + 'Pin README.md', 'Remove Reference README from Session', 'Copy URI', + 'Pin Chat settings', 'Remove Reference Chat settings from Session', ], dropdownFooterActionLabels: ['Copy Hash', 'Copy Relative Path'], diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts index f274a2adc6f9a8..551f0bcddb4901 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostChatContribution.test.ts @@ -8329,6 +8329,36 @@ suite('AgentHostChatContribution', () => { ]); })); + test('Copilot Fusion routing shows only the resolved part', () => runWithFakedTimers({ useFakeTimers: true }, async () => { + const languageModels = new Map<string, ILanguageModelChatMetadata>([ + ['agent-host-copilot:auto', upcastPartial<ILanguageModelChatMetadata>({ name: 'Copilot Fusion', autoModelFusion: true })], + ['agent-host-copilot:gpt-5.4-mini', upcastPartial<ILanguageModelChatMetadata>({ name: 'GPT-5.4 mini' })], + ]); + const reason = 'Copilot Fusion selected GPT-5.4 mini since the task has low complexity.'; + const runTurn = async (routed: boolean) => { + const { sessionHandler, agentHostService, chatAgentService } = createContribution(disposables, { languageModels }); + const { turnPromise, collected, session, turnId, fire } = await startTurn(sessionHandler, agentHostService, chatAgentService, disposables, { + userSelectedModelId: 'agent-host-copilot:auto', + }); + if (routed) { + fire({ + type: 'chat/usage', + session, + turnId, + usage: { model: 'gpt-5.4-mini', _meta: { autoModeResolved: { chosenModel: 'gpt-5.4-mini', selectionReason: reason } } }, + } as ChatAction); + } + fire({ type: 'chat/turnComplete', endedAt: '2025-01-01T00:00:00.000Z', session, turnId } as ChatAction); + await turnPromise; + return collected.flat().filter(part => part.kind === 'autoModeResolution'); + }; + + assert.deepStrictEqual({ standard: await runTurn(true), highOrMax: await runTurn(false) }, { + standard: [{ kind: 'autoModeResolution', resolved: { id: 'gpt-5.4-mini', name: 'GPT-5.4 mini', reason } }], + highOrMax: [], + }); + })); + test('Auto routing does not show an unresolved part for a host-handled slash command', () => runWithFakedTimers({ useFakeTimers: true }, async () => { const languageModels = new Map<string, ILanguageModelChatMetadata>([ ['agent-host-copilot:auto', upcastPartial<ILanguageModelChatMetadata>({ name: 'Auto' })], diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLanguageModelProvider.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLanguageModelProvider.test.ts index 474ef8a9577de8..9443889974c893 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLanguageModelProvider.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostLanguageModelProvider.test.ts @@ -258,7 +258,7 @@ suite('AgentHostLanguageModelProvider', () => { malformed: [await fusionOf({ 'vscode.chat.fusion': true }), await fusionOf({ 'vscode.chat.fusion': 'fusion' })], }, { models: [ - { name: 'Copilot Fusion', fusion: true, detail: undefined, tooltip: 'Copilot Fusion chooses models and workflows based on your task. [Learn more](https://docs.github.com/en/early-access/copilot/hydrafusion)' }, + { name: 'Copilot Fusion', fusion: true, detail: undefined, tooltip: 'Copilot Fusion selects a single model or orchestrates multiple models to complete your task. [Learn more](https://docs.github.com/en/early-access/copilot/hydrafusion)' }, { name: 'gpt-5', fusion: undefined, detail: undefined, tooltip: undefined }, ], plain: undefined, diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/computerUseSetupDialog.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/computerUseSetupDialog.test.ts index bc2e9a474c7847..88dbf2bbcef011 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/computerUseSetupDialog.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/computerUseSetupDialog.test.ts @@ -4,17 +4,18 @@ *--------------------------------------------------------------------------------------------*/ import assert from 'assert'; -import { Button } from '../../../../../../base/browser/ui/button/button.js'; import { mainWindow } from '../../../../../../base/browser/window.js'; +import { timeout } from '../../../../../../base/common/async.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { DisposableStore, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { observableValue } from '../../../../../../base/common/observable.js'; +import { runWithFakedTimers } from '../../../../../../base/test/common/timeTravelScheduler.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import type { ComputerUsePermission, ComputerUsePermissionState, IComputerUseSetupActionV1, IComputerUseSetupV1, IComputerUseStatusV1 } from '../../../../../../platform/agentHost/common/computerUse.js'; import { TestInstantiationService } from '../../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { IKeybindingService } from '../../../../../../platform/keybinding/common/keybinding.js'; +import { MockKeybindingService } from '../../../../../../platform/keybinding/test/common/mockKeybindingService.js'; import { ILayoutService } from '../../../../../../platform/layout/browser/layoutService.js'; -import { defaultButtonStyles } from '../../../../../../platform/theme/browser/defaultStyles.js'; import { IHostService } from '../../../../../services/host/browser/host.js'; import { ComputerUseSetupDialog, ComputerUseSetupPanel, getComputerUseSetupView, type IComputerUseHelperAppSupport, type IComputerUseSetupModel } from '../../../browser/agentSessions/agentHost/computerUseSetupDialog.js'; @@ -30,12 +31,8 @@ function createStatus(permissions: readonly [ComputerUsePermissionState, Compute }; } -function request(permission: ComputerUsePermission): IComputerUseSetupActionV1 { - return { action: 'request', permission }; -} - -function openSettings(permission: ComputerUsePermission): IComputerUseSetupActionV1 { - return { action: 'openSettings', permission }; +function allow(permission: ComputerUsePermission): IComputerUseSetupActionV1 { + return { action: 'allow', permission }; } const recheck: IComputerUseSetupActionV1 = { action: 'recheck' }; @@ -44,6 +41,13 @@ function setup(state: IComputerUseSetupV1['state'], round: number, actions: read return { id: 'setup-1', chat: 'chat:a', state, round, actions, ...(error ? { error } : {}) }; } +const needsBoth = createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 1, [allow('accessibility'), allow('screenRecording'), recheck])]); +const allowingAccessibility = createStatus(['notGranted', 'notGranted'], [setup('working', 1)], { setupId: 'setup-1', ...allow('accessibility') }); +const needsScreenRecording = createStatus(['granted', 'notGranted'], [setup('needsPermissions', 2, [allow('screenRecording'), recheck])]); +const checkingScreenRecording = createStatus(['granted', 'notGranted'], [setup('working', 2)], { setupId: 'setup-1', ...recheck }); +const ready = createStatus(['granted', 'granted'], [setup('ready', 3)]); +const ended = createStatus(['notGranted', 'notGranted'], [setup('ended', 1)]); + class TestSetupModel implements IComputerUseSetupModel { readonly status = observableValue<IComputerUseStatusV1 | undefined>(this, undefined); readonly requests: { readonly setupId: string; readonly action: IComputerUseSetupActionV1 }[] = []; @@ -57,271 +61,294 @@ class TestSetupModel implements IComputerUseSetupModel { } class TestHelperAppSupport implements IComputerUseHelperAppSupport { - readonly calls: string[] = []; + readonly drags: string[] = []; startDrag(path: string): void { - this.calls.push(`drag ${path}`); - } - - reveal(path: string): void { - this.calls.push(`reveal ${path}`); + this.drags.push(path); } } suite('Computer Use setup modal', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); - test('derives what it shows from the host\'s verified status', () => { - const view = (status: IComputerUseStatusV1 | undefined, setupId: string | undefined = 'setup-1') => { + test('derives what it shows from the host\'s verified status, and nothing once the setup no longer waits', () => { + const view = (status: IComputerUseStatusV1 | undefined, setupId = 'setup-1') => { const result = getComputerUseSetupView(status, setupId); - return { - phase: result.phase, - rows: result.rows.map(row => [row.permission, row.state, row.action?.action ?? null, row.busy]), - message: result.message ? result.messageKind : null, - canRecheck: result.canRecheck, - canContinue: result.canContinue, - settingsStep: result.settingsStep ?? null, - }; + return result && { ...result, rows: result.rows.map(row => `${row.permission} ${row.state}${row.current ? ' current' : ''}`) }; }; assert.deepStrictEqual({ - unavailable: view(undefined), - idle: view(createStatus(['unknown', 'unknown'], []), undefined), - needsBoth: view(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 1, [request('accessibility'), request('screenRecording'), recheck])])), - settingsStep: view(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 2, [request('screenRecording'), openSettings('screenRecording'), recheck])])), - grantedElsewhere: view(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 1, [request('accessibility'), request('screenRecording'), recheck])])), - allVerifiedElsewhere: view(createStatus(['granted', 'granted'], [setup('needsPermissions', 2, [request('screenRecording'), openSettings('screenRecording'), recheck], { code: 'stillNotGranted', message: 'Still off' })])), - requesting: view(createStatus(['notGranted', 'notGranted'], [setup('working', 1)], { setupId: 'setup-1', ...request('screenRecording') })), - checking: view(createStatus(['granted', 'notGranted'], [setup('working', 2)], { setupId: 'setup-1', ...recheck })), - stillOff: view(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 3, [request('screenRecording'), openSettings('screenRecording'), recheck], { code: 'stillNotGranted', message: 'Still off' })])), - ready: view(createStatus(['granted', 'granted'], [setup('ready', 3)])), - ended: view(createStatus(['notGranted', 'notGranted'], [setup('ended', 1, [], { code: 'notWaiting', message: 'Not waiting' })])), + unpublished: view(undefined), + missing: view(needsBoth, 'setup-2'), + ended: view(ended), + needsBoth: view(needsBoth), + allowing: view(allowingAccessibility), + grantedElsewhere: view(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 1, [allow('accessibility'), allow('screenRecording'), recheck])])), + stillOff: view(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 3, [allow('screenRecording'), recheck], { code: 'stillNotGranted', message: 'Still off' })])), + checking: view(checkingScreenRecording), + ready: view(ready), }, { - unavailable: { phase: 'unavailable', rows: [], message: 'info', canRecheck: false, canContinue: false, settingsStep: null }, - idle: { phase: 'idle', rows: [['accessibility', 'unknown', null, false], ['screenRecording', 'unknown', null, false]], message: 'info', canRecheck: false, canContinue: false, settingsStep: null }, - needsBoth: { phase: 'needsPermissions', rows: [['accessibility', 'notGranted', 'request', false], ['screenRecording', 'notGranted', 'request', false]], message: null, canRecheck: true, canContinue: false, settingsStep: null }, - settingsStep: { phase: 'needsPermissions', rows: [['accessibility', 'granted', null, false], ['screenRecording', 'notGranted', 'openSettings', false]], message: null, canRecheck: true, canContinue: false, settingsStep: 'screenRecording' }, - grantedElsewhere: { phase: 'needsPermissions', rows: [['accessibility', 'granted', null, false], ['screenRecording', 'notGranted', 'request', false]], message: null, canRecheck: true, canContinue: false, settingsStep: null }, - allVerifiedElsewhere: { phase: 'needsPermissions', rows: [['accessibility', 'granted', null, false], ['screenRecording', 'granted', null, false]], message: 'success', canRecheck: true, canContinue: true, settingsStep: null }, - requesting: { phase: 'working', rows: [['accessibility', 'notGranted', null, false], ['screenRecording', 'notGranted', null, true]], message: 'progress', canRecheck: false, canContinue: false, settingsStep: null }, - checking: { phase: 'working', rows: [['accessibility', 'granted', null, false], ['screenRecording', 'notGranted', null, true]], message: 'progress', canRecheck: false, canContinue: false, settingsStep: null }, - stillOff: { phase: 'needsPermissions', rows: [['accessibility', 'granted', null, false], ['screenRecording', 'notGranted', 'openSettings', false]], message: 'error', canRecheck: true, canContinue: false, settingsStep: 'screenRecording' }, - ready: { phase: 'ready', rows: [['accessibility', 'granted', null, false], ['screenRecording', 'granted', null, false]], message: 'success', canRecheck: false, canContinue: false, settingsStep: null }, - ended: { phase: 'ended', rows: [['accessibility', 'notGranted', null, false], ['screenRecording', 'notGranted', null, false]], message: 'error', canRecheck: false, canContinue: false, settingsStep: null }, + unpublished: undefined, + missing: undefined, + ended: undefined, + needsBoth: { setupId: 'setup-1', state: 'needsPermissions', rows: ['accessibility notGranted current', 'screenRecording notGranted'], canAllow: true, canRecheck: true }, + allowing: { setupId: 'setup-1', state: 'working', rows: ['accessibility notGranted current', 'screenRecording notGranted'], canAllow: false, canRecheck: false }, + grantedElsewhere: { setupId: 'setup-1', state: 'needsPermissions', rows: ['accessibility granted', 'screenRecording notGranted current'], canAllow: true, canRecheck: true }, + stillOff: { setupId: 'setup-1', state: 'needsPermissions', rows: ['accessibility granted', 'screenRecording notGranted current'], canAllow: true, canRecheck: true, error: 'Still off' }, + checking: { setupId: 'setup-1', state: 'working', rows: ['accessibility granted', 'screenRecording notGranted current'], canAllow: false, canRecheck: false }, + ready: { setupId: 'setup-1', state: 'ready', rows: ['accessibility granted', 'screenRecording granted'], canAllow: false, canRecheck: false }, }); }); suite('panel', () => { - function createPanel(setupId: string | undefined = 'setup-1', helperAppSupport?: IComputerUseHelperAppSupport) { + function createPanel(status: IComputerUseStatusV1, helperAppSupport?: IComputerUseHelperAppSupport) { const disposables = store.add(new DisposableStore()); const model = new TestSetupModel(helperAppSupport); + model.status.set(status, undefined); const windowFocus = disposables.add(new Emitter<boolean>()); - const panel = disposables.add(new ComputerUseSetupPanel(model, setupId, { onDidChangeWindowFocus: windowFocus.event })); + let closed = 0; + const panel = disposables.add(new ComputerUseSetupPanel(model, 'setup-1', { onDidChangeWindowFocus: windowFocus.event, close: () => closed++ })); const container = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); container.appendChild(panel.appIcon); container.appendChild(panel.element); - const dismiss = disposables.add(new Button(container, { ...defaultButtonStyles })); - panel.setDismissButton(dismiss); - disposables.add({ dispose: () => container.remove() }); - const actionButtons = () => [...panel.element.querySelectorAll<HTMLElement>('.computer-use-setup-permission-action .monaco-button')]; - const recheckButton = () => panel.element.querySelector<HTMLElement>('.computer-use-setup-actions .monaco-button'); - const visible = (selector: string) => (panel.element.querySelector(selector)?.getClientRects().length ?? 0) > 0; - const describe = (element: Element | null | undefined) => element ? { label: element.textContent, aria: element.getAttribute('aria-label'), disabled: element.classList.contains('disabled'), focused: mainWindow.document.activeElement === element } : null; - return { model, panel, windowFocus, dismiss, actionButtons, recheckButton, visible, describe }; + disposables.add(toDisposable(() => container.remove())); + const focused = (element: Element | null) => element !== null && mainWindow.document.activeElement === element; + const rows = () => [...panel.element.querySelectorAll<HTMLElement>('.computer-use-setup-permission')].map(row => { + const refresh = row.querySelector<HTMLElement>('.action-label'); + const allowButton = row.querySelector<HTMLElement>('.monaco-button'); + return { + label: row.getAttribute('aria-label'), + granted: row.querySelector('.computer-use-setup-permission-status.granted') !== null, + refresh: refresh && { aria: refresh.getAttribute('aria-label'), icon: [...refresh.classList].filter(name => name.startsWith('codicon-')).join(' '), disabled: refresh.classList.contains('disabled'), focused: focused(refresh) }, + allow: allowButton && { label: allowButton.textContent, aria: allowButton.getAttribute('aria-label'), disabled: allowButton.classList.contains('disabled'), focused: focused(allowButton) }, + }; + }); + const allowButton = () => panel.element.querySelector<HTMLElement>('.computer-use-setup-permission .monaco-button'); + const refreshButton = () => panel.element.querySelector<HTMLElement>('.computer-use-setup-permission .action-label'); + return { model, panel, windowFocus, closed: () => closed, rows, allowButton, refreshButton }; } - test('focuses the next step, keeps focus while it runs, and moves it when the step is done', () => { - const { model, panel, actionButtons, recheckButton, describe } = createPanel(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 1, [request('accessibility'), request('screenRecording'), recheck])]), undefined); + test('offers controls for the current permission only, keeps them in place while a step runs, and moves focus on with the step', () => { + const { model, panel, rows, allowButton } = createPanel(needsBoth); panel.focus(); - const initial = { actions: actionButtons().map(describe), recheck: describe(recheckButton()) }; - actionButtons()[0].click(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('working', 1)], { setupId: 'setup-1', ...request('accessibility') }), undefined); - const working = { actions: actionButtons().map(describe), busy: panel.element.querySelectorAll('.computer-use-setup-permission-status.codicon-loading').length }; - model.status.set(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 2, [request('screenRecording'), recheck])]), undefined); - const next = { actions: actionButtons().map(describe), granted: panel.element.querySelectorAll('.computer-use-setup-permission-status.granted').length }; + const first = rows(); + // The modal moves focus itself, link by link, across its body. + const tabStops = [...panel.element.querySelectorAll<HTMLElement>('a')].map(link => { + link.focus(); + return { aria: link.getAttribute('aria-label'), reached: mainWindow.document.activeElement === link }; + }); + allowButton()?.focus(); + allowButton()?.click(); + model.status.set(allowingAccessibility, undefined); + const allowing = rows(); + model.status.set(needsScreenRecording, undefined); - assert.deepStrictEqual({ initial, requests: model.requests, working, next }, { - initial: { - actions: [ - { label: 'Allow', aria: 'Allow Accessibility', disabled: false, focused: true }, - { label: 'Allow', aria: 'Allow Screen Recording', disabled: false, focused: false }, - ], - recheck: null, - }, - requests: [{ setupId: 'setup-1', action: request('accessibility') }], - working: { - actions: [ - { label: 'Allow', aria: 'Allow Accessibility', disabled: true, focused: true }, - { label: 'Allow', aria: 'Allow Screen Recording', disabled: true, focused: false }, - ], - busy: 1, - }, - next: { - actions: [{ label: 'Allow', aria: 'Allow Screen Recording', disabled: false, focused: true }], - granted: 1, - }, + assert.deepStrictEqual({ first, tabStops, requests: model.requests, allowing, next: rows() }, { + first: [ + { + label: 'Accessibility, Not granted. Click and type in apps', + granted: false, + refresh: { aria: 'Check Accessibility Again', icon: 'codicon-refresh', disabled: false, focused: false }, + allow: { label: 'Allow in Settings', aria: 'Allow Accessibility in System Settings', disabled: false, focused: true }, + }, + { label: 'Screen Recording, Not granted. See app windows', granted: false, refresh: null, allow: null }, + ], + tabStops: [{ aria: 'Check Accessibility Again', reached: true }, { aria: 'Allow Accessibility in System Settings', reached: true }], + requests: [{ setupId: 'setup-1', action: allow('accessibility') }], + allowing: [ + { + label: 'Accessibility, Not granted. Click and type in apps', + granted: false, + refresh: { aria: 'Check Accessibility Again', icon: 'codicon-loading codicon-modifier-spin', disabled: true, focused: false }, + allow: { label: 'Allow in Settings', aria: 'Allow Accessibility in System Settings', disabled: true, focused: true }, + }, + { label: 'Screen Recording, Not granted. See app windows', granted: false, refresh: null, allow: null }, + ], + next: [ + { label: 'Accessibility, Granted. Click and type in apps', granted: true, refresh: null, allow: null }, + { + label: 'Screen Recording, Not granted. See app windows', + granted: false, + refresh: { aria: 'Check Screen Recording Again', icon: 'codicon-refresh', disabled: false, focused: false }, + allow: { label: 'Allow in Settings', aria: 'Allow Screen Recording in System Settings', disabled: false, focused: true }, + }, + ], }); }); + test('checks the current permission again from its refresh button, which runs as the key goes down because the modal stops key releases', () => { + const { model, refreshButton } = createPanel(needsBoth); + refreshButton()?.click(); + refreshButton()?.focus(); + // The test window has no focus, so the browser doesn't report focus changes on its own. + refreshButton()?.dispatchEvent(new FocusEvent('focus')); + refreshButton()?.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + assert.deepStrictEqual(model.requests, [{ setupId: 'setup-1', action: recheck }, { setupId: 'setup-1', action: recheck }]); + }); + test('shows the app\'s own icon once the host read it', () => { - const { model, panel } = createPanel(); + const { model, panel } = createPanel({ ...needsBoth, helperApp: { path: helperApp.path } }); const icon = () => ({ image: panel.appIcon.classList.contains('has-image'), src: panel.appIcon.querySelector('img')?.getAttribute('src') }); - model.status.set({ ...createStatus(['unknown', 'unknown'], []), helperApp: { path: helperApp.path } }, undefined); const withoutIcon = icon(); - model.status.set(createStatus(['unknown', 'unknown'], []), undefined); + model.status.set(needsBoth, undefined); assert.deepStrictEqual({ withoutIcon, withIcon: icon() }, { withoutIcon: { image: false, src: '' }, withIcon: { image: true, src: helperApp.icon }, }); }); - test('offers Continue when every permission was already verified while this setup waits, and focuses it', () => { - const { model, panel, actionButtons, recheckButton, describe } = createPanel(); - model.status.set(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 1, [request('screenRecording'), recheck])]), undefined); - panel.focus(); - const before = describe(recheckButton()); - model.status.set(createStatus(['granted', 'granted'], [setup('needsPermissions', 1, [request('screenRecording'), recheck])]), undefined); - const continueControl = { actions: actionButtons().length, recheck: describe(recheckButton()), primary: !recheckButton()?.classList.contains('secondary') }; - recheckButton()?.click(); - assert.deepStrictEqual({ before, continueControl, requests: model.requests }, { - before: null, - continueControl: { actions: 0, recheck: { label: 'Continue', aria: 'Continue Your Task', disabled: false, focused: true }, primary: true }, - requests: [{ setupId: 'setup-1', action: recheck }], - }); - }); - - test('guides the System Settings step, offering the app for dragging into the list and in Finder', () => { + test('offers the app for dragging into System Settings under the current permission, on clients that can drag it', () => { const support = new TestHelperAppSupport(); - const { model, panel, recheckButton, visible, describe } = createPanel('setup-1', support); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 1, [request('accessibility'), request('screenRecording'), recheck])]), undefined); - const beforeSettings = visible('.computer-use-setup-settings-step'); - model.status.set(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 2, [request('screenRecording'), openSettings('screenRecording'), recheck])]), undefined); + const { model, panel } = createPanel(needsBoth, support); + const chip = () => { + const element = panel.element.querySelector<HTMLElement>('.computer-use-setup-helper-app-chip'); + const row = [...panel.element.querySelectorAll('.computer-use-setup-permission')].findIndex(candidate => !!element && candidate.contains(element)); + return element && { row, ariaHidden: element.getAttribute('aria-hidden'), draggable: element.draggable, icon: element.querySelector('img')?.getAttribute('src'), name: element.textContent }; + }; + const first = chip(); const drag = new DragEvent('dragstart', { bubbles: true, cancelable: true }); panel.element.querySelector('.computer-use-setup-helper-app-chip')?.dispatchEvent(drag); - const reveal = panel.element.querySelector<HTMLElement>('.computer-use-setup-helper-app-action .monaco-button'); - reveal?.click(); - const step = { - caption: panel.element.querySelector('.computer-use-setup-settings-step-caption')?.textContent, - app: visible('.computer-use-setup-helper-app'), - icon: panel.element.querySelector('.computer-use-setup-helper-app-icon')?.getAttribute('src'), - nativeDrag: drag.defaultPrevented, - reveal: reveal?.getAttribute('aria-label'), - recheck: describe(recheckButton())?.label, - }; - model.status.set(createStatus(['granted', 'notGranted'], [setup('working', 2)], { setupId: 'setup-1', ...recheck }), undefined); - const whileChecking = visible('.computer-use-setup-settings-step'); - model.status.set(createStatus(['granted', 'granted'], [setup('ready', 3)]), undefined); - assert.deepStrictEqual({ beforeSettings, step, whileChecking, ready: visible('.computer-use-setup-settings-step'), calls: support.calls }, { - beforeSettings: false, - step: { - caption: 'Turn on Copilot Computer Use under Screen Recording in System Settings, or drag it into the list.', - app: true, - icon: helperApp.icon, - nativeDrag: true, - reveal: 'Show Copilot Computer Use in Finder', - recheck: 'Check Again', - }, - whileChecking: true, - ready: false, - calls: [`drag ${helperApp.path}`, `reveal ${helperApp.path}`], - }); - }); - - test('lets the keyboard reach every control it shows, and moves focus on when the System Settings step ends', () => { - const { model, panel, describe } = createPanel('setup-1', new TestHelperAppSupport()); - // The modal moves focus itself, link by link, across its body. - const tabStops = () => [...panel.element.querySelectorAll<HTMLElement>('a')].map(link => { - link.focus(); - return { label: link.textContent, reached: mainWindow.document.activeElement === link }; - }); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 1, [request('accessibility'), request('screenRecording'), recheck])]), undefined); - const initial = tabStops(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 2, [request('accessibility'), openSettings('accessibility'), request('screenRecording'), recheck])]), undefined); - const settingsStep = tabStops(); - panel.element.querySelector<HTMLElement>('.computer-use-setup-helper-app-action .monaco-button')?.focus(); - model.status.set(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 3, [request('screenRecording'), recheck])]), undefined); - const focusedAfterStep = describe(mainWindow.document.activeElement); - assert.deepStrictEqual({ initial, settingsStep, focusedAfterStep, afterStep: tabStops() }, { - initial: [{ label: 'Allow', reached: true }, { label: 'Allow', reached: true }], - settingsStep: [{ label: 'Open Settings', reached: true }, { label: 'Allow', reached: true }, { label: 'Show in Finder', reached: true }, { label: 'Check Again', reached: true }], - focusedAfterStep: { label: 'Allow', aria: 'Allow Screen Recording', disabled: false, focused: true }, - afterStep: [{ label: 'Allow', reached: true }], - }); - }); + model.status.set(needsScreenRecording, undefined); + const next = chip(); + model.status.set(checkingScreenRecording, undefined); + const whileChecking = chip(); + model.status.set({ ...needsScreenRecording, helperApp: undefined }, undefined); + const unpublished = chip(); + model.status.set(ready, undefined); + const granted = chip(); + const withoutDragSupport = createPanel(needsBoth).panel.element.querySelector('.computer-use-setup-helper-app-chip'); - test('guides the System Settings step without the app on clients that can\'t drag it', () => { - const { model, panel, visible } = createPanel(); - model.status.set(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 2, [request('screenRecording'), openSettings('screenRecording'), recheck])]), undefined); - assert.deepStrictEqual({ caption: panel.element.querySelector('.computer-use-setup-settings-step-caption')?.textContent, app: visible('.computer-use-setup-helper-app') }, { - caption: 'Turn on Copilot Computer Use under Screen Recording in System Settings.', - app: false, + const shown = (row: number) => ({ row, ariaHidden: 'true', draggable: true, icon: helperApp.icon, name: 'Copilot Computer Use' }); + assert.deepStrictEqual({ first, nativeDrag: drag.defaultPrevented, drags: support.drags, next, whileChecking, unpublished, granted, withoutDragSupport }, { + first: shown(0), + nativeDrag: true, + drags: [helperApp.path], + next: shown(1), + whileChecking: shown(1), + unpublished: null, + granted: null, + withoutDragSupport: null, }); }); test('checks again once when the user comes back from macOS, after the step that sent them there', () => { - const { model, actionButtons, windowFocus } = createPanel(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 1, [request('accessibility'), request('screenRecording'), recheck])]), undefined); + const { model, windowFocus, allowButton } = createPanel(needsBoth); windowFocus.fire(true); - actionButtons()[0].click(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('working', 1)], { setupId: 'setup-1', ...request('accessibility') }), undefined); + allowButton()?.click(); + model.status.set(allowingAccessibility, undefined); windowFocus.fire(false); windowFocus.fire(true); const whileWorking = model.requests.length; - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 2, [request('accessibility'), openSettings('accessibility'), request('screenRecording'), recheck])]), undefined); + model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 2, [allow('accessibility'), allow('screenRecording'), recheck])]), undefined); windowFocus.fire(false); windowFocus.fire(true); assert.deepStrictEqual({ whileWorking, requests: model.requests.map(entry => entry.action) }, { whileWorking: 1, - requests: [request('accessibility'), recheck], + requests: [allow('accessibility'), recheck], }); }); test('skips the check on return once the host confirmed the permission the user went to grant', () => { - const { model, actionButtons, windowFocus } = createPanel(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 2, [request('accessibility'), openSettings('accessibility'), request('screenRecording'), recheck])]), undefined); + const { model, windowFocus, allowButton } = createPanel(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 2, [allow('accessibility'), allow('screenRecording'), recheck])])); windowFocus.fire(true); - actionButtons()[0].click(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 3, [request('accessibility'), openSettings('accessibility'), request('screenRecording'), recheck])]), undefined); + allowButton()?.click(); + model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 3, [allow('accessibility'), allow('screenRecording'), recheck])]), undefined); windowFocus.fire(false); // macOS reported the change while the user was in System Settings, and the host checked again on its own. model.status.set(createStatus(['notGranted', 'notGranted'], [setup('working', 3)], { setupId: 'setup-1', ...recheck }), undefined); - model.status.set(createStatus(['granted', 'notGranted'], [setup('needsPermissions', 4, [request('screenRecording'), recheck])]), undefined); + model.status.set(needsScreenRecording, undefined); windowFocus.fire(true); - assert.deepStrictEqual(model.requests.map(entry => entry.action), [openSettings('accessibility')]); + assert.deepStrictEqual(model.requests.map(entry => entry.action), [allow('accessibility')]); }); - test('labels the modal\'s button by the setup\'s progress, and follows the newest waiting setup when opened without one', () => { - const { model, dismiss } = createPanel(undefined); - const label = () => ({ label: dismiss.element.textContent, secondary: dismiss.element.classList.contains('secondary') }); - model.status.set(createStatus(['unknown', 'unknown'], []), undefined); - const idle = label(); - model.status.set(createStatus(['notGranted', 'notGranted'], [setup('needsPermissions', 1, [request('accessibility'), recheck])]), undefined); - const waiting = label(); - model.status.set(createStatus(['granted', 'granted'], [setup('ready', 2)]), undefined); - const ready = label(); - model.status.set(createStatus(['granted', 'granted'], [setup('ended', 2, [], { code: 'notWaiting', message: 'Not waiting' })]), undefined); - assert.deepStrictEqual({ idle, waiting, ready, ended: label() }, { - idle: { label: 'Close', secondary: false }, - waiting: { label: 'Not Now', secondary: true }, - ready: { label: 'Continue', secondary: false }, - ended: { label: 'Close', secondary: false }, + test('closes as soon as its setup no longer waits', () => { + const close = (status: IComputerUseStatusV1 | undefined) => { + const { model, panel, closed } = createPanel(needsBoth); + model.status.set(status, undefined); + return { closed: closed(), view: panel.view?.state }; + }; + assert.deepStrictEqual({ + ended: close(ended), + missing: close(createStatus(['notGranted', 'notGranted'], [])), + unpublished: close(undefined), + working: close(allowingAccessibility), + }, { + ended: { closed: 1, view: undefined }, + missing: { closed: 1, view: undefined }, + unpublished: { closed: 1, view: undefined }, + working: { closed: 0, view: 'working' }, }); }); + + test('shows every permission granted for a moment once the setup is ready, then closes once', () => runWithFakedTimers({}, async () => { + const { model, rows, closed } = createPanel(checkingScreenRecording); + model.status.set(ready, undefined); + const granted = rows(); + await timeout(900); + // Other updates of the status don't postpone closing. + model.status.set({ ...ready, verifiedAt: 1 }, undefined); + const before = closed(); + await timeout(200); + const after = closed(); + await timeout(2000); + assert.deepStrictEqual({ granted, before, after, later: closed() }, { + granted: [ + { label: 'Accessibility, Granted. Click and type in apps', granted: true, refresh: null, allow: null }, + { label: 'Screen Recording, Granted. See app windows', granted: true, refresh: null, allow: null }, + ], + before: 0, + after: 1, + later: 1, + }); + })); }); - test('opens with its button labelled by the setup\'s progress', () => { + function createDialog(model: TestSetupModel) { const disposables = store.add(new DisposableStore()); const container = mainWindow.document.body.appendChild(mainWindow.document.createElement('div')); disposables.add(toDisposable(() => container.remove())); const instantiationService = disposables.add(new TestInstantiationService()); instantiationService.stub(ILayoutService, { activeContainer: container }); - instantiationService.stub(IKeybindingService, {}); + instantiationService.stub(IKeybindingService, new MockKeybindingService()); instantiationService.stub(IHostService, { onDidChangeFocus: Event.None, setWindowDimmed: async () => { } }); + const dialog = disposables.add(instantiationService.createInstance(ComputerUseSetupDialog, model, 'setup-1')); + return { container, dialog }; + } + + test('opens as a modal without buttons of its own, focused on the current step, and closes itself once its setup stops waiting', async () => { const model = new TestSetupModel(); - model.status.set(createStatus(['granted', 'granted'], []), undefined); - const dialog = disposables.add(instantiationService.createInstance(ComputerUseSetupDialog, model, undefined)); - void dialog.show(); - assert.deepStrictEqual([...container.querySelectorAll('.dialog-buttons .monaco-button')].map(button => button.textContent), ['Close']); + model.status.set(needsBoth, undefined); + const { container, dialog } = createDialog(model); + let closed = false; + const shown = dialog.show().then(() => { closed = true; }); + const open = { + buttons: container.querySelectorAll('.dialog-buttons .monaco-button').length, + title: container.querySelector('.dialog-message-text')?.textContent, + focused: mainWindow.document.activeElement?.getAttribute('aria-label'), + refreshDecoration: container.querySelector<HTMLElement>('.computer-use-setup-permission .action-label')?.style.textDecoration, + }; + model.status.set(ended, undefined); + await shown; + assert.deepStrictEqual({ open, closed, modal: container.querySelector('.monaco-dialog-box') !== null }, { + open: { buttons: 0, title: 'Set Up Computer Use', focused: 'Allow Accessibility in System Settings', refreshDecoration: '' }, + closed: true, + modal: false, + }); + }); + + test('closes on Escape without buttons of its own, leaving the setup waiting', async () => { + const model = new TestSetupModel(); + model.status.set(needsBoth, undefined); + const { container, dialog } = createDialog(model); + const shown = dialog.show(); + const focused = mainWindow.document.activeElement; + for (const type of ['keydown', 'keyup']) { + focused?.dispatchEvent(new KeyboardEvent(type, { key: 'Escape', keyCode: 27, bubbles: true, cancelable: true })); + } + await shown; + assert.deepStrictEqual({ focusedInModal: !!focused && container.contains(focused), requests: model.requests }, { + focusedInModal: true, + requests: [], + }); }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationMigrationDashboard.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationMigrationDashboard.test.ts index e3dd13306b0cb3..0c20e053edb551 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationMigrationDashboard.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/customizationMigrationDashboard.test.ts @@ -9,6 +9,7 @@ import { Disposable, toDisposable } from '../../../../../../base/common/lifecycl import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IHoverService } from '../../../../../../platform/hover/browser/hover.js'; +import { IOpenerService } from '../../../../../../platform/opener/common/opener.js'; import { workbenchInstantiationService } from '../../../../../test/browser/workbenchTestServices.js'; import { CustomizationMigrationCategoryId } from '../../../browser/aiCustomization/customizationMigrationCategories.js'; import { @@ -25,8 +26,15 @@ suite('CustomizationMigrationDashboard', () => { const parent = DOM.append(document.body, DOM.$('div')); const telemetryActions: string[] = []; const hoverContents = new Map<HTMLElement, string>(); + const openedLinks: string[] = []; store.add(toDisposable(() => parent.remove())); const instantiationService = workbenchInstantiationService(undefined, store); + instantiationService.stub(IOpenerService, new class extends mock<IOpenerService>() { + override async open(resource: Parameters<IOpenerService['open']>[0]) { + openedLinks.push(resource.toString()); + return true; + } + }); instantiationService.stub(IHoverService, new class extends mock<IHoverService>() { override setupDelayedHover(...args: Parameters<IHoverService['setupDelayedHover']>) { const options = typeof args[1] === 'function' ? args[1]() : args[1]; @@ -52,7 +60,7 @@ suite('CustomizationMigrationDashboard', () => { ...callbacks, })); dashboard.layout(1000); - return { parent, dashboard, hoverContents, telemetryActions }; + return { parent, dashboard, hoverContents, telemetryActions, openedLinks }; } function button(parent: HTMLElement, label: string): HTMLElement { @@ -157,6 +165,8 @@ suite('CustomizationMigrationDashboard', () => { intro: parent.querySelector('.migration-intro')?.textContent, agentButtonInTitleRow: agentMigrationButton.parentElement?.classList.contains('migration-page-title-actions'), agentButtonIsSecondary: agentMigrationButton.classList.contains('migration-secondary-button'), + agentTooltip: hoverContents.get(agentMigrationButton), + agentDescription: agentMigrationButton.getAttribute('aria-description'), migrateButtonIsSecondary: migrateButton.classList.contains('migration-secondary-button'), migrateTooltips: [...parent.querySelectorAll<HTMLElement>('.migration-tree-group-actions .migration-secondary-button')] .filter(element => element.textContent?.startsWith('Migrate')) @@ -166,7 +176,7 @@ suite('CustomizationMigrationDashboard', () => { actions, telemetryActions, }, { - title: 'Migrations', + title: 'Keep your customizations working', groups: ['Convert Prompt to Skills (Workspace)', 'Convert Prompt to Skills (User)', 'MCP Servers (Workspace)', 'Plugin Marketplaces (User)', 'User Data (User)', 'Custom location settings (Workspace)'], counts: ['1', '2', '1', '1', '2', '1'], items: ['Build', 'Release', 'Triage', 'Postgres', 'vscode-team-kit', 'Planner', 'Review', 'Team rules'], @@ -176,9 +186,11 @@ suite('CustomizationMigrationDashboard', () => { ], warning: 'Prompt-to-skill conversion changesConvert prompts to skills.', checklistCopy: false, - intro: 'Some of your agent customizations need an update to keep working. Use Migrate to have VS Code update selected customizations, or Migrate with Agent for a guided migration in chat. Agent migration uses credits.', + intro: 'Copilot\'s new agent runtime uses different formats and locations for some customizations. Review and migrate the affected items below.', agentButtonInTitleRow: true, agentButtonIsSecondary: true, + agentTooltip: 'Open a new chat with an agent to review and migrate your customizations. This uses Copilot credits.', + agentDescription: 'Open a new chat with an agent to review and migrate your customizations. This uses Copilot credits.', migrateButtonIsSecondary: true, migrateTooltips: [ 'Convert prompt files to skills (Workspace)', @@ -195,11 +207,49 @@ suite('CustomizationMigrationDashboard', () => { }); }); - test('hides agent migration for unsupported harnesses', () => { + test('hides agent migration for unsupported harnesses while retaining the migration introduction', () => { const { parent, dashboard } = createDashboard(); dashboard.showOverview({ ...overview(), supportsAgentMigration: false }); - assert.strictEqual(parent.querySelector('[aria-label="Start a guided migration of all customization files that need migration"]'), null); + assert.deepStrictEqual({ + agentButton: parent.querySelector('[aria-label="Start a guided migration of all customization files that need migration"]'), + title: parent.querySelector('h1')?.textContent, + intro: parent.querySelector('.migration-intro')?.textContent, + learnMore: parent.querySelector('.monaco-link')?.textContent, + }, { + agentButton: null, + title: 'Keep your customizations working', + intro: 'Copilot\'s new agent runtime uses different formats and locations for some customizations. Review and migrate the affected items below.', + learnMore: 'Learn About Migrations', + }); + }); + + test('opens migration documentation by mouse and keyboard and restores link focus after refresh', () => { + const { parent, dashboard, openedLinks } = createDashboard(); + dashboard.showOverview(overview()); + const link = parent.querySelector<HTMLAnchorElement>('.monaco-link'); + assert.ok(link); + link.click(); + link.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', keyCode: 13, bubbles: true })); + link.focus(); + dashboard.showLoading('Migrations', 'Loading migrations'); + dashboard.showOverview(overview()); + + assert.deepStrictEqual({ + label: link.textContent, + href: link.getAttribute('href'), + role: link.getAttribute('role'), + tabIndex: link.tabIndex, + openedLinks, + focusedLink: document.activeElement === parent.querySelector('.monaco-link'), + }, { + label: 'Learn About Migrations', + href: 'https://aka.ms/vscode-migrate-customizations', + role: 'link', + tabIndex: 0, + openedLinks: ['https://aka.ms/vscode-migrate-customizations', 'https://aka.ms/vscode-migrate-customizations'], + focusedLink: true, + }); }); test('moves initial loading focus to the first migrate action when the overview loads', () => { @@ -255,7 +305,7 @@ suite('CustomizationMigrationDashboard', () => { test('opens customization rows and manual review rows through the same details callback', () => { const opened: string[] = []; - const { parent, dashboard } = createDashboard({ + const { parent, dashboard, hoverContents } = createDashboard({ openCustomization: (item, storage) => opened.push(`${item.id}:${storage}`), }); const model = overview(); @@ -279,10 +329,14 @@ suite('CustomizationMigrationDashboard', () => { `workspace-mcp:${PromptsStorage.local}`, `workspace-mcp-manual:${PromptsStorage.local}`, ]); + const manualReviewGroup = [...parent.querySelectorAll<HTMLElement>('.group-label')] + .find(element => element.textContent === 'Needs manual review'); assert.deepStrictEqual({ + manualReviewGuidance: manualReviewGroup && hoverContents.get(manualReviewGroup), manualReviewCheckboxDisplay: DOM.getWindow(parent).getComputedStyle(parent.querySelector<HTMLElement>('.migration-tree-item.manual-review .migration-tree-item-checkbox')!).display, reviewButtons: [...parent.querySelectorAll('.migration-tree-item-review')].filter(element => (element as HTMLElement).style.display !== 'none').map(element => element.textContent), }, { + manualReviewGuidance: 'These customizations cannot be migrated automatically. Select Review to see what needs to change.', manualReviewCheckboxDisplay: 'none', reviewButtons: ['Review'], }); @@ -299,6 +353,26 @@ suite('CustomizationMigrationDashboard', () => { assert.ok(height > 0 && height <= 400, `Unexpected tree height: ${treeContainer.style.height}`); }); + test('restores documentation link focus when refreshing a completed overview', () => { + const { parent, dashboard } = createDashboard(); + dashboard.showOverview({ scopes: [] }); + const link = parent.querySelector<HTMLAnchorElement>('.monaco-link'); + assert.ok(link); + link.focus(); + dashboard.showOverview({ scopes: [] }); + const focusedAfterRefresh = document.activeElement === parent.querySelector('.monaco-link'); + + dashboard.showLoading('Migrations', 'Loading migrations'); + dashboard.showOverview({ scopes: [] }); + assert.deepStrictEqual({ + focusedAfterRefresh, + focusedAfterLoading: document.activeElement === parent.querySelector('.monaco-link'), + }, { + focusedAfterRefresh: true, + focusedAfterLoading: true, + }); + }); + test('does not move focus into a completed overview', () => { const { parent, dashboard } = createDashboard(); const model = overview(); @@ -343,7 +417,7 @@ suite('CustomizationMigrationDashboard', () => { buttons: parent.querySelectorAll('[role="button"]').length, focus: document.activeElement?.tagName, }, { - description: 'Your customizations use supported formats and locations.', + description: 'Your customizations are ready.', empty: 'No migrations are needed.', buttons: 0, focus: 'BODY', diff --git a/src/vs/workbench/contrib/chat/test/browser/chatInputPills.test.ts b/src/vs/workbench/contrib/chat/test/browser/chatInputPills.test.ts index 653319deb50d5d..6f2a1ab883ddce 100644 --- a/src/vs/workbench/contrib/chat/test/browser/chatInputPills.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/chatInputPills.test.ts @@ -8,12 +8,15 @@ import { timeout } from '../../../../../base/common/async.js'; import { Action, SubmenuAction, toAction, type IAction } from '../../../../../base/common/actions.js'; import { AnchorPosition } from '../../../../../base/common/layout.js'; import { toDisposable } from '../../../../../base/common/lifecycle.js'; -import { constObservable, observableValue } from '../../../../../base/common/observable.js'; +import { constObservable, IObservable, observableValue } from '../../../../../base/common/observable.js'; +import { URI } from '../../../../../base/common/uri.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { IContextMenuService } from '../../../../../platform/contextview/browser/contextView.js'; +import { IActionListItem } from '../../../../../platform/actionWidget/browser/actionList.js'; import { IActionWidgetService } from '../../../../../platform/actionWidget/browser/actionWidget.js'; +import { IStorageService } from '../../../../../platform/storage/common/storage.js'; import { computePullRequestIcon, type ChatPullRequestState } from '../../../../common/chatPullRequest.js'; -import type { IChatPillSection } from '../../../../browser/chatPills.js'; +import type { IChatPillEntry, IChatPillSection } from '../../../../browser/chatPills.js'; import { workbenchInstantiationService } from '../../../../test/browser/workbenchTestServices.js'; import { TestStorageService } from '../../../../test/common/workbenchTestServices.js'; import { ChatInputPills, createChatInputPillSource, StandardChatInputPillSources, type IStandardChatInputPillsData } from '../../browser/chatInputPills.js'; @@ -30,19 +33,42 @@ suite('StandardChatInputPillSources', () => { return { instantiationService, visibility }; } - function createPills(data: IStandardChatInputPillsData, sharedVisibility?: SessionChatPillVisibility) { + function createPills(data: IStandardChatInputPillsData, sharedVisibility?: SessionChatPillVisibility, options?: { + readonly pinScope?: IObservable<string | undefined>; + readonly storageService?: TestStorageService; + }) { const { instantiationService, visibility } = createServices(sharedVisibility); + if (options?.storageService) { + instantiationService.stub(IStorageService, options.storageService); + } let menuActions: readonly IAction[] = []; + let dropdownItems: readonly IActionListItem<IChatPillEntry>[] = []; + let hideDropdown: (() => void) | undefined; instantiationService.stub(IContextMenuService, { showContextMenu: delegate => { assert.ok(delegate.getActions); menuActions = delegate.getActions(); }, }); + instantiationService.stub(IActionWidgetService, { + get isVisible() { return !!hideDropdown; }, + show: (_id, _preview, items, delegate) => { + dropdownItems = items as readonly IActionListItem<IChatPillEntry>[]; + hideDropdown = () => { + hideDropdown = undefined; + delegate.onHide?.(); + }; + }, + hide: () => hideDropdown?.(), + updateItems: items => { + dropdownItems = items as readonly IActionListItem<IChatPillEntry>[]; + }, + }); const container = document.createElement('div'); document.body.appendChild(container); store.add(toDisposable(() => container.remove())); - const sources = store.add(instantiationService.createInstance(StandardChatInputPillSources, data, SESSION_CHAT_PILL_KINDS)); + const pinScope = options?.pinScope ?? observableValue<string | undefined>('pinScope', 'chat:default'); + const sources = store.add(instantiationService.createInstance(StandardChatInputPillSources, data, SESSION_CHAT_PILL_KINDS, pinScope)); const inputPills = store.add(instantiationService.createInstance(ChatInputPills, container, { debugName: 'ChatInputPills.options.test', compact: false, @@ -52,8 +78,16 @@ suite('StandardChatInputPillSources', () => { })); return { inputPills, + pinScope, + sources, visibility, labels: () => [...inputPills.element.querySelectorAll('.chat-pill-label, .changes-stats-files')].map(element => element.textContent), + openDropdown: (index = 0) => { + dropdownItems = []; + inputPills.getPillElements()[index]?.click(); + return dropdownItems; + }, + closeDropdown: () => hideDropdown?.(), openContextMenu: (target: HTMLElement, keyboard = false) => { menuActions = []; target.dispatchEvent(keyboard @@ -91,7 +125,7 @@ suite('StandardChatInputPillSources', () => { subagents: { sections }, backgroundShells: { sections }, }; - const full = store.add(instantiationService.createInstance(StandardChatInputPillSources, data, SESSION_CHAT_PILL_KINDS)); + const full = store.add(instantiationService.createInstance(StandardChatInputPillSources, data, SESSION_CHAT_PILL_KINDS, constObservable('chat:full'))); const supportedKinds = [ SessionChatPillKind.Changes, SessionChatPillKind.PullRequests, @@ -101,7 +135,7 @@ suite('StandardChatInputPillSources', () => { SessionChatPillKind.Canvases, SessionChatPillKind.Browsers, ]; - const subset = store.add(instantiationService.createInstance(StandardChatInputPillSources, data, supportedKinds)); + const subset = store.add(instantiationService.createInstance(StandardChatInputPillSources, data, supportedKinds, constObservable('chat:subset'))); assert.deepStrictEqual({ full: full.sources.map(source => source.kind), @@ -140,7 +174,7 @@ suite('StandardChatInputPillSources', () => { browsers: { sections }, subagents: { sections }, backgroundShells: { sections }, - }, SESSION_CHAT_PILL_KINDS)); + }, SESSION_CHAT_PILL_KINDS, constObservable('chat:placement'))); const inputPills = store.add(instantiationService.createInstance(ChatInputPills, undefined, { debugName: 'ChatInputPills.placement.test', compact: false, @@ -176,6 +210,242 @@ suite('StandardChatInputPillSources', () => { }); }); + test('pins and unpins entries from every aggregated pill kind', async () => { + const cases: readonly { + readonly property: Exclude<keyof IStandardChatInputPillsData, 'changes'>; + readonly kind: SessionChatPillKind; + readonly aggregateLabel: string; + readonly remainingLabel: string; + readonly remainingPinnable?: boolean; + readonly remainingHasPopup?: boolean; + }[] = [ + { property: 'pullRequests', kind: SessionChatPillKind.PullRequests, aggregateLabel: '2 Pull Requests', remainingLabel: 'second' }, + { property: 'issues', kind: SessionChatPillKind.Issues, aggregateLabel: '2 Issues', remainingLabel: 'second' }, + { property: 'artifacts', kind: SessionChatPillKind.Artifacts, aggregateLabel: '2 Artifacts', remainingLabel: 'second' }, + { property: 'references', kind: SessionChatPillKind.References, aggregateLabel: '2 References', remainingLabel: 'second' }, + { property: 'customizations', kind: SessionChatPillKind.Customizations, aggregateLabel: '2 Customizations', remainingLabel: 'second' }, + { property: 'canvases', kind: SessionChatPillKind.Canvases, aggregateLabel: '2 Canvases', remainingLabel: 'second' }, + { property: 'browsers', kind: SessionChatPillKind.Browsers, aggregateLabel: '2 Active Browsers', remainingLabel: 'second' }, + { property: 'subagents', kind: SessionChatPillKind.Subagents, aggregateLabel: '2 Subagents', remainingLabel: 'second' }, + { property: 'backgroundShells', kind: SessionChatPillKind.BackgroundShells, aggregateLabel: '2 Background Shells', remainingLabel: '1 Background Shell', remainingPinnable: true, remainingHasPopup: true }, + ]; + const results = []; + for (const testCase of cases) { + const sections = constObservable<readonly IChatPillSection[]>([{ + title: 'Entries', + entries: ['first', 'second'].map(id => ({ id, label: id, open: () => { } })), + }]); + const pills = createPills({ [testCase.property]: { sections } }, undefined, { + pinScope: constObservable(`chat:${testCase.kind}`), + }); + if (!pills.visibility.isVisible(testCase.kind, undefined)) { + pills.visibility.toggle(testCase.kind); + } + const initial = pills.labels(); + const firstItem = pills.openDropdown().find(item => item.item?.id === 'first'); + const pinAction = firstItem?.toolbarActions?.find(action => action.label === 'Pin first'); + assert.ok(pinAction); + await pinAction.run(); + await timeout(0); + const [pinned] = pills.inputPills.getPillElements(); + const contextActions = pills.openContextMenu(pinned); + const unpinAction = contextActions.find(action => action.label === 'Unpin first'); + assert.ok(unpinAction); + const afterPin = pills.labels(); + pills.closeDropdown(); + const pinnedPicker = testCase.kind === SessionChatPillKind.BackgroundShells + ? pills.openDropdown(0).filter(item => item.item).map(item => ({ id: item.item?.id, openSubmenuOnClick: item.openSubmenuOnClick })) + : []; + pills.closeDropdown(); + const remainingAfterClose = pills.inputPills.getPillElements()[1]; + const remainingAriaLabel = remainingAfterClose.getAttribute('aria-label'); + const remainingHasPopup = remainingAfterClose.getAttribute('aria-haspopup') === 'listbox'; + const pinnedActions = contextActions.filter(action => action.label === 'Unpin first').map(action => action.label); + const remainingActions = pills.openContextMenu(remainingAfterClose).filter(action => action.label === 'Pin second').map(action => action.label); + await unpinAction.run(); + results.push({ + kind: testCase.kind, + initial, + afterPin, + pinnedPicker, + pinnedActions, + remainingActions, + remainingAriaLabel, + remainingHasPopup, + afterUnpin: pills.labels(), + }); + } + + assert.deepStrictEqual(results, cases.map(testCase => ({ + kind: testCase.kind, + initial: [testCase.aggregateLabel], + afterPin: ['first', testCase.remainingLabel], + pinnedPicker: testCase.kind === SessionChatPillKind.BackgroundShells ? [{ id: 'first', openSubmenuOnClick: true }] : [], + pinnedActions: ['Unpin first'], + remainingActions: testCase.remainingPinnable ? ['Pin second'] : [], + remainingAriaLabel: testCase.remainingHasPopup ? 'Show 1 background shell' : 'second', + remainingHasPopup: testCase.remainingHasPopup ?? false, + afterUnpin: [testCase.aggregateLabel], + }))); + }); + + test('keeps a pinned pill descriptor stable while its live entry updates', async () => { + const sections = observableValue<readonly IChatPillSection[]>('sections', [{ + title: 'Browsers', + entries: [ + { id: 'browser', label: 'Loading', open: () => { } }, + { id: 'other', label: 'Other', open: () => { } }, + ], + }]); + const pills = createPills({ browsers: { sections } }, undefined, { + pinScope: constObservable('chat:live'), + }); + const browser = pills.openDropdown().find(item => item.item?.id === 'browser'); + await browser?.toolbarActions?.find(action => action.label === 'Pin Loading')?.run(); + const source = pills.sources.sources.find(source => source.kind === SessionChatPillKind.Browsers); + assert.ok(source); + const descriptor = source.pills.get()[0]; + + sections.set([{ + title: 'Browsers', + entries: [ + { id: 'browser', label: 'Documentation', open: () => { } }, + { id: 'other', label: 'Other', open: () => { } }, + ], + }], undefined); + const updatedDescriptor = source.pills.get()[0]; + const contextActions = pills.openContextMenu(pills.inputPills.getPillElements()[0]); + + assert.deepStrictEqual({ + stable: descriptor === updatedDescriptor, + labels: pills.labels(), + unpin: contextActions.find(action => action.id.includes('.unpin.'))?.label, + }, { + stable: true, + labels: ['Documentation', 'Other'], + unpin: 'Unpin Documentation', + }); + }); + + test('places copy before pin and destructive actions on dropdown rows', () => { + const copy = toAction({ id: 'copy', label: 'Copy Path', run: () => { } }); + const remove = toAction({ id: 'remove', label: 'Remove Artifact', run: () => { } }); + const sections = constObservable<readonly IChatPillSection[]>([{ + title: 'Artifacts', + entries: [ + { id: 'plan', label: 'Plan', toolbarActions: [copy], promotedAction: remove, open: () => { } }, + { id: 'report', label: 'Report', open: () => { } }, + ], + }]); + const pills = createPills({ artifacts: { sections } }, undefined, { + pinScope: constObservable('chat:action-order'), + }); + const plan = pills.openDropdown().find(item => item.item?.id === 'plan'); + + assert.deepStrictEqual(plan?.toolbarActions?.map(action => action.label), [ + 'Copy Path', + 'Pin Plan', + 'Remove Artifact', + ]); + }); + + test('shows a clickable pinned icon without losing copy, destructive, or keyboard unpin actions', async () => { + const copy = toAction({ id: 'copy', label: 'Copy Path', run: () => { } }); + const remove = toAction({ id: 'remove', label: 'Remove Artifact', run: () => { } }); + const sections = constObservable<readonly IChatPillSection[]>([{ + title: 'Artifacts', + entries: [ + { id: 'plan', label: 'Plan', resource: URI.file('/repo/plan.md'), toolbarActions: [copy], promotedAction: remove, open: () => { } }, + { id: 'report', label: 'Report', resource: URI.file('/repo/report.md'), open: () => { } }, + ], + }]); + const pills = createPills({ artifacts: { sections } }, undefined, { + pinScope: constObservable('chat:pinned-icon'), + }); + const plan = pills.openDropdown().find(item => item.item?.id === 'plan'); + await plan?.toolbarActions?.find(action => action.label === 'Pin Plan')?.run(); + await timeout(0); + const pinned = pills.inputPills.getPillElements()[0]; + const unpin = pinned.closest('.chat-pill-item')?.querySelector<HTMLElement>('.chat-pill-promoted-action'); + assert.ok(unpin); + const contextActions = pills.openContextMenu(pinned).filter(action => ['copy', 'remove'].includes(action.id) || action.id.includes('.unpin.')); + unpin.click(); + await timeout(0); + + assert.deepStrictEqual({ + icon: { + ariaLabel: unpin.getAttribute('aria-label'), + unpin: unpin.classList.contains('codicon-unpin'), + tabIndex: unpin.getAttribute('tabindex'), + }, + contextActions: contextActions.map(action => action.label), + afterClick: pills.labels(), + }, { + icon: { ariaLabel: 'Unpin Plan', unpin: true, tabIndex: '-1' }, + contextActions: ['Copy Path', 'Remove Artifact', 'Unpin Plan'], + afterClick: ['2 Artifacts'], + }); + }); + + test('persists pins per chat scope and restores them when returning to the chat', async () => { + const storageService = store.add(new TestStorageService()); + const pinScope = observableValue<string | undefined>('pinScope', 'chat:first'); + const sections = constObservable<readonly IChatPillSection[]>([{ + title: 'Artifacts', + entries: ['plan', 'report'].map(id => ({ id, label: id, open: () => { } })), + }]); + const first = createPills({ artifacts: { sections } }, undefined, { pinScope, storageService }); + const plan = first.openDropdown().find(item => item.item?.id === 'plan'); + await plan?.toolbarActions?.find(action => action.label === 'Pin plan')?.run(); + const pinnedInFirst = first.labels(); + + pinScope.set('chat:second', undefined); + const unpinnedInSecond = first.labels(); + pinScope.set('chat:first', undefined); + const restoredInFirst = first.labels(); + + const restored = createPills({ artifacts: { sections } }, undefined, { + pinScope: constObservable('chat:first'), + storageService, + }); + const newController = restored.labels(); + + assert.deepStrictEqual({ pinnedInFirst, unpinnedInSecond, restoredInFirst, newController }, { + pinnedInFirst: ['plan', 'report'], + unpinnedInSecond: ['2 Artifacts'], + restoredInFirst: ['plan', 'report'], + newController: ['plan', 'report'], + }); + }); + + test('keeps a filtered pinned entry stored until it becomes visible again', async () => { + const pullRequestVisibility = createPullRequestVisibility(); + const data = createSessionPullRequestPillData(constObservable([{ + title: 'Pull Requests', + entries: [ + pullRequestEntry('#closed', 'closed'), + pullRequestEntry('#open', 'open'), + ], + }]), pullRequestVisibility); + const pills = createPills({ pullRequests: data }, undefined, { + pinScope: constObservable('chat:filtered'), + }); + const closed = pills.openDropdown().find(item => item.item?.id === '#closed'); + await closed?.toolbarActions?.find(action => action.label === 'Pin #closed')?.run(); + const pinned = pills.labels(); + + pullRequestVisibility.setShowAll(false); + const filtered = pills.labels(); + pullRequestVisibility.setShowAll(true); + const restored = pills.labels(); + + assert.deepStrictEqual({ pinned, filtered, restored }, { + pinned: ['#closed', '#open'], + filtered: ['#open'], + restored: ['#closed', '#open'], + }); + }); + test('a single subagent still opens a picker', () => { const pills = createPills({ subagents: { sections: constObservable([{ title: 'Active subagents', entries: [{ id: 'subagent', label: 'Research', open: () => { } }] }]) }, @@ -400,20 +670,20 @@ suite('StandardChatInputPillSources', () => { const changesMenu = pills.openContextMenu(changes); const artifactsMenu = pills.openContextMenu(artifacts); const referencesMenu = pills.openContextMenu(references); - const submenu = artifactsMenu[2]; + const submenu = artifactsMenu.find(action => action.id === 'chatInputPills.options.artifacts'); assert.ok(submenu instanceof SubmenuAction); await submenu.actions[0].run(); assert.deepStrictEqual({ changes: changesMenu.slice(0, 2).map(action => action.label), - artifacts: artifactsMenu.slice(0, 4).map(action => action.label), - references: referencesMenu.slice(0, 2).map(action => action.label), + artifacts: artifactsMenu.filter(action => ['Pin Report', 'Hide Artifacts', 'Artifacts Options'].includes(action.label)).map(action => action.label), + references: referencesMenu.filter(action => ['Pin Docs', 'Hide References'].includes(action.label)).map(action => action.label), referencesHaveOptions: referencesMenu.some(action => action instanceof SubmenuAction), invoked, }, { changes: ['Changes Options', ''], - artifacts: ['Hide Artifacts', '', 'Artifacts Options', ''], - references: ['Hide References', ''], + artifacts: ['Hide Artifacts', 'Pin Report', 'Artifacts Options'], + references: ['Pin Docs', 'Hide References'], referencesHaveOptions: false, invoked: true, }); @@ -538,7 +808,7 @@ suite('StandardChatInputPillSources', () => { const targets = pills.inputPills.getPillElements(); const menus = [false, true].map(keyboard => targets.map(target => pills.openContextMenu(target, keyboard).map(action => action.label))); - const submenu = pills.openContextMenu(targets[1], true)[2]; + const submenu = pills.openContextMenu(targets[1], true).find(action => action.id === 'chatInputPills.options.pullRequests'); assert.ok(submenu instanceof SubmenuAction); const checked = submenu.actions.map(action => ({ label: action.label, checked: action.checked })); await submenu.actions[0].run(); @@ -548,7 +818,10 @@ suite('StandardChatInputPillSources', () => { const toggles = ['Pull Requests', ...otherKinds]; const expectedMenus = [ ['Pull Requests Options', '', ...toggles], - ...otherKinds.map(label => [`Hide ${label}`, '', 'Pull Requests Options', '', ...toggles]), + ...otherKinds.map(label => [ + ...(['Artifacts', 'References', 'Customizations', 'Subagents'].includes(label) ? ['Pin Item', ''] : []), + `Hide ${label}`, '', 'Pull Requests Options', '', ...toggles, + ]), ]; assert.deepStrictEqual({ menus, checked, restoredOptions, restoredPullRequests: pills.labels()[1] }, { diff --git a/src/vs/workbench/contrib/chat/test/browser/plugins/agentPluginRepositoryService.test.ts b/src/vs/workbench/contrib/chat/test/browser/plugins/agentPluginRepositoryService.test.ts index e4e9b6ad64a83a..63a18339408c29 100644 --- a/src/vs/workbench/contrib/chat/test/browser/plugins/agentPluginRepositoryService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/plugins/agentPluginRepositoryService.test.ts @@ -733,6 +733,39 @@ suite('AgentPluginRepositoryService', () => { assert.strictEqual(clonedRef, 'marketplace'); }); + for (const sourceDescriptor of [ + { kind: PluginSourceKind.GitHub, repo: 'owner/repo', path: 'plugins/test' }, + { kind: PluginSourceKind.GitUrl, url: 'https://example.com/repo.git', path: 'plugins/test' }, + ] satisfies IPluginSourceDescriptor[]) { + for (const sha of [undefined, 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6e7f8a9b0']) { + test(`clones ${sourceDescriptor.kind} sources at ${sha ? 'the pinned SHA instead of the ref' : 'the requested ref'}`, async () => { + const calls: { operation: string; revision: string | undefined }[] = []; + const service = createService(async () => false, undefined, { + cloneRepository: async (_url, _directory, ref) => { calls.push({ operation: 'clone', revision: ref }); }, + checkoutCommit: async (_directory, commit) => { calls.push({ operation: 'checkoutCommit', revision: commit }); }, + checkout: async (_directory, ref) => { calls.push({ operation: 'checkout', revision: ref }); }, + }); + const plugin = { + ...createPlugin('microsoft/vscode', 'plugins/test'), + sourceDescriptor: { ...sourceDescriptor, ref: 'main', sha }, + }; + + const installUri = await service.ensurePluginSource(plugin); + + assert.deepStrictEqual({ + calls, + installPath: installUri.path, + }, { + calls: [ + { operation: 'clone', revision: sha ?? 'main' }, + { operation: sha ? 'checkoutCommit' : 'checkout', revision: sha ?? 'main' }, + ], + installPath: service.getPluginSourceInstallUri(plugin.sourceDescriptor).path, + }); + }); + } + } + test('concurrent ensureRepository calls for the same marketplace clone only once', async () => { let cloneCount = 0; const instantiationService = store.add(new TestInstantiationService()); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxAgentHostService.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxAgentHostService.test.ts index 3315200e11adcf..c52a09d15b4af7 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxAgentHostService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxAgentHostService.test.ts @@ -5,7 +5,7 @@ import assert from 'assert'; import sinon from 'sinon'; -import { DeferredPromise, timeout } from '../../../../../../base/common/async.js'; +import { DeferredPromise, raceCancellationError, timeout } from '../../../../../../base/common/async.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../../base/common/cancellation.js'; import { CancellationError, isCancellationError } from '../../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; @@ -30,6 +30,8 @@ import { type ICloudSandboxClientToken, type ICloudSandboxConnectionRequest, type ICloudSandboxConnectOptions, + type ICloudSandboxIdentityToken, + type IHostEncryptionKey, } from '../../../../../../platform/agentHost/common/cloudSandboxAgentHost.js'; import { IRemoteAgentHostConnectionFactory, IRemoteAgentHostConnectionInfo, IRemoteAgentHostService, RemoteAgentHostConnectionObserver, RemoteAgentHostConnectionStatus, RemoteAgentHostsEnabledSettingId } from '../../../../../../platform/agentHost/common/remoteAgentHostService.js'; import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; @@ -103,6 +105,10 @@ function createService(store: Pick<{ add<T extends { dispose(): void }>(t: T): T const accountChanged = store.add(new Emitter<string | undefined>()); let account: string | undefined = 'account-a'; let ownEnvironment: string | undefined; + const identityRequests: { account: string; forceRefresh: boolean }[] = []; + let identityResult: ((token: CancellationToken) => Promise<ICloudSandboxIdentityToken>) | undefined; + let environmentKeys: readonly IHostEncryptionKey[] | undefined; + let environmentReads = 0; const telemetry = store.add(new CloudSandboxTelemetryService(new class extends mock<ITelemetryService>() { override publicLog2(eventName: string, data?: ITelemetryData): void { events.push({ eventName, data }); } }())); @@ -136,6 +142,14 @@ function createService(store: Pick<{ add<T extends { dispose(): void }>(t: T): T instantiationService.stub(ICloudSandboxApiService, new class extends mock<ICloudSandboxApiService>() { override readonly onDidChangeAccount = accountChanged.event; override async getAccountKey(): Promise<string | undefined> { return account; } + override async getIdentityToken(account: string, token: CancellationToken, forceRefresh = false): Promise<ICloudSandboxIdentityToken> { + identityRequests.push({ account, forceRefresh }); + return identityResult ? identityResult(token) : { token: 'identity-only-token' }; + } + override async getEnvironment(id: string) { + environmentReads++; + return { id, status: 'online' as const, encryption_keys: environmentKeys }; + } override async connect(request: ICloudSandboxConnectionRequest, token: CancellationToken): Promise<CloudSandboxConnectResult> { requests.push({ method: 'connect', request, token }); return nextResult(request); @@ -206,6 +220,10 @@ function createService(store: Pick<{ add<T extends { dispose(): void }>(t: T): T }, requestCalls: () => calls, requests, + identityRequests, + setIdentityResult: (value: (token: CancellationToken) => Promise<ICloudSandboxIdentityToken>) => { identityResult = value; }, + environmentReads: () => environmentReads, + setEnvironmentKeys: (keys: readonly IHostEncryptionKey[] | undefined) => { environmentKeys = keys; }, events, powerSuspend, powerResume, @@ -239,6 +257,99 @@ suite('CloudSandboxAgentHostService', () => { teardown(() => sinon.restore()); + test('user-local hosts seal identity credentials after the handshake without requiring a broker envelope', async () => { + const key = { key_id: 'GpLyOFLckI0', public_key: 'pOCSkrZRwni5dyxWn1+puxPZBrRqtoyd+dwrRAn4ogk=', algorithm: 'x25519-sealedbox', use: 'auth-token' as const }; + const fixture = createService(store, [{ kind: 'token', token: clientToken(undefined) }]); + fixture.service.connectThroughFactory = true; + const connecting = fixture.service.connect({ + environmentId: 'native', name: 'Native', environmentKind: 'user-local', trustedEncryptionKeys: [key], + }, CancellationToken.None); + await fixture.started; + fixture.settle(); + await connecting; + fixture.instantiationService.stubInstance(AgentHostProtocolClient, new class extends mock<AgentHostProtocolClient>() { + override readonly onDidConnectionDiagnostic = Event.None; + }()); + const spy = sinon.spy(fixture.instantiationService, 'createInstance'); + const created = await fixture.getFactory().createConnection(fixture.entries()[0], { userInitiated: true }); + assert.ok(created.transportDisposable); + store.add(created.transportDisposable); + const options = spy.getCalls().find(call => call.args[0] === AgentHostProtocolClient)?.args[3] as IAgentHostProtocolClientOptions; + assert.ok(options.resolveInitialAuthentication && options.sealAuthenticationToken); + const identity = await options.resolveInitialAuthentication(); + assert.ok(identity); + const token = await options.sealAuthenticationToken({ ...identity, key, challenge: 'a'.repeat(32) }); + fixture.setEnvironmentKeys([key]); + await assert.rejects(options.sealAuthenticationToken({ ...identity, key: { ...key, public_key: 'substituted' } }), /does not match/); + const renewed = await fixture.service.resolveUserLocalAuthentication('native', identity.resource, true); + assert.deepStrictEqual({ + identity, renewed, sealed: token.startsWith('copilot-sealed.v1.GpLyOFLckI0.'), + identityRequests: fixture.identityRequests, controlPlaneRequests: fixture.requestCalls(), environmentReads: fixture.environmentReads(), + }, { + identity: { resource: 'https://api.github.com', token: 'identity-only-token' }, + renewed: { resource: 'https://api.github.com', token: 'identity-only-token' }, + sealed: true, identityRequests: [{ account: 'account-a', forceRefresh: false }, { account: 'account-a', forceRefresh: true }], + controlPlaneRequests: 1, environmentReads: 1, + }); + }); + + for (const authentication of ['initial', 'renewal'] as const) { + for (const teardown of ['connection disposal', 'disconnect', 'service disposal', 'account change', 'replace'] as const) { + test(`cancels user-local ${authentication} identity requests on ${teardown}`, async () => { + const fixture = createService(store, [{ kind: 'token', token: clientToken(undefined) }]); + fixture.service.connectThroughFactory = true; + const connecting = fixture.service.connect({ + environmentId: 'native', name: 'Native', environmentKind: 'user-local', + }, CancellationToken.None); + await fixture.started; + fixture.settle(); + await connecting; + fixture.instantiationService.stubInstance(AgentHostProtocolClient, new class extends mock<AgentHostProtocolClient>() { + override readonly onDidConnectionDiagnostic = Event.None; + }()); + const spy = sinon.spy(fixture.instantiationService, 'createInstance'); + const factory = fixture.getFactory(); + const created = await factory.createConnection(fixture.entries()[0], { userInitiated: true }); + assert.ok(created.transportDisposable); + store.add(created.transportDisposable); + const options = spy.getCalls().find(call => call.args[0] === AgentHostProtocolClient)?.args[3] as IAgentHostProtocolClientOptions; + assert.ok(options.resolveInitialAuthentication); + const requested = new DeferredPromise<CancellationToken>(); + const response = new DeferredPromise<ICloudSandboxIdentityToken>(); + fixture.setIdentityResult(token => { + requested.complete(token); + return raceCancellationError(response.p, token); + }); + const pending = authentication === 'initial' ? options.resolveInitialAuthentication() + : fixture.service.resolveUserLocalAuthentication('native', 'https://api.github.com', true); + const cancelled = assert.rejects(pending, isCancellationError); + const token = await requested.p; + if (teardown === 'connection disposal') { + created.transportDisposable.dispose(); + } else if (teardown === 'disconnect') { + await fixture.service.disconnect('native'); + } else if (teardown === 'service disposal') { + fixture.service.dispose(); + } else if (teardown === 'account change') { + fixture.changeAccount('account-b'); + } else { + const stagingFactory = factory as IRemoteAgentHostConnectionFactory & { + stageConfiguration(options: ICloudSandboxConnectOptions, token: ICloudSandboxClientToken): void; + }; + stagingFactory.stageConfiguration({ environmentId: 'native', name: 'Replacement', environmentKind: 'user-local' }, clientToken(undefined)); + } + await cancelled; + await response.complete({ token: 'late-identity' }); + await assert.rejects(options.resolveInitialAuthentication(), isCancellationError); + assert.deepStrictEqual({ + cancelled: token.isCancellationRequested, requests: fixture.identityRequests, + }, { + cancelled: true, requests: [{ account: 'account-a', forceRefresh: authentication === 'renewal' }], + }); + }); + } + } + for (const environmentKind of ['user-local', undefined] as const) { test(`captures wire traffic only on the ${environmentKind ? 'host for Mission Control' : 'client for cloud sandboxes'}`, async () => { const fixture = createService(store, [{ kind: 'token', token: clientToken('copilot-sealed.v1.key.box') }]); @@ -346,7 +457,7 @@ suite('CloudSandboxAgentHostService', () => { const transportOptions = transportCall.args[1] as IWebPubSubRelayTransportOptions; assert.strictEqual(transport.clientConnectionKind, AgentHostClientConnectionKind.MissionControl); assert.strictEqual(new URL(transportOptions.url).searchParams.get('access_token'), 'fresh-ticket'); - assert.deepStrictEqual(await options.resolveInitialAuthentication(), { resource: 'https://api.github.com', token: initial.encrypted_github_token }); + assert.deepStrictEqual(await options.resolveInitialAuthentication(), { resource: 'https://api.github.com', token: 'identity-only-token' }); await timeout(30_000); fixture.setReconnectResult({ kind: 'token', token: { ...clientToken(undefined), host_encryption_key: { ...key, key_id: 'different' } } }); await assert.rejects(options.prepareReconnect(), /could not be refreshed/); @@ -747,6 +858,7 @@ suite('CloudSandboxAgentHostService', () => { let refreshCalls = 0; const refreshTimes: number[] = []; fixture.instantiationService.stub(ICloudSandboxApiService, new class extends mock<ICloudSandboxApiService>() { + override async getIdentityToken(): Promise<ICloudSandboxIdentityToken> { return { token: 'identity-only-token' }; } override async reconnect(request: Parameters<ICloudSandboxApiService['reconnect']>[0]): Promise<CloudSandboxConnectResult> { request.onRequest?.('issued'); refreshCalls++; @@ -947,7 +1059,7 @@ suite('CloudSandboxAgentHostService', () => { requests: fixture.refreshCalls(), ticket: new URL(transportOptions.url).searchParams.get('access_token'), sealed: authentication?.token, - }, { requests: 1, ticket: 'fresh-ticket', sealed: 'copilot-sealed.v1.key.fresh' }); + }, { requests: 1, ticket: 'fresh-ticket', sealed: environmentKind === 'user-local' ? 'identity-only-token' : 'copilot-sealed.v1.key.fresh' }); transport.dispose(); })); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxApiService.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxApiService.test.ts index 9ea0dc51d8e434..b236fc0549f565 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxApiService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxApiService.test.ts @@ -31,6 +31,7 @@ import { AuthenticationSession, AuthenticationSessionsChangeEvent, IAuthenticati import { CloudSandboxApiService } from '../../../browser/remoteAgentHost/cloudSandboxApiService.js'; import { ICloudSandboxTelemetryService } from '../../../browser/remoteAgentHost/cloudSandboxTelemetry.js'; import { IWorkbenchGitHubService } from '../../../../../services/github/common/githubService.js'; +import { EnvironmentsClient } from '../../../../../../platform/github/common/missionControl/environmentsClient.js'; function jsonResponse(body: unknown, statusCode = 200, headers: Record<string, string> = {}): IRequestContext { return { @@ -205,9 +206,11 @@ function createService(store: Pick<{ add<T extends { dispose(): void }>(t: T): T return jsonResponse({ tasks: slice }, 200, { link, date: options.discoveryDate?.() ?? new Date().toUTCString() }); } }()); + let selectedSessions: readonly AuthenticationSession[] = []; instantiationService.stub(IAuthenticationService, new class extends mock<IAuthenticationService>() { override async getSessions(_providerId: string, scopes?: readonly string[]) { - return options.authenticationSessions ? options.authenticationSessions(scopes) : [{ accessToken: 'tok', id: 's', account: { id: 'a', label: 'a' }, scopes: [] }]; + selectedSessions = options.authenticationSessions ? await options.authenticationSessions(scopes) : [{ accessToken: 'tok', id: 's', account: { id: 'a', label: 'a' }, scopes: [] }]; + return selectedSessions; } override readonly onDidChangeSessions = authenticationChanges.event; override readonly onDidRegisterAuthenticationProvider = providerRegistered.event; @@ -225,17 +228,18 @@ function createService(store: Pick<{ add<T extends { dispose(): void }>(t: T): T }()); instantiationService.stub(IWorkbenchGitHubService, new class extends mock<IWorkbenchGitHubService>() { override async acquireAccountApiClient(authorization: IGitHubAccountClient['authorization']): Promise<IGitHubAccountClient> { - assert.deepStrictEqual(authorization, { - providerId: 'github', sessionId: 's', accountId: 'a', scopes: [], authorizationServer: undefined, - }); + const session = selectedSessions.find(session => session.id === authorization.sessionId && session.account.id === authorization.accountId); + assert.ok(session); + assert.strictEqual(authorization.providerId, 'github'); const provider = new class extends BufferedApiRequestProvider { - protected override async execute(request: Omit<ApiRequest, 'body'>, signal: AbortSignal): Promise<ApiResponse<string | undefined>> { + protected override async execute(request: Omit<ApiRequest, 'body'>, signal: AbortSignal, bodyText?: string): Promise<ApiResponse<string | undefined>> { const lifetime = new DisposableStore(); try { const token = CancellationToken.fromAbortSignal(signal, lifetime); const context = await requests.request({ type: request.method, url: `https://api.github.com/cmc_internal/api/agents${request.path}`, - headers: { Authorization: 'test-token', 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID }, + headers: { Authorization: `Bearer ${session.accessToken}`, 'Copilot-Integration-Id': COPILOT_INTEGRATION_ID, ...(bodyText === undefined ? {} : { 'Content-Type': 'application/json' }) }, + ...(bodyText === undefined ? {} : { data: bodyText }), callSite: request.options?.caller ?? 'test', }, token); const status = context.res.statusCode!; @@ -251,6 +255,7 @@ function createService(store: Pick<{ add<T extends { dispose(): void }>(t: T): T }(); return new class extends mock<IGitHubAccountClient>() { override readonly tasks = new TasksClient(new MissionControlClient(provider)); + override readonly environments = new EnvironmentsClient(new MissionControlClient(provider)); override dispose(): void { } }(); } @@ -896,7 +901,7 @@ suite('CloudSandboxApiService session feed', () => { { url: 'wss://user:password@feed.example.test/' }, { url: 'wss://feed.example.test/#secret' }, { reconnect_after: new Date(0).toISOString() }, - { reconnect_after: new Date(Date.now() + 20 * 60_000).toISOString() }, + { get reconnect_after() { return new Date(Date.now() + 20 * 60_000).toISOString(); } }, { frame_schema_version: 2 }, { subprotocol: 'json.reliable.webpubsub.azure.v1' }, { group: '' }, diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxConnectionCustomization.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxConnectionCustomization.test.ts index 02837775583984..f481afafe4024e 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxConnectionCustomization.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/cloudSandboxConnectionCustomization.test.ts @@ -70,19 +70,14 @@ suite('CloudSandboxConnectionCustomization authentication', () => { }); }); - test('user-local MCP renewal stays on the trusted workbench sealing path', async () => { - const requests: string[] = []; + test('user-local MCP renewal without a target remains raw until the trusted protocol send boundary', async () => { const service = new class extends mock<ICloudSandboxAgentHostService>() { }(); - const customization = createCloudSandboxConnectionCustomization(cloudSandboxAddress('env-1'), service, true, async request => { - requests.push(request.resource); - return { ...request, token: 'copilot-sealed.v1.mcp.fresh' }; - }); + const customization = createCloudSandboxConnectionCustomization(cloudSandboxAddress('env-1'), service, true); assert.ok(customization?.authenticate); const request = { resource: 'https://mcp.example.test', scopes: ['mcp'], token: 'test-mcp-token' }; const result = await customization.authenticate(request, AuthRequiredReason.Expired); - assert.deepStrictEqual({ result, requests, renewal: customization.renewAuthentication }, { - result: { ...request, token: 'copilot-sealed.v1.mcp.fresh' }, - requests: ['https://mcp.example.test'], + assert.deepStrictEqual({ result, renewal: customization.renewAuthentication }, { + result: request, renewal: undefined, }); }); @@ -100,10 +95,29 @@ suite('CloudSandboxConnectionCustomization authentication', () => { test('user-local MCP targets use MCP sealing even at the provider resource origin', async () => { const service = new class extends mock<ICloudSandboxAgentHostService>() { }(); - const customization = createCloudSandboxConnectionCustomization(cloudSandboxAddress('env-1'), service, true, async request => ({ ...request, token: 'copilot-sealed.v1.mcp.fresh' })); + const customization = createCloudSandboxConnectionCustomization(cloudSandboxAddress('env-1'), service, true); const target: McpServerAuthenticateTarget = { kind: AuthenticateTargetKind.McpServer, session: 'other-agent://tenant/conversations/opaque-session', customizationId: 'opaque/github/server' }; const request = { target, resource: 'https://api.github.com', token: 'test-mcp-token' }; - assert.deepStrictEqual(await customization?.authenticate?.(request), { ...request, token: 'copilot-sealed.v1.mcp.fresh' }); + assert.deepStrictEqual(await customization?.authenticate?.(request), request); + }); + + test('user-local provider authentication uses identity tokens rather than broker ciphertext or the workbench bearer', async () => { + const calls: boolean[] = []; + const service = new class extends mock<ICloudSandboxAgentHostService>() { + override async resolveUserLocalAuthentication(_id: string, resource: string, renew = false) { + calls.push(renew); + return { resource, token: 'identity-token', expiresIn: 120 }; + } + }(); + const customization = createCloudSandboxConnectionCustomization(cloudSandboxAddress('env-1'), service, true); + const request = { resource: 'https://api.github.com', scopes: ['read'], token: 'workbench-bearer' }; + const ordinary = await customization?.authenticate?.(request); + const renewed = await customization?.authenticate?.(request, AuthRequiredReason.Expired); + assert.deepStrictEqual({ ordinary, renewed, calls }, { + ordinary: { resource: request.resource, token: 'identity-token', expiresIn: 120, scopes: ['read'] }, + renewed: { resource: request.resource, token: 'identity-token', expiresIn: 120, scopes: ['read'] }, + calls: [false, true], + }); }); for (const token of ['plaintext', 'copilot-sealed.v1.key.challenged']) { diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlCredentialSealing.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlCredentialSealing.test.ts index 1d1e3d3ecae8ec..e588d6282bf0a3 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlCredentialSealing.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlCredentialSealing.test.ts @@ -6,23 +6,17 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import type { IMissionControlCredentialSealingRequest } from '../../../../../../platform/agentHost/common/agentService.js'; -import { createRootState } from '../../../../../../platform/agentHost/common/state/sessionState.js'; -import { sealMissionControlMcpCredential } from '../../../browser/remoteAgentHost/missionControlCredentialSealing.js'; +import { verifyMissionControlRecipient } from '../../../browser/remoteAgentHost/missionControlCredentialSealing.js'; -suite('Mission Control MCP recipient trust', () => { +suite('Mission Control recipient trust', () => { ensureNoDisposablesAreLeakedInTestSuite(); const key = { key_id: 'key', use: 'mcp-auth-token', algorithm: 'x25519-sealedbox', public_key: 'public' }; - const root = () => ({ ...createRootState(), _meta: { 'copilot.encryptionKeys': [{ keyId: key.key_id, use: key.use, algorithm: key.algorithm, publicKey: key.public_key }] } }); - const request = { resource: 'https://mcp.example.test', token: 'sensitive-test-token', scopes: ['read'] }; + const request: IMissionControlCredentialSealingRequest = { resource: 'https://mcp.example.test', token: 'sensitive-test-token', key: { ...key, use: 'mcp-auth-token' } }; - test('requires the same HTTPS descriptor and live host key before disclosing to local sealing', async () => { - const calls: IMissionControlCredentialSealingRequest[] = []; - const seal = async (value: IMissionControlCredentialSealingRequest) => { calls.push(value); return 'copilot-sealed.v1.test.box'; }; - await assert.rejects(sealMissionControlMcpCredential(request, undefined, root(), undefined, seal), /authenticated MCP/); - await assert.rejects(sealMissionControlMcpCredential(request, [{ ...key, public_key: 'substituted' }], root(), undefined, seal), /does not match/); - assert.strictEqual(calls.length, 0); - const result = await sealMissionControlMcpCredential(request, [key], root(), { 'copilot.authChallenge': { challenge: 'a'.repeat(32), required: false } }, seal); - assert.deepStrictEqual(result, { ...request, token: 'copilot-sealed.v1.test.box' }); - assert.deepStrictEqual(calls, [{ resource: request.resource, token: request.token, key, challenge: 'a'.repeat(32) }]); + test('requires every recipient field to match the independently authenticated descriptor', () => { + for (const keys of [undefined, [], [{ ...key, public_key: 'substituted' }], [{ ...key, key_id: 'other' }], [{ ...key, use: 'auth-token' }], [{ ...key, algorithm: 'unknown' }]]) { + assert.throws(() => verifyMissionControlRecipient(request, keys), /does not match/); + } + assert.doesNotThrow(() => verifyMissionControlRecipient(request, [key])); }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlEnvironmentService.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlEnvironmentService.test.ts index a982d953abd7c4..c84e8d0ed9d412 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlEnvironmentService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/missionControlEnvironmentService.test.ts @@ -35,6 +35,17 @@ function host(id: string, name = 'Machine', status = 'online'): IMissionControlE suite('Mission Control inventory', () => { const store = ensureNoDisposablesAreLeakedInTestSuite(); + test('passes independently authenticated recipient keys to connection admission', async () => { + const context = fixture(); + const keys = [{ key_id: 'key', public_key: 'public', use: 'auth-token', algorithm: 'x25519-sealedbox' }]; + context.setEnvironment(Promise.resolve({ id: 'remote', status: 'online', encryption_keys: keys })); + await context.service.refresh(CancellationToken.None); + await context.service.connect('remote', CancellationToken.None); + assert.deepStrictEqual(context.calls.connects, [{ + environmentId: 'remote', name: 'Machine', environmentKind: 'user-local', trustedEncryptionKeys: keys, + }]); + }); + function fixture(storage = store.add(new InMemoryStorageService()), initialAccount: string | undefined = firstAccount, built = true, extensionDevelopment = false) { const instantiation = store.add(new TestInstantiationService()); const accountChanged = store.add(new Emitter<string | undefined>()); diff --git a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostChatContribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostChatContribution.test.ts index 9e17ab8685f8d4..26d318ac72c4bf 100644 --- a/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostChatContribution.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/remoteAgentHost/remoteAgentHostChatContribution.test.ts @@ -162,19 +162,14 @@ suite('Remote Agent Host silent MCP authentication', () => { assert.strictEqual(context.opened.length, 0); }); - test('seals remembered MCP credentials through the user-local connection customization', async () => { - const sealed: AuthenticateParams[] = []; + test('forwards remembered MCP credentials to the user-local protocol sealing boundary', async () => { const customization = createCloudSandboxConnectionCustomization('cloudsandbox:remote', - new class extends mock<ICloudSandboxAgentHostService>() { }(), true, async params => { - sealed.push(params); - return { ...params, token: 'copilot-sealed.v1.mcp.ciphertext' }; - }); + new class extends mock<ICloudSandboxAgentHostService>() { }(), true); const context = fixture(customization); const authenticated = await context.authenticate(request); - assert.deepStrictEqual({ authenticated, sealed, sent: context.sent, silent: context.sessionOptions }, { + assert.deepStrictEqual({ authenticated, sent: context.sent, silent: context.sessionOptions }, { authenticated: true, - sealed: [{ target: request.target, resource: 'https://docs.example/mcp', scopes: ['read'], token: 'docs-token' }], - sent: [{ target: request.target, resource: 'https://docs.example/mcp', scopes: ['read'], token: 'copilot-sealed.v1.mcp.ciphertext' }], + sent: [{ target: request.target, resource: 'https://docs.example/mcp', scopes: ['read'], token: 'docs-token' }], silent: [true], }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/sessionPullRequestPill.test.ts b/src/vs/workbench/contrib/chat/test/browser/sessionPullRequestPill.test.ts index f1e8ebd6ca0c48..bbe130685e142d 100644 --- a/src/vs/workbench/contrib/chat/test/browser/sessionPullRequestPill.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/sessionPullRequestPill.test.ts @@ -9,6 +9,7 @@ import { autorun, constObservable, observableValue } from '../../../../../base/c import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { StorageScope, StorageTarget } from '../../../../../platform/storage/common/storage.js'; import { TestStorageService } from '../../../../test/common/workbenchTestServices.js'; +import { getChatPillEntryToolbarActions } from '../../../../browser/chatPills.js'; import { createSessionPullRequestPillData, type IChatPullRequestPillSection } from '../../browser/sessionPullRequestPill.js'; import { SessionChatPillVisibility } from '../../common/sessionChatPills.js'; @@ -123,7 +124,7 @@ suite('SessionPullRequestPillData', () => { }]); const data = createSessionPullRequestPillData(input, visibility); const read = () => ({ - toolbars: data.sections.get().flatMap(section => section.entries.map(entry => entry.toolbarActions?.map(action => action.id) ?? [])), + rowActions: data.sections.get().flatMap(section => section.entries.map(entry => getChatPillEntryToolbarActions(entry).map(action => action.id))), contextMenu: data.getContextMenuPrimaryActions().map(action => action.id), }); const multiple = read(); @@ -140,11 +141,11 @@ suite('SessionPullRequestPillData', () => { input.set([], undefined); assert.deepStrictEqual({ multiple, singleVisible, singleRemaining, copyOnly, empty: read(), copied, removed }, { - multiple: { toolbars: [['copy', 'remove'], []], contextMenu: [] }, - singleVisible: { toolbars: [['copy']], contextMenu: ['copy', 'remove'] }, - singleRemaining: { toolbars: [['copy']], contextMenu: ['copy', 'remove'] }, - copyOnly: { toolbars: [['copy']], contextMenu: ['copy'] }, - empty: { toolbars: [], contextMenu: [] }, + multiple: { rowActions: [['copy', 'remove'], []], contextMenu: [] }, + singleVisible: { rowActions: [['copy', 'remove']], contextMenu: ['copy', 'remove'] }, + singleRemaining: { rowActions: [['copy', 'remove']], contextMenu: ['copy', 'remove'] }, + copyOnly: { rowActions: [['copy']], contextMenu: ['copy'] }, + empty: { rowActions: [], contextMenu: [] }, copied: ['https://github.com/microsoft/vscode/pull/1'], removed: ['open'], }); diff --git a/src/vs/workbench/contrib/chat/test/browser/tools/toolSetsContribution.test.ts b/src/vs/workbench/contrib/chat/test/browser/tools/toolSetsContribution.test.ts index 49684f7b05f404..c850781e2dce40 100644 --- a/src/vs/workbench/contrib/chat/test/browser/tools/toolSetsContribution.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/tools/toolSetsContribution.test.ts @@ -92,6 +92,28 @@ suite('ToolSetsContribution', () => { }); }); + test('ClientToolSetsContribution exposes Sessions List tools only in the Sessions window', () => { + const createContribution = (isSessionsWindow: boolean) => { + const toolsService = createToolsService(); + for (const name of ['readSessionsList', 'organizeSessionsList']) { + store.add(toolsService.registerToolData({ id: name, modelDescription: name, displayName: name, toolReferenceName: name, source: ToolDataSource.Internal })); + } + const workspaceService = new class extends mock<IAICustomizationWorkspaceService>() { + override readonly isSessionsWindow = isSessionsWindow; + }(); + store.add(new ClientToolSetsContribution(toolsService, workspaceService)); + return toolsService; + }; + + assert.deepStrictEqual({ + sessionsMembers: Array.from(createContribution(true).getToolSet('vscode-sessions-list')?.getTools() ?? [], tool => tool.toolReferenceName), + coreHasSet: !!createContribution(false).getToolSet('vscode-sessions-list'), + }, { + sessionsMembers: ['readSessionsList', 'organizeSessionsList'], + coreHasSet: false, + }); + }); + test('getEnabledSelectionReferences keeps enabled tool set references and drops covered tools', () => { const toolsService = createToolsService(); diff --git a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts index afcf3da8aedf18..aa14740aa3e578 100644 --- a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceClientService.test.ts @@ -1233,7 +1233,7 @@ suite('VoiceClientService', () => { }); }); - test('does not submit a voice-answered turn with a later delegated turn', async () => { + test('delegates the current turn with voice-only history as context, not as another request', async () => { const peer = new TestRtcPeerConnection(); const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); const calls: string[] = []; @@ -1249,9 +1249,212 @@ suite('VoiceClientService', () => { peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Fix the tests', is_final: true }); peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'delegation-coding' } }); - assert.deepStrictEqual(calls, ['Fix the tests']); + assert.deepStrictEqual(calls, ['Voice conversation context:\nUser: Which session am I in?\nVoice assistant: You are in Alpha.\n\nUser: Fix the tests']); }); + for (const finishesDuringAnswer of [false, true]) { + test(`does not retain a voice-only answer while work is in progress${finishesDuringAnswer ? ', even if work finishes during the answer' : ''}`, async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + const context: IVoiceSessionContext = { sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'thinking' }], display_locale: 'en-US' }; + service.sendStartSession(context, 'machine'); + service.sendPttStart('question', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'What is TypeScript?', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'TypeScript adds optional static types to JavaScript.' }); + if (finishesDuringAnswer) { + service.sendSessionContext({ ...context, sessions: [{ ...context.sessions[0], agent_state: 'idle' }] }); + } + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: ' I have printed one through twenty.' }); + const inputs = Reflect.get(service, '_gptLiveInputs') as { text: string; context?: string; voiceResponse?: string }[]; + const storedAnswer = { context: inputs[0].context, voiceResponse: inputs[0].voiceResponse }; + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Okay, now create a file for me', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'request-delegation' } }); + + assert.deepStrictEqual({ storedAnswer, retiredQuestion: inputs[0].text, calls }, { + storedAnswer: { context: undefined, voiceResponse: undefined }, + retiredQuestion: '', + calls: ['Okay, now create a file for me'], + }); + }); + } + + test('clears idle voice context when work starts, including a partially transcribed reply', async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + const context: IVoiceSessionContext = { sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }; + service.sendStartSession(context, 'machine'); + service.sendPttStart('initial', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Light or dark?' }); + service.sendPttStart('reply', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'What is ' }); + service.sendSessionContext({ ...context, sessions: [{ ...context.sessions[0], agent_state: 'thinking' }] }); + service.sendSessionContext(context); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'TypeScript?', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'TypeScript adds types to JavaScript.' }); + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Create a file', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'request-delegation' } }); + + assert.deepStrictEqual(calls, ['Create a file']); + }); + + for (const sessionId of ['chat-session:/a', undefined]) { + test(`preserves GPT-Live clarification questions when handing off to ${sessionId ? 'an existing chat' : 'the new-session composer'}`, async () => { + const clock = sinon.useFakeTimers(); + try { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: IVoiceToolCall[] = []; + const transcriptions: IVoiceTranscription[] = []; + store.add(service.onToolCall(event => calls.push(event))); + store.add(service.onTranscription(event => transcriptions.push(event))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession({ sessions: sessionId ? [{ id: sessionId, is_active: true, agent_state: 'idle' }] : [], display_locale: 'en-US' }, 'machine'); + service.sendPttStart('request', { hasActiveSession: !!sessionId }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Should it be ' }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'light or dark?' }); + await clock.tickAsync(750); + service.sendPttStart('answer', { hasActiveSession: !!sessionId, passive: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Dark', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + + assert.deepStrictEqual({ calls, transcriptions }, { + calls: [{ + callId: 'answer-delegation', name: 'send_to_chat', turnId: 'answer', + args: { + text: 'Voice conversation context:\nUser: Add a theme\nVoice assistant: Should it be light or dark?\n\nUser: Dark', + ...(sessionId ? { coding_session_id: sessionId } : {}), + }, + }], + transcriptions: [ + { text: 'Add a theme', status: 'final', turnId: 'request' }, + { text: 'Dark', status: 'final', turnId: 'answer' }, + ], + }); + } finally { + clock.restore(); + } + }); + } + + test('preserves multiple voice-only exchanges and snapshots context before the delegated answer', async () => { + const clock = sinon.useFakeTimers(); + try { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession({ sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }, 'machine'); + for (const [text, response] of [['Add a theme', 'Light or dark?'], ['Dark', 'Which accent color?']]) { + service.sendPttStart(text, { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: text, is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: response }); + await clock.tickAsync(750); + } + service.sendPttStart('answer', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Blue', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'I will send that to chat.' }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + service.sendPttStart('next', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Run the tests', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'next-delegation' } }); + + assert.deepStrictEqual(calls, [ + 'Voice conversation context:\nUser: Add a theme\nVoice assistant: Light or dark?\n\nUser: Dark\nVoice assistant: Which accent color?\n\nUser: Blue', + 'Run the tests', + ]); + } finally { + clock.restore(); + } + }); + + test('preserves a direct voice question spoken after a chat handoff', async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: string[] = []; + store.add(service.onToolCall(event => calls.push(String(event.args.text)))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession({ sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }, 'machine'); + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'request-delegation' } }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Should it be light or dark?' }); + service.sendPttStart('answer', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Dark', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + + assert.deepStrictEqual(calls, [ + 'Add a theme', + 'Voice conversation context:\nUser: Add a theme\nVoice assistant: Should it be light or dark?\n\nUser: Dark', + ]); + }); + + for (const change of ['session', 'target', 'reconnect', 'question', 'approval'] as const) { + test(`does not carry voice-only context across a ${change} change`, async () => { + const peer = new TestRtcPeerConnection(); + const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); + const calls: IVoiceToolCall[] = []; + store.add(service.onToolCall(event => calls.push(event))); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + const context: IVoiceSessionContext = { sessions: [{ id: 'chat-session:/a', is_active: true, agent_state: 'idle' }], display_locale: 'en-US' }; + service.sendStartSession(context, 'machine'); + service.sendPttStart('request', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: 'Add a theme', is_final: true }); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'Light or dark?' }); + if (change === 'session') { + service.sendSessionContext({ ...context, sessions: [{ ...context.sessions[0], id: 'chat-session:/b' }] }); + } else if (change === 'target') { + service.prepareForInputTargetChange(); + peer.channel.fireMessage({ type: 'session.output_transcript.delta', delta: 'More speech from the previous input target.' }); + } else if (change === 'reconnect') { + service.disconnect(); + await service.connect(createTestWindow()); + peer.channel.fireMessage({ type: 'session.started' }); + service.sendStartSession(context, 'machine'); + } else { + service.sendSessionContext({ + ...context, + sessions: [{ + ...context.sessions[0], agent_state: 'waiting_for_confirmation', + pending: { + type: change === 'question' ? 'questions' : 'approval', request_id: 'request', pending_id: 'pending', + ...(change === 'question' ? { questions: [{ id: 'theme', title: 'Theme?', type: 'text', options: [], allow_freeform: true }] } : {}), + }, + }], + }); + } + service.sendPttStart('answer', { hasActiveSession: true }); + peer.channel.fireMessage({ type: 'session.input_transcript.delta', delta: change === 'approval' ? 'approve' : 'Dark', is_final: true }); + peer.channel.fireMessage({ type: 'session.delegation.created', delegation: { id: 'answer-delegation' } }); + + assert.deepStrictEqual(calls, [{ + callId: 'answer-delegation', turnId: 'answer', + name: change === 'question' || change === 'approval' ? 'respond_to_session' : 'send_to_chat', + args: change === 'question' || change === 'approval' ? { + coding_session_id: 'chat-session:/a', request_id: 'request', pending_id: 'pending', + response: change === 'approval' ? { type: 'approve' } : { type: 'answer', answers: [{ question_id: 'theme', freeform: 'Dark' }] }, + } : { text: 'Dark', coding_session_id: change === 'session' ? 'chat-session:/b' : 'chat-session:/a' }, + }]); + }); + } + test('routes an annotated session-navigation transcript as an ordinary chat request', async () => { const peer = new TestRtcPeerConnection(); const service = store.add(new TestGptLiveVoiceClientService(peer, new TestMicCaptureService(new TestMediaStream(new TestMediaStreamTrack())), productService)); diff --git a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts index bae8a8f26c87e3..baa117f9909641 100644 --- a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceInputUtils.test.ts @@ -5,9 +5,12 @@ import assert from 'assert'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; -import { mock } from '../../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { IChatWidget } from '../../../browser/chat.js'; import { acceptVoiceInput, combineVoiceInput } from '../../../browser/voiceClient/voiceInputUtils.js'; +import { ChatRequestQueueKind } from '../../../common/chatService/chatService.js'; +import { constObservable } from '../../../../../../base/common/observable.js'; +import { IChatModel } from '../../../common/model/chatModel.js'; suite('combineVoiceInput', () => { ensureNoDisposablesAreLeakedInTestSuite(); @@ -36,18 +39,53 @@ suite('combineVoiceInput', () => { suite('acceptVoiceInput', () => { ensureNoDisposablesAreLeakedInTestSuite(); - test('preserves typed input, focus and voice-progress options in the owning widget', async () => { - const sent: { text: string | undefined; options: Parameters<IChatWidget['acceptInput']>[1] }[] = []; - const widget = new class extends mock<IChatWidget>() { - override readonly viewModel = new class extends mock<NonNullable<IChatWidget['viewModel']>>() { }(); - override getInput(): string { return 'Typed draft'; } - override async acceptInput(text?: string, options?: Parameters<IChatWidget['acceptInput']>[1]) { - sent.push({ text, options }); - return undefined; - } - }(); - await acceptVoiceInput(widget, 'spoken request', true); - assert.deepStrictEqual(sent, [{ text: 'Typed draft spoken request', options: { preserveFocus: true, isVoiceModeInput: true } }]); + for (const inProgress of [false, true]) { + test(`preserves typed input, focus and voice-progress options and ${inProgress ? 'steers an active request' : 'sends normally when idle'}`, async () => { + const sent: { text: string | undefined; options: Parameters<IChatWidget['acceptInput']>[1] }[] = []; + const widget = new class extends mock<IChatWidget>() { + override readonly viewModel = new class extends mock<NonNullable<IChatWidget['viewModel']>>() { + override readonly model = new class extends mock<IChatModel>() { + override readonly requestInProgress = constObservable(inProgress); + }(); + }(); + override getInput(): string { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters<IChatWidget['acceptInput']>[1]) { + sent.push({ text, options }); + return undefined; + } + }(); + await acceptVoiceInput(widget, 'spoken request', true); + assert.deepStrictEqual(sent, [{ + text: 'Typed draft spoken request', + options: { preserveFocus: true, isVoiceModeInput: true, ...(inProgress ? { queue: ChatRequestQueueKind.Steering } : {}) }, + }]); + }); + } + + for (const hasModel of [false, true]) { + test(`submits normally when ${hasModel ? 'request progress' : 'the model'} is unavailable`, async () => { + const sent: { text: string | undefined; options: Parameters<IChatWidget['acceptInput']>[1] }[] = []; + const widget = new class extends mock<IChatWidget>() { + override readonly viewModel = upcastPartial<NonNullable<IChatWidget['viewModel']>>({ + ...(hasModel ? { model: upcastPartial<IChatModel>({}) } : {}), + }); + override getInput(): string { return 'Typed draft'; } + override async acceptInput(text?: string, options?: Parameters<IChatWidget['acceptInput']>[1]) { + sent.push({ text, options }); + return undefined; + } + }(); + await acceptVoiceInput(widget, 'spoken request', true); + assert.deepStrictEqual(sent, [{ + text: 'Typed draft spoken request', + options: { preserveFocus: true, isVoiceModeInput: true }, + }]); + }); + } + + test('rejects input when the widget has no view model', () => { + const widget = new class extends mock<IChatWidget>() { }(); + assert.strictEqual(acceptVoiceInput(widget, 'spoken request', true), false); }); test('populates an edited request for review rather than submitting it', async () => { diff --git a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts index 7fd8db1404e681..d53a1100c7b3fc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/voiceClient/voiceSessionController.test.ts @@ -12,7 +12,7 @@ import { Emitter, Event } from '../../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../../base/common/htmlContent.js'; import { autorun, derived, ISettableObservable, observableFromEvent, observableValue } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; -import { mock } from '../../../../../../base/test/common/mock.js'; +import { mock, upcastPartial } from '../../../../../../base/test/common/mock.js'; import { IAgentHostConnectionsService } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; import { IAccessibilityService } from '../../../../../../platform/accessibility/common/accessibility.js'; @@ -40,7 +40,7 @@ import { IMicCaptureService } from '../../../browser/voiceClient/micCaptureServi import { ITtsPlaybackService } from '../../../browser/voiceClient/ttsPlaybackService.js'; import { isVoiceSessionActiveForInput, VoiceNewSessionPreparationResult, VoiceSessionController } from '../../../browser/voiceClient/voiceSessionController.js'; import { IVoiceToolDispatchDelegate, IVoiceToolDispatchService } from '../../../browser/voiceClient/voiceToolDispatchService.js'; -import { ChatSendResult, ConfirmedReason, ElicitationState, IChatConfirmation, IChatModelReference, IChatSendRequestOptions, IChatService, IChatToolInvocation, ToolConfirmKind } from '../../../common/chatService/chatService.js'; +import { ChatRequestQueueKind, ChatSendResult, ConfirmedReason, ElicitationState, IChatConfirmation, IChatModelReference, IChatSendRequestOptions, IChatService, IChatToolInvocation, ToolConfirmKind } from '../../../common/chatService/chatService.js'; import { IPromptsService } from '../../../common/promptSyntax/service/promptsService.js'; import { derivePendingId, isPendingIdResolved, IVoiceAudioResponse, IVoiceBargeIn, IVoiceCheckpointNarrationMetadata, IVoiceClientService, IVoiceDispatchResult, IVoiceFatalDisconnect, IVoiceNarrationAck, IVoiceNarrationSignal, IVoicePttStartOptions, IVoiceSessionContext, IVoiceSpeechStarted, IVoiceToolCall, IVoiceTranscription, markPendingIdResolved, peekPendingId, VoiceConfirmationType, VoiceNarrationKind, VOICE_AGENT_PROGRESS_SETTING } from '../../../common/voiceClient/voiceClientService.js'; import { IChatModel, IChatProgressResponseContent, IChatResponseModel } from '../../../common/model/chatModel.js'; @@ -578,6 +578,7 @@ class NonVisibleTargetChatService extends mock<IChatService>() { } as unknown as IChatResponseModel; private readonly _model = { sessionResource: this._resource, + requestInProgress: observableValue('requestInProgress', true), onDidChange: Event.None, lastRequest: { id: 'held-request', response: this.response }, getRequests: () => [{ id: 'held-request', response: this.response }], @@ -756,12 +757,18 @@ class MaterializingChatWidget extends mock<IChatWidget>() { constructor(resource: URI) { super(); - this.viewModel = { sessionResource: resource } as IChatWidget['viewModel']; + this.viewModel = upcastPartial<NonNullable<IChatWidget['viewModel']>>({ + sessionResource: resource, + model: upcastPartial<IChatModel>({ requestInProgress: observableValue('requestInProgress', false) }), + }); } materialize(resource: URI): void { const previousSessionResource = this.viewModel?.sessionResource; - this.viewModel = { sessionResource: resource } as IChatWidget['viewModel']; + this.viewModel = upcastPartial<NonNullable<IChatWidget['viewModel']>>({ + sessionResource: resource, + model: upcastPartial<IChatModel>({ requestInProgress: observableValue('requestInProgress', false) }), + }); this._onDidChangeViewModel.fire({ previousSessionResource, currentSessionResource: resource }); } @@ -3454,6 +3461,28 @@ suite('VoiceSessionController', () => { }); }); + for (const inProgress of [false, true]) { + test(`direct voice requests ${inProgress ? 'steer ongoing work' : 'send normally when idle'}`, async () => { + const chatService = new class extends TestChatService { + override getSession(): IChatModel { + return upcastPartial<IChatModel>({ + requestInProgress: observableValue('requestInProgress', inProgress), + }); + } + }(); + const controller = createController( + new TestVoiceClientService(), undefined, undefined, undefined, undefined, + new TestConfigurationService({ 'agents.voice.handsFree': false }), chatService, + ); + const sendVoiceRequest = Reflect.get(controller, '_sendVoiceRequest') as (resource: URI, text: string) => Promise<ChatSendResult | undefined>; + await sendVoiceRequest.call(controller, URI.parse('chat-session:/target'), 'Use TypeScript instead.'); + assert.deepStrictEqual(chatService.sendRequestOptions, [{ + isVoiceModeInput: false, + ...(inProgress ? { queue: ChatRequestQueueKind.Steering } : {}), + }]); + }); + } + test('delays, coalesces, and preserves throttled voice progress for the shown request', () => { const voiceClientService = new TestVoiceClientService(); const ttsPlaybackService = new TestTtsPlaybackService(); @@ -5146,6 +5175,35 @@ suite('VoiceSessionController', () => { assert.strictEqual(buildPendingPayload.call(controller, pendingPartsModel({ kind: 'questionCarousel', questions: [] })), undefined); }); + test('narrates the carousel-level question as well as the field title and choices', () => { + const controller = createController(new TestVoiceClientService()); + const questionNarratable = Reflect.get(controller, '_questionNarratable') as (model: IChatModel) => { text: string } | undefined; + const carousel = new ChatQuestionCarouselData([{ + id: 'behavior', + type: 'singleSelect', + title: 'Function behavior', + options: [ + { id: 'name', label: 'Accept a name and return { name }, like createTurtle', value: 'name' }, + { id: 'empty', label: 'Leave the function empty for now', value: 'empty' }, + ], + }], false, undefined, undefined, undefined, new MarkdownString('What should candyFactory do?')); + + assert.strictEqual(questionNarratable.call(controller, pendingPartsModel(carousel))?.text, + 'What should candyFactory do? Function behavior Options: 1, Accept a name and return { name }, like createTurtle. 2, Leave the function empty for now. You can also give your own answer.'); + }); + + test('narrates only the first numbered field when the carousel asks multiple questions', () => { + const controller = createController(new TestVoiceClientService()); + const questionNarratable = Reflect.get(controller, '_questionNarratable') as (model: IChatModel) => { text: string } | undefined; + const carousel = new ChatQuestionCarouselData([ + { id: 'filename', type: 'text', title: 'File name' }, + { id: 'contents', type: 'text', title: 'File contents' }, + ], false, undefined, undefined, undefined, new MarkdownString('What should the new file be named, and what should it contain?')); + + assert.strictEqual(questionNarratable.call(controller, pendingPartsModel(carousel))?.text, + 'Please answer one question at a time. Question 1 of 2: File name'); + }); + test('selects the oldest still-open pending part, not the newest', () => { // Voice is a serial channel: a second form arriving must not take the turn // from the one the user was just read out and is part-way through diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerActionItem.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerActionItem.test.ts index 0d47ee9f71bcdc..1bddfe1c1689d6 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerActionItem.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerActionItem.test.ts @@ -5,9 +5,11 @@ import assert from 'assert'; import { $, append } from '../../../../../../../../base/browser/dom.js'; +import { isManagedHoverTooltipMarkdownString } from '../../../../../../../../base/browser/ui/hover/hover.js'; import { mainWindow } from '../../../../../../../../base/browser/window.js'; import { IAction } from '../../../../../../../../base/common/actions.js'; import { Emitter, Event } from '../../../../../../../../base/common/event.js'; +import { isMarkdownString } from '../../../../../../../../base/common/htmlContent.js'; import { ResolvedKeybinding } from '../../../../../../../../base/common/keybindings.js'; import { toDisposable } from '../../../../../../../../base/common/lifecycle.js'; import { constObservable, observableValue } from '../../../../../../../../base/common/observable.js'; @@ -433,7 +435,7 @@ suite('ModelPickerActionItem', () => { assert.strictEqual(getHoverContents(), 'Models • First\n\nCompare Models'); }); - test('a chat on a HydraFusion model shown as a Fusion tier names that tier in its label and hover', () => { + test('a chat on Copilot Fusion or a HydraFusion model shown as a Fusion tier names it in its label and describes Fusion in its hover', () => { const auto = createModel('auto'); const fusion: ILanguageModelChatMetadataAndIdentifier = { ...auto, @@ -444,13 +446,25 @@ suite('ModelPickerActionItem', () => { }; const max = createModel('hydrafusion-max'); const hydraFusionMax: ILanguageModelChatMetadataAndIdentifier = { ...max, metadata: { ...max.metadata, name: 'HydraFusion Max', modelGroup: { id: 'copilotcli' }, configurationSchema: undefined } }; - const { domNode, getHoverContents } = renderPicker(hydraFusionMax, { models: [fusion, hydraFusionMax] }); - assert.deepStrictEqual({ - label: domNode.querySelector('.chat-input-picker-label')?.textContent, - hover: getHoverContents(), - }, { - label: 'Copilot Fusion', - hover: 'Models • Copilot Fusion Max', + const read = (selected: ILanguageModelChatMetadataAndIdentifier) => { + const { domNode, getHoverContents } = renderPicker(selected, { models: [fusion, hydraFusionMax] }); + const hover = getHoverContents(); + return { + label: domNode.querySelector('.chat-input-picker-label')?.textContent, + hover: isManagedHoverTooltipMarkdownString(hover) && isMarkdownString(hover.markdown) ? { markdown: hover.markdown.value, fallback: hover.markdownNotSupportedFallback } : hover, + }; + }; + const description = 'Copilot Fusion selects a single model or orchestrates multiple models to complete your task.'; + const learnMore = '[Learn more](https://docs.github.com/en/early-access/copilot/hydrafusion)'; + assert.deepStrictEqual({ fusion: read(fusion), hydraFusionMax: read(hydraFusionMax) }, { + fusion: { + label: 'Copilot Fusion', + hover: { markdown: `Models • Copilot Fusion\n\n${description} ${learnMore}`, fallback: `Models • Copilot Fusion\n\n${description}` }, + }, + hydraFusionMax: { + label: 'Copilot Fusion', + hover: { markdown: `Models • Copilot Fusion Max\n\n${description} ${learnMore}`, fallback: `Models • Copilot Fusion Max\n\n${description}` }, + }, }); }); diff --git a/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerTabbedWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerTabbedWidget.test.ts index 2994e65f5bc532..d614ed1c850a67 100644 --- a/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerTabbedWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/widget/input/modelPicker/modelPickerTabbedWidget.test.ts @@ -166,6 +166,7 @@ suite('TabbedModelPicker', () => { entitlement?: ChatEntitlement; showUnavailable?: boolean; showManageModels?: boolean; + manageModelsDisabledReason?: string; comparisonKeybinding?: number; providerPlaceholders?: ITabbedModelPickerContext['providerPlaceholders']; beforeSave?: (values: IStringDictionary<unknown>) => Promise<void>; @@ -284,7 +285,7 @@ suite('TabbedModelPicker', () => { comparisonModels: options.comparisonModels, recentModelIds: [], pinnedModelIds: options.pinnedModelIds ?? [], controlModels: options.controlModels ?? Object.fromEntries(availableModels.map(model => [model.metadata.id, { exists: true, featured: true, label: model.metadata.name }])), - configurationAccess: access, isUBB: false, showManageModels: options.showManageModels ?? false, providerPlaceholders: options.providerPlaceholders ?? [], + configurationAccess: access, isUBB: false, showManageModels: options.showManageModels ?? false, manageModelsDisabledReason: options.manageModelsDisabledReason, providerPlaceholders: options.providerPlaceholders ?? [], unavailableContext: { show: !!options.showUnavailable, currentVSCodeVersion: '1.140.0', manageSettingsUrl: undefined, updateStateType: StateType.Idle }, onUnavailableLinkClick: () => { }, onSelect: model => selections.push(model.identifier), @@ -555,6 +556,17 @@ suite('TabbedModelPicker', () => { }, { label: 'Add Models...', addIcon: true, comparisonFooter: false }); }); + test('model management is disabled with its reason when models cannot be added', () => { + const { popup, picker } = createPicker({ showManageModels: true, manageModelsDisabledReason: 'Not supported here' }); + const action = element(popup, '[data-id="addProvider"]'); + action.click(); + assert.deepStrictEqual({ + disabled: action.getAttribute('aria-disabled'), + title: action.title, + stillOpen: picker.isVisible, + }, { disabled: 'true', title: 'Not supported here', stillOpen: true }); + }); + test('comparison footer shows the configured shortcut and the shortcut opens Attempts without selecting a model', () => { const state = observableValue<IModelPickerComparisonState | undefined>('comparison', undefined); const comparison: IModelPickerComparison = { @@ -1647,6 +1659,16 @@ suite('TabbedModelPicker', () => { }); }); + test('the Copilot Fusion row describes Fusion in its tooltip', () => { + const rowTitle = (popup: HTMLElement, label: string) => Array.from(popup.querySelectorAll<HTMLElement>('.chat-model-picker-model')).find(row => row.querySelector('.title')?.textContent === label)?.title; + const fusion = createPicker({ models: [...models, createFusionModel()], selectedModelId: models[0].identifier }); + const auto = createPicker({ models: [...models, createAutoModel()], selectedModelId: models[0].identifier }); + assert.deepStrictEqual({ fusion: rowTitle(fusion.popup, copilotFusionName), auto: rowTitle(auto.popup, 'Auto') }, { + fusion: 'Copilot Fusion selects a single model or orchestrates multiple models to complete your task.', + auto: 'Auto \u00b7 Balance', + }); + }); + test('Fusion does not offer HydraFusion Max beside provider tiers that hide it', () => { const fusion = createFusionModel(); const providerFusion: ILanguageModelChatMetadataAndIdentifier = { diff --git a/src/vs/workbench/contrib/chat/test/common/chatSessionsService.test.ts b/src/vs/workbench/contrib/chat/test/common/chatSessionsService.test.ts new file mode 100644 index 00000000000000..b39fbcb5b612ee --- /dev/null +++ b/src/vs/workbench/contrib/chat/test/common/chatSessionsService.test.ts @@ -0,0 +1,34 @@ +/*--------------------------------------------------------------------------------------------- + * 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 { getAddModelsUnavailableReason } from '../../common/chatSessionsService.js'; + +suite('getAddModelsUnavailableReason', () => { + + ensureNoDisposablesAreLeakedInTestSuite(); + + test('only the remotely running Copilot agent-host harness cannot add models', () => { + const reason = (sessionType: string | undefined, remoteAuthority?: string) => getAddModelsUnavailableReason(sessionType, remoteAuthority) !== undefined; + assert.deepStrictEqual({ + noHarness: reason(undefined, 'ssh-remote+host'), + localHarnessInRemoteWindow: reason('local', 'ssh-remote+host'), + copilotHarnessLocally: reason('agent-host-copilotcli'), + copilotHarnessInRemoteWindow: reason('agent-host-copilotcli', 'ssh-remote+host'), + remoteAgentHostCopilotHarness: reason('remote-my-host-copilotcli'), + remoteAgentHostClaudeHarness: reason('remote-my-host-claude'), + claudeHarnessInRemoteWindow: reason('agent-host-claude', 'ssh-remote+host'), + }, { + noHarness: false, + localHarnessInRemoteWindow: false, + copilotHarnessLocally: false, + copilotHarnessInRemoteWindow: true, + remoteAgentHostCopilotHarness: true, + remoteAgentHostClaudeHarness: false, + claudeHarnessInRemoteWindow: false, + }); + }); +}); diff --git a/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts b/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts index 3f8d0c6ec67798..7d2cdb0606fc0b 100644 --- a/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/voiceClient/voiceLiveInputRouter.test.ts @@ -29,6 +29,58 @@ suite('VoiceLiveInputRouter', () => { }; } + test('reads form context with a single question and its retry', () => { + const router = new VoiceLiveInputRouter(); + router.updateContext(context('chat-session:/a', { + ...questions, + message: 'What should candyFactory do?', + questions: [{ ...questions.questions![0], title: 'Function behavior' }], + })); + const initial = router.getQuestionPrompt('chat-session:/a', 'questions'); + const retry = router.resolve('retry', 'not a choice', router.captureTarget()).clarification; + assert.deepStrictEqual({ initial, retry }, { + initial: 'What should candyFactory do? Function behavior 1. West 2. East', + retry: 'Please say an exact choice or its number. What should candyFactory do? Function behavior 1. West 2. East', + }); + }); + + test('asks one numbered field at a time instead of a compound form question', () => { + const router = new VoiceLiveInputRouter(); + router.updateContext(context('chat-session:/a', { + ...questions, + message: 'What should the new file be named, and what should it contain?', + questions: [ + { id: 'filename', type: 'text', title: 'File name', allow_freeform: true, options: [] }, + { id: 'contents', type: 'text', title: 'File contents', allow_freeform: true, options: [] }, + ], + })); + const initial = router.getQuestionPrompt('chat-session:/a', 'questions'); + const first = router.resolve('filename', 'chocolate.ts', router.captureTarget()); + const current = router.getQuestionPrompt('chat-session:/a', 'questions'); + const final = router.resolve('contents', 'A function called chocolate', router.captureTarget()); + assert.deepStrictEqual({ initial, first, current, response: final.toolCall?.args.response }, { + initial: 'Please answer one question at a time. Question 1 of 2: File name', + first: { clarification: 'Question 2 of 2: File contents' }, + current: 'Question 2 of 2: File contents', + response: { type: 'answer', answers: [{ question_id: 'filename', freeform: 'chocolate.ts' }, { question_id: 'contents', freeform: 'A function called chocolate' }] }, + }); + }); + + test('normalizes question titles and form context before formatting or deduplicating them', () => { + const router = new VoiceLiveInputRouter(); + const prompts = [' Deployment settings ', ' Which region? '].map(message => { + router.updateContext(context('chat-session:/a', { + ...questions, message, + questions: [{ ...questions.questions![0], title: ' Which region? ' }], + })); + return router.getQuestionPrompt('chat-session:/a', 'questions'); + }); + assert.deepStrictEqual(prompts, [ + 'Deployment settings Which region? 1. West 2. East', + 'Which region? 1. West 2. East', + ]); + }); + test('omits reply guidance until a voice locale is known', () => { const router = new VoiceLiveInputRouter(); const guidance = () => [router.getQuestionReplyGuidance(), router.getApprovalReplyGuidance()]; @@ -119,7 +171,7 @@ suite('VoiceLiveInputRouter', () => { const first = router.resolve('first', 'option two', router.captureTarget()); const final = router.resolve('final', 'My deployment', router.captureTarget()); assert.deepStrictEqual({ first, final }, { - first: { clarification: 'What name?' }, + first: { clarification: 'Question 2 of 2: What name?' }, final: { toolCall: { callId: 'final', name: 'respond_to_session', args: { @@ -160,7 +212,7 @@ suite('VoiceLiveInputRouter', () => { router.resolve('new-first', 'first', router.captureTarget()); const final = router.resolve('new-second', 'New deployment', router.captureTarget()); assert.deepStrictEqual({ resetIndex, nextPrompt, stale: stale.clarification !== undefined, response: final.toolCall?.args.response }, { - resetIndex: 0, nextPrompt: 'Which region? 1. West 2. East', stale: true, + resetIndex: 0, nextPrompt: 'Please answer one question at a time. Question 1 of 2: Which region? 1. West 2. East', stale: true, response: { type: 'answer', answers: [{ question_id: 'region', value: 'new-westus' }, { question_id: 'name', freeform: 'New deployment' }] }, }); }); @@ -179,7 +231,7 @@ suite('VoiceLiveInputRouter', () => { firstB, staleA: staleA.clarification !== undefined, answers: finalA.toolCall?.args.response, }, { - firstB: { clarification: 'What name?' }, staleA: true, + firstB: { clarification: 'Question 2 of 2: What name?' }, staleA: true, answers: { type: 'answer', answers: [{ question_id: 'region', value: 'westus' }, { question_id: 'name', freeform: 'A deployment' }] }, }); }); @@ -411,9 +463,9 @@ suite('VoiceLiveInputRouter', () => { const next = router.resolve('first', 'second', router.captureTarget()); const final = router.resolve('final', 'My deployment', router.captureTarget()); assert.deepStrictEqual({ initial, invalid, next, response: final.toolCall?.args.response }, { - initial: 'Which region? 1. West 2. East Please answer by voice, or use the controls in chat.', - invalid: { clarification: 'Please say an exact choice or its number. Which region? 1. West 2. East Please answer by voice, or use the controls in chat.' }, - next: { clarification: 'What name? Please answer by voice, or use the controls in chat.' }, + initial: 'Please answer one question at a time. Question 1 of 2: Which region? 1. West 2. East Please answer by voice, or use the controls in chat.', + invalid: { clarification: 'Please say an exact choice or its number. Please answer one question at a time. Question 1 of 2: Which region? 1. West 2. East Please answer by voice, or use the controls in chat.' }, + next: { clarification: 'Question 2 of 2: What name? Please answer by voice, or use the controls in chat.' }, response: { type: 'answer', answers: [{ question_id: 'region', value: 'eastus' }, { question_id: 'name', freeform: 'My deployment' }] }, }); }); @@ -434,8 +486,8 @@ suite('VoiceLiveInputRouter', () => { const first = router.resolve('first', 'Osten', router.captureTarget()); const final = router.resolve('final', 'Meine Bereitstellung', router.captureTarget()); assert.deepStrictEqual({ prompt, first, response: final.toolCall?.args.response }, { - prompt: 'Welche Region? 1. Westen 2. Osten Please answer by voice, or use the controls in chat.', - first: { clarification: 'Welcher Name? Please answer by voice, or use the controls in chat.' }, + prompt: 'Please answer one question at a time. Question 1 of 2: Welche Region? 1. Westen 2. Osten Please answer by voice, or use the controls in chat.', + first: { clarification: 'Question 2 of 2: Welcher Name? Please answer by voice, or use the controls in chat.' }, response: { type: 'answer', answers: [{ question_id: 'region', value: 'eastus' }, { question_id: 'name', freeform: 'Meine Bereitstellung' }] }, }); }); @@ -477,7 +529,7 @@ suite('VoiceLiveInputRouter', () => { const prompt = router.getQuestionPrompt('chat-session:/a', 'questions'); const skipped = router.resolve('skip', 'skip', router.captureTarget()); assert.deepStrictEqual({ prompt, response: skipped.toolCall?.args.response }, { - prompt: 'What name?', response: { type: 'skip', answers: [{ question_id: 'region', value: 'westus' }] }, + prompt: 'Question 2 of 2: What name?', response: { type: 'skip', answers: [{ question_id: 'region', value: 'westus' }] }, }); }); diff --git a/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts b/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts index 2aa8ff9838891e..325124eed7c34d 100644 --- a/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts +++ b/src/vs/workbench/contrib/chat/test/common/voiceClient/voicePendingNarration.test.ts @@ -55,6 +55,24 @@ suite('formatQuestionPrompt', () => { ); }); + test('reads the form-level question before its short field title and options', () => { + assert.strictEqual( + formatQuestionPrompt({ ...single, title: 'Function behavior' }, false, 'What should candyFactory do?'), + 'What should candyFactory do? Function behavior Options: 1, West US. 2, East US.', + ); + }); + + test('does not repeat form context that is also the question text', () => { + assert.strictEqual(formatQuestionPrompt(single, false, ' Which region? '), 'Which region? Options: 1, West US. 2, East US.'); + }); + + test('asks only the first numbered field of a multi-question form', () => { + assert.strictEqual( + formatQuestionPrompt({ ...text, title: 'File name' }, false, 'What should the new file be named, and what should it contain?', 2), + 'Please answer one question at a time. Question 1 of 2: File name', + ); + }); + test('appends the skip hint when the form allows skipping', () => { assert.strictEqual( formatQuestionPrompt(single, true), diff --git a/src/vs/workbench/contrib/extensions/electron-browser/debugExtensionHostAction.ts b/src/vs/workbench/contrib/extensions/electron-browser/debugExtensionHostAction.ts index ec42257d80e2be..8fe3531c02ee87 100644 --- a/src/vs/workbench/contrib/extensions/electron-browser/debugExtensionHostAction.ts +++ b/src/vs/workbench/contrib/extensions/electron-browser/debugExtensionHostAction.ts @@ -37,7 +37,10 @@ async function getExtensionHostPort( dialogService: IDialogService, productService: IProductService, ): Promise<number | undefined> { - const inspectPorts = await extensionService.getInspectPorts(ExtensionHostKind.LocalProcess, false); + // Try to enable the inspector on the running extension host (same as profiling does) + // so that debugging does not require a restart. Only fall back to restarting with + // `--inspect-extensions` if the inspector could not be enabled. + const inspectPorts = await extensionService.getInspectPorts(ExtensionHostKind.LocalProcess, true); if (inspectPorts.length === 0) { const res = await dialogService.confirm({ message: nls.localize('restart1', "Debug Extensions"), diff --git a/src/vs/workbench/contrib/mcp/common/mcpRegistryTypes.ts b/src/vs/workbench/contrib/mcp/common/mcpRegistryTypes.ts index b0b52375a849f6..b16735c20cbad5 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpRegistryTypes.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpRegistryTypes.ts @@ -9,6 +9,7 @@ import { IObservable } from '../../../../base/common/observable.js'; import { ConfigurationTarget } from '../../../../platform/configuration/common/configuration.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; import { ILogger, LogLevel } from '../../../../platform/log/common/log.js'; +import { McpServerPolicyValues } from '../../../../platform/mcp/common/allowedMcpServers.js'; import { StorageScope } from '../../../../platform/storage/common/storage.js'; import { IWorkspaceFolderData } from '../../../../platform/workspace/common/workspace.js'; import { IResolvedValue } from '../../../services/configurationResolver/common/configurationResolverExpression.js'; @@ -38,7 +39,13 @@ export interface IMcpHostDelegate { * the launch, using the environment of the host that will run or connect to the server. */ expandEnvironmentVariables(serverDefinition: McpServerDefinition, launch: McpServerLaunch): Promise<McpServerLaunch>; - start(collectionDefinition: McpCollectionDefinition, serverDefinition: McpServerDefinition, resolvedLaunch: McpServerLaunch, options?: { errorOnUserInteraction?: boolean }): IMcpMessageTransport; + /** Expands matcher strings against this host's environment without authorizing a server or exposing the whole environment. */ + resolvePolicyVariables(values: readonly string[]): Promise<McpServerPolicyValues>; + start(collectionDefinition: McpCollectionDefinition, serverDefinition: McpServerDefinition, resolvedLaunch: McpServerLaunch, options?: { + errorOnUserInteraction?: boolean; + /** Expansions used to authorize this launch, retained for request-destination checks. */ + policyValues?: McpServerPolicyValues; + }): IMcpMessageTransport; } export interface IMcpResolveConnectionOptions { diff --git a/src/vs/workbench/contrib/mcp/common/mcpServer.ts b/src/vs/workbench/contrib/mcp/common/mcpServer.ts index 195e23ee1bbd82..1bcf7f38d21a02 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpServer.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpServer.ts @@ -22,7 +22,7 @@ import { ICommandService } from '../../../../platform/commands/common/commands.j import { hasConfigurationVariable } from '../../../../platform/configuration/common/configurationVariables.js'; import { IDialogService } from '../../../../platform/dialogs/common/dialogs.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; -import { IMcpServerIdentity } from '../../../../platform/mcp/common/allowedMcpServers.js'; +import { IMcpServerIdentity, McpServerPolicyValues } from '../../../../platform/mcp/common/allowedMcpServers.js'; import { IAllowedMcpServersService } from '../../../../platform/mcp/common/mcpManagement.js'; import { ILogger, ILoggerService } from '../../../../platform/log/common/log.js'; import { INotificationService, IPromptChoice, Severity } from '../../../../platform/notification/common/notification.js'; @@ -533,12 +533,11 @@ export class McpServer extends Disposable implements IMcpServer { this._policyBlock = derived<McpConnectionState.Error | undefined>(this, reader => { this._policyEpoch.read(reader); const connection = this._connection.read(reader); - if (connection) { - // Authoritative: the connection carries the fully resolved launch. - return this._evaluatePolicy(this._identityFromLaunch(connection.launchDefinition)); - } const definition = this._fullDefinitions.read(reader).server; const resolved = this._resolvedPolicyIdentity.read(reader); + if (connection) { + return this._evaluatePolicy({ ...this._identityFromLaunch(connection.launchDefinition), policyValues: resolved?.identity.policyValues }); + } if (resolved && definition && McpServerDefinition.equals(resolved.definition, definition)) { return this._evaluatePolicy(resolved.identity); } @@ -750,7 +749,8 @@ export class McpServer extends Disposable implements IMcpServer { const definition = this._fullDefinitions.get().server; const identity = definition && this._identityFromLaunch(definition.launch); const canResolveAgain = !errorOnUserInteraction && this._resolvedPolicyIdentity.get() - && identity && McpServer._hasUnresolvedVariables(identity) && !this._evaluatePolicy(identity, 'definition'); + && identity && (McpServer._hasUnresolvedVariables(identity) || this._allowedMcpServersService.getServerPolicyVariableValues().length > 0) + && !this._evaluatePolicy(identity, 'definition'); // Keep cached metadata blocked while an interactive retry resolves the current inputs. if (!canResolveAgain) { return preStartBlock; @@ -804,7 +804,19 @@ export class McpServer extends Disposable implements IMcpServer { return { state: McpConnectionState.Kind.Stopped }; } - const resolvedPolicyIdentity = { definition: connection.definition, identity: this._identityFromLaunch(connection.launchDefinition) }; + const values = this._allowedMcpServersService.getServerPolicyVariableValues(); + let policyValues: McpServerPolicyValues; + try { + policyValues = values.length ? await connection.resolvePolicyVariables(values) : {}; + } catch (error) { + connection.dispose(); + throw error; + } + if (this._store.isDisposed) { + connection.dispose(); + return { state: McpConnectionState.Kind.Stopped }; + } + const resolvedPolicyIdentity = { definition: connection.definition, identity: { ...this._identityFromLaunch(connection.launchDefinition), policyValues } }; transaction(tx => { this._resolvedPolicyIdentity.set(resolvedPolicyIdentity, tx); this._connection.set(connection, tx); @@ -816,7 +828,8 @@ export class McpServer extends Disposable implements IMcpServer { } // Check the local resolved connection: reactive policy enforcement may already have cleared `_connection`. - const resolvedBlock = this._evaluatePolicy(this._identityFromLaunch(connection.launchDefinition)); + const policyValues = this._resolvedPolicyIdentity.get()?.identity.policyValues ?? {}; + const resolvedBlock = this._evaluatePolicy({ ...this._identityFromLaunch(connection.launchDefinition), policyValues }); if (resolvedBlock) { this._connection.set(undefined, undefined); // dispose the just-resolved connection return resolvedBlock; @@ -844,7 +857,7 @@ export class McpServer extends Disposable implements IMcpServer { r.dispose(); return r.value; } - }); + }, policyValues); const policyBlock = this._policyBlock.get(); if (policyBlock) { diff --git a/src/vs/workbench/contrib/mcp/common/mcpServerConnection.ts b/src/vs/workbench/contrib/mcp/common/mcpServerConnection.ts index 2931760e06f47f..d8da7d0a68fc27 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpServerConnection.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpServerConnection.ts @@ -11,6 +11,7 @@ import { autorun, IObservable, observableValue, transaction } from '../../../../ import { localize } from '../../../../nls.js'; import { IInstantiationService } from '../../../../platform/instantiation/common/instantiation.js'; import { ILogger, log, LogLevel } from '../../../../platform/log/common/log.js'; +import { McpServerPolicyValues } from '../../../../platform/mcp/common/allowedMcpServers.js'; import { IMcpHostDelegate, IMcpMessageTransport } from './mcpRegistryTypes.js'; import { McpServerRequestHandler } from './mcpServerRequestHandler.js'; import { McpTaskManager } from './mcpTaskManager.js'; @@ -41,7 +42,12 @@ export class McpServerConnection extends Disposable implements IMcpServerConnect } /** @inheritdoc */ - public async start(methods: IMcpClientMethods): Promise<McpConnectionState> { + resolvePolicyVariables(values: readonly string[]): Promise<McpServerPolicyValues> { + return this._delegate.resolvePolicyVariables(values); + } + + /** @inheritdoc */ + public async start(methods: IMcpClientMethods, policyValues: McpServerPolicyValues): Promise<McpConnectionState> { if (this._store.isDisposed) { return this._state.get(); } @@ -58,7 +64,7 @@ export class McpServerConnection extends Disposable implements IMcpServerConnect this._logger.info(localize('mcpServer.starting', 'Starting server {0}', this.definition.label)); try { - const launch = this._delegate.start(this._collection, this.definition, this.launchDefinition, { errorOnUserInteraction: this._errorOnUserInteraction }); + const launch = this._delegate.start(this._collection, this.definition, this.launchDefinition, { errorOnUserInteraction: this._errorOnUserInteraction, policyValues }); this._launch.value = this.adoptLaunch(launch, methods); return this._waitForState(McpConnectionState.Kind.Running, McpConnectionState.Kind.Error); } catch (e) { @@ -102,7 +108,7 @@ export class McpServerConnection extends Disposable implements IMcpServerConnect }, cts.token).then( handler => { if (!store.isDisposed) { - this._requestHandler.set(handler, undefined); + this._requestHandler.set(store.add(handler), undefined); } else { handler.dispose(); } @@ -137,7 +143,6 @@ export class McpServerConnection extends Disposable implements IMcpServerConnect public override dispose(): void { transaction(tx => { this._stopRequested.set(true, tx); - this._requestHandler.get()?.dispose(); super.dispose(); this._state.set({ state: McpConnectionState.Kind.Stopped }, tx); }); diff --git a/src/vs/workbench/contrib/mcp/common/mcpTypes.ts b/src/vs/workbench/contrib/mcp/common/mcpTypes.ts index 087295dd333480..a925c7204b84bc 100644 --- a/src/vs/workbench/contrib/mcp/common/mcpTypes.ts +++ b/src/vs/workbench/contrib/mcp/common/mcpTypes.ts @@ -23,6 +23,7 @@ import { RawContextKey } from '../../../../platform/contextkey/common/contextkey import { IEditorOptions } from '../../../../platform/editor/common/editor.js'; import { ExtensionIdentifier } from '../../../../platform/extensions/common/extensions.js'; import { createDecorator } from '../../../../platform/instantiation/common/instantiation.js'; +import { McpServerPolicyValues } from '../../../../platform/mcp/common/allowedMcpServers.js'; import { IMcpGalleryManifest, McpGalleryManifestStatus } from '../../../../platform/mcp/common/mcpGalleryManifest.js'; import { IGalleryMcpServer, IGalleryMcpServerConfiguration, IInstallableMcpServer, IQueryOptions } from '../../../../platform/mcp/common/mcpManagement.js'; import { IMcpDevModeConfig, IMcpSandboxConfiguration, IMcpServerConfiguration, McpServerType } from '../../../../platform/mcp/common/mcpPlatformTypes.js'; @@ -881,12 +882,14 @@ export interface IMcpServerConnection extends IDisposable { * resolution logic in extension-provided MCPs. */ readonly launchDefinition: McpServerLaunch; + /** Resolves matcher strings on the executing host without caching them or changing connection state. */ + resolvePolicyVariables(values: readonly string[]): Promise<McpServerPolicyValues>; /** - * Starts the server if it's stopped. Returns a promise that resolves once - * server exits a 'starting' state. + * Starts a stopped server using the host expansions the caller already checked against the resolved launch; pass `{}` when none are required. + * The expansions are forwarded for request-destination enforcement, not treated as authorization by the connection. */ - start(methods: IMcpClientMethods): Promise<McpConnectionState>; + start(methods: IMcpClientMethods, policyValues: McpServerPolicyValues): Promise<McpConnectionState>; /** * Stops the server. diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpRegistry.test.ts b/src/vs/workbench/contrib/mcp/test/common/mcpRegistry.test.ts index d4fb4de0cc1b3d..71f16bdb6b7ae2 100644 --- a/src/vs/workbench/contrib/mcp/test/common/mcpRegistry.test.ts +++ b/src/vs/workbench/contrib/mcp/test/common/mcpRegistry.test.ts @@ -95,6 +95,7 @@ class TestConfigurationResolverService { class TestMcpHostDelegate implements IMcpHostDelegate { priority = 0; + resolvePolicyVariables = async () => ({}); substituteVariables(serverDefinition: McpServerDefinition, launch: McpServerLaunch): Promise<McpServerLaunch> { return Promise.resolve(launch); diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpRegistryTypes.ts b/src/vs/workbench/contrib/mcp/test/common/mcpRegistryTypes.ts index 0d0f3dbb814a2a..b3e4bcf7367c12 100644 --- a/src/vs/workbench/contrib/mcp/test/common/mcpRegistryTypes.ts +++ b/src/vs/workbench/contrib/mcp/test/common/mcpRegistryTypes.ts @@ -180,6 +180,7 @@ export class TestMcpRegistry implements IMcpRegistry { }]); delegates = observableValue<readonly IMcpHostDelegate[]>(this, [{ priority: 0, + resolvePolicyVariables: async () => ({}), canStart: () => true, substituteVariables(serverDefinition, launch) { return Promise.resolve(launch); diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpResourceFilesystem.test.ts b/src/vs/workbench/contrib/mcp/test/common/mcpResourceFilesystem.test.ts index e6584d54f18e53..e7dadaa9da5fff 100644 --- a/src/vs/workbench/contrib/mcp/test/common/mcpResourceFilesystem.test.ts +++ b/src/vs/workbench/contrib/mcp/test/common/mcpResourceFilesystem.test.ts @@ -46,7 +46,7 @@ suite('Workbench - MCP - ResourceFilesystem', () => { [IWorkbenchEnvironmentService, {}], [ITelemetryService, NullTelemetryService], [IProductService, TestProductService], - [IAllowedMcpServersService, { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }], + [IAllowedMcpServersService, { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }], ); const parentInsta1 = ds.add(new TestInstantiationService(services)); diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpServerConnection.test.ts b/src/vs/workbench/contrib/mcp/test/common/mcpServerConnection.test.ts index 5de360527cbb77..800d99f0198a6e 100644 --- a/src/vs/workbench/contrib/mcp/test/common/mcpServerConnection.test.ts +++ b/src/vs/workbench/contrib/mcp/test/common/mcpServerConnection.test.ts @@ -6,12 +6,13 @@ import * as assert from 'assert'; import { raceTimeout, timeout } from '../../../../../base/common/async.js'; import { Disposable } from '../../../../../base/common/lifecycle.js'; -import { autorun, observableValue } from '../../../../../base/common/observable.js'; +import { autorun, observableValue, waitForState } from '../../../../../base/common/observable.js'; import { upcast } from '../../../../../base/common/types.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../base/test/common/utils.js'; import { ServiceCollection } from '../../../../../platform/instantiation/common/serviceCollection.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILogger, ILoggerService, LogLevel, NullLogger } from '../../../../../platform/log/common/log.js'; +import { McpServerPolicyValues } from '../../../../../platform/mcp/common/allowedMcpServers.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; import { IStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; import { IOutputService } from '../../../../services/output/common/output.js'; @@ -29,6 +30,7 @@ class TestMcpHostDelegate extends Disposable implements IMcpHostDelegate { private _canStartValue = true; priority = 0; + resolvePolicyVariables = async () => ({}); constructor() { super(); @@ -136,6 +138,63 @@ suite('Workbench - MCP - ServerConnection', () => { }); } + test('start forwards explicit policy values without requiring a resolution call', async () => { + const host: IMcpHostDelegate = delegate; + const policyValues: McpServerPolicyValues = { '${NODE}/bin/node': '/host/bin/node' }; + const received: (McpServerPolicyValues | undefined)[] = []; + host.resolvePolicyVariables = async () => { + throw new Error('start must not depend on a prior resolution call'); + }; + host.start = (_collection, _definition, _launch, options) => { + received.push(options?.policyValues); + return transport; + }; + const connection = store.add(instantiationService.createInstance( + McpServerConnection, collection, serverDefinition, host, serverDefinition.launch, + new NullLogger(), false, store.add(new McpTaskManager()), + )); + + const starting = connection.start({}, policyValues); + transport.setConnectionState({ state: McpConnectionState.Kind.Running }); + const state = await starting; + await waitForHandler(connection); + assert.deepStrictEqual({ state: state.state, received }, { state: McpConnectionState.Kind.Running, received: [policyValues] }); + }); + + test('resolution does not supply hidden policy state to a start or restart', async () => { + const host: IMcpHostDelegate = delegate; + const resolvedValues: McpServerPolicyValues = { '${NODE}/bin/node': '/resolved/bin/node' }; + const received: (McpServerPolicyValues | undefined)[] = []; + let currentTransport = transport; + host.resolvePolicyVariables = async () => resolvedValues; + host.start = (_collection, _definition, _launch, options) => { + received.push(options?.policyValues); + currentTransport = store.add(new TestMcpMessageTransport()); + return currentTransport; + }; + const connection = store.add(instantiationService.createInstance( + McpServerConnection, collection, serverDefinition, host, serverDefinition.launch, + new NullLogger(), false, store.add(new McpTaskManager()), + )); + const suppliedValues: McpServerPolicyValues[] = [{ '${NODE}/bin/node': '/checked/bin/node' }, {}]; + const results: { resolved: McpServerPolicyValues; beforeStart: McpConnectionState.Kind; started: McpConnectionState.Kind }[] = []; + for (const policyValues of suppliedValues) { + const resolved = await connection.resolvePolicyVariables(['${NODE}/bin/node']); + const beforeStart = connection.state.get().state; + const previousHandler = connection.handler.get(); + const starting = connection.start({}, policyValues); + currentTransport.setConnectionState({ state: McpConnectionState.Kind.Running }); + const state = await starting; + await waitForState(connection.handler, handler => !!handler && handler !== previousHandler); + results.push({ resolved, beforeStart, started: state.state }); + await connection.stop(); + } + assert.deepStrictEqual({ results, received }, { + results: suppliedValues.map(() => ({ resolved: resolvedValues, beforeStart: McpConnectionState.Kind.Stopped, started: McpConnectionState.Kind.Running })), + received: suppliedValues, + }); + }); + test('should start and set state to Running when transport succeeds', async () => { // Create server connection const connection = instantiationService.createInstance( @@ -151,7 +210,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // Start the connection - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); // Simulate successful connection transport.setConnectionState({ state: McpConnectionState.Kind.Running }); @@ -181,7 +240,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // Start the connection - const state = await connection.start({}); + const state = await connection.start({}, {}); assert.strictEqual(state.state, McpConnectionState.Kind.Error); assert.ok(state.message); @@ -193,7 +252,7 @@ suite('Workbench - MCP - ServerConnection', () => { McpServerConnection, collection, serverDefinition, delegate, serverDefinition.launch, new NullLogger(), false, store.add(new McpTaskManager()), )); - const pending = [connection.start({}), connection.start({})]; + const pending = [connection.start({}, {}), connection.start({}, {})]; if (action === 'dispose') { connection.dispose(); } else { @@ -218,7 +277,7 @@ suite('Workbench - MCP - ServerConnection', () => { return transport; }; connection.dispose(); - const state = await raceTimeout(connection.start({}), 1000); + const state = await raceTimeout(connection.start({}, {}), 1000); assert.deepStrictEqual({ state: state?.state, launches }, { state: McpConnectionState.Kind.Stopped, launches: 0, @@ -240,7 +299,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // Start the connection - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); // Simulate error in transport transport.setConnectionState({ @@ -268,7 +327,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // Start the connection - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); await startPromise; @@ -294,10 +353,10 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // Start the connection - const startPromise1 = connection.start({}); + const startPromise1 = connection.start({}, {}); // Try to start again while starting - const startPromise2 = connection.start({}); + const startPromise2 = connection.start({}, {}); // Simulate successful connection transport.setConnectionState({ state: McpConnectionState.Kind.Running }); @@ -329,7 +388,7 @@ suite('Workbench - MCP - ServerConnection', () => { ); // Start the connection - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); await startPromise; @@ -365,7 +424,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // Start the connection - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); // Simulate log message from transport transport.simulateLog('Test log message'); @@ -401,7 +460,7 @@ suite('Workbench - MCP - ServerConnection', () => { const message = 'error: failed to open file `/test-for-sandbox/.git`: Read-only file system (os error 30)'; const sandboxBlock = Event.toPromise(connection.onPotentialSandboxBlock); - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); transport.simulateLog(message); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); @@ -438,7 +497,7 @@ suite('Workbench - MCP - ServerConnection', () => { const message = 'error: failed to open file `/test-for-sandbox/.testfile`: Read-only file system (os error 30)'; const sandboxBlock = Event.toPromise(connection.onPotentialSandboxBlock); - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); transport.simulateLog(message); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); @@ -475,7 +534,7 @@ suite('Workbench - MCP - ServerConnection', () => { const message = 'error: Read-only file system (os error 30) at path "/test-for-sandbox/.testfile"'; const sandboxBlock = Event.toPromise(connection.onPotentialSandboxBlock); - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); transport.simulateLog(message); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); @@ -511,7 +570,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); const sandboxBlock = Event.toPromise(connection.onPotentialSandboxBlock); - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); transport.simulateLog('No matching config rule, denying: api.example.com:443.'); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); @@ -543,7 +602,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // Start the connection - const startPromise = connection.start({}); + const startPromise = connection.start({}, {}); // Transition to error state const errorState: McpConnectionState = { @@ -559,7 +618,7 @@ suite('Workbench - MCP - ServerConnection', () => { transport.setConnectionState({ state: McpConnectionState.Kind.Stopped }); // Transition back to running state - const startPromise2 = connection.start({}); + const startPromise2 = connection.start({}, {}); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); state = await startPromise2; assert.deepStrictEqual(state, { state: McpConnectionState.Kind.Running }); @@ -583,7 +642,7 @@ suite('Workbench - MCP - ServerConnection', () => { store.add(connection); // First cycle - let startPromise = connection.start({}); + let startPromise = connection.start({}, {}); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); await startPromise; @@ -591,7 +650,7 @@ suite('Workbench - MCP - ServerConnection', () => { assert.deepStrictEqual(connection.state.get(), { state: McpConnectionState.Kind.Stopped }); // Second cycle - startPromise = connection.start({}); + startPromise = connection.start({}, {}); transport.setConnectionState({ state: McpConnectionState.Kind.Running }); await startPromise; diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts b/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts index 7c9ab728761605..5de7cb22d7aca2 100644 --- a/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts +++ b/src/vs/workbench/contrib/mcp/test/common/mcpServerRequestHandler.test.ts @@ -28,6 +28,7 @@ class TestMcpHostDelegate extends Disposable implements IMcpHostDelegate { private readonly _transport: TestMcpMessageTransport; priority = 0; + resolvePolicyVariables = async () => ({}); constructor() { super(); diff --git a/src/vs/workbench/contrib/mcp/test/common/mcpService.test.ts b/src/vs/workbench/contrib/mcp/test/common/mcpService.test.ts index 01fedc208167e5..5e3a25c329fc96 100644 --- a/src/vs/workbench/contrib/mcp/test/common/mcpService.test.ts +++ b/src/vs/workbench/contrib/mcp/test/common/mcpService.test.ts @@ -20,6 +20,7 @@ import { ServiceCollection } from '../../../../../platform/instantiation/common/ import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; import { ILoggerService, NullLogger, NullLogService } from '../../../../../platform/log/common/log.js'; import { AllowedMcpServersService } from '../../../../../platform/mcp/common/allowedMcpServersService.js'; +import { createEnvVarResolver } from '../../../../../platform/mcp/common/envVarResolution.js'; import { IAllowedMcpServersService, mcpAccessConfig, McpAccessValue, mcpAllowedServersConfig, mcpAutoStartConfig, McpAutoStartValue, mcpDeniedServersConfig } from '../../../../../platform/mcp/common/mcpManagement.js'; import { IProductService } from '../../../../../platform/product/common/productService.js'; import { IStorageService, StorageScope } from '../../../../../platform/storage/common/storage.js'; @@ -51,7 +52,7 @@ suite('Workbench - MCP - McpService', () => { [IWorkbenchEnvironmentService, {}], [ITelemetryService, NullTelemetryService], [IProductService, TestProductService], - [IAllowedMcpServersService, allowedMcpServersService ?? { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true }], + [IAllowedMcpServersService, allowedMcpServersService ?? { _serviceBrand: undefined, onDidChangeAllowedMcpServers: Event.None, isAllowed: () => true, isServerAllowedBeforeResolution: () => true, isServerAllowed: () => true, getServerPolicyVariableValues: () => [] }], ); const parentInstantiationService = store.add(new TestInstantiationService(services)); @@ -141,6 +142,89 @@ suite('Workbench - MCP - McpService', () => { }); }; + test('a name match does not authorize a different resolved endpoint', async () => { + const { server, configurationService, resolution, transports } = createPolicyServer('https://trusted.example/mcp', 'https://other.example/mcp'); + await configurationService.setUserConfiguration(mcpAllowedServersConfig, [ + { serverName: 'Test Server' }, + { serverUrl: 'https://trusted.example/mcp' }, + ]); + const state = await server.start(); + assert.deepStrictEqual({ state: state.state, resolved: resolution.callCount, started: transports.length }, { + state: McpConnectionState.Kind.Error, resolved: 1, started: 0, + }); + }); + + test('resolves policy values on the selected host before starting and retains deny enforcement', async () => { + const { server, configurationService, registry, transports } = createPolicyServer('https://trusted.example/mcp'); + await configurationService.setUserConfiguration(mcpAllowedServersConfig, [{ serverUrl: 'https://${MCP_HOST}/mcp' }]); + const requested: string[][] = []; + const resolve = createEnvVarResolver({ MCP_HOST: 'trusted.example' }, false); + const host = sinon.stub(registry.delegates.get()[0], 'resolvePolicyVariables').callsFake(async values => { + requested.push([...values]); + return Object.fromEntries(values.map(value => [value, resolve(value)])); + }); + store.add(toDisposable(() => host.restore())); + + const started = await server.start(); + await setDeniedUrls(configurationService, ['https://${MCP_HOST}/mcp']); + const blocked = server.connectionState.get(); + const restarted = await server.start(); + assert.deepStrictEqual({ + started: started.state, blocked: blocked.state, restarted: restarted.state, + requested, transports: transports.length, + }, { + started: McpConnectionState.Kind.Running, blocked: McpConnectionState.Kind.Error, restarted: McpConnectionState.Kind.Error, + requested: [['https://${MCP_HOST}/mcp'], ['https://${MCP_HOST}/mcp']], transports: 1, + }); + }); + + test('stdio name fallback cannot bypass a final command mismatch', async () => { + const configuration = new TestConfigurationService({ + [mcpAllowedServersConfig]: [{ serverName: 'Test Server' }, { serverCommand: ['echo', 'approved'] }], + }); + const policy = store.add(new AllowedMcpServersService(configuration)); + const { mcpService, registry } = createMcpService(policy); + let started = 0; + registry.makeTestTransport = () => { + started++; + return store.add(new TestMcpMessageTransport()); + }; + mcpService.updateCollectedServers(); + const state = await mcpService.servers.get()[0].start(); + assert.deepStrictEqual({ state: state.state, started }, { state: McpConnectionState.Kind.Error, started: 0 }); + }); + + test('disposal while resolving host policy values does not start or retain a connection', async () => { + const { server, configurationService, registry, transports } = createPolicyServer('https://trusted.example/mcp'); + await configurationService.setUserConfiguration(mcpAllowedServersConfig, [{ serverUrl: 'https://${HOST}/mcp' }]); + const resolving = new DeferredPromise<void>(); + const resolved = new DeferredPromise<Readonly<Record<string, string>>>(); + const host = sinon.stub(registry.delegates.get()[0], 'resolvePolicyVariables').callsFake(() => { + resolving.complete(); + return resolved.p; + }); + store.add(toDisposable(() => host.restore())); + const starting = server.start(); + await resolving.p; + server.dispose(); + resolved.complete({ 'https://${HOST}/mcp': 'https://trusted.example/mcp' }); + const state = await starting; + assert.deepStrictEqual({ state: state.state, started: transports.length, connected: !!server.connection.get() }, { + state: McpConnectionState.Kind.Stopped, started: 0, connected: false, + }); + }); + + test('missing host policy resolutions report an explicit error before execution', async () => { + const { server, configurationService, transports } = createPolicyServer('https://trusted.example/mcp'); + await configurationService.setUserConfiguration(mcpAllowedServersConfig, [{ serverUrl: 'https://${HOST}/mcp' }]); + const state = await server.start(); + assert.deepStrictEqual({ + state: state.state, + message: state.state === McpConnectionState.Kind.Error && state.message.includes('policy environment variables have not been resolved'), + started: transports.length, + }, { state: McpConnectionState.Kind.Error, message: true, started: 0 }); + }); + const provideCachedMetadata = (registry: TestMcpRegistry) => { const createTransport = registry.makeTestTransport; registry.makeTestTransport = () => { @@ -186,6 +270,7 @@ suite('Workbench - MCP - McpService', () => { tools: server.tools.get().length, prompts: server.prompts.get().length, }); + return { ...context, snapshot }; }; diff --git a/src/vs/workbench/contrib/search/browser/searchWidget.ts b/src/vs/workbench/contrib/search/browser/searchWidget.ts index 44bf3df1f9083e..8c6b39875db86c 100644 --- a/src/vs/workbench/contrib/search/browser/searchWidget.ts +++ b/src/vs/workbench/contrib/search/browser/searchWidget.ts @@ -177,6 +177,7 @@ export class SearchWidget extends Widget { readonly onDidToggleContext: Event<void> = this._onDidToggleContext.event; private showContextToggle!: Toggle; + private hideSearchOptions = false; public contextLinesInput!: InputBox; private _notebookFilters: NotebookFindFilters; @@ -311,8 +312,13 @@ export class SearchWidget extends Widget { this.searchInput.inputBox.setAriaLabel(searchLabel); } - setWidth(width: number) { - this.searchInput?.inputBox.layout(); + setWidth(width: number, hideSearchOptions = false) { + this.hideSearchOptions = hideSearchOptions; + this.searchInput?.layout({ + collapsedFindWidget: hideSearchOptions, + narrowFindWidget: false, + reducedFindWidget: false, + }); if (this.replaceInput) { this.replaceInput.width = width - 28; this.replaceInput.inputBox.layout(); @@ -700,7 +706,7 @@ export class SearchWidget extends Widget { keyboardEvent.preventDefault(); } - else if (keyboardEvent.equals(KeyCode.Tab)) { + else if (keyboardEvent.equals(KeyCode.Tab) && !this.hideSearchOptions) { if (this.isReplaceShown()) { this.replaceInput?.focus(); } else { diff --git a/src/vs/workbench/contrib/searchEditor/browser/media/searchEditor.css b/src/vs/workbench/contrib/searchEditor/browser/media/searchEditor.css index 968719314c75fa..61cb06470bae02 100644 --- a/src/vs/workbench/contrib/searchEditor/browser/media/searchEditor.css +++ b/src/vs/workbench/contrib/searchEditor/browser/media/searchEditor.css @@ -10,6 +10,7 @@ .search-editor .search-results { flex: 1; + min-height: 0; } .search-editor .query-container { diff --git a/src/vs/workbench/contrib/searchEditor/browser/searchEditor.ts b/src/vs/workbench/contrib/searchEditor/browser/searchEditor.ts index 02af278de4e0ac..de675a7fe50b0d 100644 --- a/src/vs/workbench/contrib/searchEditor/browser/searchEditor.ts +++ b/src/vs/workbench/contrib/searchEditor/browser/searchEditor.ts @@ -80,6 +80,7 @@ export class SearchEditor extends AbstractTextCodeEditor<SearchEditorViewState> private queryEditorWidget!: SearchWidget; private get searchResultEditor() { return this.editorControl!; } private queryEditorContainer!: HTMLElement; + private searchResultContainer!: HTMLElement; private dimension?: DOM.Dimension; private inputPatternIncludes!: IncludePatternInputWidget; private inputPatternExcludes!: ExcludePatternInputWidget; @@ -135,8 +136,8 @@ export class SearchEditor extends AbstractTextCodeEditor<SearchEditorViewState> protected override createEditor(parent: HTMLElement) { DOM.append(parent, this.container); this.queryEditorContainer = DOM.append(this.container, DOM.$('.query-container')); - const searchResultContainer = DOM.append(this.container, DOM.$('.search-results')); - super.createEditor(searchResultContainer); + this.searchResultContainer = DOM.append(this.container, DOM.$('.search-results')); + super.createEditor(this.searchResultContainer); this.registerEditorListeners(); const scopedContextKeyService = assertReturnsDefined(this.scopedContextKeyService); @@ -283,7 +284,14 @@ export class SearchEditor extends AbstractTextCodeEditor<SearchEditorViewState> if (!this.updatingModelForSearch) { this.getInput()?.setDirty(true); } + this.updateEmptyState(); })); + this._register(this.searchResultEditor.onDidChangeModel(() => this.updateEmptyState())); + } + + private updateEmptyState(): void { + this.container.classList.toggle('search-editor-empty', this.searchResultEditor.getModel()?.getValueLength() === 0); + this.reLayout(); } override getControl() { @@ -666,6 +674,7 @@ export class SearchEditor extends AbstractTextCodeEditor<SearchEditorViewState> override layout(dimension: DOM.Dimension) { this.dimension = dimension; + DOM.size(this.container, dimension.width, dimension.height); this.reLayout(); } @@ -679,10 +688,14 @@ export class SearchEditor extends AbstractTextCodeEditor<SearchEditorViewState> private reLayout() { if (this.dimension) { - const configuredOffset = Number.parseFloat(DOM.getWindow(this.queryEditorContainer).getComputedStyle(this.queryEditorContainer).getPropertyValue('--search-editor-query-layout-offset')); - const queryEditorWidth = this.dimension.width - (Number.isFinite(configuredOffset) ? configuredOffset : DEFAULT_QUERY_EDITOR_LAYOUT_OFFSET); - this.queryEditorWidget.setWidth(queryEditorWidth); - this.searchResultEditor.layout({ height: this.dimension.height - DOM.getTotalHeight(this.queryEditorContainer), width: this.dimension.width }); + const queryStyle = DOM.getWindow(this.queryEditorContainer).getComputedStyle(this.queryEditorContainer); + const configuredOffset = Number.parseFloat(queryStyle.getPropertyValue('--search-editor-query-layout-offset')); + const queryWidth = queryStyle.maxWidth === 'none' ? this.dimension.width : this.queryEditorContainer.clientWidth; + const queryEditorWidth = Math.max(0, queryWidth - (Number.isFinite(configuredOffset) ? configuredOffset : DEFAULT_QUERY_EDITOR_LAYOUT_OFFSET)); + const controlsHidden = queryStyle.getPropertyValue('--search-editor-query-controls-hidden').trim() === 'true'; + this.queryEditorWidget.setWidth(queryEditorWidth, controlsHidden); + this.searchResultEditor.updateOptions({ tabIndex: controlsHidden ? -1 : 0 }); + this.searchResultEditor.layout({ height: this.searchResultContainer.clientHeight, width: this.searchResultContainer.clientWidth }); this.inputPatternExcludes.setWidth(queryEditorWidth); this.inputPatternIncludes.setWidth(queryEditorWidth); } diff --git a/src/vs/workbench/services/github/browser/githubCredentialProvider.ts b/src/vs/workbench/services/github/browser/githubCredentialProvider.ts index 18b6255ec46a23..1382f2af7babfc 100644 --- a/src/vs/workbench/services/github/browser/githubCredentialProvider.ts +++ b/src/vs/workbench/services/github/browser/githubCredentialProvider.ts @@ -134,6 +134,7 @@ export function getWorkbenchMissionControlOptions(providerId: string, enterprise endpoint: { apiBaseUri: `${GITHUB_DOT_COM_COPILOT_API_BASE_URI}/agents`, feedApiBaseUri: `${deriveGitHubEndpoints(undefined).apiBaseUri}/cmc_internal/api/agents`, + identityApiBaseUri: `${deriveGitHubEndpoints(undefined).apiBaseUri}/cmc_internal/api/agents`, integrationId: COPILOT_INTEGRATION_ID, }, } : undefined; diff --git a/src/vs/workbench/services/github/test/browser/githubCredentialProvider.test.ts b/src/vs/workbench/services/github/test/browser/githubCredentialProvider.test.ts index 9ac70a1bf6d83e..3b796dfc98e3b5 100644 --- a/src/vs/workbench/services/github/test/browser/githubCredentialProvider.test.ts +++ b/src/vs/workbench/services/github/test/browser/githubCredentialProvider.test.ts @@ -48,6 +48,7 @@ suite('Workbench GitHub credential broker', () => { endpoint: { apiBaseUri: 'https://api.githubcopilot.com/agents', feedApiBaseUri: 'https://api.github.com/cmc_internal/api/agents', + identityApiBaseUri: 'https://api.github.com/cmc_internal/api/agents', integrationId: COPILOT_INTEGRATION_ID, }, }, diff --git a/src/vs/workbench/test/browser/chatPills.test.ts b/src/vs/workbench/test/browser/chatPills.test.ts index f47511bcabef26..3289bd44c52650 100644 --- a/src/vs/workbench/test/browser/chatPills.test.ts +++ b/src/vs/workbench/test/browser/chatPills.test.ts @@ -1280,9 +1280,19 @@ suite('ChatPills', () => { summaryAriaLabel: count => `Show ${count} canvases`, promotedActionIcon, })); - const container = mainWindow.document.createElement('div'); - mainWindow.document.body.appendChild(container); - store.add(toDisposable(() => container.remove())); + const pillsContainer = mainWindow.document.createElement('div'); + pillsContainer.className = 'chat-pills'; + const actionBar = mainWindow.document.createElement('div'); + actionBar.className = 'monaco-action-bar'; + const actionsContainer = mainWindow.document.createElement('ul'); + actionsContainer.className = 'actions-container'; + const container = mainWindow.document.createElement('li'); + container.className = 'action-item'; + actionsContainer.appendChild(container); + actionBar.appendChild(actionsContainer); + pillsContainer.appendChild(actionBar); + mainWindow.document.body.appendChild(pillsContainer); + store.add(toDisposable(() => pillsContainer.remove())); viewItem.render(container); return { container, hoverActions: () => getDropdownPillHoverOptions.call(viewItem)?.actions?.map(action => action.label) }; }; @@ -1303,17 +1313,30 @@ suite('ChatPills', () => { pillHoverActions: hoverActions(), compactGlyph: promoted.classList.contains('codicon-close-compact'), reservesSpace: container.classList.contains('has-promoted-action'), + itemDisplay: mainWindow.getComputedStyle(container).display, + actionCentered: Math.abs( + promoted.getBoundingClientRect().top + promoted.getBoundingClientRect().height / 2 + - (container.getBoundingClientRect().top + container.getBoundingClientRect().height / 2) + ) <= 1, keepsFocus: mouseDown.defaultPrevented, clicked, tapped, }; - const withoutIconSingle = { promoted: withoutIcon.container.querySelector('.chat-pill-promoted-action'), pillHoverActions: withoutIcon.hoverActions() }; + const withoutIconSingle = { + promoted: withoutIcon.container.querySelector('.chat-pill-promoted-action'), + reservesSpace: withoutIcon.container.classList.contains('has-promoted-action'), + pillHoverActions: withoutIcon.hoverActions(), + }; sections.set([{ title: 'Canvases', entries: [entry, { id: 'other', label: 'Other', promotedAction, open: () => { } }] }], undefined); + const summarized = { shown: container.contains(promoted), reservesSpace: container.classList.contains('has-promoted-action') }; + sections.set([{ title: 'Canvases', entries: [entry] }], undefined); + const restoredPromoted = container.querySelector('.chat-pill-promoted-action'); assert.deepStrictEqual({ single, withoutIcon: withoutIconSingle, - summarized: { shown: container.contains(promoted), reservesSpace: container.classList.contains('has-promoted-action') }, + summarized, + restoredPromotedRecreated: !!restoredPromoted && restoredPromoted !== promoted, }, { single: { attributes: { role: 'button', tabIndex: '-1', ariaLabel: 'Close Canvas Preview' }, @@ -1321,12 +1344,15 @@ suite('ChatPills', () => { pillHoverActions: undefined, compactGlyph: true, reservesSpace: true, + itemDisplay: 'flex', + actionCentered: true, keepsFocus: true, clicked: ['closed'], tapped: ['closed'], }, - withoutIcon: { promoted: null, pillHoverActions: ['Close Canvas Preview'] }, + withoutIcon: { promoted: null, reservesSpace: false, pillHoverActions: ['Close Canvas Preview'] }, summarized: { shown: false, reservesSpace: false }, + restoredPromotedRecreated: true, }); }); }); diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/chatReferences.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/sessions/chatReferences.fixture.ts index fd10d8389e8ccd..d29d8388fcf962 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/chatReferences.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/sessions/chatReferences.fixture.ts @@ -174,8 +174,8 @@ async function renderReferences(ctx: ComponentFixtureContext, scenario: Scenario }); let finishHoverConstruction: (() => void) | undefined; try { - renderPills(ctx, session, { - height: referenceList ? '420px' : resourcePreview ? '600px' : dedicatedCollection ? '280px' : '420px', + await renderPills(ctx, session, { + height: referenceList ? '420px' : resourcePreview ? '600px' : dedicatedCollection ? '320px' : '420px', width: referenceList ? '700px' : scenario === 'single' ? '660px' : '1200px', popupPlacement: 'above', prepareServices: services => { @@ -260,7 +260,7 @@ async function renderReferences(ctx: ComponentFixtureContext, scenario: Scenario ? scenario === 'cold' ? 'Cold cache: IDs stay in front while titles are pending.' : 'Resolved titles: IDs stay in the same leading position.' : 'Click a collection, then hover or focus a row for details. Escape returns to the pills.'; const toolbar = container.querySelector<HTMLElement>('.session-chat-input-toolbar')!; - toolbar.style.top = referenceList ? '330px' : scenario === 'single' ? '52px' : resourcePreview ? '450px' : `${toolbar.offsetTop}px`; + toolbar.style.top = referenceList ? '330px' : scenario === 'single' ? '52px' : resourcePreview ? '450px' : dedicatedCollection ? '200px' : `${toolbar.offsetTop}px`; toolbar.style.bottom = 'auto'; // Icon fonts must be ready before the dropdown measures row widths. @@ -349,7 +349,7 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { 'Pull Request Collection': defineComponentFixture({ virtualTime: { enabled: false }, render: ctx => renderReferences(ctx, 'pullRequests'), - expectedVisualDescriptions: ['The open Pull Requests collection uses the same leading number, resolving-title slot, and trailing copy/remove actions as the Issues and References collections.'], + expectedVisualDescriptions: ['The open Pull Requests collection uses the same leading number and resolving-title slot as the Issues and References collections. Its trailing actions appear as Open Changes, Copy, Pin, then Remove, with the destructive X right-most.'], }), 'Copied Feedback': defineComponentFixture({ virtualTime: { enabled: false }, diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/sessionChatInputToolbar.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/sessions/sessionChatInputToolbar.fixture.ts index 0123ef35d1eb92..5cbaa406f53812 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/sessionChatInputToolbar.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/sessions/sessionChatInputToolbar.fixture.ts @@ -10,11 +10,18 @@ import { Codicon } from '../../../../../base/common/codicons.js'; import { constObservable, IObservable, observableValue } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; import { ActionWidgetService, IActionWidgetService } from '../../../../../platform/actionWidget/browser/actionWidget.js'; -import { IContextViewService } from '../../../../../platform/contextview/browser/contextView.js'; +import { IContextMenuService, IContextViewService } from '../../../../../platform/contextview/browser/contextView.js'; +import { ContextMenuService } from '../../../../../platform/contextview/browser/contextMenuService.js'; import { ContextViewService } from '../../../../../platform/contextview/browser/contextViewService.js'; +import { CanvasesEnabledSettingId } from '../../../../../platform/agentHost/common/agentService.js'; +import { IConfigurationService } from '../../../../../platform/configuration/common/configuration.js'; +import { TestConfigurationService } from '../../../../../platform/configuration/test/common/testConfigurationService.js'; import { IFileContent, IFileService } from '../../../../../platform/files/common/files.js'; import { ILayoutService } from '../../../../../platform/layout/browser/layoutService.js'; import { TestInstantiationService } from '../../../../../platform/instantiation/test/common/instantiationServiceMock.js'; +import { IQuickInputService } from '../../../../../platform/quickinput/common/quickInput.js'; +import { IStorageService } from '../../../../../platform/storage/common/storage.js'; +import { IExternalUriOpenerService } from '../../../../contrib/externalUriOpener/common/externalUriOpenerService.js'; import { chatPersistentContentVisibleClass } from '../../../../contrib/chat/browser/widget/chatWidget.js'; import { ISessionChatPillVisibilityService, SESSION_CHAT_PILL_KINDS } from '../../../../contrib/chat/common/sessionChatPills.js'; import { BrowserEditorInput } from '../../../../contrib/browserView/common/browserEditorInput.js'; @@ -37,7 +44,7 @@ import { IAgentWorkbenchLayoutService } from '../../../../../sessions/browser/wo // eslint-disable-next-line local/code-import-patterns import { ISessionChangesService } from '../../../../../sessions/contrib/changes/browser/sessionChangesService.js'; // eslint-disable-next-line local/code-import-patterns -import { ChatOriginKind, type IGitHubInfo, type IGitHubPullRequestRef, ISessionArtifact, ISessionChatCustomization, ISessionTurnFileChange, ISessionWorkspace, IChat, ISessionCapabilities, ISessionFolder, ISessionGitRepository, SessionArtifactKind, SessionCustomizationKind, SessionStatus } from '../../../../../sessions/services/sessions/common/session.js'; +import { ChatOriginKind, type IGitHubInfo, type IGitHubPullRequestRef, ISessionArtifact, ISessionCanvas, ISessionChatCustomization, ISessionTurnFileChange, ISessionWorkspace, IChat, ISessionCapabilities, ISessionFolder, ISessionGitRepository, SessionArtifactKind, SessionCustomizationKind, SessionStatus } from '../../../../../sessions/services/sessions/common/session.js'; // eslint-disable-next-line local/code-import-patterns import { IActiveSession, ISessionsManagementService } from '../../../../../sessions/services/sessions/common/sessionsManagement.js'; // eslint-disable-next-line local/code-import-patterns @@ -46,6 +53,7 @@ import { ComponentFixtureContext, createEditorServices, defineComponentFixture, import { registerChatFixtureServices } from '../chat/chatFixtureUtils.js'; import { IFixtureMessage, renderChatWidget } from '../chat/chatWidget.fixture.js'; import { createFixtureGitHubService, createFixtureWorkbenchGitHubService } from './githubFixtureUtils.js'; +import { TestStorageService } from '../../../common/workbenchTestServices.js'; // ============================================================================ // Mock helpers @@ -70,6 +78,7 @@ interface ISessionSpec { readonly turnChanges?: readonly ISessionTurnFileChange[]; readonly browsers?: readonly { readonly title?: string; readonly ownerSubagent?: number }[]; readonly subagents?: readonly string[]; + readonly canvases?: readonly string[]; /** Artifacts and references the agent recorded on the session. */ readonly artifacts?: readonly ISessionArtifact[]; readonly removableArtifacts?: boolean; @@ -84,6 +93,7 @@ interface IMockSessionAndChat { readonly chat: IChat; readonly browsers: readonly BrowserEditorInput[]; removeArtifact(id: string): void; + closeCanvas(canvas: ISessionCanvas): void; } export function createMockSession(spec: ISessionSpec): IMockSessionAndChat { @@ -123,6 +133,14 @@ export function createMockSession(spec: ISessionSpec): IMockSessionAndChat { spec.turnChanges !== undefined ? constObservable(spec.turnChanges) : undefined; override readonly customizations: IObservable<readonly ISessionChatCustomization[]> | undefined = spec.customizations !== undefined ? constObservable(spec.customizations) : undefined; + override readonly canvases = spec.canvases !== undefined + ? observableValue<readonly ISessionCanvas[] | undefined>('fixture.canvases', spec.canvases.map(title => ({ + resource: URI.parse(`agent-host-canvas:/${title.toLowerCase().replaceAll(' ', '-')}`), + instanceId: title.toLowerCase().replaceAll(' ', '-'), + title, + source: URI.parse(`https://example.test/${title.toLowerCase().replaceAll(' ', '-')}`), + }))) + : undefined; }(); const subagents = (spec.subagents ?? []).map((title, index) => new class extends mock<IChat>() { override readonly resource = URI.parse(`chat:subagent-${index}`); @@ -140,7 +158,7 @@ export function createMockSession(spec: ISessionSpec): IMockSessionAndChat { override readonly loading = constObservable(false); override readonly isArchived = constObservable(false); override readonly isRead = constObservable(true); - override readonly capabilities: IObservable<ISessionCapabilities> = constObservable({ supportsMultipleChats: false, supportsRemoveArtifacts: spec.removableArtifacts }); + override readonly capabilities: IObservable<ISessionCapabilities> = constObservable({ supportsMultipleChats: false, supportsRemoveArtifacts: spec.removableArtifacts, supportsCanvases: spec.canvases !== undefined }); override readonly workspace: IObservable<ISessionWorkspace | undefined> = constObservable(workspace); override readonly artifacts = artifacts; }(); @@ -156,7 +174,13 @@ export function createMockSession(spec: ISessionSpec): IMockSessionAndChat { override readonly onDidChangeLabel = Event.None; }(); }); - return { session, chat, browsers, removeArtifact: id => artifacts.set(artifacts.get().filter(artifact => artifact.id !== id), undefined) }; + return { + session, + chat, + browsers, + removeArtifact: id => artifacts.set(artifacts.get().filter(artifact => artifact.id !== id), undefined), + closeCanvas: canvas => chat.canvases?.set(chat.canvases.get()?.filter(candidate => candidate !== canvas), undefined), + }; } function createBrowserViewService(inputs: readonly BrowserEditorInput[]): IBrowserViewWorkbenchService { @@ -169,6 +193,10 @@ function createBrowserViewService(inputs: readonly BrowserEditorInput[]): IBrows } function registerSessionChatPillFixtureServices(registration: ServiceRegistration, sessionMock: IMockSessionAndChat): void { + registration.defineInstance(IQuickInputService, new class extends mock<IQuickInputService>() { }()); + registration.defineInstance(IExternalUriOpenerService, new class extends mock<IExternalUriOpenerService>() { + override async getOpener() { return undefined; } + }()); registration.defineInstance(ISessionsProvidersService, new class extends mock<ISessionsProvidersService>() { override getProvider() { return undefined; } }()); @@ -181,11 +209,14 @@ function registerSessionChatPillFixtureServices(registration: ServiceRegistratio }()); registration.defineInstance(IGitHubService, createFixtureGitHubService([])); registration.defineInstance(IWorkbenchGitHubService, createFixtureWorkbenchGitHubService({})); - if (sessionMock.session.capabilities.get().supportsRemoveArtifacts) { + if (sessionMock.session.capabilities.get().supportsRemoveArtifacts || sessionMock.session.capabilities.get().supportsCanvases) { registration.defineInstance(ISessionsManagementService, new class extends mock<ISessionsManagementService>() { override async removeSessionArtifact(_session: IActiveSession, artifactId: string): Promise<void> { sessionMock.removeArtifact(artifactId); } + override async closeCanvas(_session: IActiveSession, _chat: IChat, canvas: ISessionCanvas): Promise<void> { + sessionMock.closeCanvas(canvas); + } }()); } } @@ -213,7 +244,7 @@ async function createImageReferenceContent(resource: URI): Promise<IFileContent> }; } -export function renderPills(ctx: ComponentFixtureContext, sessionMock: IMockSessionAndChat, options?: { readonly compact?: boolean | 'auto'; readonly debugData?: ISessionChatPillsDebugData; readonly height?: string; readonly width?: string; readonly popupPlacement?: 'above'; readonly additionalServices?: (reg: ServiceRegistration) => void; readonly prepareServices?: (services: TestInstantiationService) => void }): void { +export async function renderPills(ctx: ComponentFixtureContext, sessionMock: IMockSessionAndChat, options?: { readonly compact?: boolean | 'auto'; readonly debugData?: ISessionChatPillsDebugData; readonly height?: string; readonly width?: string; readonly popupPlacement?: 'above'; readonly additionalServices?: (reg: ServiceRegistration) => void; readonly prepareServices?: (services: TestInstantiationService) => void }): Promise<void> { const { container, disposableStore } = ctx; const instantiationService = createEditorServices(disposableStore, { @@ -226,6 +257,8 @@ export function renderPills(ctx: ComponentFixtureContext, sessionMock: IMockSess // (which register a partial ISessionsService). registerChatFixtureServices(reg); registerSessionChatPillFixtureServices(reg, sessionMock); + reg.defineInstance(IStorageService, disposableStore.add(new TestStorageService())); + reg.define(IContextMenuService, ContextMenuService); reg.defineInstance(ILayoutService, new class extends mock<ILayoutService>() { override readonly mainContainer = container; override readonly activeContainer = container; @@ -256,6 +289,13 @@ export function renderPills(ctx: ComponentFixtureContext, sessionMock: IMockSess const actionWidgetService = disposableStore.add(instantiationService.createInstance(ActionWidgetService)); instantiationService.stub(IActionWidgetService, actionWidgetService); options?.prepareServices?.(instantiationService); + if (sessionMock.session.capabilities.get().supportsCanvases) { + const configurationService = instantiationService.get(IConfigurationService); + if (!(configurationService instanceof TestConfigurationService)) { + throw new Error('Expected TestConfigurationService'); + } + await configurationService.setUserConfiguration(CanvasesEnabledSettingId, true); + } const visibility = instantiationService.get(ISessionChatPillVisibilityService); for (const kind of SESSION_CHAT_PILL_KINDS) { @@ -460,6 +500,16 @@ export default defineThemedFixtureGroup({ path: 'sessions/' }, { })), }), + // --- Canvases ----------------------------------------------------------- + + SessionChatPills_CanvasPinning: defineComponentFixture({ + virtualTime: { enabled: false }, + expectedVisualDescriptions: ['A session status row with a 3 Canvases pill ready to open a picker and demonstrate pinning.'], + render: ctx => renderPills(ctx, createMockSession({ + canvases: ['Plan', 'Preview', 'Architecture'], + }), { width: '620px', height: '360px' }), + }), + // --- Browser and background activity pills ------------------------------ SessionChatPills_BackgroundBrowser: defineComponentFixture({